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

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

// --- 1. PROCESSAMENTO ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $nome_painel    = trim($_POST['nome_painel']);
        $legenda_painel = trim($_POST['legenda_painel']);
        $tema_painel    = trim($_POST['tema_painel']);

        // Verifica se já existe configuração (ID 1)
        $check = $connGeral->query("SELECT id FROM site_config WHERE id = 1");
        
        if ($check->rowCount() > 0) {
            // Atualiza
            $sql = "UPDATE site_config SET NomePainel = ?, LegendaPainel = ?, TemaPainel = ? WHERE id = 1";
            $stmt = $connGeral->prepare($sql);
            $stmt->execute([$nome_painel, $legenda_painel, $tema_painel]);
        } else {
            // Cria a primeira vez
            $sql = "INSERT INTO site_config (id, NomePainel, LegendaPainel, TemaPainel) VALUES (1, ?, ?, ?)";
            $stmt = $connGeral->prepare($sql);
            $stmt->execute([$nome_painel, $legenda_painel, $tema_painel]);
        }

        $msg = "Personalização salva com sucesso!";
        $msg_tipo = "success";

    } catch (PDOException $e) {
        $msg = "Erro ao salvar: " . $e->getMessage();
        $msg_tipo = "danger";
    }
}

// --- 2. BUSCAR DADOS ---
try {
    $stmt = $connGeral->query("SELECT * FROM site_config WHERE id = 1");
    $config = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // Se der erro ou não existir tabela ainda, segue vazio
    $config = [];
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Personalizar Painel | Admin</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 { --bg-body: #151521; --bg-card: #1e1e2d; --primary: #7367f0; }
        body { background: var(--bg-body); 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: 30px; transition: 0.3s; }
        
        .form-label { color: #ffffff !important; font-weight: 700; margin-bottom: 5px; display: block; }
        .text-obs { color: #aaaaaa !important; font-size: 0.85rem; margin-top: 5px; }

        .card-custom { background: var(--bg-card); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; padding: 25px; }
        .form-control, .form-select { background: #2b2b40 !important; border: 1px solid #444 !important; color: #fff !important; height: 45px; }
        .form-control:focus, .form-select:focus { border-color: var(--primary); box-shadow: none; }

        /* PREVIEW DO TEMA */
        .theme-preview { width: 100%; height: 100px; border-radius: 8px; margin-bottom: 10px; border: 2px solid transparent; cursor: pointer; transition: 0.3s; position: relative; overflow: hidden; }
        .theme-preview:hover { transform: scale(1.02); }
        .theme-selected { border-color: var(--primary); box-shadow: 0 0 15px rgba(115, 103, 240, 0.5); }
        
        /* Cores dos Temas (Exemplo visual) */
        .theme-dark { background: linear-gradient(135deg, #1e1e2d 0%, #151521 100%); }
        .theme-blue { background: linear-gradient(135deg, #0d47a1 0%, #002171 100%); }
        .theme-purple { background: linear-gradient(135deg, #4a148c 0%, #311b92 100%); }

        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); }
            .main-content { margin-left: 0; padding: 15px; } .mobile-toggle { display: block !important; }
        }
        .mobile-toggle { display: none; font-size: 1.5rem; color: #fff; background: none; border: none; margin-bottom: 20px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999; }
        .overlay.show { display: block; }
        .nav-link { color: #a6a6b7; text-decoration: none; display: flex; align-items: center; gap: 10px; padding: 10px; border-radius: 8px; }
        .nav-link.active { background: var(--primary); color: #fff; }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold text-white"><i class="fas fa-tv text-primary"></i> Painel v3.0</h4>
    <div class="nav flex-column gap-2">
        <a href="index.php" class="nav-link text-white"><i class="fas fa-home"></i> Dashboard</a>
        
        <?php if ($_SESSION['nivel'] === 'admin'): ?>
            <div class="mt-2 mb-1 px-3 text-uppercase fw-bold text-light" style="font-size: 0.75rem; opacity: 0.7;">Administração</div>
            <a href="config_geral.php" class="nav-link text-white"><i class="fas fa-cogs text-info"></i> Config. Servidor</a>
            <a href="gerenciar_dns.php" class="nav-link text-white"><i class="fas fa-network-wired text-success"></i> Servidores DNS</a>
            <a href="gerenciar_perfis.php" class="nav-link text-white"><i class="fas fa-layer-group text-primary"></i> Perfis de Conexão</a>
            <a href="gerenciar_mascara.php" class="nav-link text-white"><i class="fas fa-mask text-warning"></i> Máscaras URL</a>
            <a href="personalizar_painel.php" class="nav-link active text-white"><i class="fas fa-paint-brush text-danger"></i> Personalizar Painel</a>
            
            <a href="permissoes_server.php" class="nav-link text-white"><i class="fas fa-server text-white"></i> Permissões CSP</a>
            <a href="revendedores.php" class="nav-link text-white"><i class="fas fa-store"></i> Revendedores</a>
            <a href="configuracoes.php" class="nav-link text-white"><i class="fas fa-wallet"></i> Pagamentos (Global)</a>
            <div class="mb-2 border-bottom border-secondary opacity-50"></div>
        <?php else: ?>
            <a href="configuracoes.php" class="nav-link text-white"><i class="fas fa-wallet"></i> Meus Pagamentos</a>
        <?php endif; ?>

        <a href="clientes.php" class="nav-link text-white"><i class="fas fa-users"></i> Clientes</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">
    <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>

    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card card-custom">
                <h4 class="text-white mb-4"><i class="fas fa-paint-brush me-2 text-danger"></i> Personalizar Aparência</h4>
                
                <?php if($msg): ?>
                    <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show">
                        <?= $msg ?> <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <form method="POST">
                    <div class="mb-3">
                        <label class="form-label">Nome do Painel</label>
                        <input type="text" name="nome_painel" class="form-control" value="<?= $config['NomePainel'] ?? 'Painel v3.0' ?>" placeholder="Ex: TV Top Master" required>
                        <div class="text-obs">Este nome aparecerá no topo do menu lateral e na aba do navegador.</div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Legenda / Slogan</label>
                        <input type="text" name="legenda_painel" class="form-control" value="<?= $config['LegendaPainel'] ?? '' ?>" placeholder="Ex: O melhor sistema de gestão">
                        <div class="text-obs">Pequeno texto descritivo (opcional).</div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label mb-3">Escolha o Tema Principal</label>
                        <input type="hidden" name="tema_painel" id="inputTema" value="<?= $config['TemaPainel'] ?? 'dark' ?>">
                        
                        <div class="row g-3">
                            <div class="col-4">
                                <div class="theme-preview theme-dark <?= ($config['TemaPainel'] ?? 'dark') == 'dark' ? 'theme-selected' : '' ?>" onclick="selecionarTema('dark', this)">
                                    <div class="d-flex h-100 align-items-center justify-content-center text-white fw-bold">Dark (Padrão)</div>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="theme-preview theme-blue <?= ($config['TemaPainel'] ?? '') == 'blue' ? 'theme-selected' : '' ?>" onclick="selecionarTema('blue', this)">
                                    <div class="d-flex h-100 align-items-center justify-content-center text-white fw-bold">Azul Profundo</div>
                                </div>
                            </div>
                            <div class="col-4">
                                <div class="theme-preview theme-purple <?= ($config['TemaPainel'] ?? '') == 'purple' ? 'theme-selected' : '' ?>" onclick="selecionarTema('purple', this)">
                                    <div class="d-flex h-100 align-items-center justify-content-center text-white fw-bold">Roxo Vibrante</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="mt-4 border-top border-secondary pt-3">
                        <button type="submit" class="btn btn-primary w-100 p-3 fw-bold">
                            <i class="fas fa-save me-2"></i> Salvar Personalização
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</main>

<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 selecionarTema(tema, elemento) {
        document.getElementById('inputTema').value = tema;
        // Remove seleção visual de todos
        document.querySelectorAll('.theme-preview').forEach(el => el.classList.remove('theme-selected'));
        // Adiciona ao clicado
        elemento.classList.add('theme-selected');
    }
</script>
</body>
</html>
