<?php
require_once __DIR__.'/includes/config.php';
require_admin();
$db=db();
$err=''; $edit=null;

if(isset($_GET['edit'])){
    $st=$db->prepare('SELECT * FROM panel_notices WHERE id=:id');
    $st->bindValue(':id',(int)$_GET['edit'],SQLITE3_INTEGER);
    $edit=$st->execute()->fetchArray(SQLITE3_ASSOC) ?: null;
}
if(isset($_GET['delete'])){
    $id=(int)$_GET['delete'];
    $st=$db->prepare('DELETE FROM panel_notices WHERE id=:id');
    $st->bindValue(':id',$id,SQLITE3_INTEGER);
    $st->execute();
    header('Location: avisos_painel.php?ok=deleted'); exit;
}
if(isset($_GET['toggle'])){
    $id=(int)$_GET['toggle'];
    $st=$db->prepare('UPDATE panel_notices SET is_active=CASE WHEN is_active=1 THEN 0 ELSE 1 END, updated_at=CURRENT_TIMESTAMP WHERE id=:id');
    $st->bindValue(':id',$id,SQLITE3_INTEGER);
    $st->execute();
    header('Location: avisos_painel.php?ok=toggled'); exit;
}

if($_SERVER['REQUEST_METHOD']==='POST'){
    $id=(int)($_POST['id'] ?? 0);
    $target=(string)($_POST['target'] ?? '');
    [$target_type,$target_id]=array_pad(explode(':',$target,2),2,0);
    $target_id=(int)$target_id;
    $title=trim((string)($_POST['title'] ?? ''));
    $message=trim((string)($_POST['message'] ?? ''));
    $active=isset($_POST['is_active']) ? 1 : 0;

    if(!in_array($target_type,['revenda','subrevenda'],true) || $target_id<=0){
        $err='Selecione uma revenda ou sub revenda.';
    } elseif($message===''){
        $err='Digite a mensagem do aviso.';
    } else {
        if($id>0){
            $st=$db->prepare('UPDATE panel_notices SET title=:title,message=:msg,target_type=:tt,target_id=:tid,is_active=:a,updated_at=CURRENT_TIMESTAMP WHERE id=:id');
            $st->bindValue(':id',$id,SQLITE3_INTEGER);
        } else {
            $st=$db->prepare('INSERT INTO panel_notices(title,message,target_type,target_id,is_active,created_by) VALUES(:title,:msg,:tt,:tid,:a,:by)');
            $st->bindValue(':by',$_SESSION['name'] ?? 'admin',SQLITE3_TEXT);
        }
        $st->bindValue(':title',$title,SQLITE3_TEXT);
        $st->bindValue(':msg',$message,SQLITE3_TEXT);
        $st->bindValue(':tt',$target_type,SQLITE3_TEXT);
        $st->bindValue(':tid',$target_id,SQLITE3_INTEGER);
        $st->bindValue(':a',$active,SQLITE3_INTEGER);
        $st->execute();
        header('Location: avisos_painel.php?ok=1'); exit;
    }
}

$revendas=[]; $res=$db->query('SELECT id,nome,usuario FROM revendas ORDER BY nome,usuario');
while($r=$res->fetchArray(SQLITE3_ASSOC)) $revendas[]=$r;
$subs=[]; $res=$db->query('SELECT s.id,s.nome,s.usuario,r.nome AS revenda_nome,r.usuario AS revenda_usuario FROM sub_revendas s LEFT JOIN revendas r ON r.id=s.revenda_id ORDER BY s.nome,s.usuario');
while($r=$res->fetchArray(SQLITE3_ASSOC)) $subs[]=$r;

$rows=[]; $res=$db->query('SELECT * FROM panel_notices ORDER BY id DESC');
while($r=$res->fetchArray(SQLITE3_ASSOC)) $rows[]=$r;

