<?php
require_once __DIR__.'/includes/config.php';
require_login();

$db = db();
if (function_exists('cleanup_message_history')) { cleanup_message_history(false); }
$msg = '';
$erro = '';

function dt_local_to_sql($v){
    $v = trim((string)$v);
    if ($v === '') return '';
    $ts = strtotime($v);
    return $ts ? date('Y-m-d H:i:s', $ts) : '';
}
function dt_sql_to_input($v){
    $v = trim((string)$v);
    if ($v === '') return '';
    $ts = strtotime($v);
    return $ts ? date('Y-m-d\TH:i', $ts) : '';
}
function aviso_target_label($type){
    $labels = [
        'global' => 'Todos',
        'username' => 'Usuário',
        'password' => 'Senha',
        'android_id' => 'Android ID',
        'code' => 'Código',
        'client_key' => 'Chave APK'
    ];
    return $labels[$type] ?? $type;
}
function aviso_status_now($m){
    if ((int)($m['is_active'] ?? 0) !== 1) return ['Inativo', 'bad'];
    $now = time();
    $start = trim((string)($m['start_at'] ?? ''));
    $end = trim((string)($m['end_at'] ?? ''));
    if ($start !== '' && strtotime($start) > $now) return ['Programado', 'warn'];
    if ($end !== '' && strtotime($end) < $now) return ['Finalizado', 'bad'];
    return ['Ativo', 'ok'];
}

if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $db->prepare('DELETE FROM screen_messages WHERE id=:id');
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $stmt->execute();
    header('Location: avisos.php?ok=deleted');
    exit;
}

if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $stmt = $db->prepare('UPDATE screen_messages SET is_active = CASE WHEN is_active=1 THEN 0 ELSE 1 END, updated_at=CURRENT_TIMESTAMP WHERE id=:id');
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $stmt->execute();
    header('Location: avisos.php?ok=toggled');
    exit;
}

if (isset($_GET['duplicate'])) {
    $id = (int)$_GET['duplicate'];
    $stmt = $db->prepare("INSERT INTO screen_messages(title,message,target_type,target_value,position,speed,is_active,start_at,end_at,repeat_minutes,priority,color)
        SELECT title || ' - cópia', message, target_type, target_value, position, speed, 0, start_at, end_at, repeat_minutes, priority, color FROM screen_messages WHERE id=:id");
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $stmt->execute();
    header('Location: avisos.php?ok=duplicated');
    exit;
}

if (isset($_GET['ok'])) {
    $oks = [
        'deleted' => 'Aviso excluído.',
        'toggled' => 'Status alterado.',
        'duplicated' => 'Aviso duplicado como inativo.',
        'saved' => 'Aviso salvo com sucesso.',
        'history_deleted' => 'Registro do histórico apagado.',
        'history_selected_deleted' => 'Histórico selecionado apagado.',
        'history_cleared' => 'Histórico completo apagado.',
        'history_old_cleared' => 'Histórico antigo apagado.',
        'history_settings_saved' => 'Configuração da limpeza automática salva.'
    ];
    $msg = $oks[$_GET['ok']] ?? '';
}


if (isset($_GET['delete_hit'])) {
    $id = (int)$_GET['delete_hit'];
    $stmt = $db->prepare('DELETE FROM screen_message_hits WHERE id=:id');
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $stmt->execute();
    header('Location: avisos.php?ok=history_deleted#historico');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['history_action'])) {
    $action = (string)$_POST['history_action'];
    if ($action === 'delete_selected') {
        $ids = $_POST['hit_ids'] ?? [];
        if (is_array($ids) && $ids) {
            $clean = [];
            foreach ($ids as $id) { $id=(int)$id; if($id>0) $clean[]=$id; }
            if ($clean) {
                $db->exec('DELETE FROM screen_message_hits WHERE id IN ('.implode(',', $clean).')');
            }
        }
        header('Location: avisos.php?ok=history_selected_deleted#historico');
        exit;
    }
    if ($action === 'clear_all') {
        $db->exec('DELETE FROM screen_message_hits');
        header('Location: avisos.php?ok=history_cleared#historico');
        exit;
    }
    if ($action === 'clear_old') {
        $days = (int)($_POST['old_days'] ?? 30);
        if ($days < 1) $days = 30;
        if ($days > 3650) $days = 3650;
        $cutoff = date('Y-m-d H:i:s', strtotime('-'.$days.' days'));
        $stmt = $db->prepare('DELETE FROM screen_message_hits WHERE shown_at < :cutoff');
        $stmt->bindValue(':cutoff', $cutoff, SQLITE3_TEXT);
        $stmt->execute();
        header('Location: avisos.php?ok=history_old_cleared#historico');
        exit;
    }
    if ($action === 'save_auto_clean') {
        $enabled = !empty($_POST['auto_clean_enabled']) ? '1' : '0';
        $days = (int)($_POST['retention_days'] ?? 30);
        $allowed = [1,7,15,30,60,90,180,365,0];
        if (!in_array($days, $allowed, true)) $days = 30;
        set_setting('history_auto_clean_enabled', $enabled);
        set_setting('history_retention_days', (string)$days);
        if ($enabled === '1' && $days > 0) cleanup_message_history(true);
        header('Location: avisos.php?ok=history_settings_saved#historico');
        exit;
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['banner_settings'])) {
    $pos = (string)($_POST['banner_position'] ?? 'top');
    if (!in_array($pos, ['top','center','bottom'], true)) $pos = 'top';
    $dur = (int)($_POST['banner_duration'] ?? 12);
    if ($dur < 1) $dur = 12;
    if ($dur > 300) $dur = 300;
    set_setting('banner_position', $pos);
    set_setting('banner_duration', (string)$dur);
    header('Location: avisos.php?ok=banner_settings_saved#tarja');
    exit;
}

