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

$isAdmin = (strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'];

// --- 1. BUSCA CONFIGURAÇÕES DO SITE (NOME E COR) ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config WHERE id=1 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) { }

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

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

        if ($acao === 'criar') {
            $sql = "INSERT INTO mascaraurl (CadUser, perfil, nome, url, porta, bloqueado) VALUES (?, ?, ?, ?, ?, 'nao')";
            $connGeral->prepare($sql)->execute([$usuarioLogado, $perfil, $nome, $url, $porta]);
            $msg = "Máscara <b>$nome</b> criada com sucesso!"; $msg_tipo = "success";
        }
        if ($acao === 'editar') {
            $sql = "UPDATE mascaraurl SET perfil=?, nome=?, url=?, porta=? WHERE id=? $filtroSeguranca";
            $connGeral->prepare($sql)->execute([$perfil, $nome, $url, $porta, $id]);
            $msg = "Máscara atualizada com sucesso!"; $msg_tipo = "primary";
        }
        if ($acao === 'toggle_block') {
            $curr = $connGeral->query("SELECT bloqueado FROM mascaraurl WHERE id=$id $filtroSeguranca")->fetchColumn();
            if ($curr !== false) {
                $novo = ($curr == 'sim') ? 'nao' : 'sim';
                $connGeral->prepare("UPDATE mascaraurl SET bloqueado=? WHERE id=?")->execute([$novo, $id]);
                $msg = "Status da máscara alterado!"; $msg_tipo = "warning";
            }
        }
        if ($acao === 'excluir') {
            $connGeral->prepare("DELETE FROM mascaraurl WHERE id=? $filtroSeguranca")->execute([$id]);
            $msg = "Máscara removida!"; $msg_tipo = "danger";
        }
    } catch (PDOException $e) { $msg = "Erro: " . $e->getMessage(); $msg_tipo = "danger"; }
}

// --- 3. BUSCAS ---
// Busca máscaras vinculando com o nome do Perfil e separando por usuário logado
$whereLista = $isAdmin ? "" : " WHERE m.CadUser = '$usuarioLogado'";
$sql_lista = "SELECT m.*, p.nome as nome_perfil 
              FROM mascaraurl m 
              LEFT JOIN perfil p ON m.perfil = p.id 
              $whereLista
              ORDER BY m.id DESC";
$mascaras = $connGeral->query($sql_lista)->fetchAll(PDO::FETCH_ASSOC);

// Busca perfis ativos para o select do modal (Revendedor vê só o que pode vender)
$perfis_ativos = [];
if ($isAdmin) {
    $perfis_ativos = $connGeral->query("SELECT id, nome FROM perfil WHERE (bloqueado IS NULL OR bloqueado != 'sim') ORDER BY nome ASC")->fetchAll(PDO::FETCH_ASSOC);
} else {
    $st_rev = $connUser->prepare("SELECT perfil FROM rev WHERE usuario = ? LIMIT 1");
    $st_rev->execute([$usuarioLogado]);
    $perfil_liberado = $st_rev->fetchColumn();
    
    if (!empty($perfil_liberado)) {
        $nomes = explode(',', $perfil_liberado);
        $in_query = str_repeat('?,', count($nomes) - 1) . '?';
        $st_p = $connGeral->prepare("SELECT id, nome FROM perfil WHERE (bloqueado IS NULL OR bloqueado != 'sim') AND nome IN ($in_query) ORDER BY nome ASC");
        $st_p->execute($nomes);
        $perfis_ativos = $st_p->fetchAll(PDO::FETCH_ASSOC);
    }
}

// Para o sistema do topo
$total_msg_nao_lidas = 0;
try {
    $stmtMsg = $connUser->prepare("SELECT COUNT(*) FROM chamados_suporte WHERE destinatario = ? AND lida = 'nao'");
    $stmtMsg->execute([$usuarioLogado]);
    $total_msg_nao_lidas = $stmtMsg->fetchColumn();
} catch (Exception $e) { } 
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>

