<?php
session_start();
require_once '../config/db.php';

// Verifique se está logado como superadmin
if (!isset($_SESSION['superadmin_id'])) {
    header("Location: login.php");
    exit;
}

// BUSCA USUÁRIOS E CALCULA VENCIMENTO
$stmt = $pdo->query("SELECT id, name, email, phone, created_at, active FROM users ORDER BY created_at DESC");
$clientes = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Função para gerar link do WhatsApp com mensagem
function gerarLinkZap($phone, $nome, $data_venc, $bloqueado) {
    $telefone = preg_replace('/\D/', '', $phone);
    if (strlen($telefone) < 10) return '#';
    $venc = date('d/m/Y', strtotime($data_venc));
    $msg = "Olá $nome, tudo bem? 
Seu acesso ao sistema Fiado Fácil vence em $venc.
";
    if ($bloqueado) {
        $msg .= "Seu sistema foi bloqueado por falta de pagamento. Entre em contato para regularizar.";
    } else {
        $msg .= "Por favor, regularize seu pagamento para evitar o bloqueio do sistema.";
    }
    $zap = "https://wa.me/55$telefone?text=" . urlencode($msg);
    return $zap;
}

// Função para calcular vencimento (31 dias do cadastro)
function dataVencimento($created_at) {
    return date('Y-m-d', strtotime($created_at . ' +31 days'));
}

?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Cobranças - Fiado Fácil</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Fonts e Icons -->
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700;400&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        body {margin:0;font-family:'Montserrat',Arial,sans-serif;background:#F5FAFF;}
        .sidebar {
            position:fixed;left:0;top:0;bottom:0;width:220px;background:#1876F2;color:#fff;display:flex;flex-direction:column;align-items:center;padding-top:32px;box-shadow:2px 0 12px rgba(24,118,242,0.10);z-index:100;
        }
        .sidebar .logo {
            font-size:1.6rem;font-weight:700;margin-bottom:34px;letter-spacing:0.03em;
        }
        .sidebar nav {width:100%;}
        .sidebar nav a {
            display:flex;align-items:center;gap:13px;color:#fff;text-decoration:none;font-size:1.08rem;font-weight:600;padding:12px 28px;margin:2px 0;border-radius:8px 0 0 8px;transition:background 0.17s;
        }
        .sidebar nav a.active, .sidebar nav a:hover {background:#1356b3;}
        .sidebar .bottom {margin-top:auto;margin-bottom:34px;}
        .sidebar .logout-link {color:#eaf4ff;font-weight:700;font-size:1.02rem;text-decoration:underline;background:none;border:none;cursor:pointer;padding:0;}
        .main-content {margin-left:220px;padding:38px 18px;max-width:1100px;}
        h2 { color:#1876F2; font-size:1.5rem; margin-bottom:22px; margin-top:0;}
        .clientes-table-container {overflow-x:auto; border-radius:9px; background:#fff;}
        .clientes-table {width:100%; border-collapse:collapse;}
        .clientes-table th, .clientes-table td { padding:13px 8px; text-align:left;}
        .clientes-table th {background:#eef4fd; color:#1876F2; font-size:1.03rem; font-weight:700;}
        .clientes-table tr:not(:last-child) td { border-bottom:1px solid #f1f4fa;}
        .clientes-table td { font-size:1.01rem;}
        .badge { padding:4px 10px; border-radius:20px; font-size:0.95rem; font-weight:600; display:inline-block;}
        .badge-vencido { background:#ffeaea; color:#d9534f; }
        .badge-emdia { background:#eafff4; color:#1bbf5c; }
        .badge-bloq  { background:#d9534f; color:#fff; }
        .zap-btn { background:#25d366; color:#fff; border:none; border-radius:6px; padding:7px 16px; font-size:1.07rem; cursor:pointer; font-weight:700; margin-right:6px; display:inline-flex; align-items:center; gap:7px; text-decoration:none;}
        .zap-btn:hover { background:#1ba94c;}
        @media(max-width:900px) {
            .main-content{margin-left:0;padding:15px 3vw;}
            .sidebar{position:relative;width:100%;height:auto;box-shadow:none;padding:14px 0;}
            .sidebar .logo{font-size:1.2rem;}
            .sidebar nav{gap:5px;width:auto;display:flex;}
            .sidebar nav a{font-size:0.99rem;padding:8px 14px;}
            .cards-row{flex-direction:column;}
        }
    </style>
</head>
<body>
    <aside class="sidebar">
        <div class="logo">
            <i class="fa-solid fa-shield-halved"></i> Fiado Fácil
        </div>
        <nav>
            <a href="dashboard.php"><i class="fa-solid fa-gauge"></i> Dashboard</a>
            <a href="usuarios.php"><i class="fa-solid fa-user"></i> Usuários</a>
            <a href="cobrancas.php" class="active"><i class="fa-solid fa-users"></i> Cobranças</a>
        </nav>
        <div class="bottom">
            <a href="logout.php" class="logout-link"><i class="fa-solid fa-right-from-bracket"></i> Sair</a>
        </div>
    </aside>
    <div class="main-content">
        <h2><i class="fa-solid fa-money-bill-wave"></i> Gerenciar Cobranças de Clientes</h2>
        <div class="clientes-table-container">
            <table class="clientes-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Nome</th>
                        <th>E-mail</th>
                        <th>Telefone</th>
                        <th>Cadastro</th>
                        <th>Vencimento</th>
                        <th>Status</th>
                        <th>Ação</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                $hoje = date('Y-m-d');
                foreach($clientes as $cli):
                    $vencimento = dataVencimento($cli['created_at']);
                    $esta_vencido = ($hoje > $vencimento);
                    $bloqueado = !$cli['active'];
                ?>
                    <tr>
                        <td><?= htmlspecialchars($cli['id']) ?></td>
                        <td><?= htmlspecialchars($cli['name']) ?></td>
                        <td><?= htmlspecialchars($cli['email']) ?></td>
                        <td><?= htmlspecialchars($cli['phone']) ?></td>
                        <td><?= date('d/m/Y', strtotime($cli['created_at'])) ?></td>
                        <td><?= date('d/m/Y', strtotime($vencimento)) ?></td>
                        <td>
                            <?php if ($bloqueado): ?>
                                <span class="badge badge-bloq">Bloqueado</span>
                            <?php elseif ($esta_vencido): ?>
                                <span class="badge badge-vencido">Vencido</span>
                            <?php else: ?>
                                <span class="badge badge-emdia">Em dia</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if (!empty($cli['phone'])): ?>
                                <a class="zap-btn"
                                   href="<?= gerarLinkZap($cli['phone'], $cli['name'], $vencimento, $bloqueado) ?>"
                                   target="_blank" title="Cobrar no WhatsApp">
                                    <i class="fa-brands fa-whatsapp"></i> Cobrar
                                </a>
                            <?php else: ?>
                                <span style="color:#aaa;">Sem telefone</span>
                            <?php endif;?>
                        </td>
                    </tr>
                <?php endforeach;?>
                <?php if (count($clientes) === 0): ?>
                    <tr><td colspan="8" style="text-align:center;color:#888;">Nenhum cliente cadastrado.</td></tr>
                <?php endif;?>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>