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

require_once 'conexao.php';

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

// Identifica o domínio e pasta atual automaticamente
$url_painel = "http://" . $_SERVER['HTTP_HOST'] . str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);

// --- 1. BUSCA PERFIS E REVENDEDORES ---
try {
    $perfis_sistema = $connGeral->query("SELECT id, nome FROM perfil WHERE bloqueado IS NULL OR bloqueado != 'sim' ORDER BY nome ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $perfis_sistema = []; }

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

        // CRIAR E EDITAR - LÓGICA CORRIGIDA
        if ($acao === 'criar' || $acao === 'editar') {
            $user = trim($_POST['usuario']);
            $pass = trim($_POST['senha']);
            $limite = (int)$_POST['limite']; 
            $venc_ts = $_POST['data_premio'] ? strtotime($_POST['data_premio']) : 0;

            if ($acao === 'criar') {
                $check = $connUser->prepare("SELECT id FROM rev WHERE usuario = ?");
                $check->execute([$user]);
                if($check->rowCount() > 0){
                    $msg = "Usuário já existe!"; $msg_tipo = "warning";
                } else {
                    $sql = "INSERT INTO rev (usuario, senha, LimiteUser, data_premio, data_cadastro, CadUser) VALUES (?, ?, ?, ?, NOW(), ?)";
                    $connUser->prepare($sql)->execute([$user, $pass, $limite, $venc_ts, $usuarioLogado]);
                    $id_rev = $connUser->lastInsertId();

                    // MENSAGEM COM LINK DO DOMÍNIO LOGADO
                    $texto_zap = "*🚀 NOVO PAINEL DE REVENDA*\n\n🌐 *Link:* $url_painel\n👤 *User:* $user\n🔑 *Senha:* $pass\n📅 *Expira:* ".($_POST['data_premio'] ? date('d/m/Y', $venc_ts) : '---')."\n💰 *Créditos:* $limite";
                    $msg = "Revendedor criado!"; $msg_tipo = "success";
                }
            } else {
                $sql = "UPDATE rev SET usuario=?, senha=?, LimiteUser=?, data_premio=? WHERE id=? $filtroSeguranca";
                $connUser->prepare($sql)->execute([$user, $pass, $limite, $venc_ts, $id_rev]);
                $msg = "Dados atualizados!"; $msg_tipo = "primary";
            }

            // Sincroniza Perfis Liberados no Banco Geral
            if ($id_rev > 0) {
                $connGeral->prepare("DELETE FROM rev_perfil WHERE id_rev = ?")->execute([$id_rev]);
                if (!empty($_POST['perfis'])) {
                    $stmt_p = $connGeral->prepare("INSERT INTO rev_perfil (id_rev, id_perfil) VALUES (?,?)");
                    foreach ($_POST['perfis'] as $pid) { $stmt_p->execute([$id_rev, (int)$pid]); }
                }
            }
        }

        if ($acao === 'renovar') {
            $qtd = (int)$_POST['qtd_adicionar'];
            $connUser->prepare("UPDATE rev SET LimiteUser = LimiteUser + ? WHERE id=? $filtroSeguranca")->execute([$qtd, $id_rev]);
            $msg = "Créditos adicionados!"; $msg_tipo = "success";
        }

        if ($acao === 'excluir') {
            $connUser->prepare("DELETE FROM rev WHERE id=? $filtroSeguranca")->execute([$id_rev]);
            $connGeral->prepare("DELETE FROM rev_perfil WHERE id_rev=?")->execute([$id_rev]);
            $msg = "Removido!"; $msg_tipo = "danger";
        }
    } catch (Exception $e) { $msg = "Erro: " . $e->getMessage(); $msg_tipo = "danger"; }
}

// --- 3. LISTAGEM COM FILTROS E PAGINAÇÃO ---
$limit_pg = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$pg = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
$offset = ($pg - 1) * $limit_pg;
$busca = trim($_GET['busca'] ?? '');

