<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$page_title = "Dashboard";

/* ══════════════════════════════════════
   BANCO DE DADOS
══════════════════════════════════════ */
$db_file = __DIR__ . "/ibo_panel.db";
$conn    = new PDO("sqlite:$db_file");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Totais
// Detecta nomes reais das tabelas
$tables = $conn->query("SELECT name FROM sqlite_master WHERE type='table'")->fetchAll(PDO::FETCH_COLUMN);

// Tabela de MACs — pode ser playlist, mac, macs, mac_addresses
$mac_table = 'playlist';
foreach (['playlist','mac','macs','mac_addresses','playlists'] as $t) {
    if (in_array($t, $tables)) { $mac_table = $t; break; }
}

// Tabela de chatbots — pode ser chatbot, chatbots, bots
$bot_table = 'chatbot';
foreach (['chatbot','chatbots','bots','bot'] as $t) {
    if (in_array($t, $tables)) { $bot_table = $t; break; }
}

// Tabela de DNS — pode ser dns, dns_list
$dns_table = 'dns';
foreach (['dns','dns_list','dns_records'] as $t) {
    if (in_array($t, $tables)) { $dns_table = $t; break; }
}

$total_dns   = $conn->query("SELECT COUNT(*) FROM $dns_table")->fetchColumn();
$total_mac   = $conn->query("SELECT COUNT(*) FROM $mac_table")->fetchColumn();

// Chatbot pode não existir
$total_bots  = in_array($bot_table, $tables) ? $conn->query("SELECT COUNT(*) FROM $bot_table")->fetchColumn() : 0;
$bots_ativos = in_array($bot_table, $tables) ? $conn->query("SELECT COUNT(*) FROM $bot_table WHERE bot_status=1")->fetchColumn() : 0;

