<?php
include('api/conexao_rev.php'); 

// 1. LÓGICA PARA CADASTRAR
if(isset($_POST['cadastrar_rev'])){
    $user_new = $_POST['login_rev'];
    $pass_new = password_hash($_POST['senha_rev'], PASSWORD_DEFAULT); 
    $nivel_new = $_POST['nivel_rev']; 
    $sql_cad = "INSERT INTO dados_rev (login_rev, senha_rev, creditos_rev, nivel_rev) VALUES ('$user_new', '$pass_new', 0, '$nivel_new')";
    if($conn_rev->query($sql_cad)){
        header("Location: gerenciar_rev.php?status=cadastro");
        exit();
    }
}

// 2. LÓGICA PARA ADICIONAR CRÉDITOS
if(isset($_POST['add_credito_rev'])){
    $id = $_POST['id_rev'];
    $qtd = $_POST['quantidade'];
    if($conn_rev->query("UPDATE dados_rev SET creditos_rev = creditos_rev + $qtd WHERE id_rev = $id")){
        header("Location: gerenciar_rev.php?status=credito");
        exit();
    }
}

// 3. LÓGICA PARA EXCLUIR
if(isset($_GET['excluir_confirmado'])){
    $id_excluir = $_GET['excluir_confirmado'];
    if($conn_rev->query("DELETE FROM dados_rev WHERE id_rev = $id_excluir")){
        header("Location: gerenciar_rev.php?status=excluido");
        exit();
    }
}

