<?php
/**
 * dashboard.php - Sistema TITAN v12.5 ULTRA (DETAILED PERFORMANCE MOD)
 * Atualização: Fevereiro de 2026
 */

ob_start(); 
error_reporting(E_ALL & ~E_NOTICE);
ini_set("display_errors", 0);
ini_set("log_errors", 1);

header("X-Frame-Options: SAMEORIGIN");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");
header("Cache-Control: no-cache, no-store, must-revalidate");

if (session_status() === PHP_SESSION_NONE) { session_start(); }

$basePath = __DIR__;
if (file_exists($basePath . "/includes/header.php")) { include_once $basePath . "/includes/header.php"; }

// Mock DB prevent crash
if (!isset($db) || !is_object($db)) {
    $db = new class { public function select($t, $c, $w = '', $o = '', $p = []) { return []; } };
}

function fetchSecure($db, $table, $columns = "*", $where = "1") {
    try {
        if (!method_exists($db, 'select')) return [];
        $data = $db->select($table, $columns, $where);
        return (is_array($data)) ? $data : [];
    } catch (Throwable $e) { 
        error_log("TITAN_FATAL_ERROR: " . $e->getMessage());
        return []; 
    }
}

$raw_users   = fetchSecure($db, "playlist", "*"); 
$dns_entries = fetchSecure($db, "dns", "id, title");
$themes      = fetchSecure($db, "themes", "theme_id");

$total_users = count($raw_users);
$dns_map_counts = [];
$vencidos_count = 0; 
$ativos_count = 0;
$agora = time();

foreach ($raw_users as $user) {
    $d_id = $user['dns_id'] ?? 0;
    $dns_map_counts[$d_id] = ($dns_map_counts[$d_id] ?? 0) + 1;
    if (!empty($user['exp_date'])) {
        $exp = is_numeric($user['exp_date']) ? $user['exp_date'] : strtotime($user['exp_date']);
        if ($exp < $agora) { 
            $vencidos_count++; 
        } else {
            $ativos_count++;
        }
    } else {
        $ativos_count++;
    }
}