$editing = null;
if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    $stmt = $db->prepare('SELECT * FROM screen_messages WHERE id=:id');
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $res = $stmt->execute();
    $editing = $res ? $res->fetchArray(SQLITE3_ASSOC) : null;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $title = trim((string)($_POST['title'] ?? ''));
    $message = trim((string)($_POST['message'] ?? ''));
    $target_type = (string)($_POST['target_type'] ?? 'global');
    $target_value = trim((string)($_POST['target_value'] ?? ''));
    $position = (string)($_POST['position'] ?? 'top');
    $speed = (int)($_POST['speed'] ?? 18);
    $is_active = !empty($_POST['is_active']) ? 1 : 0;
    $start_at = dt_local_to_sql($_POST['start_at'] ?? '');
    $end_at = dt_local_to_sql($_POST['end_at'] ?? '');
    $repeat_minutes = (int)($_POST['repeat_minutes'] ?? 0);
    $priority = (string)($_POST['priority'] ?? 'normal');
    $color = trim((string)($_POST['color'] ?? '#ffffff'));

    $allowed_targets = ['global','username','password','android_id','code','client_key'];
    if (!in_array($target_type, $allowed_targets, true)) $target_type = 'global';
    if (!in_array($position, ['top','center','bottom'], true)) $position = 'top';
    if (!in_array($priority, ['normal','urgente'], true)) $priority = 'normal';
    if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) $color = '#ffffff';
    if ($speed < 5) $speed = 5;
    if ($speed > 60) $speed = 60;
    if ($repeat_minutes < 0) $repeat_minutes = 0;
    if ($repeat_minutes > 1440) $repeat_minutes = 1440;

    if ($message === '') {
        $erro = 'Digite a mensagem do aviso.';
    } elseif ($target_type !== 'global' && $target_value === '') {
        $erro = 'Para mensagem individual, informe o cliente/código/Android ID.';
    } elseif ($start_at !== '' && $end_at !== '' && strtotime($end_at) < strtotime($start_at)) {
        $erro = 'A data final não pode ser menor que a data inicial.';
    } else {
        if ($id > 0) {
            $stmt = $db->prepare('UPDATE screen_messages SET title=:title,message=:message,target_type=:target_type,target_value=:target_value,position=:position,speed=:speed,is_active=:is_active,start_at=:start_at,end_at=:end_at,repeat_minutes=:repeat_minutes,priority=:priority,color=:color,updated_at=CURRENT_TIMESTAMP WHERE id=:id');
            $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        } else {
            $stmt = $db->prepare('INSERT INTO screen_messages(title,message,target_type,target_value,position,speed,is_active,start_at,end_at,repeat_minutes,priority,color) VALUES(:title,:message,:target_type,:target_value,:position,:speed,:is_active,:start_at,:end_at,:repeat_minutes,:priority,:color)');
        }
        $stmt->bindValue(':title', $title, SQLITE3_TEXT);
        $stmt->bindValue(':message', $message, SQLITE3_TEXT);
        $stmt->bindValue(':target_type', $target_type, SQLITE3_TEXT);
        $stmt->bindValue(':target_value', $target_type === 'global' ? '' : $target_value, SQLITE3_TEXT);
        $stmt->bindValue(':position', $position, SQLITE3_TEXT);
        $stmt->bindValue(':speed', $speed, SQLITE3_INTEGER);
        $stmt->bindValue(':is_active', $is_active, SQLITE3_INTEGER);
        $stmt->bindValue(':start_at', $start_at, SQLITE3_TEXT);
        $stmt->bindValue(':end_at', $end_at, SQLITE3_TEXT);
        $stmt->bindValue(':repeat_minutes', $repeat_minutes, SQLITE3_INTEGER);
        $stmt->bindValue(':priority', $priority, SQLITE3_TEXT);
        $stmt->bindValue(':color', $color, SQLITE3_TEXT);
        $stmt->execute();
        header('Location: avisos.php?ok=saved');
        exit;
    }
}