// Últimos DNS
$last_dns = $conn->query("SELECT id, title, url FROM $dns_table ORDER BY id DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);

// Últimos MACs — descobre colunas disponíveis
$mac_cols = $conn->query("PRAGMA table_info($mac_table)")->fetchAll(PDO::FETCH_ASSOC);
$mac_col_names = array_column($mac_cols, 'name');
$mac_user_col = in_array('username', $mac_col_names) ? 'username' : (in_array('user', $mac_col_names) ? 'user' : 'id');
$mac_mac_col  = in_array('mac_address', $mac_col_names) ? 'mac_address' : (in_array('mac', $mac_col_names) ? 'mac' : 'id');
$mac_dns_col  = in_array('dns_id', $mac_col_names) ? 'dns_id' : 'id';

$last_mac = $conn->query("SELECT id, $mac_dns_col as dns_id, $mac_mac_col as mac_address, $mac_user_col as username FROM $mac_table ORDER BY id DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);

// Últimos Chatbots
$last_bots = in_array($bot_table, $tables)
    ? $conn->query("SELECT id, bot_name, bot_status FROM $bot_table ORDER BY id DESC LIMIT 4")->fetchAll(PDO::FETCH_ASSOC)
    : [];

// Manutenção
$maintenance = ['btnCanais'=>false,'btnFilmes'=>false,'btnSeries'=>false,'message'=>''];
$mFile = __DIR__ . '/maintenance.json';
if (file_exists($mFile)) $maintenance = json_decode(file_get_contents($mFile), true);
$maint_count = (int)($maintenance['btnCanais']??0) + (int)($maintenance['btnFilmes']??0) + (int)($maintenance['btnSeries']??0);

// Alerta vencimento
$alerta = ['alerta_vencimento_ativo'=>false];
$aFile = __DIR__ . '/alerta_status.json';
if (file_exists($aFile)) $alerta = json_decode(file_get_contents($aFile), true);
$alerta_ativo = (bool)($alerta['alerta_vencimento_ativo'] ?? false);

// QR Code
$qr_url = '';
$qFile = __DIR__ . '/api/qrcode.json';
if (file_exists($qFile)) {
    $qdata  = json_decode(file_get_contents($qFile), true);
    $qr_url = $qdata['qrcode'] ?? '';
}
$qr_img = $qr_url ? "https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=" . urlencode($qr_url) . "&bgcolor=ffffff&color=000000&margin=6" : '';

/* ══════════════════════════════════════
   HELPERS
══════════════════════════════════════ */
function truncUrl($url, $max = 38) {
    return strlen($url) > $max ? substr($url, 0, $max) . '…' : $url;
}

$page_content = '
<style>
/* ═══════════════════════════
   PAGE HEADER
═══════════════════════════ */
.mac-page-header {
    background: linear-gradient(135deg, #0d1117 0%, #1a2744 50%, #0d1117 100%);
    border: 1px solid rgba(99,179,237,0.12);
    border-radius: 16px;
    padding: 28px 32px;
    margin-bottom: 28px;
    margin-top: 24px;
    position: relative;
    overflow: hidden;
}
.mac-page-header::before {
    content:""; position:absolute; top:-60px; right:-60px;
    width:200px; height:200px;
    background:radial-gradient(circle,rgba(99,179,237,0.1) 0%,transparent 70%);
    pointer-events:none;
}
.mac-page-header::after {
    content:""; position:absolute; bottom:-40px; left:30%;
    width:150px; height:150px;
    background:radial-gradient(circle,rgba(139,92,246,0.07) 0%,transparent 70%);
    pointer-events:none;
}
.mac-page-header h1 {
    color:#e2e8f0; font-size:22px; font-weight:700;
    margin:0 0 4px; display:flex; align-items:center; gap:12px;
}
.mac-page-header h1 .icon-wrap {
    width:40px; height:40px;
    background:rgba(99,179,237,0.12); border:1px solid rgba(99,179,237,0.22);
    border-radius:10px; display:flex; align-items:center; justify-content:center;
    font-size:18px; color:#63b3ed; flex-shrink:0;
}
.mac-page-header p { color:rgba(148,163,184,0.7); font-size:13px; margin:0; }
.dash-time { color:rgba(148,163,184,0.4); font-size:12px; }

/* ═══════════════════════════
   STAT CARDS
═══════════════════════════ */
.stat-card {
    background:#161b22;
    border:1px solid rgba(99,179,237,0.08);
    border-radius:16px;
    padding:22px 24px;
    box-shadow:0 4px 24px rgba(0,0,0,0.3);
    display:flex; align-items:center; gap:18px;
    transition:transform 0.2s ease, border-color 0.2s ease;
    position:relative; overflow:hidden;
}

.stat-card:hover { transform:translateY(-3px); border-color:rgba(99,179,237,0.15); }
.stat-icon {
    width:52px; height:52px; border-radius:14px;
    display:flex; align-items:center; justify-content:center;
    font-size:22px; flex-shrink:0;
    background:var(--icon-bg); border:1px solid var(--icon-border);
    color:var(--icon-color);
}
.stat-info { flex:1; min-width:0; }
.stat-value {
    color:#e2e8f0; font-size:30px; font-weight:800;
    line-height:1; margin-bottom:4px;
}
.stat-label { color:rgba(148,163,184,0.55); font-size:12px; font-weight:600; text-transform:uppercase; letter-spacing:0.06em; }
.stat-badge {
    padding:3px 10px; border-radius:50px; font-size:11px; font-weight:700;
    margin-top:6px; display:inline-block;
}

/* ═══════════════════════════
   PANEL
═══════════════════════════ */
.dash-panel {
    background:#161b22;
    border:1px solid rgba(99,179,237,0.08);
    border-radius:16px;
    overflow:hidden;
    box-shadow:0 4px 24px rgba(0,0,0,0.3);
    height:100%;
}
.dash-panel-header {
    background:rgba(255,255,255,0.02);
    border-bottom:1px solid rgba(255,255,255,0.06);
    padding:16px 20px;
    display:flex; align-items:center; justify-content:space-between;
}
.dash-panel-title {
    display:flex; align-items:center; gap:10px;
    color:#e2e8f0; font-size:13px; font-weight:700;
}
.dash-panel-title .ph-icon {
    width:30px; height:30px; border-radius:8px;
    display:flex; align-items:center; justify-content:center;
    font-size:13px; flex-shrink:0;
}
.dash-panel-link {
    color:rgba(99,179,237,0.6); font-size:11px; font-weight:600;
    text-decoration:none; transition:color 0.2s ease;
}
.dash-panel-link:hover { color:#63b3ed; }
.dash-panel-body { padding:0; }

/* Mini list */
.mini-list { list-style:none; padding:0; margin:0; }
.mini-list li {
    display:flex; align-items:center; gap:12px;
    padding:11px 20px;
    border-bottom:1px solid rgba(255,255,255,0.04);
    transition:background 0.15s ease;
}
.mini-list li:last-child { border-bottom:none; }
.mini-list li:hover { background:rgba(255,255,255,0.02); }
.mini-id {
    background:rgba(99,179,237,0.08); border:1px solid rgba(99,179,237,0.12);
    border-radius:5px; padding:2px 7px;
    font-size:11px; font-weight:700; color:#63b3ed;
    flex-shrink:0;
}
.mini-name { color:#e2e8f0; font-size:13px; font-weight:600; flex:1; min-width:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.mini-sub  { color:rgba(148,163,184,0.4); font-size:11px; font-family:monospace; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:160px; }
.mini-mac  { color:#34d399; font-size:11px; font-family:monospace; }

/* Bot cards mini */
.bot-mini-grid { display:grid; grid-template-columns:1fr 1fr; gap:10px; padding:16px; }
.bot-mini-card {
    background:rgba(255,255,255,0.02);
    border:1px solid rgba(255,255,255,0.06);
    border-radius:10px; padding:12px 14px;
    display:flex; align-items:center; gap:10px;
    transition:all 0.2s ease;
}
.bot-mini-card:hover { background:rgba(139,92,246,0.05); border-color:rgba(139,92,246,0.15); }
.bot-mini-icon {
    width:32px; height:32px; border-radius:8px;
    background:rgba(139,92,246,0.12); border:1px solid rgba(139,92,246,0.2);
    display:flex; align-items:center; justify-content:center;
    font-size:14px; color:#a78bfa; flex-shrink:0;
}
.bot-mini-name { color:#e2e8f0; font-size:12px; font-weight:600; flex:1; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.bot-status-dot {
    width:7px; height:7px; border-radius:50%; flex-shrink:0;
}
.dot-on  { background:#34d399; box-shadow:0 0 5px rgba(52,211,153,0.6); }
.dot-off { background:rgba(148,163,184,0.25); }

/* Status cards (manutenção + alerta) */
.status-row { display:grid; grid-template-columns:1fr 1fr; gap:12px; padding:16px; }
.status-tile {
    background:rgba(255,255,255,0.02);
    border:1px solid rgba(255,255,255,0.06);
    border-radius:10px; padding:14px 16px;
    display:flex; flex-direction:column; gap:6px;
}
.status-tile-label { color:rgba(148,163,184,0.5); font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:0.07em; }
.status-tile-value { color:#e2e8f0; font-size:13px; font-weight:700; display:flex; align-items:center; gap:6px; }

/* QR mini */
.qr-mini-wrap {
    padding:20px; display:flex; flex-direction:column; align-items:center; gap:14px;
}
.qr-mini-img {
    background:#fff; border-radius:10px; padding:8px;
    box-shadow:0 4px 16px rgba(0,0,0,0.4);
}
.qr-mini-img img { display:block; width:110px; height:110px; border-radius:4px; }
.qr-mini-url {
    background:rgba(52,211,153,0.06); border:1px solid rgba(52,211,153,0.12);
    border-radius:8px; padding:8px 12px; width:100%;
    font-family:monospace; font-size:11px; color:#34d399;
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
    text-align:center;
}
.qr-empty { color:rgba(148,163,184,0.25); font-size:12px; padding:30px 20px; text-align:center; }
.qr-empty i { font-size:36px; display:block; margin-bottom:10px; }
</style>

<!-- PAGE HEADER -->
<div class="mac-page-header d-flex align-items-center justify-content-between flex-wrap gap-3">
    <div>
        <h1>
            <span class="icon-wrap"><i class="fa-solid fa-chart-line"></i></span>
            Dashboard
        </h1>
        <p>Visão geral do sistema — dados em tempo real.</p>
    </div>
    <span class="dash-time"><i class="fa-regular fa-clock me-1"></i>' . date('d/m/Y H:i') . '</span>
</div>

<!-- STAT CARDS -->
<div class="row g-3 mb-4">

    <!-- DNS -->
    <div class="col-6 col-lg-3">
        <div class="stat-card" style="--card-accent:linear-gradient(90deg,#38bdf8,#63b3ed);--icon-bg:rgba(56,189,248,0.1);--icon-border:rgba(56,189,248,0.2);--icon-color:#38bdf8;">
            <div class="stat-icon"><i class="fa-solid fa-globe"></i></div>
            <div class="stat-info">
                <div class="stat-value">' . $total_dns . '</div>
                <div class="stat-label">DNS</div>
                <span class="stat-badge" style="background:rgba(56,189,248,0.1);border:1px solid rgba(56,189,248,0.2);color:#38bdf8;">Registrados</span>
            </div>
        </div>
    </div>

    <!-- Usuários MAC -->
    <div class="col-6 col-lg-3">
        <div class="stat-card" style="--card-accent:linear-gradient(90deg,#34d399,#059669);--icon-bg:rgba(52,211,153,0.1);--icon-border:rgba(52,211,153,0.2);--icon-color:#34d399;">
            <div class="stat-icon"><i class="fa-solid fa-users"></i></div>
            <div class="stat-info">
                <div class="stat-value">' . $total_mac . '</div>
                <div class="stat-label">Usuários</div>
                <span class="stat-badge" style="background:rgba(52,211,153,0.1);border:1px solid rgba(52,211,153,0.2);color:#34d399;">Ativos</span>
            </div>
        </div>
    </div>

    <!-- Chatbots -->
    <div class="col-6 col-lg-3">
        <div class="stat-card" style="--card-accent:linear-gradient(90deg,#a78bfa,#6d28d9);--icon-bg:rgba(167,139,250,0.1);--icon-border:rgba(167,139,250,0.2);--icon-color:#a78bfa;">
            <div class="stat-icon"><i class="fa-solid fa-robot"></i></div>
            <div class="stat-info">
                <div class="stat-value">' . $total_bots . '</div>
                <div class="stat-label">Chatbots</div>
                <span class="stat-badge" style="background:rgba(52,211,153,0.1);border:1px solid rgba(52,211,153,0.2);color:#34d399;">' . $bots_ativos . ' ativos</span>
            </div>
        </div>
    </div>

    <!-- Manutenção -->
    <div class="col-6 col-lg-3">
        <div class="stat-card" style="--card-accent:linear-gradient(90deg,' . ($maint_count > 0 ? '#f87171,#b91c1c' : '#34d399,#059669') . ');--icon-bg:rgba(' . ($maint_count > 0 ? '248,113,113' : '52,211,153') . ',0.1);--icon-border:rgba(' . ($maint_count > 0 ? '248,113,113' : '52,211,153') . ',0.2);--icon-color:' . ($maint_count > 0 ? '#f87171' : '#34d399') . ';">
            <div class="stat-icon"><i class="fa-solid fa-screwdriver-wrench"></i></div>
            <div class="stat-info">
                <div class="stat-value">' . $maint_count . '</div>
                <div class="stat-label">Manutenção</div>
                <span class="stat-badge" style="background:rgba(' . ($maint_count > 0 ? '248,113,113' : '52,211,153') . ',0.1);border:1px solid rgba(' . ($maint_count > 0 ? '248,113,113' : '52,211,153') . ',0.2);color:' . ($maint_count > 0 ? '#f87171' : '#34d399') . ';">' . ($maint_count > 0 ? $maint_count . ' bloqueado(s)' : 'Tudo normal') . '</span>
            </div>
        </div>
    </div>

</div>

<!-- ROW 2: DNS + MACs recentes -->
<div class="row g-3 mb-4">

    <!-- Últimos DNS -->
    <div class="col-lg-6">
        <div class="dash-panel">
            <div class="dash-panel-header">
                <div class="dash-panel-title">
                    <div class="ph-icon" style="background:rgba(56,189,248,0.1);border:1px solid rgba(56,189,248,0.2);color:#38bdf8;">
                        <i class="fa-solid fa-globe"></i>
                    </div>
                    DNS Recentes
                </div>
                <a href="dns.php" class="dash-panel-link">Ver todos <i class="fa-solid fa-arrow-right ms-1"></i></a>
            </div>
            <div class="dash-panel-body">
                <ul class="mini-list">';

foreach ($last_dns as $d) {
    $page_content .= '
                    <li>
                        <span class="mini-id">#' . $d['id'] . '</span>
                        <span class="mini-name">' . htmlspecialchars($d['title']) . '</span>
                        <span class="mini-sub">' . truncUrl($d['url']) . '</span>
                    </li>';
}

$page_content .= '
                </ul>
            </div>
        </div>
    </div>

    <!-- Últimos MACs -->
    <div class="col-lg-6">
        <div class="dash-panel">
            <div class="dash-panel-header">
                <div class="dash-panel-title">
                    <div class="ph-icon" style="background:rgba(52,211,153,0.1);border:1px solid rgba(52,211,153,0.2);color:#34d399;">
                        <i class="fa-solid fa-users"></i>
                    </div>
                    Usuários Recentes
                </div>
                <a href="mac.php" class="dash-panel-link">Ver todos <i class="fa-solid fa-arrow-right ms-1"></i></a>
            </div>
            <div class="dash-panel-body">
                <ul class="mini-list">';

foreach ($last_mac as $m) {
    $page_content .= '
                    <li>
                        <span class="mini-id">#' . $m['id'] . '</span>
                        <span class="mini-name">' . htmlspecialchars($m['username']) . '</span>
                        <span class="mini-mac">' . htmlspecialchars($m['mac_address']) . '</span>
                    </li>';
}

$page_content .= '
                </ul>
            </div>
        </div>
    </div>

</div>

<!-- ROW 3: Chatbots + Status + QR -->
<div class="row g-3">

    <!-- Chatbots recentes -->
    <div class="col-lg-4">
        <div class="dash-panel">
            <div class="dash-panel-header">
                <div class="dash-panel-title">
                    <div class="ph-icon" style="background:rgba(167,139,250,0.1);border:1px solid rgba(167,139,250,0.2);color:#a78bfa;">
                        <i class="fa-solid fa-robot"></i>
                    </div>
                    Chatbots
                </div>
                <a href="teste.php" class="dash-panel-link">Ver todos <i class="fa-solid fa-arrow-right ms-1"></i></a>
            </div>
            <div class="dash-panel-body">
                <div class="bot-mini-grid">';

foreach ($last_bots as $b) {
    $page_content .= '
                    <div class="bot-mini-card">
                        <div class="bot-mini-icon"><i class="fa-solid fa-robot"></i></div>
                        <span class="bot-mini-name">' . htmlspecialchars($b['bot_name']) . '</span>
                        <span class="bot-status-dot ' . ($b['bot_status'] ? 'dot-on' : 'dot-off') . '"></span>
                    </div>';
}

$page_content .= '
                </div>
            </div>
        </div>
    </div>

    <!-- Status do sistema -->
    <div class="col-lg-4">
        <div class="dash-panel">
            <div class="dash-panel-header">
                <div class="dash-panel-title">
                    <div class="ph-icon" style="background:rgba(251,191,36,0.1);border:1px solid rgba(251,191,36,0.2);color:#fbbf24;">
                        <i class="fa-solid fa-circle-info"></i>
                    </div>
                    Status do Sistema
                </div>
            </div>
            <div class="dash-panel-body">
                <div class="status-row">
                    <div class="status-tile">
                        <span class="status-tile-label">Canais</span>
                        <span class="status-tile-value">
                            <i class="fa-solid fa-circle" style="font-size:8px;color:' . ($maintenance['btnCanais'] ? '#f87171' : '#34d399') . ';"></i>
                            ' . ($maintenance['btnCanais'] ? 'Bloqueado' : 'Normal') . '
                        </span>
                    </div>
                    <div class="status-tile">
                        <span class="status-tile-label">Filmes</span>
                        <span class="status-tile-value">
                            <i class="fa-solid fa-circle" style="font-size:8px;color:' . ($maintenance['btnFilmes'] ? '#f87171' : '#34d399') . ';"></i>
                            ' . ($maintenance['btnFilmes'] ? 'Bloqueado' : 'Normal') . '
                        </span>
                    </div>
                    <div class="status-tile">
                        <span class="status-tile-label">Séries</span>
                        <span class="status-tile-value">
                            <i class="fa-solid fa-circle" style="font-size:8px;color:' . ($maintenance['btnSeries'] ? '#f87171' : '#34d399') . ';"></i>
                            ' . ($maintenance['btnSeries'] ? 'Bloqueado' : 'Normal') . '
                        </span>
                    </div>
                    <div class="status-tile">
                        <span class="status-tile-label">Alerta Venc.</span>
                        <span class="status-tile-value">
                            <i class="fa-solid fa-circle" style="font-size:8px;color:' . ($alerta_ativo ? '#34d399' : '#f87171') . ';"></i>
                            ' . ($alerta_ativo ? 'Ativo' : 'Inativo') . '
                        </span>
                    </div>
                    <div class="status-tile" style="grid-column:1/-1;">
                        <span class="status-tile-label">Mensagem de Manutenção</span>
                        <span class="status-tile-value" style="font-size:12px;font-weight:400;color:rgba(148,163,184,0.6);">'
                            . (empty($maintenance['message']) ? '—' : htmlspecialchars(mb_substr($maintenance['message'], 0, 55)) . (mb_strlen($maintenance['message']) > 55 ? '…' : ''))
                        . '</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- QR Code -->
    <div class="col-lg-4">
        <div class="dash-panel">
            <div class="dash-panel-header">
                <div class="dash-panel-title">
                    <div class="ph-icon" style="background:rgba(52,211,153,0.1);border:1px solid rgba(52,211,153,0.2);color:#34d399;">
                        <i class="fa-solid fa-qrcode"></i>
                    </div>
                    QR Code Atual
                </div>
                <a href="qrcode.php" class="dash-panel-link">Editar <i class="fa-solid fa-arrow-right ms-1"></i></a>
            </div>
            <div class="dash-panel-body">
                ' . ($qr_img ? '
                <div class="qr-mini-wrap">
                    <div class="qr-mini-img">
                        <img src="' . $qr_img . '" alt="QR Code">
                    </div>
                    <div class="qr-mini-url">' . htmlspecialchars($qr_url) . '</div>
                </div>' : '
                <div class="qr-empty">
                    <i class="fa-solid fa-qrcode"></i>
                    Nenhum QR Code configurado
                </div>') . '
            </div>
        </div>
    </div>

</div>
';

include 'includes/layout.php';
?>