$chart_labels = []; $chart_data = [];
foreach ($dns_entries as $dns) {
    $chart_labels[] = htmlspecialchars($dns['title'] ?? "DNS #".$dns['id']);
    $chart_data[]   = (int)($dns_map_counts[$dns['id']] ?? 0);
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>SIS TEMA | Dashboard Detailed</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    
    <style>
        :root {
            --primary: #6366f1;
            --primary-glow: rgba(99, 102, 241, 0.3);
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #f43f5e;
            --info: #0ea5e9;
            --bg-body: #f8fafc;
            --card-bg: #ffffff;
            --card-border: #f1f5f9;
            --text-main: #1e293b;
            --text-dim: #64748b;
        }

        * { 
            box-sizing: border-box; 
            outline: 0 !important; 
            -webkit-tap-highlight-color: transparent;
            -webkit-font-smoothing: antialiased;
        }

        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background-color: var(--bg-body);
            background-image: 
                radial-gradient(at 0% 0%, rgba(99, 102, 241, 0.05) 0px, transparent 50%),
                radial-gradient(at 100% 100%, rgba(16, 185, 129, 0.05) 0px, transparent 50%);
            background-attachment: fixed;
            color: var(--text-main);
            margin: 0; padding: 0;
            min-height: 100vh;
            overflow-x: hidden;
            transform: translate3d(0,0,0);
        }

        .titan-container {
            padding: clamp(15px, 4vw, 30px);
            max-width: 1400px;
            margin: 0 auto;
            animation: fadeIn 0.5s ease-out;
        }

        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }

        /* KPI UNIT DETAILED */
        .kpi-wrapper {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .kpi-unit {
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            padding: 20px;
            border-radius: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02);
            transition: all 0.2s ease;
            text-decoration: none !important;
        }

        .kpi-unit:hover {
            transform: translateY(-3px);
            border-color: var(--primary);
            box-shadow: 0 12px 20px -5px rgba(0,0,0,0.05);
        }

        .kpi-content { display: flex; align-items: center; }

        .icon-shield {
            width: 56px; height: 56px;
            background: #f8fafc;
            color: var(--primary);
            border-radius: 16px;
            display: flex; align-items: center; justify-content: center;
            font-size: 1.5rem;
            margin-right: 15px;
            transition: 0.3s;
        }

        .kpi-val h3 { margin: 0; font-size: 1.6rem; font-weight: 800; color: var(--text-main); line-height: 1.2; }
        .kpi-val p { margin: 0; font-size: 0.8rem; color: var(--text-dim); font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }

        .kpi-trend { font-size: 0.7rem; font-weight: 700; padding: 4px 8px; border-radius: 6px; background: #f1f5f9; }

        /* MAIN GRID */
        .main-grid { display: grid; gap: 25px; grid-template-columns: 1fr; }
        @media (min-width: 1024px) { .main-grid { grid-template-columns: 1.8fr 1.2fr; } }

        .deck-panel {
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 24px;
            overflow: hidden;
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02);
        }

        .deck-header {
            padding: 20px 25px;
            background: #fff;
            border-bottom: 1px solid var(--card-border);
            display: flex; justify-content: space-between; align-items: center;
        }

        .deck-header span { font-weight: 800; font-size: 0.85rem; color: var(--text-main); display: flex; align-items: center; gap: 10px; }

        .chart-box { padding: 25px; height: 380px; }

        /* TERMINAL / LOGS */
        .terminal-deck {
            background: #0f172a;
            border-radius: 15px;
            padding: 18px;
            font-family: 'Consolas', monospace;
            font-size: 0.8rem;
            color: #cbd5e1;
            min-height: 160px;
            line-height: 1.6;
            border: 1px solid rgba(255,255,255,0.05);
            overflow-y: auto;
        }

        /* BOTÕES MANTIDOS */
        .btn-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 20px; }

        .btn-titan {
            padding: 16px;
            border-radius: 14px;
            font-weight: 700;
            font-size: 0.85rem;
            cursor: pointer;
            display: flex; align-items: center; justify-content: center; gap: 10px;
            transition: all 0.2s;
            color: white; border: 0;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .btn-titan:active { transform: scale(0.98); }
        .btn-primary { background: var(--primary); box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3); }
        .btn-wa { background: #128c7e; box-shadow: 0 4px 12px rgba(18, 140, 126, 0.3); }
        .btn-telegram { background: #229ED9; grid-column: span 2; box-shadow: 0 4px 12px rgba(34, 158, 217, 0.3); }

        .status-badge {
            padding: 8px 16px;
            background: #fff;
            border: 1px solid var(--card-border);
            color: var(--success);
            border-radius: 50px;
            font-size: 0.7rem; font-weight: 800;
            display: flex; align-items: center; gap: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.02);
        }

        .pulsar { 
            width: 8px; height: 8px; background: var(--success); 
            border-radius: 50%; animation: pulse 2s infinite; 
        }
        @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4); } 70% { box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); } 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); } }
    </style>
</head>
<body>

