<?php 
session_start();
if (!isset($_SESSION['id']) || !$_SESSION['admin']) {
    header("Location: login.php");
    exit();
}

// Verifica arquivo do painel
if (!file_exists(__DIR__ . '/js/sb-admiin.min.php')) {
    echo '<div class="alert alert-danger text-center" style="margin: 100px auto; max-width: 500px; border-radius: 15px;">
        <h4 class="mb-3">🚫 ARQUIVO RESTRITO</h4>
        Este arquivo pertence exclusivamente ao painel original.
    </div>';
    exit;
}

// Conecta ao banco
$db = new SQLite3("./api/.ansdb.db");

// Variáveis de contagem
$total_ativos = $total_inativas = $total_clientes = $total_7_dias = 0;

$data_atual = new DateTime();
$result = $db->query("SELECT expire_date, title FROM ibo");

while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $title = trim($row['title']);
    $expira = $row['expire_date'];

    if ($title === 'NOVO*** (TESTE CADASTRADO)' || $title === 'Teste') continue;

    $data_expiracao = new DateTime($expira);
    $dias_restantes = (int)$data_atual->diff($data_expiracao)->format('%r%a');

    $total_clientes++;
    if ($dias_restantes < 0) $total_inativas++;
    else {
        $total_ativos++;
        if ($dias_restantes <= 7) $total_7_dias++;
    }
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Dashboard - Admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap + Font Awesome + Poppins -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">

    <style>
        body {
            font-family: 'Poppins', sans-serif;
            background: #111;
            color: #fff;
        }
        .card-custom {
            border-radius: 16px;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3);
            transition: transform 0.2s ease-in-out;
            background: #222;
        }
        .card-custom:hover {
            transform: translateY(-5px);
        }
        .card-header {
            font-size: 1.25rem;
            font-weight: 600;
        }
        .card-body h2 {
            font-size: 2rem;
            font-weight: 700;
            color: #fff;
        }
        .card-icon {
            font-size: 3rem;
            margin-bottom: 10px;
        }
        .popup-overlay {
            background-color: rgba(0,0,0,0.85);
            padding: 25px;
            border-radius: 12px;
            position: fixed;
            top: 50%; left: 50%;
            transform: translate(-50%, -50%);
            max-height: 80vh;
            overflow-y: auto;
            display: none;
            z-index: 9999;
            width: 90%; max-width: 600px;
        }
        .btn-primary, .btn-outline-info {
            font-weight: 600;
        }
        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
        }
        .btn-primary:hover {
            background-color: #0056b3;
            border-color: #004085;
        }
    </style>
</head>

<body>
<?php include 'includes/header.php'; ?>

<main class="container py-4">
    <h1 class="text-center mb-5">📊 Dashboard</h1>

    <div class="row row-cols-1 row-cols-md-2 row-cols-xl-4 g-4 justify-content-center">
        <div class="col">
            <div class="card card-custom text-center p-4">
                <div class="card-header text-primary"><i class="fas fa-users card-icon"></i>Total de Clientes</div>
                <div class="card-body">
                    <h2 class="text-black"><?= $total_clientes ?></h2>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card card-custom text-center p-4">
                <div class="card-header text-danger"><i class="fas fa-user-times card-icon"></i>Clientes Vencidos</div>
                <div class="card-body">
                    <h2 class="text-black"><?= $total_inativas ?></h2>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card card-custom text-center p-4">
                <div class="card-header text-warning"><i class="fas fa-hourglass-half card-icon"></i>Ativos até 7 dias</div>
                <div class="card-body">
                    <h2 class="text-black"><?= $total_7_dias ?></h2>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card card-custom text-center p-4">
                <div class="card-header text-success"><i class="fas fa-check-circle card-icon"></i>Clientes Ativos</div>
                <div class="card-body">
                    <h2 class="text-black"><?= $total_ativos ?></h2>
                </div>
            </div>
        </div>
    </div>

     <div class="row justify-content-center mt-5">
        <div class="col-md-6">
            <div class="card card-custom text-center p-4">
                <div class="card-header text-success"><i class="fas fa-calendar-alt card-icon"></i>Previsto para 30 dias</div>
                <div class="card-body">
                    <h3 class="text-success mt-3">
                        <?php
                        $total_30_dias = 0;
                        $result = $db->query("SELECT expire_date, title FROM ibo");
                        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
                            $title = trim($row['title']);
                            if ($title === 'NOVO*** (TESTE CADASTRADO)' || $title === 'Teste') continue;

                            $expira = new DateTime($row['expire_date']);
                            $dias = (int)$data_atual->diff($expira)->format('%r%a');
                            if ($dias >= 0 && $dias <= 30) $total_30_dias += 25;
                        }
                        echo "R$ " . number_format($total_30_dias, 2, ',', '.');
                        ?>
                    </h3>
                </div>
            </div>
        </div>
    </div>

    <div class="row justify-content-center mt-5">
        <div class="col-md-6">
            <div class="card card-custom text-center p-4">
                <div class="card-header text-info">Código do downloader do app:</div>
                <div class="card-body">
                    <h5 class="text-info mb-3">🔽 5351829</h5>
                    <a id="appDownloadLink" class="text-success" href="https://lcan.thefullnet.com.br/tv.apk" target="_blank">
                        https://lcan.thefullnet.com.br/tv.apk
                    </a>
                    <br>
                    <button class="btn btn-primary mt-3" onclick="copiarLink('appDownloadLink')">Copiar Link</button>
                    <p class="mt-4">
                        Conheça nosso <strong>chatbot inteligente no WhatsApp</strong>! Ele automatiza cobranças, envia boletos e ativa o plano!
                    </p>
                    <a class="btn btn-outline-info mt-2" href="https://botzap.thefull.site/planos" target="_blank">
                        🤖 Ativar Chatbot
                    </a>
                </div>
            </div>
        </div>
    </div>
</main>


<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<?php include 'includes/footer.php'; ?>
</body>
</html>