$where = " WHERE 1=1";
$params = [];
if (!$isAdmin) { $where .= " AND CadUser = :u"; $params[':u'] = $usuarioLogado; }
if ($busca) { $where .= " AND usuario LIKE :b"; $params[':b'] = "%$busca%"; }

$total_reg = $connUser->prepare("SELECT COUNT(*) FROM rev $where");
$total_reg->execute($params);
$total_paginas = ceil($total_reg->fetchColumn() / $limit_pg);

$stmt = $connUser->prepare("SELECT * FROM rev $where ORDER BY id DESC LIMIT $limit_pg OFFSET $offset");
$stmt->execute($params);
$revendas = $stmt->fetchAll();

// --- 4. FUNÇÕES DE RESUMO (A/V) ---
function getStatsRev($usuario, $connUser) {
    $hoje = date('Y-m-d'); $ts = time();
    $sql_a = "SELECT COUNT(*) FROM usuario WHERE CadUser = ? AND ( (data_premio >= '$ts' AND data_premio REGEXP '^[0-9]+$') OR (data_premio >= '$hoje' AND data_premio NOT REGEXP '^[0-9]+$') ) AND bloqueado != 'sim'";
    $st_a = $connUser->prepare($sql_a); $st_a->execute([$usuario]);
    $sql_v = "SELECT COUNT(*) FROM usuario WHERE CadUser = ? AND ( (data_premio < '$ts' AND data_premio REGEXP '^[0-9]+$') OR (data_premio < '$hoje' AND data_premio NOT REGEXP '^[0-9]+$') ) AND bloqueado != 'sim'";
    $st_v = $connUser->prepare($sql_v); $st_v->execute([$usuario]);
    return ['a' => $st_a->fetchColumn(), 'v' => $st_v->fetchColumn()];
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Revendedores | IPTV</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; }
        .sidebar.show { transform: translateX(0); }
        .main-content { margin-left: 260px; padding: 25px; 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.active, .nav-link:hover { 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); }
        @media (max-width: 992px) { .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); } .main-content { margin-left: 0; } .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_email.php" class="nav-link"><i class="fas fa-envelope"></i> Config. E-mail</a>
        <?php endif; ?>
        <div class="nav-group-title">Operacional</div>
        <a href="revendedores.php" class="nav-link active"><i class="fas fa-store"></i> Revendedores</a>
        <a href="clientes.php" class="nav-link"><i class="fas fa-users"></i> Clientes</a>
        <a href="testes.php" class="nav-link"><i class="fas fa-stopwatch"></i> Testes</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 Revendedores</h3>
        <button onclick="new bootstrap.Modal(document.getElementById('modalCriar')).show()" class="btn btn-primary fw-bold px-4"><i class="fas fa-plus me-2"></i>Novo Cadastro</button>
    </div>

    <div class="card card-custom p-3 mb-4">
        <form method="GET" class="row g-2">
            <div class="col-md-7"><input type="text" name="busca" class="form-control" placeholder="Pesquisar Usuário..." value="<?= $busca ?>"></div>
            <div class="col-md-3"><select name="limit" class="form-select"><?php foreach([10,50,100,500,1000,3000,30000] as $o): ?><option value="<?= $o ?>" <?= $limit_pg==$o?'selected':'' ?>><?= $o ?> registros</option><?php endforeach; ?></select></div>
            <div class="col-md-2"><button class="btn btn-primary w-100"><i class="fas fa-search"></i></button></div>
        </form>
    </div>

    <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

    <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-4">Usuário / Dono</th>
                        <th class="text-center">Clientes (A/V)</th>
                        <th>Créditos</th>
                        <th class="text-end pe-4">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($revendas as $r): 
                        $st = getStatsRev($r['usuario'], $connUser);
                        $venc_f = is_numeric($r['data_premio']) && $r['data_premio'] > 0 ? date('d/m/Y', (int)$r['data_premio']) : '---';
                        $venc_inp = is_numeric($r['data_premio']) && $r['data_premio'] > 0 ? date('Y-m-d', (int)$r['data_premio']) : '';
                        
                        $stmt = $connGeral->prepare("SELECT id_perfil FROM rev_perfil WHERE id_rev = ?");
                        $stmt->execute([$r['id']]); $perfis_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
                    ?>
                    <tr>
                        <td class="ps-4"><div class="fw-bold"><?= htmlspecialchars($r['usuario']) ?></div><div class="text-white-50 small">Dono: <span class="text-info"><?= $r['CadUser'] ?></span></div></td>
                        <td class="text-center"><span class="text-success"><?= $st['a'] ?></span> / <span class="text-danger"><?= $st['v'] ?></span></td>
                        <td><span class="badge bg-warning text-dark px-3"><?= $r['LimiteUser'] ?></span></td>
                        <td class="text-end pe-4">
                            <button onclick='abrirVisualizar(<?= json_encode($r) ?>, <?= json_encode($st) ?>, "<?= $venc_f ?>", "<?= $url_painel ?>")' class="btn btn-sm btn-light rounded-circle me-1"><i class="fas fa-eye text-dark"></i></button>
                            <button onclick='abrirRenovar(<?= $r['id'] ?>, "<?= $r['usuario'] ?>")' class="btn btn-sm btn-success rounded-circle me-1"><i class="fas fa-plus"></i></button>
                            <button onclick='abrirEditar(<?= json_encode($r) ?>, "<?= $venc_inp ?>", <?= json_encode($perfis_ids) ?>)' class="btn btn-sm btn-info rounded-circle me-1"><i class="fas fa-pen text-white"></i></button>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Excluir?')"><input type="hidden" name="acao" value="excluir"><input type="hidden" name="id_rev" value="<?= $r['id'] ?>"><button class="btn btn-sm btn-danger rounded-circle"><i class="fas fa-trash"></i></button></form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </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 da Revenda</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body p-4">
                <div class="mb-2"><label class="small text-white-50">Link do Painel:</label><input type="text" readonly class="form-control bg-dark border-info text-info" id="view_link"></div>
                <div class="mb-2"><label class="small text-white-50">Usuário:</label><input type="text" readonly class="form-control bg-dark border-secondary" id="view_user"></div>
                <div class="mb-2"><label class="small text-white-50">Senha:</label><input type="text" readonly class="form-control bg-dark border-secondary" id="view_pass"></div>
                <div class="mb-3"><label class="small text-white-50">Vencimento:</label><input type="text" readonly class="form-control bg-dark border-secondary text-warning" id="view_venc"></div>
                <hr class="border-secondary">
                <div class="row text-center mb-3"><div class="col-6"><h6 class="text-success small">Ativos</h6><h4 id="view_a">0</h4></div><div class="col-6"><h6 class="text-danger small">Vencidos</h6><h4 id="view_v">0</h4></div></div>
                <div class="d-flex gap-2"><button onclick="copiarVisualizar()" class="btn btn-outline-light w-50">COPIAR</button><button onclick="zapVisualizar()" class="btn btn-success w-50">WHATSAPP</button></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalCriar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered"><div class="modal-content bg-dark border-secondary text-white">
        <form method="POST"><input type="hidden" name="acao" value="criar">
            <div class="modal-header border-secondary"><h5>Novo Revendedor</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body p-4">
                <div class="mb-3"><label>Usuário</label><input type="text" name="usuario" class="form-control" required></div>
                <div class="mb-3"><label>Senha</label><input type="text" name="senha" class="form-control" required></div>
                <div class="row"><div class="col-6 mb-3"><label>Limite</label><input type="number" name="limite" class="form-control" value="10"></div><div class="col-6 mb-3"><label>Vencimento</label><input type="date" name="data_premio" class="form-control"></div></div>
                <label class="text-info fw-bold mb-2 small">LIBERAR PERFIS:</label>
                <div style="max-height: 120px; overflow-y: auto;" class="p-2 border border-secondary rounded">
                    <?php foreach($perfis_sistema as $p): ?><div class="form-check"><input class="form-check-input" type="checkbox" name="perfis[]" value="<?= $p['id'] ?>" id="c_<?= $p['id'] ?>"><label class="form-check-label" for="c_<?= $p['id'] ?>"><?= $p['nome'] ?></label></div><?php endforeach; ?>
                </div>
            </div>
            <div class="modal-footer border-secondary"><button type="submit" class="btn btn-primary w-100 fw-bold">CADASTRAR REVENDA</button></div>
        </form>
    </div></div>
