<?php
session_start();
// Apenas Admin tem acesso
if (!isset($_SESSION['logado']) || $_SESSION['nivel'] !== 'admin') { 
    header("Location: index.php"); 
    exit; 
}
require_once 'conexao.php'; 

$msg = "";
$msg_tipo = "";

// --- 1. BUSCA CONFIGURAÇÕES DO SITE (NOME E COR) ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf) {
        if (!empty($conf['NomePainel'])) $nomePainel = $conf['NomePainel'];
        if (!empty($conf['TemaPainel'])) $corPrimaria = $conf['TemaPainel'];
    }
} catch (Exception $e) { }

// --- 2. PROCESSAMENTO DE AÇÕES (CRUD) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $acao = $_POST['acao'];
        $id   = $_POST['id'] ?? 0;

        if ($acao === 'criar' || $acao === 'editar') {
            $nome     = $_POST['nome'] ?? '';
            $painel_id= $_POST['painel'] ?? 0;
            $valorcsp = $_POST['valorcsp'] ?? '';
            $url      = $_POST['url'] ?? '';
            $porta    = $_POST['porta'] ?? '';
            $tipo     = $_POST['tipo'] ?? '';
            $imagem   = $_POST['imagem'] ?? 0;

            if ($acao === 'criar') {
                $sql = "INSERT INTO perfil (painel, imagem, nome, valorcsp, url, porta, tipo, bloqueado) VALUES (?, ?, ?, ?, ?, ?, ?, 'nao')";
                $connGeral->prepare($sql)->execute([$painel_id, $imagem, $nome, $valorcsp, $url, $porta, $tipo]);
                $msg = "Perfil criado!"; $msg_tipo = "success";
            } else {
                $sql = "UPDATE perfil SET painel=?, imagem=?, nome=?, valorcsp=?, url=?, porta=?, tipo=? WHERE id=?";
                $connGeral->prepare($sql)->execute([$painel_id, $imagem, $nome, $valorcsp, $url, $porta, $tipo, $id]);
                $msg = "Perfil atualizado!"; $msg_tipo = "primary";
            }
        }

        if ($acao === 'toggle_block') {
            $curr = $connGeral->query("SELECT bloqueado FROM perfil WHERE id=$id")->fetchColumn();
            $novo = ($curr == 'sim') ? 'nao' : 'sim';
            $connGeral->prepare("UPDATE perfil SET bloqueado=? WHERE id=?")->execute([$novo, $id]);
            $msg = "Status alterado!"; $msg_tipo = "warning";
        }

        if ($acao === 'excluir') {
            $connGeral->prepare("DELETE FROM perfil WHERE id=?")->execute([$id]);
            $msg = "Perfil excluído!"; $msg_tipo = "danger";
        }
    } catch (PDOException $e) { $msg = "Erro: " . $e->getMessage(); $msg_tipo = "danger"; }
}

// --- 3. BUSCAS PARA LISTAGEM ---
$perfis = $connGeral->query("SELECT p.*, pn.nome as nome_painel FROM perfil p LEFT JOIN painel pn ON p.painel = pn.id ORDER BY p.id DESC")->fetchAll(PDO::FETCH_ASSOC);
$paineis = $connGeral->query("SELECT id, nome FROM painel")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar Perfis | <?= htmlspecialchars($nomePainel) ?></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: <?= $corPrimaria ?>; --bg-body: #151521; --bg-card: #1e1e2d; --text-color: #d0d2d6; --border-color: #2b2b40; }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; }
        
        /* Sidebar */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid #333; z-index: 1050; padding: 20px; overflow-y: auto; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 12px 15px; border-radius: 8px; display: flex; align-items: center; gap: 12px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        /* Main Content */
        .main-content { margin-left: 260px; transition: 0.3s; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--primary) 100%); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; }

        .card-custom { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; overflow: hidden; }
        .form-control, .form-select { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; }
        
        @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; color: #fff; font-size: 1.5rem; background: none; border: none; margin-right: 15px; }
        .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">
    <div class="text-center mb-4"><h4 class="fw-bold text-white"><?= htmlspecialchars($nomePainel) ?></h4></div>
    <div class="nav flex-column">
        <a href="index.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
        
        <div class="nav-group-title">ADMINISTRATIVO</div>
        <a href="gerenciar_perfis.php" class="nav-link active"><i class="fas fa-layer-group"></i> 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> Admins</a>
        <a href="personalizar_painel.php" class="nav-link"><i class="fas fa-paint-brush"></i> Personalizar</a>
        <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Configurações</a>
        <a href="gerenciar_ips.php" class="nav-link"><i class="fas fa-shield-halved"></i> Firewall IPs</a>
        <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backup</a>

        <div class="nav-group-title">MENU</div>
        <a href="revendedores.php" class="nav-link"><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>
        <a href="monitor.php" class="nav-link"><i class="fas fa-wifi"></i> Monitor Online</a>
        <a href="config_mp_revenda.php" class="nav-link"><i class="fas fa-wallet"></i> Pagamento</a>
        <a href="gerenciar_planos.php" class="nav-link"><i class="fas fa-tags"></i> Planos</a>
        <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> SMTP Email</a>
        <a href="gerador_robo.php" class="nav-link"><i class="fas fa-robot"></i> WhatsAuto</a>
        
        <a href="sair.php" class="nav-link text-danger mt-4"><i class="fas fa-sign-out-alt"></i> Sair</a>
    </div>
