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

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

// --- 1. BUSCAR CONFIGURAÇÕES ATUAIS ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf_db = $connGeral->query("SELECT * FROM site_config WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf_db) {
        if (!empty($conf_db['NomePainel'])) $nomePainel = $conf_db['NomePainel'];
        if (!empty($conf_db['TemaPainel'])) $corPrimaria = $conf_db['TemaPainel'];
        $config = $conf_db;
    } else { $config = []; }
} catch (Exception $e) { $config = []; }

// --- 2. 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']);

        $check = $connGeral->query("SELECT id FROM site_config WHERE id = 1");
        if ($check->rowCount() > 0) {
            $sql = "UPDATE site_config SET NomePainel = ?, LegendaPainel = ?, TemaPainel = ? WHERE id = 1";
            $connGeral->prepare($sql)->execute([$nome_painel, $legenda_painel, $tema_painel]);
        } else {
            $sql = "INSERT INTO site_config (id, NomePainel, LegendaPainel, TemaPainel) VALUES (1, ?, ?, ?)";
            $connGeral->prepare($sql)->execute([$nome_painel, $legenda_painel, $tema_painel]);
        }
        $nomePainel = $nome_painel; $corPrimaria = $tema_painel;
        $msg = "Personalização salva!"; $msg_tipo = "success";
    } catch (PDOException $e) { $msg = "Erro: " . $e->getMessage(); $msg_tipo = "danger"; }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Personalizar | <?= 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; }
        body { background: var(--bg-body); color: #fff; font-family: 'Segoe UI', sans-serif; overflow-x: hidden; }
        
        /* Menu Lateral */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); padding: 20px; border-right: 1px solid #333; transition: 0.3s; z-index: 1050; overflow-y: auto; }
        .main-content { margin-left: 260px; padding: 30px; transition: 0.3s; }
        .nav-link { color: #a6a6b7; padding: 10px 12px; border-radius: 8px; margin-bottom: 2px; display: flex; align-items: center; gap: 10px; transition: 0.2s; text-decoration: none; font-size: 0.9rem; }
        .nav-link:hover, .nav-link.active { background: var(--primary); color: #fff; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 20px 0 10px 12px; }

        /* AJUSTE DE VISIBILIDADE DOS TEXTOS */
        .form-label { color: #ffffff !important; font-weight: 700 !important; font-size: 1rem; margin-bottom: 8px; display: block; text-shadow: 1px 1px 2px rgba(0,0,0,0.5); }
        .text-obs { color: #00cfe8 !important; font-size: 0.85rem; margin-top: 5px; font-weight: 500; }
        
        .card-custom { background: var(--bg-card); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; padding: 25px; }
        .form-control { background: #2b2b40 !important; border: 1px solid #444 !important; color: #fff !important; }
        
        /* Preview Cores */
        .theme-preview { width: 100%; height: 70px; border-radius: 8px; margin-bottom: 10px; border: 3px solid transparent; cursor: pointer; transition: 0.2s; display: flex; align-items: center; justify-content: center; font-weight: bold; color: #fff; text-shadow: 1px 1px 2px #000; }
        .theme-selected { border-color: #fff; box-shadow: 0 0 15px var(--primary); transform: scale(1.05); }

        @media (max-width: 992px) { .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: 1040; }
        .overlay.show { display: block; }
    </style>
</head>
<body>

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

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold text-white text-center"><i class="fas fa-tv text-primary"></i> <?= htmlspecialchars($nomePainel) ?></h4>
    <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">Administração</div>
        <a href="gerenciar_perfis.php" class="nav-link"><i class="fas fa-layer-group"></i> Gerenciar 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> Gestão de Admins</a>
        <a href="gerenciar_email.php" class="nav-link"><i class="fas fa-envelope"></i> Config. E-mail</a>
        <a href="personalizar_painel.php" class="nav-link active"><i class="fas fa-paint-brush"></i> Personalizar</a>
        <a href="gerenciar_backups.php" class="nav-link"><i class="fas fa-database"></i> Backups</a>
        <a href="config_geral.php" class="nav-link"><i class="fas fa-cogs"></i> Config. Geral</a>
        <div class="nav-group-title">Operacional</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>
        <hr class="border-secondary mt-4"><a href="sair.php" class="nav-link text-danger"><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 shadow-lg">
                <h4 class="text-white mb-4"><i class="fas fa-paint-brush me-2 text-primary"></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-4">
                        <label class="form-label">Nome do Painel</label>
                        <input type="text" name="nome_painel" class="form-control form-control-lg" value="<?= htmlspecialchars($config['NomePainel'] ?? '') ?>" required>
                        <div class="text-obs">Aparece no topo do menu e na aba do navegador.</div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Legenda / Slogan do Sistema</label>
                        <input type="text" name="legenda_painel" class="form-control" value="<?= htmlspecialchars($config['LegendaPainel'] ?? '') ?>">
                        <div class="text-obs">Texto descritivo curto.</div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Cor de Destaque (Tema Principal)</label>
                        <input type="hidden" name="tema_painel" id="inputTema" value="<?= $corPrimaria ?>">
                        
                        <div class="row g-2">
                            <?php 
                            $cores = ['#7367f0' => 'Roxo', '#00cfe8' => 'Azul', '#ea5455' => 'Vermelho', '#ff9f43' => 'Laranja', '#28c76f' => 'Verde'];
                            foreach($cores as $hex => $nome): ?>
                            <div class="col">
                                <div class="theme-preview <?= $corPrimaria == $hex ? 'theme-selected' : '' ?>" style="background: <?= $hex ?>;" onclick="selecionarTema('<?= $hex ?>', this)">
                                    <?= $nome ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="mt-3">
                            <label class="form-label" style="font-size: 0.8rem;">Ou escolha uma cor personalizada:</label>
                            <input type="color" class="form-control form-control-color w-100" style="height: 50px;" value="<?= $corPrimaria ?>" onchange="selecionarTema(this.value, null)">
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary w-100 p-3 fw-bold fs-5"><i class="fas fa-save me-2"></i> SALVAR PERSONALIZAÇÃO</button>
                </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(cor, elemento) {
        document.getElementById('inputTema').value = cor;
        document.querySelectorAll('.theme-preview').forEach(el => el.classList.remove('theme-selected'));
        if(elemento) elemento.classList.add('theme-selected');
        document.documentElement.style.setProperty('--primary', cor); // Preview imediato
    }
</script>
</body>
</html>
