<?php
// /admin/configuracoes.php
require 'db.php';

if(!defined('VX_OK')||!VX_OK){header('HTTP/1.0 403 Forbidden');exit;}

if (!isset($_SESSION['admin_logado'])) {
    header("Location: login.php");
    exit;
}

$mensagem = '';
$tipo_alerta = 'success';

// ==========================================
// PROCESSAMENTO DO FORMULÁRIO
// ==========================================
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // 1. Atualizar Campos de Texto (Motor UPSERT Blindado)
    $campos_texto = [
        'nome_artista', 'home_subtitulo', 'titulo_portfolio',
        'cor_header', 'cor_menu_fonte', 'cor_botao_especial',
        'whatsapp_numero', 'email_principal', 'email_cc', 
        'botao_menu_label', 'botao_menu_link', 
        'link_facebook', 'link_instagram', 'link_youtube',
        'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass' // 🛰️ CHAVES DO SMTP ADICIONADAS AQUI
    ];
    
    $stmt = $pdo->prepare("INSERT INTO configs (chave, valor) VALUES (?, ?) ON DUPLICATE KEY UPDATE valor = ?");
    foreach ($campos_texto as $campo) {
        if (isset($_POST[$campo])) { 
            $stmt->execute([$campo, $_POST[$campo], $_POST[$campo]]); 
        }
    }

    // 2. Processar Uploads de Imagens
    $uploads = [
        'logo_header'     => '../img/logo_header.png',
        'favicon_publico' => '../img/favicon_publico.png',
        'favicon_admin'   => '../img/favicon_admin.png'
    ];

    foreach ($uploads as $chave => $caminho_final) {
        if (!empty($_FILES[$chave]['name'])) {
            $ext = strtolower(pathinfo($_FILES[$chave]['name'], PATHINFO_EXTENSION));
            $extensoes_permitidas = ['jpg', 'jpeg', 'png', 'ico', 'webp', 'svg'];

            if (in_array($ext, $extensoes_permitidas)) {
                if (move_uploaded_file($_FILES[$chave]['tmp_name'], $caminho_final)) {
                    $caminho_banco = str_replace('../', '', $caminho_final);
                    $pdo->prepare("UPDATE configs SET valor = ? WHERE chave = ?")->execute([$caminho_banco, $chave]);
                }
            } else {
                $mensagem = "Erro: Formato de arquivo inválido para $chave.";
                $tipo_alerta = 'danger';
            }
        }
    }
    if (empty($mensagem)) { $mensagem = "Configurações de sistema atualizadas com sucesso!"; }
}

// ----------------------------------------------------
// BUSCA CONFIGURAÇÕES ATUAIS
// ----------------------------------------------------
$stmt = $pdo->query("SELECT chave, valor FROM configs");
$configs = [];
while ($row = $stmt->fetch()) { $configs[$row['chave']] = $row['valor']; }

