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

// --- INÍCIO DA CORREÇÃO DO MENU LATERAL ---
$isAdmin = (isset($_SESSION['nivel']) && strtolower($_SESSION['nivel']) === 'admin');
$usuarioLogado = $_SESSION['usuario'] ?? '';
$total_msg_nao_lidas = 0;
try {
    if (!empty($usuarioLogado) && isset($connUser)) {
        $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) { }
// --- FIM DA CORREÇÃO DO MENU LATERAL ---

$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 (POST) ---
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>

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



    <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; --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 Estilo IPTV */
        .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; }
        
        /* Layout */
        .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; }

        /* Elementos da Página */
        .card-custom { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; padding: 25px; }
        .form-label { color: #ffffff !important; font-weight: 700; font-size: 0.9rem; text-transform: uppercase; }
        .form-control { background: #151521 !important; border: 1px solid #444 !important; color: #fff !important; padding: 12px; }
        .text-obs { color: #00cfe8 !important; font-size: 0.8rem; margin-top: 5px; font-weight: 500; }
        
        .theme-preview { width: 100%; height: 60px; 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; font-size: 0.8rem; }
        .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; }
            .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>
<?php include 'menu.php'; ?>


<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">Personalização</div>
        </div>
        <div class="header-icons">
            <a href="sair.php" class="btn btn-danger btn-sm rounded-pill px-3 shadow-sm"><i class="fas fa-power-off"></i></a>
        </div>
    </div>

    <div class="container-fluid p-3 p-md-4">
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="card card-custom shadow-lg">
                    <div class="d-flex align-items-center mb-4">
                        <div class="bg-primary p-3 rounded-3 me-3 shadow"><i class="fas fa-palette text-white fs-4"></i></div>
                        <div>
                            <h4 class="text-white fw-bold m-0">Identidade Visual</h4>
                            <p class="text-muted small m-0">Altere o nome e as cores globais do painel.</p>
                        </div>
                    </div>
                    
                    <?php if($msg): ?>
                        <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm">
                            <?= $msg ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="row g-4">
                            <div class="col-md-6">
                                <label class="form-label">Nome do Painel</label>
                                <input type="text" name="nome_painel" class="form-control" value="<?= htmlspecialchars($config['NomePainel'] ?? '') ?>" required>
                                <div class="text-obs">Aparece no topo do menu e na aba do navegador.</div>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Legenda / Slogan</label>
                                <input type="text" name="legenda_painel" class="form-control" value="<?= htmlspecialchars($config['LegendaPainel'] ?? '') ?>">
                                <div class="text-obs">Subtítulo que aparece no login ou dashboard.</div>
                            </div>

                            <div class="col-12">
                                <label class="form-label">Cor de Destaque (Tema Principal)</label>
                                <input type="hidden" name="tema_painel" id="inputTema" value="<?= $corPrimaria ?>">
                                
                                <div class="row row-cols-2 row-cols-md-5 g-2 mt-1">
                                    <?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-4 p-3 bg-dark rounded border border-secondary">
                                    <label class="form-label" style="font-size: 0.75rem;">Escolha uma cor exata no seletor:</label>
                                    <input type="color" class="form-control form-control-color w-100" style="height: 50px; cursor: pointer;" value="<?= $corPrimaria ?>" onchange="selecionarTema(this.value, null)">
                                </div>
                            </div>
                        </div>

                        <div class="mt-5">
                            <button type="submit" class="btn btn-primary w-100 py-3 fw-bold shadow"><i class="fas fa-save me-2"></i> SALVAR CONFIGURAÇÕES</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <?php include 'rodape.php'; ?>
</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); 
    }
</script>
</body>
</html>