<?php
$u=current_user();$canManage=can_manage_manual_notifications($u);$companyId=(int)($u['company_id']??0);
$q=db()->prepare('SELECT * FROM notifications WHERE user_id=? ORDER BY id DESC LIMIT 150');$q->execute([(int)$u['id']]);$items=$q->fetchAll();
$roles=notification_role_options();$companies=is_admin()?db()->query("SELECT id,name FROM companies WHERE status='active' ORDER BY name")->fetchAll():[];
$broadcasts=[];
if($canManage){
    if(is_role('super_admin')){
        $bq=db()->query("SELECT n.*,(SELECT COUNT(*) FROM notifications x WHERE x.broadcast_id=n.broadcast_id) recipient_count FROM notifications n WHERE n.broadcast_id IS NOT NULL AND n.id IN (SELECT MAX(id) FROM notifications WHERE broadcast_id IS NOT NULL GROUP BY broadcast_id) ORDER BY n.id DESC LIMIT 100");
    }elseif(is_role('sub_admin')){
        $bq=db()->prepare("SELECT n.*,(SELECT COUNT(*) FROM notifications x WHERE x.broadcast_id=n.broadcast_id) recipient_count FROM notifications n LEFT JOIN users iu ON iu.id=n.issuer_user_id WHERE n.broadcast_id IS NOT NULL AND (n.issuer_user_id=? OR iu.role IS NULL OR iu.role NOT IN ('super_admin','sub_admin')) AND n.id IN (SELECT MAX(nn.id) FROM notifications nn LEFT JOIN users iuu ON iuu.id=nn.issuer_user_id WHERE nn.broadcast_id IS NOT NULL AND (nn.issuer_user_id=? OR iuu.role IS NULL OR iuu.role NOT IN ('super_admin','sub_admin')) GROUP BY nn.broadcast_id) ORDER BY n.id DESC LIMIT 100");
        $bq->execute([(int)$u['id'],(int)$u['id']]);
    }else{
        $bq=db()->prepare("SELECT n.*,(SELECT COUNT(*) FROM notifications x WHERE x.broadcast_id=n.broadcast_id) recipient_count FROM notifications n WHERE n.broadcast_id IS NOT NULL AND n.source_company_id=? AND n.id IN (SELECT MAX(id) FROM notifications WHERE broadcast_id IS NOT NULL AND source_company_id=? GROUP BY broadcast_id) ORDER BY n.id DESC LIMIT 100");
        $bq->execute([$companyId,$companyId]);
    }
    $broadcasts=$bq->fetchAll();
}
$employeePermission=0;if($companyId){$pq=db()->prepare('SELECT employees_can_manage_notifications FROM companies WHERE id=?');$pq->execute([$companyId]);$employeePermission=(int)$pq->fetchColumn();}
$deletionRequests=[];if(is_admin()){$deletionRequests=db()->query("SELECT r.*,u.id live_user_id,u.public_id,u.email live_user_email,c.id live_company_id,c.slug live_company_slug,ou.email live_company_owner_email FROM account_deletion_requests r LEFT JOIN users u ON u.id=r.user_id LEFT JOIN companies c ON c.id=r.company_id LEFT JOIN users ou ON ou.id=c.owner_user_id WHERE r.status='pending' ORDER BY r.id DESC LIMIT 100")->fetchAll();}
function notification_datetime_local($value): string { if(!$value)return ''; $ts=strtotime((string)$value);return $ts?date('Y-m-d\TH:i',$ts):''; }
function render_notification_form(array $item,array $u,array $roles,array $companies): void {
    $admin=in_array(($u['role']??''),['super_admin','sub_admin'],true);$type=(string)($item['audience_type']??($admin?'all':'company_clients'));$value=(string)($item['audience_value']??'');
?>
<form method="post" action="actions.php" enctype="multipart/form-data"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="save_manual_notification"><input type="hidden" name="return_page" value="notifications"><input type="hidden" name="broadcast_id" value="<?= e($item['broadcast_id']??'') ?>">
<div class="form-grid"><div class="form-group"><label>Título</label><input class="input" name="title" value="<?= e($item['title']??'') ?>" required></div><div class="form-group"><label>Tipo</label><select name="type"><option value="info"<?= selected($item['type']??'info','info') ?>>Informação</option><option value="success"<?= selected($item['type']??'info','success') ?>>Sucesso</option><option value="warning"<?= selected($item['type']??'info','warning') ?>>Aviso</option></select></div><div class="form-group full"><label>Mensagem</label><textarea name="message" required><?= e($item['message']??'') ?></textarea></div>
<div class="form-group"><label>Público</label><select name="audience_type" data-notification-audience><?php if($admin):?><option value="all"<?= selected($type,'all') ?>>Todos os usuários</option><option value="role"<?= selected($type,'role') ?>>Por perfil</option><option value="company"<?= selected($type,'company') ?>>Por empresa</option><option value="user"<?= selected($type,'user') ?>>Usuário individual</option><?php else:?><option value="company_clients"<?= selected($type,'company_clients') ?>>Clientes da empresa</option><option value="company_couriers"<?= selected($type,'company_couriers') ?>>Entregadores da empresa</option><option value="company_employees"<?= selected($type,'company_employees') ?>>Funcionários da empresa</option><option value="company_all"<?= selected($type,'company_all') ?>>Todos vinculados à empresa</option><option value="user"<?= selected($type,'user') ?>>Usuário individual</option><?php endif;?></select></div>
<?php if($admin):?><div class="form-group" data-notification-field="role"><label>Perfil</label><select name="target_role"><?php foreach($roles as $role=>$label):?><option value="<?= e($role) ?>"<?= selected($type==='role'?$value:'',$role) ?>><?= e($label) ?></option><?php endforeach;?></select></div><div class="form-group" data-notification-field="company"><label>Empresa</label><select name="target_company_id"><option value="">Selecione</option><?php foreach($companies as $company):?><option value="<?= (int)$company['id'] ?>"<?= selected($type==='company'?$value:'',$company['id']) ?>><?= e($company['name']) ?></option><?php endforeach;?></select></div><?php endif;?><div class="form-group" data-notification-field="user"><label>ID do usuário ou e-mail</label><input class="input" name="target_user" value="<?= e($type==='user'?$value:'') ?>" placeholder="LXU-... ou e-mail"></div>
<div class="form-group"><label>Exibir na tela inicial até</label><input class="input" type="datetime-local" name="expires_at" value="<?= e(notification_datetime_local($item['expires_at']??'')) ?>"><small>Vazio = permanece na tela inicial até ser apagada.</small></div><div class="form-group"><label>Imagem</label><input class="input" type="file" name="image_file" accept="image/jpeg,image/png,image/webp"><?php if(!empty($item['image'])):?><label class="check-line"><input type="checkbox" name="remove_image" value="1"> Remover imagem atual</label><?php endif;?></div><div class="form-group full"><label>URL da imagem (opcional)</label><input class="input" type="url" name="image_url" value="<?= (!empty($item['image'])&&preg_match('~^https?://~i',(string)$item['image']))?e($item['image']):'' ?>" placeholder="https://..."></div></div>
<div class="form-actions"><button class="btn btn-primary">Salvar e enviar notificação</button></div></form>
<?php }
?>
<section class="page-intro"><div><span class="mini-label">COMUNICAÇÃO</span><h2>Central de notificações</h2><p>Avisos do sistema e comunicados enviados pelo administrador ou pela sua empresa.</p></div><?php if($canManage):?><button class="btn btn-primary" data-modal-open="#notificationModal">+ Nova notificação</button><?php endif;?></section>
<?php if(is_admin()):?><section class="panel"><div class="panel-header"><div><h3>Solicitações de exclusão</h3><p>Pedidos enviados por usuários e responsáveis de empresas. A exclusão nunca é automática.</p></div><?php if($deletionRequests):?><span class="status status-pending"><?= count($deletionRequests) ?> pendente(s)</span><?php endif;?></div><div class="table-wrap"><table><thead><tr><th>Tipo</th><th>Solicitante</th><th>Motivo</th><th>Solicitado em</th><th>Ações</th></tr></thead><tbody><?php if(!$deletionRequests):?><tr><td colspan="5"><div class="empty-state"><strong>Nenhuma solicitação pendente</strong></div></td></tr><?php endif;?><?php foreach($deletionRequests as $dr):?><tr><td><?= ($dr['request_type']??'user')==='company'?'<span class="status status-pending">Empresa</span>':'<span class="status status-pending">Usuário</span>' ?></td><td><strong><?= e(($dr['request_type']??'user')==='company'?($dr['company_name_snapshot']?:'Empresa'):($dr['user_name_snapshot']?:'Usuário')) ?></strong><small style="display:block"><?= e($dr['user_email_snapshot']?:'') ?><?= !empty($dr['public_id'])?' • '.e($dr['public_id']):'' ?></small></td><td><?= e($dr['reason']?:'Não informado') ?></td><td><?= e(date('d/m/Y H:i',strtotime($dr['created_at']))) ?></td><td><div class="actions"><?php if(($dr['request_type']??'user')==='company'&&!empty($dr['live_company_id'])):?><a class="btn btn-danger btn-sm" href="<?= e(url('dashboard.php?page=companies&focus_id='.(int)$dr['company_id'])) ?>">Acessar empresa para excluir</a><?php elseif(($dr['request_type']??'user')==='user'&&!empty($dr['live_user_id'])):?><a class="btn btn-danger btn-sm" href="<?= e(url('dashboard.php?page=users&focus_id='.(int)$dr['user_id'])) ?>">Acessar usuário para excluir</a><?php else:?><span class="muted">Cadastro não encontrado</span><?php endif;?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="resolve_account_deletion_request"><input type="hidden" name="return_page" value="notifications"><input type="hidden" name="id" value="<?= (int)$dr['id'] ?>"><button class="btn btn-secondary btn-sm" type="submit" data-confirm="Arquivar esta solicitação sem excluir o cadastro?">Arquivar</button></form></div></td></tr><?php endforeach;?></tbody></table></div></section><?php endif;?>
<?php if(($u['role']??'')==='company'&&$companyId):?><section class="panel"><div class="panel-header"><div><h3>Permissão para funcionários</h3><p>Libere ou bloqueie a equipe para criar, editar e apagar notificações da empresa.</p></div><form method="post" action="actions.php" class="actions"><?= csrf_field() ?><input type="hidden" name="action" value="save_company_notification_permission"><input type="hidden" name="return_page" value="notifications"><select name="enabled"><option value="0"<?= selected($employeePermission,0) ?>>Bloqueado</option><option value="1"<?= selected($employeePermission,1) ?>>Liberado</option></select><button class="btn btn-secondary btn-sm">Salvar</button></form></div></section><?php endif;?>
<?php if(($u['role']??'')==='employee'&&$companyId):?><div class="notice" style="margin-bottom:18px">Publicação de notificações pelos funcionários: <strong><?= $employeePermission?'liberada pela empresa':'bloqueada pela empresa' ?></strong>.</div><?php endif;?>
<?php if($canManage):?><section class="panel"><div class="panel-header"><div><h3>Notificações publicadas</h3><p>Edite, apague ou confira até quando o aviso ficará na tela inicial.</p></div></div><div class="cards-list notification-manage-grid"><?php if(!$broadcasts):?><div class="empty-state"><strong>Nenhuma publicação manual</strong>Crie a primeira notificação.</div><?php endif;?><?php foreach($broadcasts as $n):?><article class="item-card notification-admin-card"><?php if($n['image']):?><div class="notification-card-image"><img src="<?= e(media_url($n['image'])) ?>" alt=""></div><?php endif;?><div class="item-body"><div class="item-meta"><span><?= e($n['audience_label']?:'Público definido') ?></span><span><?= (int)$n['recipient_count'] ?> destinatário(s)</span></div><h3><?= e($n['title']) ?></h3><p><?= e($n['message']) ?></p><small>Exibe até: <?= $n['expires_at']?e(date('d/m/Y H:i',strtotime($n['expires_at']))):'sem prazo' ?></small><div class="actions" style="margin-top:14px"><button class="btn btn-secondary btn-sm" data-modal-open="#notificationModal<?= e(preg_replace('/[^a-zA-Z0-9_-]/','',$n['broadcast_id'])) ?>">Editar</button><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="delete_manual_notification"><input type="hidden" name="return_page" value="notifications"><input type="hidden" name="broadcast_id" value="<?= e($n['broadcast_id']) ?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar esta notificação para todos os destinatários?">Apagar</button></form></div></div></article><?php endforeach;?></div></section><?php endif;?>
<section class="panel"><div class="panel-header"><div><h3>Minhas notificações</h3><p>Toque em um aviso para marcá-lo como lido e acessar a área relacionada quando houver link.</p></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="mark_notifications"><input type="hidden" name="return_page" value="notifications"><button class="btn btn-secondary" type="submit">Marcar todas como lidas</button></form></div><div class="activity-list">
<?php if(!$items):?><div class="empty-state"><strong>Nenhuma notificação</strong>Seus avisos aparecerão aqui.</div><?php endif;?>
<?php foreach($items as $n):?><a class="activity notification-row<?= $n['read_at']?'':' notification-unread' ?>" href="<?= e(url('notification_open.php?id='.(int)$n['id'])) ?>"><?php if(!empty($n['image'])):?><span class="notification-list-thumb"><img src="<?= e(media_url($n['image'])) ?>" alt=""></span><?php else:?><span class="activity-dot" style="background:<?= $n['read_at']?'var(--muted)':'var(--accent)' ?>"></span><?php endif;?><div><p><strong><?= e($n['title']) ?></strong> — <?= e($n['message']) ?></p><small><?= e(date('d/m/Y H:i',strtotime($n['created_at']))) ?><?= $n['read_at']?' • lida':' • nova' ?><?= !empty($n['audience_label'])?' • '.e($n['audience_label']):'' ?></small></div><span class="notification-arrow">›</span></a><?php endforeach;?>
</div></section>
<?php if($canManage):?><div class="modal" id="notificationModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Nova notificação</h2><button class="close-btn" data-modal-close>×</button></div><?php render_notification_form([], $u,$roles,$companies); ?></div></div><?php foreach($broadcasts as $n):$safe=preg_replace('/[^a-zA-Z0-9_-]/','',$n['broadcast_id']);?><div class="modal" id="notificationModal<?= e($safe) ?>"><div class="modal-card modal-large"><div class="modal-head"><h2>Editar notificação</h2><button class="close-btn" data-modal-close>×</button></div><?php render_notification_form($n,$u,$roles,$companies); ?></div></div><?php endforeach;?><?php endif;?>