// Define a cor de fundo padrão para o PHP carregar na Logo
$corHeaderAtual = htmlspecialchars($configs['cor_header'] ?? '#0ea5e9');
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Configurações Gerais | VoxCore Admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="admin.css">
    
    <style>
        .card-tars { border: none; border-radius: 15px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }
        .preview-img { max-height: 80px; border-radius: 8px; border: 1px solid #dee2e6; margin-top: 10px; background: #eee; }
        .preview-favicon { width: 32px; height: 32px; object-fit: contain; background: #fff; padding: 2px; }
        
        /* 🛰️ Removi a cor fixa daqui. O fundo agora será dinâmico pelo JavaScript e PHP */
        .preview-logo { padding: 10px; object-fit: contain; transition: background-color 0.3s ease; } 
        
        .color-item { display: flex; align-items: center; gap: 12px; background: #fff; padding: 10px; border-radius: 10px; border: 1px solid #eee; margin-bottom: 10px; }
        .form-control-color { width: 45px; height: 45px; padding: 2px; cursor: pointer; border-radius: 5px; border: 1px solid #ddd; }
    </style>

    <?php 
        $stmt_fav_adm = $pdo->query("SELECT valor FROM configs WHERE chave = 'favicon_admin'");
        $fav_adm_path = $stmt_fav_adm->fetchColumn() ?: 'img/favicon_admin.png';
    ?>
    <link rel="icon" href="../<?= $fav_adm_path ?>?v=<?= time() ?>" type="image/png">
</head>
<body>

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

    <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content pt-4">
        
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-palette text-primary me-2"></i> Configurações Visuais</h2>
        </div>

        <?php if ($mensagem): ?>
            <div class="alert alert-<?= $tipo_alerta ?> alert-dismissible fade show">
                <i class="fas fa-info-circle"></i> <?= $mensagem ?>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
        <?php endif; ?>

        <form method="POST" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-6">
                    
                    <div class="card card-tars p-4 mb-4">
                        <h5 class="mb-3 border-bottom pb-2 text-primary"><i class="fas fa-fingerprint"></i> Identidade e Títulos</h5>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold small">Nome do Artista / Projeto</label>
                            <input type="text" name="nome_artista" class="form-control" value="<?= htmlspecialchars($configs['nome_artista'] ?? '') ?>">
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold small">Subtítulo do Site</label>
                            <input type="text" name="home_subtitulo" class="form-control" value="<?= htmlspecialchars($configs['home_subtitulo'] ?? '') ?>">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold small text-primary">Título da Página de Portfólio</label>
                            <input type="text" name="titulo_portfolio" class="form-control" value="<?= htmlspecialchars($configs['titulo_portfolio'] ?? '') ?>" placeholder="Ex: Lista Completa de Dublagens">
                        </div>

                        <hr>

                        <div class="mb-3">
                            <label class="form-label fw-bold small">Logotipo (Header)</label>
                            <input type="file" name="logo_header" class="form-control form-control-sm">
                            <img src="../<?= $configs['logo_header'] ?? 'img/logo_header.png' ?>?v=<?= time() ?>" id="logoPreview" class="preview-img preview-logo mt-2" alt="Logo" style="background-color: <?= $corHeaderAtual ?>;">
                        </div>

                        <div class="row mt-3">
                            <div class="col-md-6 mb-2">
                                <label class="form-label fw-bold small">Favicon Público</label>
                                <input type="file" name="favicon_publico" class="form-control form-control-sm">
                                <img src="../<?= $configs['favicon_publico'] ?? 'img/favicon_publico.png' ?>?v=<?= time() ?>" class="preview-img preview-favicon" alt="Favicon">
                            </div>
                            <div class="col-md-6 mb-2">
                                <label class="form-label fw-bold small">Favicon Admin</label>
                                <input type="file" name="favicon_admin" class="form-control form-control-sm">
                                <img src="../<?= $configs['favicon_admin'] ?? 'img/favicon_admin.png' ?>?v=<?= time() ?>" class="preview-img preview-favicon" alt="Favicon Admin">
                            </div>
                        </div>
                    </div>

                    <div class="card card-tars p-4 mb-4">
                        <h5 class="mb-3 border-bottom pb-2 text-warning"><i class="fas fa-brush"></i> Cores do Cabeçalho</h5>
                        
                        <div class="color-item">
                            <input type="color" name="cor_header" id="colorHeaderPicker" class="form-control form-control-color" value="<?= $corHeaderAtual ?>">
                            <div>
                                <label class="form-label fw-bold small mb-0">Barra de Fundo</label>
                                <div class="text-muted" style="font-size: 11px;">Cor principal do topo do site. Altera o fundo da logo acima em tempo real!</div>
                            </div>
                        </div>

                        <div class="color-item">
                            <input type="color" name="cor_menu_fonte" class="form-control form-control-color" value="<?= htmlspecialchars($configs['cor_menu_fonte'] ?? '#ffffff') ?>">
                            <div>
                                <label class="form-label fw-bold small mb-0">Fonte do Menu</label>
                                <div class="text-muted" style="font-size: 11px;">Cor dos links (Início, Biografia, etc).</div>
                            </div>
                        </div>

                        <div class="color-item">
                            <input type="color" name="cor_botao_especial" class="form-control form-control-color" value="<?= htmlspecialchars($configs['cor_botao_especial'] ?? '#f59e0b') ?>">
                            <div>
                                <label class="form-label fw-bold small mb-0">Botão de Destaque</label>
                                <div class="text-muted" style="font-size: 11px;">Cor do botão personalizado no menu.</div>
                            </div>
                        </div>
                    </div>

                </div>

                <div class="col-md-6">
                    
                    <div class="card card-tars p-4 mb-4">
                        <h5 class="mb-3 border-bottom pb-2 text-info"><i class="fas fa-share-nodes"></i> Redes Sociais</h5>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold small"><i class="fab fa-facebook text-primary"></i> Facebook</label>
                            <input type="url" name="link_facebook" class="form-control form-control-sm" value="<?= htmlspecialchars($configs['link_facebook'] ?? '') ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold small"><i class="fab fa-instagram text-danger"></i> Instagram</label>
                            <input type="url" name="link_instagram" class="form-control form-control-sm" value="<?= htmlspecialchars($configs['link_instagram'] ?? '') ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold small"><i class="fab fa-youtube text-danger"></i> YouTube</label>
                            <input type="url" name="link_youtube" class="form-control form-control-sm" value="<?= htmlspecialchars($configs['link_youtube'] ?? '') ?>">
                        </div>
                    </div>

                    <div class="card card-tars p-4 mb-4">
                        <h5 class="mb-3 border-bottom pb-2 text-success"><i class="fas fa-envelope"></i> Contato e Links</h5>
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold small">WhatsApp</label>
                            <input type="text" name="whatsapp_numero" class="form-control" value="<?= htmlspecialchars($configs['whatsapp_numero'] ?? '') ?>">
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold small">E-mail Principal</label>
                                <input type="email" name="email_principal" class="form-control" value="<?= htmlspecialchars($configs['email_principal'] ?? '') ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold small">E-mail CC</label>
                                <input type="email" name="email_cc" class="form-control" value="<?= htmlspecialchars($configs['email_cc'] ?? '') ?>">
                            </div>
                        </div>

                        <hr>
                        
                        <h6 class="text-success fw-bold mb-3 small"><i class="fas fa-link"></i> Botão Personalizado (Menu)</h6>
                        
                        <div class="row">
                            <div class="col-md-6 mb-2">
                                <label class="form-label fw-bold small">Rótulo</label>
                                <input type="text" name="botao_menu_label" class="form-control form-control-sm" value="<?= htmlspecialchars($configs['botao_menu_label'] ?? '') ?>">
                            </div>
                            <div class="col-md-6 mb-2">
                                <label class="form-label fw-bold small">Link</label>
                                <input type="text" name="botao_menu_link" class="form-control form-control-sm" value="<?= htmlspecialchars($configs['botao_menu_link'] ?? '') ?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="card card-tars p-4 mb-4">
                        <h5 class="mb-3 border-bottom pb-2 text-danger"><i class="fas fa-server"></i> Servidor de E-mail (SMTP)</h5>
                        <div class="alert alert-light border small text-muted">
                            <i class="fas fa-info-circle"></i> Configure estas opções para que o formulário de contato do site funcione sem cair no SPAM.
                        </div>
                        
                        <div class="row">
                            <div class="col-md-8 mb-3">
                                <label class="form-label fw-bold small">Servidor SMTP (Host)</label>
                                <input type="text" name="smtp_host" class="form-control form-control-sm" value="<?= htmlspecialchars($configs['smtp_host'] ?? '') ?>" placeholder="Ex: smtp.seusite.com">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label fw-bold small">Porta</label>
                                <input type="number" name="smtp_port" class="form-control form-control-sm" value="<?= htmlspecialchars($configs['smtp_port'] ?? '465') ?>" placeholder="465 ou 587">
                            </div>
                        </div>
                    
                        <div class="mb-3">
                            <label class="form-label fw-bold small">E-mail de Autenticação (Usuário)</label>
                            <input type="email" name="smtp_user" class="form-control form-control-sm" value="<?= htmlspecialchars($configs['smtp_user'] ?? '') ?>" placeholder="Ex: contato@seudominio.com">
                        </div>
                    
                        <div class="mb-2">
                            <label class="form-label fw-bold small">Senha do E-mail</label>
                            <input type="password" name="smtp_pass" class="form-control form-control-sm" value="<?= htmlspecialchars($configs['smtp_pass'] ?? '') ?>" placeholder="Sua senha">
                        </div>
                    </div>

                </div>
            </div>

            <div class="mt-2 mb-5">
                <button type="submit" class="btn btn-primary btn-lg w-100 fw-bold shadow">
                    <i class="fas fa-save"></i> Gravar Configurações
                </button>
            </div>
        </form>
    </main>

</div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    document.getElementById('btnToggleMenu')?.addEventListener('click', function() {
        document.getElementById('sidebarMenu').classList.toggle('show');
        document.getElementById('sidebarOverlay').classList.toggle('show');
    });

    // 🛰️ A MÁGICA AO VIVO: Conecta o Seletor de Cor com a Imagem de Preview da Logo
    const colorPicker = document.getElementById('colorHeaderPicker');
    const logoPreview = document.getElementById('logoPreview');

    if (colorPicker && logoPreview) {
        colorPicker.addEventListener('input', function(event) {
            logoPreview.style.backgroundColor = event.target.value;
        });
    }
</script>
</body>
</html>