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

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

// Carrega valores do JSON
$valores = json_decode(file_get_contents("./api/valores.json"), true);
$valor_plano_1_mes = 0;
foreach ($valores['planos'] as $plano) {
    if ($plano['nome'] === "Plano 1 Mes") {
        $valor_plano_1_mes = $plano['valor'];
        break;
    }
}

// Variáveis
$total_ativos = $total_inativas = $total_clientes = $total_7_dias = 0;
$lucro_proximos_30 = 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++;
        if ($dias_restantes <= 30) {
            $lucro_proximos_30 += $valor_plano_1_mes;
        }
    }
}
?>


<!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;
}

/* Cards principais */
.card-custom {
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    transition: transform 0.2s ease-in-out;
    background: #222;
    padding: 0.8rem;
    height: 100%;
}
.card-custom:hover {
    transform: translateY(-5px);
}

/* Ícones */
.card-icon {
    font-size: 1.4rem;
    margin-bottom: 0.3rem;
}

/* Números */
.card-body h2 {
    font-size: 1.2rem;
    font-weight: 700;
    margin: 0;
}

/* Labels */
.card-body small {
    font-size: 0.75rem;
    font-weight: 500;
    color: #bbb;
    display: block;
    margin-top: 0.2rem;
    white-space: nowrap;
}

/* Card Header (para outros blocos maiores) */
.card-header {
    font-size: 0.9rem;
    font-weight: 600;
    background: transparent;
    border: none;
    color: inherit;
}

/* Responsividade */
@media (max-width: 768px) {
    .card-icon { font-size: 1.2rem; }
    .card-body h2 { font-size: 1rem; }
    .card-body small { font-size: 0.65rem; }
}

@media (max-width: 576px) {
    .card-icon { font-size: 1rem; }
    .card-body h2 { font-size: 0.9rem; }
    .card-body small { font-size: 0.6rem; }
}
/* Card principal com label e valor lado a lado */
.card-body .card-info {
    display: flex;
    justify-content: center; /* centraliza horizontalmente */
    align-items: center;     /* centraliza verticalmente */
    gap: 0.5rem;             /* espaçamento entre valor e label */
}

.card-body .card-info h2 {
    margin: 0;
    font-size: 1.2rem;
    font-weight: 700;
}

.card-body .card-info small {
    font-size: 0.9rem;
    font-weight: 500;
    color: #bbb;
}

</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-4 g-2 justify-content-center">
     
    <div class="col">
        <div class="card card-custom text-center p-2">
            <div class="card-header text-primary"><i class="fas fa-users card-icon"></i></div>
           <div class="card-body">
    <div class="card-info">
        <h2 class="text-black"><?= $total_clientes ?></h2>
       
    </div>
</div>

        </div>
    </div>

    <div class="col">
        <div class="card card-custom text-center p-2">
            <div class="card-header text-danger"><i class="fas fa-user-times card-icon"></i></div>
           <div class="card-body">
    <div class="card-info">
        <h2 class="text-black"><?= $total_inativas ?></h2>
     
    </div>
</div>
        </div>
    </div>
    <div class="col">
        <div class="card card-custom text-center p-2">
            <div class="card-header text-warning"><i class="fas fa-hourglass-half card-icon"></i></div>
          <div class="card-body">
    <div class="card-info">
        <h2 class="text-black"><?= $total_7_dias ?></h2>
       
    </div>
</div>
        </div>
    </div>
    <div class="col">
        <div class="card card-custom text-center p-2">
            <div class="card-header text-success"><i class="fas fa-check-circle card-icon"></i></div>
           <div class="card-body">
    <div class="card-info">
        <h2 class="text-black"><?= $total_ativos ?></h2>
      
    </div>
</div>
        </div>
    </div>
</div>
<br>
    <div class="col">
    <div class="card card-custom text-center p-2">
        <div class="card-header text-success"><i class="fas fa-money-bill-wave card-icon"></i></div>
        <div class="card-body">
            <div class="card-info">
                <h2 class="text-black">R$ <?= number_format($lucro_proximos_30, 2, ',', '.') ?></h2>
                <small>Próximos 30 dias</small>
            </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-plug card-icon"></i>Clientes Online</div>
                <div class="card-body">
                    <h2 class="text-black" id="total-online">Carregando...</h2>
                    <button class="btn btn-outline-info mt-3" id="verClientesOnlineBtn" data-bs-toggle="modal" data-bs-target="#onlineModal">Ver Clientes Online</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal de Clientes Online -->
    <div class="modal fade" id="onlineModal" tabindex="-1" aria-labelledby="onlineModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="onlineModalLabel">Clientes Online</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
                </div>
                <div class="modal-body" id="clientes-online-modal">
                    Carregando clientes online...
                </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>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Carregar clientes online via AJAX
        fetch('online.php')
            .then(response => response.json())
            .then(data => {
                // Atualizar total de clientes online
                document.getElementById('total-online').textContent = `${data.total_online} Online`;
                
                // Atualizar modal de clientes online
                const modalBody = document.getElementById('clientes-online-modal');
                modalBody.innerHTML = '';
                if (data.total_online > 0) {
                    const list = document.createElement('ul');
                    list.classList.add('list-group');
                    data.clientes_online.forEach(cliente => {
                        const item = document.createElement('li');
                        item.classList.add('list-group-item', 'bg-dark', 'text-white');
                        item.innerHTML = `<strong>${cliente.nome}</strong> (MAC: ${cliente.mac}) - Conexões: ${cliente.conexoes}`;
                        list.appendChild(item);
                    });
                    modalBody.appendChild(list);
                } else {
                    modalBody.innerHTML = '<p class="text-warning">Nenhum cliente online no momento.</p>';
                }
            })
            .catch(error => console.error('Erro ao carregar clientes online:', error));
    });
</script>

<?php include 'includes/footer.php'; ?>
</body>
</html>