// Captura o status da URL
$msg_status = isset($_GET['status']) ? $_GET['status'] : "";
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin | Gerenciar Revendas</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        html, body { background-color: #020617 !important; color: #e2e8f0 !important; font-family: 'Inter', sans-serif; margin: 0; padding: 0; }
        .container { padding: 15px; max-width: 800px; margin: 0 auto; }
        
        .btn-voltar { color: #3b82f6; text-decoration: none; font-size: 0.8rem; font-weight: 800; text-transform: uppercase; display: flex; align-items: center; gap: 5px; margin-bottom: 15px; transition: 0.3s; }
        .btn-voltar:hover { opacity: 0.7; }

        .premium-header { background: linear-gradient(135deg, #0f172a 0%, #020617 100%); padding: 25px 20px; border-radius: 20px; border: 1px solid #1e293b; margin-bottom: 25px; box-shadow: 0 10px 25px rgba(0,0,0,0.3); }
        .welcome-text h1 { font-size: 1.4rem; font-weight: 800; color: #fff; margin: 0; }
        .welcome-text p { color: #3b82f6; font-size: 0.8rem; font-weight: 700; text-transform: uppercase; margin-top: 5px; }
        .card-premium { background: #070e1b; border: 1px solid #1e293b; border-radius: 18px; padding: 20px; margin-bottom: 25px; }
        .section-label { color: #3b82f6; font-size: 0.75rem; font-weight: 800; text-transform: uppercase; margin-bottom: 15px; display: block; }
        
        input, select { width: 100%; background: #0f172a; border: 1px solid #1e293b; border-radius: 12px; padding: 12px; margin-bottom: 12px; color: #fff; outline: none; box-sizing: border-box; appearance: none; }
        
        .btn-blue { width: 100%; background: #3b82f6; color: #fff; border: none; padding: 14px; border-radius: 12px; font-weight: 800; cursor: pointer; transition: 0.3s; }
        .rev-card { background: #0f172a; border: 1px solid #1e293b; border-radius: 15px; padding: 15px; margin-bottom: 15px; }
        .rev-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
        .rev-name { font-weight: 800; color: #fff; font-size: 1rem; display: flex; align-items: center; gap: 8px; }
        .rev-creds { color: #22c55e; font-weight: 800; font-size: 0.9rem; }
        
        .badge-master { background: rgba(241, 196, 15, 0.1); color: #f1c40f; font-size: 0.6rem; padding: 3px 8px; border-radius: 5px; border: 1px solid rgba(241, 196, 15, 0.2); }
        .badge-comum { background: rgba(100, 116, 139, 0.1); color: #64748b; font-size: 0.6rem; padding: 3px 8px; border-radius: 5px; border: 1px solid rgba(100, 116, 139, 0.2); }

        .add-creds-box { display: flex; gap: 10px; margin-top: 10px; padding-top: 10px; border-top: 1px solid rgba(255,255,255,0.05); }
        .btn-add { background: rgba(34, 197, 94, 0.1); color: #22c55e; border: 1px solid rgba(34, 197, 94, 0.2); padding: 8px 15px; border-radius: 8px; font-size: 0.75rem; font-weight: 800; cursor: pointer; }
        .btn-del { background: rgba(239, 68, 68, 0.1); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.2); padding: 8px; border-radius: 8px; text-decoration: none; font-size: 0.75rem; cursor: pointer; }
        
        .swal2-popup { background: #0f172a !important; color: #fff !important; border: 1px solid #1e293b !important; border-radius: 20px !important; }
        .swal2-title { color: #fff !important; }
        .swal2-html-container { color: #64748b !important; }

        .id-label { background: #1e293b; color: #3b82f6; font-size: 0.65rem; padding: 2px 5px; border-radius: 4px; font-weight: 900; margin-right: 5px; }
    </style>
</head>
<body>

<div class="container">
    <a href="index.php" class="btn-voltar">
        <i class="fas fa-arrow-left"></i> Voltar ao Painel
    </a>

    <div class="premium-header">
        <div class="welcome-text">
            <h1>Controle de Revendas</h1>
            <p><i class="fas fa-user-shield"></i> Administrador</p>
        </div>
    </div>

    <div class="card-premium">
        <span class="section-label">Criar Novo Acesso</span>
        <form method="POST">
            <input type="text" name="login_rev" placeholder="Login do Revendedor" required>
            <input type="password" name="senha_rev" placeholder="Senha de Acesso" required>
            
            <select name="nivel_rev" required>
                <option value="1">REVENDA COMUM</option>
                <option value="2">REVENDA MASTER (Cria Sub-Revendas)</option>
            </select>

            <button type="submit" name="cadastrar_rev" class="btn-blue">CRIAR REVENDA</button>
        </form>
    </div>

    <span class="section-label">Revendedores Ativos</span>

    <?php
    $buscar = $conn_rev->query("SELECT * FROM dados_rev ORDER BY id_rev DESC");
    while($item = $buscar->fetch_assoc()){
        ?>
        <div class="rev-card">
            <div class="rev-header">
                <div class="rev-name">
                    <span class="id-label">#<?php echo $item['id_rev']; ?></span>
                    <i class="fas fa-user-tie" style="color:#3b82f6"></i> 
                    <?php echo $item['login_rev']; ?>
                    <?php if($item['nivel_rev'] == 2): ?>
                        <span class="badge-master"><i class="fas fa-crown"></i> MASTER</span>
                    <?php else: ?>
                        <span class="badge-comum">COMUM</span>
                    <?php endif; ?>
                </div>
                <div class="rev-creds"><?php echo $item['creditos_rev']; ?> Créditos</div>
            </div>
            
            <form method="POST" class="add-creds-box">
                <input type="hidden" name="id_rev" value="<?php echo $item['id_rev']; ?>">
                <input type="number" name="quantidade" placeholder="0" style="margin-bottom:0; flex:1; padding:8px;" required>
                <button type="submit" name="add_credito_rev" class="btn-add">ADD CRÉDITOS</button>
                <a onclick="confirmarExclusao(<?php echo $item['id_rev']; ?>, '<?php echo $item['login_rev']; ?>')" class="btn-del"><i class="fas fa-trash"></i></a>
            </form>
        </div>
        <?php
    }
    ?>
</div>

<script>
function confirmarExclusao(id, nome) {
    Swal.fire({
        title: 'Excluir Revenda?',
        text: "O acesso de " + nome + " será removido permanentemente!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#1e293b',
        confirmButtonText: 'Sim, excluir!',
        cancelButtonText: 'Cancelar',
        background: '#0f172a'
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = 'gerenciar_rev.php?excluir_confirmado=' + id;
        }
    })
}

// Lógica de Pop-ups baseada na URL limpa
const urlParams = new URLSearchParams(window.location.search);
const status = urlParams.get('status');

if (status === 'cadastro') {
    Swal.fire({ icon: 'success', title: 'Revenda Criada!', text: 'O novo acesso já está ativo.', timer: 2000, showConfirmButton: false });
} else if (status === 'credito') {
    Swal.fire({ icon: 'success', title: 'Créditos Adicionados!', text: 'O saldo foi atualizado com sucesso.', timer: 2000, showConfirmButton: false });
} else if (status === 'excluido') {
    Swal.fire({ icon: 'success', title: 'Removido!', text: 'A revenda foi excluída do sistema.', timer: 2000, showConfirmButton: false });
}
</script>

</body>
</html>