$filter = (string)($_GET['filter'] ?? 'all');
$allowed_filters = ['all','active','inactive','scheduled','expired','urgent'];
if (!in_array($filter, $allowed_filters, true)) $filter = 'all';

$messages = [];
$res = $db->query('SELECT * FROM screen_messages ORDER BY id DESC');
while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
    [$statusText, $statusClass] = aviso_status_now($row);
    $include = true;
    if ($filter === 'active') $include = ($statusText === 'Ativo');
    if ($filter === 'inactive') $include = ((int)$row['is_active'] !== 1);
    if ($filter === 'scheduled') $include = ($statusText === 'Programado');
    if ($filter === 'expired') $include = ($statusText === 'Finalizado');
    if ($filter === 'urgent') $include = (($row['priority'] ?? 'normal') === 'urgente');
    if ($include) $messages[] = $row;
}

$autoCleanEnabled = (int)get_setting('history_auto_clean_enabled','0');
$retentionDays = (int)get_setting('history_retention_days','30');
$lastClean = get_setting('history_last_clean','');
$oldCutoff = $retentionDays > 0 ? date('Y-m-d H:i:s', strtotime('-'.$retentionDays.' days')) : '';
$oldCount = $retentionDays > 0 ? (int)$db->querySingle("SELECT COUNT(*) FROM screen_message_hits WHERE shown_at < '" . SQLite3::escapeString($oldCutoff) . "'") : 0;
$todayStart = date('Y-m-d 00:00:00');
$hitsTotal = (int)$db->querySingle('SELECT COUNT(*) FROM screen_message_hits');
$hitsToday = (int)$db->querySingle("SELECT COUNT(*) FROM screen_message_hits WHERE shown_at >= '" . SQLite3::escapeString($todayStart) . "'");

$hits = [];
$resHits = $db->query('SELECT h.*, m.title, m.message FROM screen_message_hits h LEFT JOIN screen_messages m ON m.id=h.message_id ORDER BY h.id DESC LIMIT 80');
while ($row = $resHits->fetchArray(SQLITE3_ASSOC)) $hits[] = $row;

$stats = [
    'total' => (int)$db->querySingle('SELECT COUNT(*) FROM screen_messages'),
    'active' => (int)$db->querySingle('SELECT COUNT(*) FROM screen_messages WHERE is_active=1'),
    'urgent' => (int)$db->querySingle("SELECT COUNT(*) FROM screen_messages WHERE priority='urgente'"),
    'hits' => $hitsTotal
];