</div>

<div class="modal fade" id="modalEditar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered"><div class="modal-content bg-dark border-secondary text-white">
        <form method="POST"><input type="hidden" name="acao" value="editar"><input type="hidden" name="id_rev" id="edit_id">
            <div class="modal-header border-secondary"><h5>Editar Revenda</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <div class="modal-body p-4">
                <div class="mb-3"><label>Usuário</label><input type="text" name="usuario" id="edit_user" class="form-control"></div>
                <div class="mb-3"><label>Senha</label><input type="text" name="senha" id="edit_pass" class="form-control"></div>
                <div class="row"><div class="col-6 mb-3"><label>Limite</label><input type="number" name="limite" id="edit_limite" class="form-control"></div><div class="col-6 mb-3"><label>Vencimento</label><input type="date" name="data_premio" id="edit_venc" class="form-control"></div></div>
                <label class="text-info fw-bold mb-2 small">PERMISSÕES:</label>
                <div style="max-height: 120px; overflow-y: auto;" class="p-2 border border-secondary rounded">
                    <?php foreach($perfis_sistema as $p): ?><div class="form-check"><input class="form-check-input chk-edit" type="checkbox" name="perfis[]" value="<?= $p['id'] ?>" id="e_<?= $p['id'] ?>"><label class="form-check-label" for="e_<?= $p['id'] ?>"><?= $p['nome'] ?></label></div><?php endforeach; ?>
                </div>
            </div>
            <div class="modal-footer border-secondary"><button type="submit" class="btn btn-info w-100 fw-bold">SALVAR ALTERAÇÕES</button></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">Revenda Criada!</h5>
        <textarea id="textoZapArea" class="form-control mb-3" rows="8" style="background:#111; color:#0f0; border:none; font-family:monospace;"><?= $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(r, st, venc, url) {
        document.getElementById('view_link').value = url; document.getElementById('view_user').value = r.usuario;
        document.getElementById('view_pass').value = r.senha; document.getElementById('view_venc').value = venc;
        document.getElementById('view_a').innerText = st.a; document.getElementById('view_v').innerText = st.v;
        new bootstrap.Modal(document.getElementById('modalVerDados')).show();
    }
    function copiarVisualizar() { const m = `🌐 Link: ${document.getElementById('view_link').value}\n👤 User: ${document.getElementById('view_user').value}\n🔑 Senha: ${document.getElementById('view_pass').value}\n📅 Expira: ${document.getElementById('view_venc').value}`; navigator.clipboard.writeText(m).then(() => alert("Copiado!")); }
    function zapVisualizar() { const m = `🌐 *Link:* ${document.getElementById('view_link').value}\n👤 *User:* ${document.getElementById('view_user').value}\n🔑 *Senha:* ${document.getElementById('view_pass').value}\n📅 *Expira:* ${document.getElementById('view_venc').value}`; window.open("https://api.whatsapp.com/send?text=" + encodeURIComponent(m), '_blank'); }
    
    function abrirRenovar(id, user) { /* Implementar modalRenovar conforme anterior */ }
    
    function abrirEditar(r, venc, perfis) {
        document.getElementById('edit_id').value = r.id; document.getElementById('edit_user').value = r.usuario;
        document.getElementById('edit_pass').value = r.senha; document.getElementById('edit_limite').value = r.LimiteUser;
        document.getElementById('edit_venc').value = venc;
        document.querySelectorAll('.chk-edit').forEach(el => el.checked = false);
        if(perfis) perfis.forEach(pid => { let c = document.getElementById('e_' + pid); if(c) c.checked = true; });
        new bootstrap.Modal(document.getElementById('modalEditar')).show();
    }

    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>
