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

require_once 'conexao.php';

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

// --- 1. CONFIGURAÇÃO DE PAGINAÇÃO E BUSCA ---
$limite_pg = 10;
$pg = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
if ($pg < 1) $pg = 1;
$offset = ($pg - 1) * $limite_pg;
$busca = trim($_GET['busca'] ?? '');

// --- 2. BUSCA PERFIS DO SISTEMA (Banco Geral) ---
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 = []; }

// --- 3. 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'";

        if ($acao === 'criar' || $acao === 'editar') {
            $user = trim($_POST['usuario']);
            $pass = trim($_POST['senha']);
            $limite = (int)$_POST['limite']; 
            $venc_input = $_POST['data_premio'];
            $vencimento = $venc_input ? strtotime($venc_input) : "";

            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 {
                    // CadUser salva quem criou (permite sub-revenda)
                    $sql = "INSERT INTO rev (usuario, senha, LimiteUser, data_premio, data_cadastro, CadUser) VALUES (?, ?, ?, ?, NOW(), ?)";
                    $connUser->prepare($sql)->execute([$user, $pass, $limite, $vencimento, $usuarioLogado]);
                    $id_rev = $connUser->lastInsertId();

                    // Gera mensagem personalizada
                    $link = "http://" . $_SERVER['HTTP_HOST'] . "/painel";
                    $data_f = $venc_input ? date('d/m/Y', strtotime($venc_input)) : "---";
                    $texto_zap = "*🚀 NOVO PAINEL DE REVENDA*\n\n🌐 *Link:* $link\n👤 *User:* $user\n🔑 *Senha:* $pass\n📅 *Vencimento:* $data_f";
                    $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, $vencimento, $id_rev]);
                $msg = "Dados atualizados!"; $msg_tipo = "primary";
            }

            // Atualiza Permissões 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, $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"; }
}

// --- 4. LISTAGEM COM FILTRO DE HIERARQUIA ---
$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 = $connUser->prepare("SELECT COUNT(*) FROM rev $where"); $total->execute($params);
$total_paginas = ceil($total->fetchColumn() / $limite_pg);

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