</nav>

<main class="main-content">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title">Gerenciar Perfis</div>
        </div>
        <button class="btn btn-light btn-sm fw-bold px-3 rounded-pill" data-bs-toggle="modal" data-bs-target="#modalCriar">
            <i class="fas fa-plus me-1"></i> NOVO PERFIL
        </button>
    </div>

    <div class="container-fluid p-3 p-md-4">
        <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="card card-custom shadow-lg">
            <div class="table-responsive">
                <table class="table table-dark table-hover mb-0 align-middle">
                    <thead>
                        <tr class="text-muted small text-uppercase">
                            <th class="ps-4">Nome</th>
                            <th>Servidor</th>
                            <th>Valor CSP</th> 
                            <th>URL / DNS</th>
                            <th>Porta</th>
                            <th>Status</th>
                            <th class="text-end pe-4">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($perfis as $p): 
                            $is_block = ($p['bloqueado'] == 'sim');
                        ?>
                        <tr>
                            <td class="ps-4 fw-bold text-white"><?= htmlspecialchars($p['nome']) ?></td>
                            <td><span class="badge bg-dark"><?= htmlspecialchars($p['nome_painel'] ?? 'Desconhecido') ?></span></td>
                            <td><code class="text-info fw-bold"><?= htmlspecialchars($p['valorcsp']) ?></code></td>
                            <td class="small"><?= htmlspecialchars($p['url']) ?></td>
                            <td><span class="text-warning fw-bold"><?= htmlspecialchars($p['porta']) ?></span></td>
                            <td><?= $is_block ? '<span class="badge bg-danger">Bloqueado</span>' : '<span class="badge bg-success">Ativo</span>' ?></td>
                            <td class="text-end pe-4">
                                <div class="btn-group">
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                        <input type="hidden" name="acao" value="toggle_block">
                                        <button class="btn btn-sm btn-outline-<?= $is_block ? 'success' : 'warning' ?> border-0">
                                            <i class="fas <?= $is_block ? 'fa-lock-open' : 'fa-lock' ?>"></i>
                                        </button>
                                    </form>
                                    <button class="btn btn-sm btn-outline-info border-0" onclick='abrirEditar(<?= json_encode($p) ?>)'>
                                        <i class="fas fa-pen"></i>
                                    </button>
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                        <input type="hidden" name="acao" value="excluir">
                                        <button class="btn btn-sm btn-outline-danger border-0" onclick="return confirm('Excluir?')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="modalCriar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content bg-dark border-secondary">
            <form method="POST" id="formPerfil">
                <input type="hidden" name="acao" value="criar" id="inputAcao">
                <input type="hidden" name="id" id="inputId">
                <div class="modal-header border-secondary text-white">
                    <h5 class="modal-title fw-bold" id="modalTitulo">Adicionar Perfil</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3"><label class="form-label text-white-50 small">Nome do Perfil</label><input type="text" name="nome" id="nome" class="form-control" required></div>
                        <div class="col-md-6 mb-3"><label class="form-label text-white-50 small">Servidor Vinculado</label><select name="painel" id="painel" class="form-select" required><option value="">Selecione...</option><?php foreach($paineis as $pn): ?><option value="<?= $pn['id'] ?>"><?= $pn['nome'] ?></option><?php endforeach; ?></select></div>
                    </div>
                    <div class="row">
                        <div class="col-md-8 mb-3"><label class="form-label text-white-50 small">URL do Perfil</label><input type="text" name="url" id="url" class="form-control" required></div>
                        <div class="col-md-4 mb-3"><label class="form-label text-white-50 small">Porta</label><input type="number" name="porta" id="porta" class="form-control" required></div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3"><label class="form-label text-white-50 small">Valor CSP</label><input type="text" name="valorcsp" id="valorcsp" class="form-control"></div>
                        <div class="col-md-4 mb-3"><label class="form-label text-white-50 small">Tipo (SAT/CABO)</label><input type="text" name="tipo" id="tipo" class="form-control"></div>
                        <div class="col-md-4 mb-3"><label class="form-label text-white-50 small">ID Imagem</label><input type="number" name="imagem" id="imagem" class="form-control" value="1"></div>
                    </div>
                </div>
                <div class="modal-footer border-secondary">
                    <button type="submit" class="btn btn-primary w-100 fw-bold py-2">SALVAR PERFIL</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 toggleMenu() { 
        document.getElementById('sidebar').classList.toggle('show'); 
        document.getElementById('overlay').classList.toggle('show'); 
    }
    
    function abrirEditar(p) {
        document.getElementById('inputAcao').value = 'editar'; 
        document.getElementById('inputId').value = p.id;
        document.getElementById('modalTitulo').innerText = 'Editar Perfil';
        document.getElementById('nome').value = p.nome; 
        document.getElementById('painel').value = p.painel;
        document.getElementById('url').value = p.url; 
        document.getElementById('porta').value = p.porta;
        document.getElementById('valorcsp').value = p.valorcsp; 
        document.getElementById('tipo').value = p.tipo;
        document.getElementById('imagem').value = p.imagem; 
        new bootstrap.Modal(document.getElementById('modalCriar')).show();
    }
</script>
</body>
</html>