include __DIR__.'/includes/header.php';
?>
<div class="card">
    <h3>📨 Central de Avisos do Painel</h3>
    <p class="muted">Somente o admin envia avisos individuais para revendas ou sub revendas. Eles verão a mensagem dentro do painel.</p>
    <?php if(isset($_GET['ok'])): ?><p class="ok">Aviso salvo.</p><?php endif; ?>
    <?php if($err): ?><p class="bad"><?=h($err)?></p><?php endif; ?>

    <form method="post">
        <input type="hidden" name="id" value="<?=h($edit['id'] ?? 0)?>">
        <div class="grid" style="grid-template-columns:repeat(2,minmax(0,1fr));gap:12px">
            <div>
                <label>Enviar para</label>
                <select name="target" required>
                    <option value="">Selecione...</option>
                    <optgroup label="Revendas">
                        <?php foreach($revendas as $rv): $val='revenda:'.$rv['id']; ?>
                        <option value="<?=h($val)?>" <?=($edit && $edit['target_type']==='revenda' && (int)$edit['target_id']===(int)$rv['id'])?'selected':''?>><?=h($rv['nome'] ?: $rv['usuario'])?></option>
                        <?php endforeach; ?>
                    </optgroup>
                    <optgroup label="Sub Revendas">
                        <?php foreach($subs as $sr): $val='subrevenda:'.$sr['id']; ?>
                        <option value="<?=h($val)?>" <?=($edit && $edit['target_type']==='subrevenda' && (int)$edit['target_id']===(int)$sr['id'])?'selected':''?>><?=h(($sr['nome'] ?: $sr['usuario']).' - Revenda: '.($sr['revenda_nome'] ?: $sr['revenda_usuario']))?></option>
                        <?php endforeach; ?>
                    </optgroup>
                </select>
            </div>
            <div>
                <label>Título</label>
                <input name="title" value="<?=h($edit['title'] ?? '')?>" placeholder="Ex: Aviso importante">
            </div>
        </div>
        <label>Mensagem</label>
        <textarea name="message" rows="5" placeholder="Digite o aviso..." required><?=h($edit['message'] ?? '')?></textarea>
        <label style="display:flex;gap:8px;align-items:center;margin-top:12px"><input type="checkbox" name="is_active" <?=(!isset($edit['is_active']) || (int)$edit['is_active']===1)?'checked':''?>> Aviso ativo</label>
        <p><button class="btn">Enviar/Salvar Aviso</button> <?php if($edit): ?><a class="btn dark" href="avisos_painel.php">Cancelar</a><?php endif; ?></p>
    </form>
</div>

<div class="card">
    <h3>Histórico de avisos enviados</h3>
    <table>
        <tr><th>ID</th><th>Destino</th><th>Título</th><th>Mensagem</th><th>Status</th><th>Data</th><th>Ações</th></tr>
        <?php foreach($rows as $r): ?>
        <tr>
            <td>#<?=h($r['id'])?></td>
            <td><?=h(panel_notice_target_label($r['target_type'],$r['target_id']))?></td>
            <td><?=h($r['title'])?></td>
            <td><?=h(mb_strimwidth((string)$r['message'],0,80,'...','UTF-8'))?></td>
            <td><?=(int)$r['is_active']===1?'<span class="pill">Ativo</span>':'<span class="bad">Inativo</span>'?></td>
            <td><?=h($r['created_at'])?></td>
            <td>
                <a class="btn dark" href="avisos_painel.php?edit=<?=h($r['id'])?>">Editar</a>
                <a class="btn dark" href="avisos_painel.php?toggle=<?=h($r['id'])?>"><?=(int)$r['is_active']===1?'Desativar':'Ativar'?></a>
                <a class="btn red" onclick="return confirm('Excluir este aviso?')" href="avisos_painel.php?delete=<?=h($r['id'])?>">Excluir</a>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>
<?php include __DIR__.'/includes/footer.php'; ?>