function getBadgesPerfis($id_rev, $connGeral) {
    try {
        $stmt = $connGeral->prepare("SELECT p.nome FROM rev_perfil rp JOIN perfil p ON rp.id_perfil = p.id WHERE rp.id_rev = ?");
        $stmt->execute([$id_rev]);
        $nomes = $stmt->fetchAll(PDO::FETCH_COLUMN);
        if (empty($nomes)) return '<span class="text-white-50 small">Nenhum</span>';
        $h = '<div class="d-flex flex-wrap gap-1" style="max-width:250px">';
        foreach ($nomes as $n) { $h .= "<span class='badge bg-primary' style='font-size:0.6rem'>$n</span>"; }
        return $h . '</div>';
    } catch (Exception $e) { return "---"; }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Revendedores | Painel 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>
        body { background: #151521; color: #fff; font-family: 'Segoe UI', sans-serif; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: #1e1e2d; padding: 20px; border-right: 1px solid #333; z-index: 1000; transition: 0.3s; }
        .main-content { margin-left: 260px; padding: 25px; transition: 0.3s; }
        .card-custom { background: #1e1e2d; border: 1px solid #333; border-radius: 12px; }
        .form-control, .form-select { background: #2b2b40; border: 1px solid #444; color: #fff; }
        .table-dark { background: #1e1e2d; --bs-table-bg: #1e1e2d; }
        .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; } .mobile-toggle { display: block !important; } }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; margin-bottom: 20px; }
    </style>
</head>
<body>

<nav class="sidebar" id="sidebar">
    <h4 class="mb-5 fw-bold text-primary"><i class="fas fa-tv me-2"></i>IPTV PANEL</h4>
    <div class="nav flex-column gap-2">
        <a href="index.php" class="btn btn-dark text-start border-0 py-2"><i class="fas fa-home me-2"></i> Dashboard</a>
        <a href="revendedores.php" class="btn btn-primary text-start border-0 py-2"><i class="fas fa-store me-2"></i> Revendedores</a>
        <a href="clientes.php" class="btn btn-dark text-start border-0 py-2"><i class="fas fa-users me-2"></i> Clientes</a>
    </div>
</nav>

<main class="main-content">
    <button class="mobile-toggle" onclick="document.getElementById('sidebar').classList.toggle('show')"><i class="fas fa-bars"></i></button>

    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-3">
        <h3 class="fw-bold m-0">Gestão de Revendedores</h3>
        <button onclick="new bootstrap.Modal(document.getElementById('modalCriar')).show()" class="btn btn-primary fw-bold"><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-10"><input type="text" name="busca" class="form-control" placeholder="Pesquisar por usuário..." value="<?= htmlspecialchars($busca) ?>"></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</th>
                        <th>Limite</th>
                        <th>Vencimento</th>
                        <th>Perfis</th>
                        <th class="text-end pe-4">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($revendas as $r): 
                        $limite = $r['LimiteUser'] ?? 0;
                        $venc = is_numeric($r['data_premio']) ? date('d/m/Y', (int)$r['data_premio']) : '---';
                        $venc_inp = is_numeric($r['data_premio']) ? 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 fw-bold"><?= htmlspecialchars($r['usuario']) ?></td>
                        <td><span class="badge bg-warning text-dark px-3"><?= $limite ?></span></td>
                        <td class="text-info"><?= $venc ?></td>
                        <td><?= getBadgesPerfis($r['id'], $connGeral) ?></td>
                        <td class="text-end pe-4">
                            <button class="btn btn-sm btn-success rounded-circle me-1" onclick='abrirRenovar(<?= $r['id'] ?>, "<?= $r['usuario'] ?>")'><i class="fas fa-plus"></i></button>
                            <button class="btn btn-sm btn-info rounded-circle me-1" onclick='abrirEditar(<?= json_encode($r) ?>, "<?= $venc_inp ?>", <?= json_encode($perfis_ids) ?>)'><i class="fas fa-pen text-white"></i></button>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Excluir este revendedor?')">
                                <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>
        
        <?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==$pg?'active':'' ?>"><a class="page-link" href="?pagina=<?= $i ?>&busca=<?= $busca ?>"><?= $i ?></a></li>
            <?php endfor; ?>
        </ul></nav>
        <?php endif; ?>
    </div>
</main>

<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>
                <div class="d-flex justify-content-center gap-2">
                    <button onclick="copiarTexto()" class="btn btn-outline-light px-4">Copiar</button>
                    <button onclick="enviarZap()" class="btn btn-success px-4">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 class="modal-title">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: 150px; 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="p_<?= $p['id'] ?>"><label class="form-check-label" for="p_<?= $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</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 class="modal-title">Editar Cadastro</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" required></div>
                    <div class="mb-3"><label>Senha</label><input type="text" name="senha" id="edit_pass" class="form-control" required></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: 150px; 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="ed_p_<?= $p['id'] ?>"><label class="form-check-label" for="ed_p_<?= $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 text-white">SALVAR</button></div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalRenovar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-sm text-center">
        <div class="modal-content bg-dark border-secondary text-white">
            <form method="POST">
                <input type="hidden" name="acao" value="renovar"><input type="hidden" name="id_rev" id="renov_id">
                <div class="modal-header border-secondary"><h5>Adicionar Créditos</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
                <div class="modal-body p-4">
                    <h5 id="renov_user" class="text-primary fw-bold mb-3"></h5>
                    <input type="number" name="qtd_adicionar" class="form-control text-center fs-3 fw-bold" value="10">
                </div>
                <div class="modal-footer border-secondary"><button type="submit" class="btn btn-success w-100 fw-bold">ADICIONAR</button></div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function abrirRenovar(id, user) { document.getElementById('renov_id').value = id; document.getElementById('renov_user').innerText = user; new bootstrap.Modal(document.getElementById('modalRenovar')).show(); }
    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 || 0;
        document.getElementById('edit_venc').value = venc;
        document.querySelectorAll('.chk-edit').forEach(el => el.checked = false);
        if(perfis) { perfis.forEach(pid => { let chk = document.getElementById('ed_p_' + pid); if(chk) chk.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>