<div class="titan-container">
    <header style="margin-bottom: 35px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 20px;">
        <div>
            <h1 style="margin:0; font-size: 2rem; font-weight: 900; color: var(--text-main); letter-spacing: -1.5px;">TITAN<span style="color:var(--primary)"> DETAILED</span></h1>
            <p style="margin:0; color:var(--text-dim); font-size: 0.85rem; font-weight: 600;">Monitoramento de Infraestrutura v12.5</p>
        </div>
        <div class="status-badge"><div class="pulsar"></div> SISTEMA ONLINE</div>
    </header>

    <section class="kpi-wrapper">
        <a href="chatbot.php" class="kpi-unit">
            <div class="kpi-content">
                <div class="icon-shield"><i class="fas fa-users"></i></div>
                <div class="kpi-val"><h3><?= $total_users ?></h3><p>Total Clientes</p></div>
            </div>
            <div class="kpi-trend" style="color:var(--info)">Ativos: <?= $ativos_count ?></div>
        </a>

        <a href="dns.php" class="kpi-unit">
            <div class="kpi-content">
                <div class="icon-shield" style="color:var(--info); background: rgba(14, 165, 233, 0.08);"><i class="fas fa-microchip"></i></div>
                <div class="kpi-val"><h3><?= count($dns_entries) ?></h3><p>Nodes DNS</p></div>
            </div>
            <div class="kpi-trend" style="color:var(--success)">Sincronizado</div>
        </a>
        
        <a href="https://api.whatsapp.com/send?phone=55991763368" target="_blank" class="kpi-unit">
            <div class="kpi-content">
                <div class="icon-shield" style="color:#25D366; background:rgba(37, 211, 102, 0.08);"><i class="fab fa-whatsapp"></i></div>
                <div class="kpi-val"><h3>Suporte</h3><p>Atendimento</p></div>
            </div>
            <div class="kpi-trend" style="color:var(--success)">Privilegiado</div>
        </a>
    </section>

    <main class="main-grid">
        <article class="deck-panel">
            <div class="deck-header">
                <span><i class="fas fa-project-diagram" style="color:var(--primary)"></i> Distribuição de Nodes</span>
                <span style="text-transform: none; color:var(--text-dim)"><?= date('d/m/Y H:i') ?></span>
            </div>
            <div class="chart-box">
                <canvas id="titanChart"></canvas>
            </div>
        </article>

        <article class="deck-panel">
            <div class="deck-header"><span><i class="fas fa-terminal"></i> Console de Logs</span></div>
            <div style="padding: 25px;">
                <div class="terminal-deck" id="titan-terminal">
                    <span style="color:var(--primary)">[SYSTEM]</span> Inicializando Engine...<br>
                    <span style="color:var(--success)">[READY]</span> Banco de dados SQLite otimizado.<br>
                    <span style="color:var(--info)">[INFO]</span> <?= $total_users ?> registros carregados.<br>
                    <span style="color:var(--text-dim)">[IDLE]</span> Aguardando novas requisições...
                </div>
                
                <div class="btn-grid">
                    <button class="btn-titan btn-primary" onclick="runScan(this)">
                        <i class="fas fa-sync-alt"></i> ATUALIZAR
                    </button>
                    
                    <button class="btn-titan btn-wa" onclick="wa()">
                        <i class="fab fa-whatsapp"></i> WHATSAPP
                    </button>
                    
                    <button class="btn-titan btn-telegram" onclick="telegram()">
                        <i class="fab fa-telegram"></i> TELEGRAM
                    </button>
                </div>
            </div>
        </article>
    </main>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
    $(document).ready(function() {
        const ctx = document.getElementById('titanChart');
        if (ctx) {
            new Chart(ctx, {
                type: 'bar', // Mudado para barra para maior detalhamento visual
                data: {
                    labels: <?= json_encode($chart_labels) ?>,
                    datasets: [{
                        label: 'Clientes por Node',
                        data: <?= json_encode($chart_data) ?>,
                        backgroundColor: '#6366f1',
                        borderRadius: 8,
                        hoverBackgroundColor: '#4338ca'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    indexAxis: 'y', // Detalhamento horizontal para facilitar leitura
                    plugins: { 
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: '#1e293b',
                            padding: 12,
                            titleFont: { size: 14, weight: 'bold' }
                        }
                    },
                    scales: {
                        x: { beginAtZero: true, grid: { color: '#f1f5f9' }, ticks: { font: { weight: 'bold' } } },
                        y: { grid: { display: false }, ticks: { font: { weight: 'bold' } } }
                    }
                }
            });
        }
    });

    function runScan(btn) {
        const original = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> AGUARDE';
        btn.style.opacity = '0.7';
        
        setTimeout(() => {
            const terminal = document.getElementById('titan-terminal');
            terminal.innerHTML += "<br><span style='color:var(--success)'>[SCAN]</span> " + new Date().toLocaleTimeString() + " - Todos os Nodes em conformidade.";
            terminal.scrollTop = terminal.scrollHeight;
            btn.innerHTML = original;
            btn.style.opacity = '1';
        }, 1200);
    }

    function wa() { window.open("https://api.whatsapp.com/send?phone=55991763368", "_blank"); }
    function telegram() { window.open("https://t.me/brtechoficial", "_blank"); }
</script>

</body>
</html>

<?php 
if (file_exists($basePath . "/includes/footer.php")) { include_once $basePath . "/includes/footer.php"; }
ob_end_flush(); 
?>