<?php
session_start();
require_once 'conexao.php';

if (!isset($_SESSION['logado'])) { header("Location: login.php"); exit; }

$isAdmin = (strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'];
$msg = ""; $msg_tipo = ""; $texto_zap = "";

// --- 1. CONFIGURAÇÃO DE FILTROS E PAGINAÇÃO ---
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$pagina = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
$offset = ($pagina - 1) * $limit;

$busca = trim($_GET['busca'] ?? '');
$status_f = $_GET['status'] ?? 'todos';
$rev_f = $_GET['revendedor'] ?? '';

// --- 2. BUSCAR DADOS PARA OS FILTROS ---
$mapa_perfis = [];
$lista_perfis_select = [];
$lista_revendedores = [];

try {
    $res_p = $connGeral->query("SELECT id, valorcsp, nome, url, porta FROM perfil WHERE (bloqueado IS NULL OR bloqueado != 'sim')")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($res_p as $p) { $mapa_perfis[$p['valorcsp']] = $p; $lista_perfis_select[] = $p; }
    
    if ($isAdmin) {
        $lista_revendedores = $connUser->query("SELECT usuario FROM rev ORDER BY usuario ASC")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) { }

// --- 3. PROCESSAMENTO DE AÇÕES ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $acao = $_POST['acao'];
        $id_user = (int)($_POST['id_user'] ?? 0);
        $filtroSeguranca = $isAdmin ? "" : " AND CadUser = '$usuarioLogado'";

        if ($acao === 'renovar') {
            $stmt = $connUser->prepare("SELECT usuario, senha, data_premio FROM usuario WHERE id = ? $filtroSeguranca");
            $stmt->execute([$id_user]);
            $c = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($c) {
                $tipo_renov = $_POST['tipo_renov'] ?? 'auto'; 
                if ($tipo_renov === 'manual') { $nova_data = $_POST['data_manual']; }
                else {
                    $meses = (int)$_POST['qtd_meses'];
                    $venc_raw = $c['data_premio'];
                    $atual_ts = is_numeric($venc_raw) ? (int)$venc_raw : strtotime($venc_raw);
                    $base = ($atual_ts > time()) ? $atual_ts : time();
                    $nova_data = date('Y-m-d', strtotime("+$meses months", $base));
                }
                $connUser->prepare("UPDATE usuario SET data_premio=?, bloqueado='nao' WHERE id=?")->execute([$nova_data, $id_user]);
                $texto_zap = "*Plano CS renovado!*\n\n👤 User: {$c['usuario']}\n🔑 Senha: {$c['senha']}\n📆 Venc: ".date('d/m/Y', strtotime($nova_data));
                $msg = "Renovado com sucesso!"; $msg_tipo = "success";
            }
        }
        
        if ($acao === 'bloquear_toggle') {
            $novoStatus = ($_POST['status_atual'] == 'sim') ? 'nao' : 'sim';
            $connUser->prepare("UPDATE usuario SET bloqueado=? WHERE id=? $filtroSeguranca")->execute([$novoStatus, $id_user]);
            $msg = "Status atualizado!"; $msg_tipo = "info";
        }
        
        if ($acao === 'excluir') {
            $connUser->prepare("DELETE FROM usuario WHERE id=? $filtroSeguranca")->execute([$id_user]);
            $msg = "Removido!"; $msg_tipo = "danger";
        }
    } catch (Exception $e) { $msg = "Erro: ".$e->getMessage(); $msg_tipo = "danger"; }
}

// --- 4. CONSTRUÇÃO DA SQL COM FILTROS (FIXED VENCIDOS) ---
$where = " WHERE 1=1";
$params = [];

if (!$isAdmin) { $where .= " AND CadUser = :u"; $params[':u'] = $usuarioLogado; }
elseif ($rev_f !== '') { $where .= " AND CadUser = :rev"; $params[':rev'] = $rev_f; }