$form = [
    'id' => $editing['id'] ?? 0,
    'title' => $editing['title'] ?? '',
    'message' => $editing['message'] ?? '',
    'target_type' => $editing['target_type'] ?? 'global',
    'target_value' => $editing['target_value'] ?? '',
    'position' => $editing['position'] ?? 'top',
    'speed' => $editing['speed'] ?? 18,
    'is_active' => isset($editing) ? (int)($editing['is_active'] ?? 1) : 1,
    'start_at' => dt_sql_to_input($editing['start_at'] ?? ''),
    'end_at' => dt_sql_to_input($editing['end_at'] ?? ''),
    'repeat_minutes' => $editing['repeat_minutes'] ?? 5,
    'priority' => $editing['priority'] ?? 'normal',
    'color' => $editing['color'] ?? '#ffffff'
];
$bannerPos = get_setting('banner_position','top');
if (!in_array($bannerPos, ['top','center','bottom'], true)) $bannerPos = 'top';
$bannerDur = (int)get_setting('banner_duration','12');
if ($bannerDur < 1) $bannerDur = 12;

include __DIR__.'/includes/header.php';
?>
<style>
.notice-grid{display:grid;grid-template-columns:1.1fr .9fr;gap:18px;align-items:start}
.mini-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:18px}
.mini-stat{background:linear-gradient(135deg,#101923,#172637);border:1px solid #26394e;border-radius:14px;padding:14px}
.mini-stat b{display:block;font-size:22px}
.toolbar{display:flex;gap:8px;flex-wrap:wrap;margin:10px 0 16px}
.pill{display:inline-block;padding:8px 12px;border-radius:999px;background:#111a25;border:1px solid #2c4056;color:#dce9ff;text-decoration:none}
.pill.on{background:#ff7a00;color:#111;border-color:#ff9d3d;font-weight:bold}
.quick-box{display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin:8px 0 14px}
.quick-btn{border:1px solid #334a63;background:#0e151e;color:#fff;border-radius:10px;padding:10px;cursor:pointer;text-align:left}
.quick-btn:hover{border-color:#ff7a00}
.preview-tv{background:radial-gradient(circle at 30% 20%,#27364a,#05070a 70%);border:1px solid #304057;border-radius:16px;min-height:190px;position:relative;overflow:hidden;margin-top:8px}
.preview-epg{position:absolute;left:18px;right:18px;bottom:18px;background:rgba(0,0,0,.72);border-left:4px solid #ff7a00;border-radius:12px;padding:12px}
.preview-text{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:bold;text-shadow:0 1px 4px #000}
.notice-actions{display:flex;gap:6px;flex-wrap:wrap}
.btn.small{padding:7px 10px;font-size:12px}.btn.orange{background:#ff7a00;color:#111}.warn{color:#ffb84d}.msg-row-urgent{box-shadow:inset 4px 0 0 #ff3b30}
.history-panel{display:grid;grid-template-columns:1fr 1fr;gap:14px}.history-actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:12px 0}
.danger-zone{border:1px solid #6b1b1b;background:rgba(120,20,20,.16);border-radius:14px;padding:14px}.clean-box{border:1px solid #2b4056;background:#0d141d;border-radius:14px;padding:14px}.check-cell{width:34px}
.history-stats{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin:10px 0 14px}.history-stat{background:#0e151e;border:1px solid #26394e;border-radius:12px;padding:12px}.history-stat b{font-size:20px;display:block}
@media(max-width:850px){.notice-grid,.mini-stats,.history-panel,.history-stats{grid-template-columns:1fr}.quick-box{grid-template-columns:1fr}}

.banner-config{border:1px solid rgba(255,138,0,.35);background:linear-gradient(135deg,rgba(255,138,0,.08),rgba(11,17,26,.95));border-radius:18px;padding:18px;margin-bottom:18px}
.banner-options{display:grid;grid-template-columns:1fr 1fr;gap:14px}
.banner-preview{height:190px;border-radius:16px;background:radial-gradient(circle at 30% 20%,#27364a,#05070a 70%);position:relative;border:1px solid #304057;overflow:hidden}
.banner-tarja{position:absolute;left:18px;right:18px;background:rgba(0,0,0,.84);border:2px solid #ff8a00;border-radius:10px;padding:10px 14px;box-shadow:0 0 18px rgba(255,138,0,.55);font-weight:900}
.banner-tarja:before{content:'⚠️ AVISO DO SISTEMA';display:block;color:#ff1744;font-size:13px;margin-bottom:4px}
.banner-tarja.top{top:14px}.banner-tarja.center{top:50%;transform:translateY(-50%)}.banner-tarja.bottom{bottom:14px}
.tab-title{display:flex;align-items:center;justify-content:space-between;gap:10px}
@media(max-width:900px){.banner-options,.notice-grid,.history-panel{grid-template-columns:1fr!important}.mini-stats,.history-stats{grid-template-columns:repeat(2,1fr)!important}}

</style>

<div class="mini-stats">
    <div class="mini-stat"><span class="muted">Total</span><b><?=h($stats['total'])?></b></div>
    <div class="mini-stat"><span class="muted">Ativos</span><b><?=h($stats['active'])?></b></div>
    <div class="mini-stat"><span class="muted">Urgentes</span><b><?=h($stats['urgent'])?></b></div>
    <div class="mini-stat"><span class="muted">Entregues</span><b><?=h($stats['hits'])?></b></div>
</div>


<div class="banner-config" id="tarja">
    <div class="tab-title">
        <div>
            <h2 style="margin:0">⚠️ Configuração da Tarja</h2>
            <p class="muted" style="margin:6px 0 0">Escolha onde a tarja independente aparece no APK e por quanto tempo fica visível.</p>
        </div>
        <span class="pill on"><?=strtoupper($bannerPos)?> • <?=$bannerDur?>s</span>
    </div>
    <form method="post" style="margin-top:14px">
        <input type="hidden" name="banner_settings" value="1">
        <div class="banner-options">
            <div>
                <label>Posição da tarja</label>
                <select name="banner_position" id="banner_position" onchange="updateBannerPreview()">
                    <option value="top" <?=$bannerPos==='top'?'selected':''?>>Topo da tela</option>
                    <option value="center" <?=$bannerPos==='center'?'selected':''?>>Centro da tela</option>
                    <option value="bottom" <?=$bannerPos==='bottom'?'selected':''?>>Rodapé da tela</option>
                </select>
                <label>Tempo visível</label>
                <select onchange="document.getElementById('banner_duration').value=this.value">
                    <?php foreach([5,10,12,15,20,30,45,60] as $sec): ?>
                    <option value="<?=$sec?>" <?=$bannerDur===$sec?'selected':''?>><?=$sec?> segundos</option>
                    <?php endforeach; ?>
                </select>
                <input id="banner_duration" type="number" min="1" max="300" name="banner_duration" value="<?=h($bannerDur)?>" placeholder="Personalizado em segundos">
                <p><button class="btn">Salvar Tarja</button></p>
            </div>
            <div>
                <label>Prévia da posição</label>
                <div class="banner-preview">
                    <div id="bannerPreviewBox" class="banner-tarja <?=$bannerPos?>">Mensagem enviada pelo painel</div>
                </div>
            </div>
        </div>
    </form>
</div>

<div class="notice-grid">
    <div class="card">
        <h3><?=((int)$form['id']>0) ? 'Editar aviso' : 'Central de avisos'?></h3>
        <p class="muted">Crie aviso global ou individual para aparecer no APK. Esta tela mantém compatibilidade com o APK atual.</p>
        <?php if($msg): ?><p class="ok"><?=h($msg)?></p><?php endif; ?>
        <?php if($erro): ?><p class="bad"><?=h($erro)?></p><?php endif; ?>

        <div class="quick-box">
            <button class="quick-btn" type="button" onclick="quickMsg('Manutenção','⚠️ MANUTENÇÃO PROGRAMADA HOJE ÀS 23:00', '#ffcc00','urgente')">⚠️ Manutenção</button>
            <button class="quick-btn" type="button" onclick="quickMsg('Cobrança','📢 REGULARIZE SEU ACESSO PARA EVITAR BLOQUEIO', '#ffffff','normal')">💰 Cobrança</button>
            <button class="quick-btn" type="button" onclick="quickMsg('Promoção','🔥 PROMOÇÃO DISPONÍVEL POR TEMPO LIMITADO', '#ff7a00','normal')">🔥 Promoção</button>
            <button class="quick-btn" type="button" onclick="quickMsg('Urgente','🚨 AVISO URGENTE: VERIFIQUE SEU ACESSO', '#ff3333','urgente')">🚨 Urgente</button>
        </div>

        <form method="post" id="noticeForm">
            <input type="hidden" name="id" value="<?=h($form['id'])?>">
            <label>Título interno</label>
            <input name="title" id="title" value="<?=h($form['title'])?>" placeholder="Ex: Manutenção, Cobrança, Promoção">

            <label>Mensagem que vai aparecer na tela</label>
            <input name="message" id="message" value="<?=h($form['message'])?>" oninput="updatePreview()" placeholder="Ex: ⚠️ Manutenção hoje às 23:00" required>

            <label>Enviar para</label>
            <select name="target_type" id="target_type" onchange="toggleTargetValue()" style="width:100%;padding:12px;margin:7px 0 14px;border-radius:9px;border:1px solid #38475c;background:#0e131b;color:#fff">
                <?php foreach(['global'=>'Todos os clientes','username'=>'Cliente por usuário','password'=>'Cliente por senha','android_id'=>'Cliente por Android ID / aparelho','code'=>'Cliente por código','client_key'=>'Cliente por chave enviada pelo APK'] as $k=>$v): ?>
                    <option value="<?=h($k)?>" <?=$form['target_type']===$k?'selected':''?>><?=h($v)?></option>
                <?php endforeach; ?>
            </select>

            <div id="target_box" style="display:none">
                <label>Identificação do cliente</label>
                <input name="target_value" value="<?=h($form['target_value'])?>" placeholder="Digite usuário, código, senha ou Android ID">
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
                <div><label>Iniciar em</label><input type="datetime-local" name="start_at" value="<?=h($form['start_at'])?>"></div>
                <div><label>Parar em</label><input type="datetime-local" name="end_at" value="<?=h($form['end_at'])?>"></div>
            </div>

            <label>Repetir no APK</label>
            <select name="repeat_minutes" style="width:100%;padding:12px;margin:7px 0 14px;border-radius:9px;border:1px solid #38475c;background:#0e131b;color:#fff">
                <?php foreach([0=>'Sempre que o APK consultar',1=>'A cada 1 minuto',5=>'A cada 5 minutos',10=>'A cada 10 minutos',15=>'A cada 15 minutos',30=>'A cada 30 minutos',60=>'A cada 1 hora'] as $k=>$v): ?>
                    <option value="<?=h($k)?>" <?=((int)$form['repeat_minutes']===(int)$k)?'selected':''?>><?=h($v)?></option>
                <?php endforeach; ?>
            </select>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
                <div><label>Cor da mensagem</label><input type="color" id="color" name="color" value="<?=h($form['color'])?>" oninput="updatePreview()" style="height:46px"></div>
                <div><label>Prioridade</label><select id="priority" name="priority" onchange="updatePreview()" style="width:100%;padding:12px;margin:7px 0 14px;border-radius:9px;border:1px solid #38475c;background:#0e131b;color:#fff"><option value="normal" <?=$form['priority']==='normal'?'selected':''?>>Normal</option><option value="urgente" <?=$form['priority']==='urgente'?'selected':''?>>Urgente</option></select></div>
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
                <div><label>Posição padrão da mensagem</label><select name="position" style="width:100%;padding:12px;margin:7px 0 14px;border-radius:9px;border:1px solid #38475c;background:#0e131b;color:#fff"><option value="top" <?=$form['position']==='top'?'selected':''?>>Topo</option><option value="center" <?=$form['position']==='center'?'selected':''?>>Centro</option><option value="bottom" <?=$form['position']==='bottom'?'selected':''?>>Rodapé</option></select></div>
                <div><label>Velocidade do letreiro</label><input type="number" name="speed" min="5" max="60" value="<?=h($form['speed'])?>"></div>
            </div>

            <label style="display:flex;gap:8px;align-items:center;margin:8px 0 18px"><input type="checkbox" name="is_active" value="1" <?=$form['is_active']?'checked':''?> style="width:auto;margin:0"> Ativo</label>
            <button class="btn" type="submit"><?=((int)$form['id']>0) ? 'Salvar edição' : 'Salvar aviso'?></button>
            <?php if((int)$form['id']>0): ?><a class="btn gray" href="avisos.php">Cancelar edição</a><?php endif; ?>
        </form>
    </div>

    <div class="card">
        <h3>Prévia em tempo real</h3>
        <p class="muted">Exemplo visual do aviso dentro da tela do aplicativo.</p>
        <div class="preview-tv">
            <div class="preview-epg">
                <div id="previewText" class="preview-text">Digite uma mensagem para visualizar</div>
                <div class="muted" style="margin-top:8px">Agora: Canal ao vivo<br>A seguir: Próximo programa</div>
            </div>
        </div>
        <p class="muted" style="margin-top:12px">Dica: use mensagem curta para aparecer melhor na TV.</p>
    </div>
</div>

<div class="card" style="margin-top:18px">
    <h3>Avisos cadastrados</h3>
    <div class="toolbar">
        <?php foreach(['all'=>'Todos','active'=>'Ativos','inactive'=>'Inativos','scheduled'=>'Programados','expired'=>'Finalizados','urgent'=>'Urgentes'] as $k=>$v): ?>
            <a class="pill <?=$filter===$k?'on':''?>" href="avisos.php?filter=<?=h($k)?>"><?=h($v)?></a>
        <?php endforeach; ?>
    </div>
    <table>
        <tr><th>ID</th><th>Mensagem</th><th>Destino</th><th>Programação</th><th>Repetição</th><th>Status</th><th>Ações</th></tr>
        <?php foreach($messages as $m): [$st,$cls]=aviso_status_now($m); ?>
            <tr class="<?=($m['priority'] ?? 'normal')==='urgente'?'msg-row-urgent':''?>">
                <td><?=h($m['id'])?></td>
                <td><strong><?=h($m['title'] ?: 'Sem título')?></strong><br><span style="color:<?=h($m['color'] ?? '#ffffff')?>"><?=h($m['message'])?></span><br><span class="muted">Prioridade: <?=h(($m['priority'] ?? 'normal') === 'urgente' ? 'Urgente' : 'Normal')?></span></td>
                <td><?=h(($m['target_type']==='global') ? 'Todos' : aviso_target_label($m['target_type']).': '.$m['target_value'])?></td>
                <td><span class="muted">Início: <?=h(($m['start_at'] ?? '') ?: 'agora')?><br>Fim: <?=h(($m['end_at'] ?? '') ?: 'sem fim')?></span></td>
                <td><?=((int)($m['repeat_minutes'] ?? 0) > 0) ? 'A cada '.h($m['repeat_minutes']).' min' : 'Sempre'?></td>
                <td><span class="<?=$cls?>"><?=h($st)?></span></td>
                <td><div class="notice-actions">
                    <a class="btn small orange" href="avisos.php?edit=<?=h($m['id'])?>">Editar</a>
                    <a class="btn small gray" href="avisos.php?duplicate=<?=h($m['id'])?>">Duplicar</a>
                    <a class="btn small gray" href="avisos.php?toggle=<?=h($m['id'])?>"><?=((int)$m['is_active']===1) ? 'Pausar' : 'Ativar'?></a>
                    <a class="btn small red" href="avisos.php?delete=<?=h($m['id'])?>" onclick="return confirm('Excluir este aviso?')">Excluir</a>
                </div></td>
            </tr>
        <?php endforeach; ?>
    </table>
    <?php if(!$messages): ?><p class="muted">Nenhum aviso encontrado neste filtro.</p><?php endif; ?>
</div>

<div class="card" id="historico" style="margin-top:18px">
    <h3>Histórico de avisos entregues</h3>
    <p class="muted">Controle completo dos avisos já entregues pelo APK. Apagar histórico não remove avisos ativos.</p>

    <div class="history-stats">
        <div class="history-stat"><span class="muted">Total</span><b><?=h($hitsTotal)?></b></div>
        <div class="history-stat"><span class="muted">Hoje</span><b><?=h($hitsToday)?></b></div>
        <div class="history-stat"><span class="muted">Antigos</span><b><?=h($oldCount)?></b></div>
        <div class="history-stat"><span class="muted">Limpeza</span><b><?=$autoCleanEnabled ? 'Ativa' : 'Off'?></b></div>
    </div>

    <div class="history-panel">
        <div class="clean-box">
            <h4>Limpeza automática</h4>
            <form method="post">
                <input type="hidden" name="history_action" value="save_auto_clean">
                <label style="display:flex;gap:8px;align-items:center;margin:8px 0 12px">
                    <input type="checkbox" name="auto_clean_enabled" value="1" <?=$autoCleanEnabled?'checked':''?> style="width:auto;margin:0"> Ativar limpeza automática
                </label>
                <label>Manter histórico por</label>
                <select name="retention_days" style="width:100%;padding:12px;margin:7px 0 14px;border-radius:9px;border:1px solid #38475c;background:#0e131b;color:#fff">
                    <?php foreach([1=>'1 dia',7=>'7 dias',15=>'15 dias',30=>'30 dias',60=>'60 dias',90=>'90 dias',180=>'180 dias',365=>'365 dias',0=>'Nunca apagar'] as $k=>$v): ?>
                        <option value="<?=h($k)?>" <?=((int)$retentionDays===(int)$k)?'selected':''?>><?=h($v)?></option>
                    <?php endforeach; ?>
                </select>
                <p class="muted">Última limpeza: <?=h($lastClean ?: 'ainda não executou')?></p>
                <p class="muted">Registros que seriam apagados agora: <?=h($oldCount)?></p>
                <button class="btn" type="submit">Salvar configuração</button>
            </form>
        </div>

        <div class="danger-zone">
            <h4>Apagar histórico</h4>
            <form method="post" class="history-actions" onsubmit="return confirm('Apagar histórico antigo?')">
                <input type="hidden" name="history_action" value="clear_old">
                <select name="old_days" style="padding:10px;border-radius:9px;border:1px solid #38475c;background:#0e131b;color:#fff">
                    <option value="7">mais de 7 dias</option>
                    <option value="15">mais de 15 dias</option>
                    <option value="30" selected>mais de 30 dias</option>
                    <option value="60">mais de 60 dias</option>
                    <option value="90">mais de 90 dias</option>
                    <option value="180">mais de 180 dias</option>
                    <option value="365">mais de 365 dias</option>
                </select>
                <button class="btn gray" type="submit">Apagar antigo</button>
            </form>
            <form method="post" onsubmit="return confirm('ATENÇÃO: limpar TODO o histórico? Esta ação não apaga os avisos ativos.')">
                <input type="hidden" name="history_action" value="clear_all">
                <button class="btn red" type="submit">Limpar histórico completo</button>
            </form>
        </div>
    </div>

    <form method="post" onsubmit="return confirm('Apagar os registros selecionados?')">
        <input type="hidden" name="history_action" value="delete_selected">
        <div class="history-actions">
            <button class="btn red" type="submit">Apagar selecionados</button>
            <button class="btn gray" type="button" onclick="toggleAllHits(this)">Selecionar todos</button>
        </div>
        <table>
            <tr><th class="check-cell"></th><th>Data</th><th>Aviso</th><th>Cliente</th><th>IP</th><th>Ação</th></tr>
            <?php foreach($hits as $hrow): ?>
                <tr>
                    <td><input type="checkbox" name="hit_ids[]" value="<?=h($hrow['id'])?>" style="width:auto"></td>
                    <td><?=h($hrow['shown_at'])?></td>
                    <td><strong><?=h($hrow['title'] ?: 'Sem título')?></strong><br><span class="muted"><?=h($hrow['message'])?></span></td>
                    <td><span class="muted">Usuário: <?=h($hrow['username'] ?: '-')?><br>Android ID: <?=h($hrow['android_id'] ?: '-')?><br>Código: <?=h($hrow['code'] ?: '-')?><br>Chave: <?=h($hrow['client_key'] ?: '-')?></span></td>
                    <td><?=h($hrow['ip'])?></td>
                    <td><a class="btn small red" href="avisos.php?delete_hit=<?=h($hrow['id'])?>" onclick="return confirm('Apagar este registro do histórico?')">Excluir</a></td>
                </tr>
            <?php endforeach; ?>
        </table>
    </form>
    <?php if(!$hits): ?><p class="muted">Nenhum aviso entregue ainda.</p><?php endif; ?>
</div>
<script>
function toggleAllHits(btn){
    var boxes = document.querySelectorAll('input[name="hit_ids[]"]');
    var allChecked = true;
    boxes.forEach(function(b){ if(!b.checked) allChecked = false; });
    boxes.forEach(function(b){ b.checked = !allChecked; });
    btn.textContent = allChecked ? 'Selecionar todos' : 'Desmarcar todos';
}


<script>
function updateBannerPreview(){
    var p=document.getElementById('banner_position');
    var b=document.getElementById('bannerPreviewBox');
    if(!p||!b)return;
    b.className='banner-tarja '+p.value;
}
</script>

<?php include __DIR__.'/includes/footer.php'; ?>