<?php include 'tema_global.php'; ?>

    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>MÁSCARAS | <?= 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;
            --overlay-desk: rgba(0, 0, 0, 0.65); 
            --overlay-mob: rgba(0, 0, 0, 0.85); 
        }
        body.light-mode { 
            --bg-body: #f4f5f8; 
            --bg-card: #ffffff; 
            --text-color: #5e5873; 
            --border-color: #ebe9f1; 
            --overlay-desk: rgba(255, 255, 255, 0.1); 
            --overlay-mob: rgba(255, 255, 255, 0); 
        }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; padding: 0; }
        
        /* Sidebar Premium */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid var(--border-color); z-index: 1050; padding: 20px; overflow-y: auto; transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .sidebar .nav-link { white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; color: #a6a6b7; padding: 12px 15px; border-radius: 8px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .sidebar .nav-link i.fa-fw { margin-right: 8px; text-align: center; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        /* Layout Flexbox para forçar Rodapé no Final */
        .main-content { margin-left: 260px; transition: 0.3s; display: flex; flex-direction: column; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--overlay-desk) 100%), var(--primary); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.3);}
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; margin: 0; }

        /* Tabela Dinâmica que respeita Tema Claro/Escuro */
        .card-custom { background-color: var(--bg-card) !important; border: 1px solid var(--border-color) !important; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .table-responsive { background: transparent !important; }
        .table-custom { width: 100%; margin-bottom: 0; border-collapse: separate; border-spacing: 0; background: transparent !important; }
        .table-custom th { background-color: rgba(0,0,0,0.02) !important; border-bottom: 1px solid var(--border-color) !important; color: #a6a6b7 !important; font-size: 0.8rem; text-transform: uppercase; font-weight: 700; padding: 15px; white-space: nowrap; }
        .table-custom td { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: var(--text-color) !important; vertical-align: middle; padding: 15px; font-size: 0.95rem; white-space: nowrap; }
        .table-custom tbody tr:hover td { background-color: rgba(115, 103, 240, 0.05) !important; }
        
        .label-visivel { color: var(--text-color) !important; font-weight: 700; text-transform: uppercase; font-size: 0.75rem; opacity: 0.7;}
        .nome-destaque { color: var(--text-color) !important; font-weight: 700; }
        
        .btn-sq { width: 32px; height: 32px; border-radius: 6px; border: none; color: #fff !important; display: inline-flex; align-items: center; justify-content: center; transition: 0.2s; box-shadow: 0 2px 4px rgba(0,0,0,0.3); }
        .btn-sq:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.4); }
        .bg-sq-blue { background-color: #00cfe8 !important; } 
        .bg-sq-purple { background-color: #7367f0 !important; } 
        .bg-sq-orange { background-color: #ff9f43 !important; } 
        .bg-sq-red { background-color: #ea5455 !important; }

        .status-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 6px; }
        .online { background-color: #28c76f; box-shadow: 0 0 8px #28c76f; }
        .offline { background-color: #ea5455; box-shadow: 0 0 8px #ea5455; }

        /* Inputs Customizados Dinâmicos */
        .form-control, .form-select { background-color: rgba(0,0,0,0.1) !important; border: 1px solid var(--border-color) !important; color: var(--text-color) !important; border-radius: 8px; padding: 10px 15px; transition: 0.2s; }
        body.light-mode .form-control, body.light-mode .form-select { background-color: rgba(0,0,0,0.03) !important; }
        .form-control:focus, .form-select:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 0.25rem rgba(115, 103, 240, 0.25) !important; background-color: transparent !important;}

        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); box-shadow: none; z-index: 1050; } 
            .sidebar.show { transform: translateX(0); box-shadow: 5px 0 30px rgba(0,0,0,0.9); } 
            .main-content { margin-left: 0; width: 100%;}
            .mobile-toggle { display: block !important; margin-right: 15px; } 
            .top-header { flex-direction: row; padding: 15px 20px; background: linear-gradient(var(--overlay-mob), var(--overlay-mob)), var(--primary); border-bottom: none; }
        }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; z-index: 9999; cursor: pointer; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 1040; backdrop-filter: blur(3px); }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>
<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<main class="main-content d-flex flex-column min-vh-100">
    <div class="top-header">
        <div class="d-flex align-items-center w-100">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title"><i class="fas fa-mask me-2 text-warning"></i> Máscaras URL</div>
        </div>
        <button class="btn btn-light fw-bold px-4 shadow-sm rounded-pill mt-3 mt-lg-0" data-bs-toggle="modal" data-bs-target="#modalCriar" style="white-space: nowrap;">
            <i class="fas fa-plus me-1"></i> NOVO
        </button>
    </div>

    <!-- Container flex-grow-1 empurra o rodapé para baixo -->
    <div class="container-fluid p-3 p-md-4 flex-grow-1">
        <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm fw-bold mb-4"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="card card-custom shadow-lg overflow-hidden border-0">
            <div class="table-responsive">
                <table class="table-custom align-middle">
                    <thead>
                        <tr>
                            <th class="ps-4">Nome da Máscara</th>
                            <th>Perfil Vinculado</th>
                            <th>DNS Mascarado</th>
                            <th class="text-center">Porta</th>
                            <th>Status</th>
                            <th class="text-end pe-4">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(count($mascaras) > 0): ?>
                            <?php foreach($mascaras as $m): $is_block = ($m['bloqueado'] == 'sim'); ?>
                            <tr>
                                <td class="ps-4">
                                    <div class="d-flex align-items-center">
                                        <span class="status-dot <?= $is_block ? 'offline' : 'online' ?>"></span>
                                        <span class="nome-destaque <?= $is_block ? 'text-danger' : '' ?>"><?= htmlspecialchars($m['nome']) ?></span>
                                    </div>
                                </td>
                                <td><span class="badge bg-primary px-3 shadow-sm"><?= htmlspecialchars($m['nome_perfil'] ?? '---') ?></span></td>
                                <td class="fw-bold text-info"><?= htmlspecialchars($m['url']) ?></td>
                                <td class="text-center text-warning fw-bold opacity-75"><?= htmlspecialchars($m['porta']) ?></td>
                                <td>
                                    <span class="badge <?= $is_block ? 'bg-danger bg-opacity-10 text-danger border border-danger' : 'bg-success bg-opacity-10 text-success border border-success' ?> px-2 py-1">
                                        <?= $is_block ? 'BLOQUEADO' : 'ATIVO' ?>
                                    </span>
                                </td>
                                <td class="text-end pe-4">
                                    <div class="d-flex gap-2 justify-content-end">
                                        <form method="POST" class="d-inline m-0">
                                            <input type="hidden" name="acao" value="toggle_block"><input type="hidden" name="id" value="<?= $m['id'] ?>">
                                            <button class="btn-sq bg-sq-orange" title="Alterar Status"><i class="fas <?= $is_block ? 'fa-lock-open' : 'fa-lock' ?>"></i></button>
                                        </form>
                                        <button class="btn-sq bg-sq-blue" onclick='abrirEditar(<?= json_encode($m) ?>)' title="Editar"><i class="fas fa-pen"></i></button>
                                        <form method="POST" class="d-inline m-0" onsubmit="return confirm('Tem certeza que deseja excluir esta máscara?')">
                                            <input type="hidden" name="acao" value="excluir"><input type="hidden" name="id" value="<?= $m['id'] ?>">
                                            <button class="btn-sq bg-sq-red" title="Excluir"><i class="fas fa-trash"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="6" class="text-center py-5" style="color: var(--text-color); opacity: 0.5;"><i class="fas fa-mask fs-2 mb-2"></i><br>Nenhuma máscara cadastrada no momento.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Rodapé fixado no final do Main Content -->
    <div class="mt-auto w-100">
        <?php include 'rodape.php'; ?>
    </div>
</main>

<div class="modal fade" id="modalCriar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-secondary" style="background-color: var(--bg-card);">
            <form method="POST" id="formMascara">
                <input type="hidden" name="acao" value="criar" id="inputAcao">
                <input type="hidden" name="id" id="inputId">
                <div class="modal-header border-secondary">
                    <h5 class="modal-title fw-bold" style="color: var(--text-color);" id="modalTitulo"><i class="fas fa-mask me-2 text-primary"></i> Nova Máscara URL</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1) grayscale(100%) brightness(200%);"></button>
                </div>
                <div class="modal-body p-4">
                    <div class="mb-3">
                        <label class="label-visivel mb-1">NOME DA MÁSCARA</label>
                        <input type="text" name="nome" id="nome" class="form-control fw-bold text-primary" placeholder="Ex: DNS Claro HD" required>
                    </div>
                    <div class="mb-3">
                        <label class="label-visivel mb-1">VINCULAR AO PERFIL</label>
                        <select name="perfil" id="perfil" class="form-select" required>
                            <option value="">Selecione o Perfil...</option>
                            <?php foreach($perfis_ativos as $p): ?>
                                <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['nome']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text" style="color: var(--text-color); opacity: 0.6; font-size: 0.75rem;"><i class="fas fa-info-circle me-1"></i> Apenas os perfis liberados para você aparecerão aqui.</div>
                    </div>
                    <div class="row g-3">
                        <div class="col-8 mb-2">
                            <label class="label-visivel mb-1">URL (DNS MASCARADO)</label>
                            <input type="text" name="url" id="url" class="form-control" placeholder="dns.meuip.com" required>
                        </div>
                        <div class="col-4 mb-2">
                            <label class="label-visivel mb-1">PORTA</label>
                            <input type="number" name="porta" id="porta" class="form-control" placeholder="80" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-secondary">
                    <button type="submit" class="btn btn-primary w-100 fw-bold py-2 shadow-sm rounded-pill">SALVAR MÁSCARA</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(m) {
        document.getElementById('inputAcao').value = 'editar'; 
        document.getElementById('inputId').value = m.id; 
        document.getElementById('modalTitulo').innerHTML = '<i class="fas fa-pen me-2 text-warning"></i> Editar Máscara URL';
        document.getElementById('nome').value = m.nome; 
        document.getElementById('perfil').value = m.perfil; 
        document.getElementById('url').value = m.url; 
        document.getElementById('porta').value = m.porta;
        new bootstrap.Modal(document.getElementById('modalCriar')).show();
    }

    document.getElementById('modalCriar').addEventListener('hidden.bs.modal', function () { 
        document.getElementById('formMascara').reset(); 
        document.getElementById('inputAcao').value = 'criar'; 
        document.getElementById('modalTitulo').innerHTML = '<i class="fas fa-mask me-2 text-primary"></i> Nova Máscara URL'; 
    });
</script>
</body>
</html>