if ($busca) { $where .= " AND (nome LIKE :b OR usuario LIKE :b)"; $params[':b'] = "%$busca%"; }

$hoje_iso = date('Y-m-d');
$hoje_ts = time();

// Lógica de Filtro que entende tanto Data ISO quanto Timestamp
if ($status_f === 'ativos') { 
    $where .= " AND ( (data_premio >= '$hoje_ts' AND data_premio REGEXP '^[0-9]+$') OR (data_premio >= '$hoje_iso' AND data_premio NOT REGEXP '^[0-9]+$') ) AND bloqueado != 'sim'"; 
} elseif ($status_f === 'vencidos') { 
    $where .= " AND ( (data_premio < '$hoje_ts' AND data_premio REGEXP '^[0-9]+$') OR (data_premio < '$hoje_iso' AND data_premio NOT REGEXP '^[0-9]+$') )"; 
} elseif ($status_f === 'bloqueados') { 
    $where .= " AND bloqueado = 'sim'"; 
}

$total_stmt = $connUser->prepare("SELECT COUNT(*) FROM usuario $where");
$total_stmt->execute($params);
$total_registos = $total_stmt->fetchColumn();
$total_paginas = ceil($total_registos / $limit);

$stmt = $connUser->prepare("SELECT * FROM usuario $where ORDER BY id DESC LIMIT $limit OFFSET $offset");
$stmt->execute($params);
$usuarios = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clientes | IPTV Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        :root { --primary: #7367f0; --bg-body: #151521; --bg-card: #1e1e2d; }
        body { background: var(--bg-body); color: #fff; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); padding: 20px; border-right: 1px solid #333; transition: 0.3s; z-index: 1050; overflow-y: auto; }
        .main-content { margin-left: 260px; padding: 30px; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 10px 12px; border-radius: 8px; margin-bottom: 2px; display: flex; align-items: center; gap: 10px; transition: 0.2s; text-decoration: none; font-size: 0.9rem; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 20px 0 10px 12px; }
        .card-custom { background: var(--bg-card); border: 1px solid #333; border-radius: 12px; }
        .form-control, .form-select { background: #2b2b40; border: 1px solid #444; color: #fff; }
        .table-dark { background: var(--bg-card); --bs-table-bg: var(--bg-card); }
        .status-blocked { color: #ff4d4d !important; font-weight: bold; }
        .info-acesso { font-size: 0.75rem; color: #aaa; margin-top: 2px; }
        .info-acesso b { color: #7367f0; }
        .pagination .page-link { background: #2b2b40; border-color: #444; color: #fff; }
        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; padding: 15px; } .mobile-toggle { display: block !important; } }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1040; }
        .overlay.show { display: block; }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold text-white text-center"><i class="fas fa-tv text-primary"></i> IPTV PANEL</h4>
    <div class="nav flex-column">
        <a href="index.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        <?php if ($isAdmin): ?>
            <div class="nav-group-title">Administração</div>
            <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Gerenciar Perfis</a>
            <a href="gerenciar_dns.php" class="nav-link"><i class="fas fa-network-wired"></i> Servidores DNS</a>
            <a href="gerenciar_admins.php" class="nav-link"><i class="fas fa-user-shield"></i> Gestão de Admins</a>
            <a href="gerenciar_permissoes.php" class="nav-link"><i class="fas fa-lock"></i> Permissões</a>
            <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> Config. E-mail</a>
            <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
            <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backups</a>
            <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Config. Geral</a>
        <?php endif; ?>
        <div class="nav-group-title">Operacional</div>
        <a href="revendedores.php" class="nav-link"><i class="fas fa-store"></i> Revendedores</a>
        <a href="clientes.php" class="nav-link active"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link"><i class="fas fa-stopwatch"></i> Testes</a>
        <a href="status_online.php" class="nav-link"><i class="fas fa-wifi"></i> Monitor Online</a>
        <hr class="border-secondary mt-4"><a href="sair.php" class="nav-link text-danger"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>

    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <h3 class="fw-bold">Gestão de Clientes</h3>
        <button onclick="new bootstrap.Modal(document.getElementById('modalCriar')).show()" class="btn btn-success fw-bold px-4"><i class="fas fa-plus me-2"></i>Novo Cliente</button>
    </div>

    <div class="card card-custom p-3 mb-4">
        <form method="GET" class="row g-2">
            <div class="col-md-3"><input type="text" name="busca" class="form-control" placeholder="Nome ou Usuário..." value="<?= $busca ?>"></div>
            
            <div class="col-6 col-md-2">
                <select name="status" class="form-select">
                    <option value="todos" <?= $status_f=='todos'?'selected':'' ?>>Todos Status</option>
                    <option value="ativos" <?= $status_f=='ativos'?'selected':'' ?>>Ativos</option>
                    <option value="vencidos" <?= $status_f=='vencidos'?'selected':'' ?>>Vencidos</option>
                    <option value="bloqueados" <?= $status_f=='bloqueados'?'selected':'' ?>>Bloqueados</option>
                </select>
            </div>

            <?php if($isAdmin): ?>
            <div class="col-6 col-md-2">
                <select name="revendedor" class="form-select">
                    <option value="">Todos Revendedores</option>
                    <?php foreach($lista_revendedores as $r): ?>
                        <option value="<?= $r['usuario'] ?>" <?= $rev_f==$r['usuario']?'selected':'' ?>><?= $r['usuario'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>

            <div class="col-6 col-md-2">
                <select name="limit" class="form-select">
                    <?php $opts = [10,20,50,100,250,500,1000,2000,30000]; 
                    foreach($opts as $o): ?>
                        <option value="<?= $o ?>" <?= $limit==$o?'selected':'' ?>><?= $o ?> por página</option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-6 col-md-1"><button class="btn btn-primary w-100"><i class="fas fa-filter"></i></button></div>
        </form>
    </div>

    <div class="card card-custom overflow-hidden">
        <div class="table-responsive">
            <table class="table table-dark table-hover mb-0 align-middle">
                <thead>
                    <tr class="text-secondary small text-uppercase">
                        <th class="ps-3">Cliente / Acesso</th>
                        <th>Vencimento</th>
                        <th>Dono</th>
                        <th class="text-end pe-3">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($usuarios as $u): 
                        $venc_raw = $u['data_premio'];
                        $venc_ts = is_numeric($venc_raw) ? (int)$venc_raw : strtotime($venc_raw);
                        $vencido = (time() > $venc_ts);
                        $data_br = ($venc_ts > 0) ? date('d/m/Y', $venc_ts) : '---';
                        $data_inp = ($venc_ts > 0) ? date('Y-m-d', $venc_ts) : '';
                        $isBlocked = ($u['bloqueado'] == 'sim' || $u['bloqueado'] == 'S');
                        $p_info = $mapa_perfis[$u['perfil']] ?? ['nome' => 'S/ Perfil', 'url' => '---', 'porta' => '---'];
                    ?>
                    <tr>
                        <td class="ps-3">
                            <div class="fw-bold text-white"><?= htmlspecialchars($u['nome']) ?></div>
                            <div class="info-acesso"><b>User:</b> <?= $u['usuario'] ?> | <b>Senha:</b> <?= $u['senha'] ?></div>
                            <div class="text-info" style="font-size: 0.7rem;"><?= $p_info['nome'] ?></div>
                        </td>
                        <td class="<?= $vencido ? 'text-danger fw-bold fst-italic' : ($isBlocked ? 'status-blocked' : 'text-success') ?>">
                            <?= $isBlocked ? 'BLOQUEADO' : $data_br ?>
                        </td>
                        <td><span class="badge bg-dark border border-secondary"><?= htmlspecialchars($u['CadUser']) ?></span></td>
                        <td class="text-end pe-3">
                            <button onclick='abrirVisualizar(<?= json_encode($u) ?>, <?= json_encode($p_info) ?>, "<?= $data_br ?>")' class="btn btn-sm btn-light rounded-circle me-1" title="Ver Dados"><i class="fas fa-eye text-dark"></i></button>
                            <button onclick="abrirRenovar(<?= $u['id'] ?>, '<?= $u['nome'] ?>')" class="btn btn-sm btn-success rounded-circle me-1" title="Renovar"><i class="fas fa-sync-alt"></i></button>
                            <button onclick='abrirEditar(<?= json_encode($u) ?>, "<?= $data_inp ?>")' class="btn btn-sm btn-info rounded-circle me-1" title="Editar"><i class="fas fa-pen text-white"></i></button>
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="acao" value="bloquear_toggle"><input type="hidden" name="id_user" value="<?= $u['id'] ?>"><input type="hidden" name="status_atual" value="<?= $u['bloqueado'] ?>">
                                <button type="submit" class="btn btn-sm <?= $isBlocked ? 'btn-danger' : 'btn-warning' ?> rounded-circle me-1"><i class="fas <?= $isBlocked ? 'fa-lock' : 'fa-lock-open' ?>"></i></button>
                            </form>
                            <form method="POST" class="d-inline"><input type="hidden" name="acao" value="excluir"><input type="hidden" name="id_user" value="<?= $u['id'] ?>"><button class="btn btn-sm btn-outline-danger rounded-circle" onclick="return confirm('Excluir?')"><i class="fas fa-trash"></i></button></form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($total_paginas > 1): ?>
        <nav class="p-3"><ul class="pagination justify-content-center mb-0">
            <?php for($i=1; $i<=$total_paginas; $i++): ?>
                <li class="page-item <?= $i==$pagina?'active':'' ?>"><a class="page-link" href="?pagina=<?= $i ?>&busca=<?= $busca ?>&status=<?= $status_f ?>&revendedor=<?= $rev_f ?>&limit=<?= $limit ?>"><?= $i ?></a></li>
            <?php endfor; ?>
        </ul></nav>
        <?php endif; ?>
    </div>
</main>

<div class="modal fade" id="modalVerDados" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-info text-white">
            <div class="modal-header border-secondary"><h5><i class="fas fa-id-card me-2 text-info"></i>Dados do Cliente</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body p-4">
                <div class="mb-3"><label class="text-white-50 small">Usuário:</label><input type="text" readonly class="form-control bg-dark border-secondary" id="view_user"></div>
                <div class="mb-3"><label class="text-white-50 small">Senha:</label><input type="text" readonly class="form-control bg-dark border-secondary" id="view_pass"></div>
                <div class="mb-3"><label class="text-white-50 small">Vencimento:</label><input type="text" readonly class="form-control bg-dark border-secondary text-success fw-bold" id="view_venc"></div>
                <hr class="border-secondary">
                <div class="mb-3"><label class="text-white-50 small">URL / DNS:</label><input type="text" readonly class="form-control bg-dark border-secondary text-info" id="view_url"></div>
                <div class="mb-4"><label class="text-white-50 small">Porta:</label><input type="text" readonly class="form-control bg-dark border-secondary text-warning" id="view_porta"></div>
                <div class="d-flex gap-2"><button onclick="copiarDadosVisualizar()" class="btn btn-outline-light w-50 fw-bold">COPIAR</button><button onclick="enviarZapVisualizar()" class="btn btn-success w-50 fw-bold">WHATSAPP</button></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalRenovar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary text-white">
            <form method="POST" id="formRenovar">
                <input type="hidden" name="acao" value="renovar"><input type="hidden" name="id_user" id="renov_id"><input type="hidden" name="tipo_renov" id="tipo_renov" value="auto"><input type="hidden" name="qtd_meses" id="qtd_meses" value="1">
                <div class="modal-header"><h5>Renovar: <span id="renov_nome" class="text-info"></span></h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
                <div class="modal-body p-4 text-center">
                    <div class="row g-2 mb-4">
                        <div class="col-3"><button type="button" class="btn btn-outline-primary w-100" onclick="submitRenov(1)">1 Mês</button></div>
                        <div class="col-3"><button type="button" class="btn btn-outline-primary w-100" onclick="submitRenov(3)">3 Meses</button></div>
                        <div class="col-3"><button type="button" class="btn btn-outline-primary w-100" onclick="submitRenov(6)">6 Meses</button></div>
                        <div class="col-3"><button type="button" class="btn btn-outline-primary w-100" onclick="submitRenov(12)">1 Ano</button></div>
                    </div>
                    <hr class="border-secondary">
                    <div class="mt-3"><label class="small mb-2">Data Manual:</label><div class="input-group"><input type="date" name="data_manual" id="data_manual" class="form-control"><button type="button" class="btn btn-info" onclick="submitManual()">SALVAR</button></div></div>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalZap" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered text-center"><div class="modal-content bg-dark border-success text-white"><div class="modal-header border-0 pb-0"><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body p-4 pt-0"><h5 class="text-success mb-3">Concluído!</h5><textarea id="textoZapArea" class="form-control mb-3" rows="6" style="background:#111; color:#0f0; border:none;"><?= $texto_zap ?></textarea><button onclick="copiarTexto()" class="btn btn-outline-light me-2">Copiar</button><button onclick="enviarZap()" class="btn btn-success">WhatsApp</button></div></div></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }
    function abrirVisualizar(u, p, data_br) { document.getElementById('view_user').value = u.usuario; document.getElementById('view_pass').value = u.senha; document.getElementById('view_venc').value = data_br; document.getElementById('view_url').value = p.url; document.getElementById('view_porta').value = p.porta; new bootstrap.Modal(document.getElementById('modalVerDados')).show(); }
    function copiarDadosVisualizar() { const msg = `👤 User: ${document.getElementById('view_user').value}\n🔑 Senha: ${document.getElementById('view_pass').value}\n📅 Vencimento: ${document.getElementById('view_venc').value}\n🌐 URL: ${document.getElementById('view_url').value}\n🔌 Porta: ${document.getElementById('view_porta').value}`; navigator.clipboard.writeText(msg).then(() => alert("Copiado!")); }
    function enviarZapVisualizar() { const msg = `👤 *User:* ${document.getElementById('view_user').value}\n🔑 *Senha:* ${document.getElementById('view_pass').value}\n📅 *Vencimento:* ${document.getElementById('view_venc').value}\n🌐 *URL:* ${document.getElementById('view_url').value}\n🔌 *Porta:* ${document.getElementById('view_porta').value}`; window.open("https://api.whatsapp.com/send?text=" + encodeURIComponent(msg), '_blank'); }
    function abrirRenovar(id, nome) { document.getElementById('renov_id').value = id; document.getElementById('renov_nome').innerText = nome; new bootstrap.Modal(document.getElementById('modalRenovar')).show(); }
    function submitRenov(m) { document.getElementById('tipo_renov').value = 'auto'; document.getElementById('qtd_meses').value = m; document.getElementById('formRenovar').submit(); }
    function submitManual() { document.getElementById('tipo_renov').value = 'manual'; document.getElementById('formRenovar').submit(); }
    function abrirEditar(u, data_inp) { /* Carregar e abrir modalEditar */ }
    window.onload = function() { if(`<?= trim($texto_zap) ?>` !== "") new bootstrap.Modal(document.getElementById('modalZap')).show(); }
    function copiarTexto() { document.getElementById("textoZapArea").select(); document.execCommand("copy"); alert("Copiado!"); }
    function enviarZap() { window.open("https://api.whatsapp.com/send?text=" + encodeURIComponent(document.getElementById("textoZapArea").value), '_blank'); }
</script>
</body>
</html>
