<?php 
// Conexão com o banco de dados
// Nota: Autenticação já verificada em dashboard/index.php
require_once __DIR__ . '/../../config/config_db.php';
require_once __DIR__ . '/../../backend/gateway_helper.php';

// Inicialização das variáveis de controle
$credenciaisAtualizadas = false;
$credenciaisExistem = false;

// Verifica se há credenciais já existentes no banco de dados (tabela credenciais - compatibilidade)
$sql = "SELECT * FROM credenciais LIMIT 1";
$stmt = $pdo->query($sql);
$credenciais = $stmt->fetch(PDO::FETCH_ASSOC);

if ($credenciais) {
    $credenciaisExistem = true;
}

// Carregar configurações dos gateways (tabela configuracoes)
$mercadopago_config = get_all_gateway_config('mercadopago');
$stripe_config = get_all_gateway_config('stripe');
$paypal_config = get_all_gateway_config('paypal');
$pagarme_config = get_all_gateway_config('pagarme');

// Processa o formulário quando ele é submetido
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Mercado Pago (compatibilidade com tabela credenciais)
    $access_token = isset($_POST['access_token']) ? trim($_POST['access_token']) : '';
    $public_key = isset($_POST['public_key']) ? trim($_POST['public_key']) : '';

    // LOGICA INTELIGENTE: Só atualiza se o usuário digitou algo novo
    if ($credenciaisExistem) {
        // Se já existem credenciais, atualizamos apenas o que foi preenchido
        $sql_parts = [];
        $params = [':id' => $credenciais['id']];

        if (!empty($access_token)) {
            $sql_parts[] = "access_token = :access_token";
            $params[':access_token'] = $access_token;
        }
        
        if (!empty($public_key)) {
            $sql_parts[] = "public_key = :public_key";
            $params[':public_key'] = $public_key;
        }

        // Se tem algo para atualizar, roda o UPDATE
        if (!empty($sql_parts)) {
            $sql = "UPDATE credenciais SET " . implode(', ', $sql_parts) . ", data_atualizacao = CURRENT_TIMESTAMP WHERE id = :id";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            
            // Também salvar na tabela configuracoes para compatibilidade
            if (!empty($access_token)) {
                save_gateway_config('mercadopago', 'access_token', $access_token);
            }
            if (!empty($public_key)) {
                save_gateway_config('mercadopago', 'public_key', $public_key);
            }
            
            // Recarrega os dados para garantir consistência
            $credenciaisAtualizadas = true;
            
            // Atualiza a variável local para refletir a mudança imediata (se necessário)
            if(!empty($access_token)) $credenciais['access_token'] = $access_token;
            if(!empty($public_key)) $credenciais['public_key'] = $public_key;
        } 
    } else {
        // Se NÃO existem credenciais, é OBRIGATÓRIO preencher tudo para criar
        if (!empty($access_token) && !empty($public_key)) {
            $sql = "INSERT INTO credenciais (access_token, public_key) VALUES (:access_token, :public_key)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':access_token' => $access_token,
                ':public_key' => $public_key
            ]);
            
            // Também salvar na tabela configuracoes
            save_gateway_config('mercadopago', 'access_token', $access_token);
            save_gateway_config('mercadopago', 'public_key', $public_key);
            
            $credenciaisExistem = true;
            $credenciaisAtualizadas = true;
            
            // Define a variável local para mostrar o status "Configurado"
            $credenciais = ['access_token' => $access_token, 'public_key' => $public_key];
        }
    }
    
    // Processar Stripe
    if (isset($_POST['stripe_public_key'])) {
        $stripe_public_key = trim($_POST['stripe_public_key']);
        $stripe_secret_key = isset($_POST['stripe_secret_key']) ? trim($_POST['stripe_secret_key']) : '';
        $stripe_enabled = isset($_POST['stripe_enabled']) ? 1 : 0;
        
        if (!empty($stripe_public_key)) {
            save_gateway_config('stripe', 'public_key', $stripe_public_key);
        }
        if (!empty($stripe_secret_key)) {
            save_gateway_config('stripe', 'secret_key', $stripe_secret_key);
        }
        save_gateway_config('stripe', 'enabled', $stripe_enabled);
        
        $stripe_config = get_all_gateway_config('stripe');
        $credenciaisAtualizadas = true;
    }
    
    // Processar PayPal
    if (isset($_POST['paypal_client_id'])) {
        $paypal_client_id = trim($_POST['paypal_client_id']);
        $paypal_client_secret = isset($_POST['paypal_client_secret']) ? trim($_POST['paypal_client_secret']) : '';
        $paypal_mode = isset($_POST['paypal_mode']) ? trim($_POST['paypal_mode']) : 'sandbox';
        $paypal_enabled = isset($_POST['paypal_enabled']) ? 1 : 0;
        
        if (!empty($paypal_client_id)) {
            save_gateway_config('paypal', 'client_id', $paypal_client_id);
        }
        if (!empty($paypal_client_secret)) {
            save_gateway_config('paypal', 'client_secret', $paypal_client_secret);
        }
        save_gateway_config('paypal', 'mode', $paypal_mode);
        save_gateway_config('paypal', 'enabled', $paypal_enabled);
        
        $paypal_config = get_all_gateway_config('paypal');
        $credenciaisAtualizadas = true;
    }
    
    // Processar ativação Mercado Pago
    if (isset($_POST['mercadopago_enabled'])) {
        $mercadopago_enabled = isset($_POST['mercadopago_enabled']) ? 1 : 0;
        save_gateway_config('mercadopago', 'enabled', $mercadopago_enabled);
        $mercadopago_config = get_all_gateway_config('mercadopago');
        $credenciaisAtualizadas = true;
    }
    
    // Processar Pagar.me
    if (isset($_POST['pagarme_api_key'])) {
        $pagarme_api_key = trim($_POST['pagarme_api_key']);
        $pagarme_encryption_key = isset($_POST['pagarme_encryption_key']) ? trim($_POST['pagarme_encryption_key']) : '';
        $pagarme_enabled = isset($_POST['pagarme_enabled']) ? 1 : 0;
        
        if (!empty($pagarme_api_key)) {
            save_gateway_config('pagarme', 'api_key', $pagarme_api_key);
        }
        if (!empty($pagarme_encryption_key)) {
            save_gateway_config('pagarme', 'encryption_key', $pagarme_encryption_key);
        }
        save_gateway_config('pagarme', 'enabled', $pagarme_enabled);
        
        $pagarme_config = get_all_gateway_config('pagarme');
        $credenciaisAtualizadas = true;
    }
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar Credenciais de Pagamento | Sales Studio Pro</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        /* ==========================================================
           2. ESTILOS CSS (COM SUPORTE A DARK MODE)
           ========================================================== */
        :root {
            /* Cores Padrão (Light Mode) */
            --primary-color: #009846;
            --primary-light: #00A85A;
            --primary-dark: #007635;
            --success-color: #4CAF50;
            --warning-color: #FFC107;
            --danger-color: #F44336;
            --info-color: #2196F3;
            
            --text-primary: #212121;
            --text-secondary: #757575;
            --text-muted: #9E9E9E;
            
            --bg-light: #f4f4f4;
            --bg-white: var(--bg-card, #FFFFFF);
            
            --border-color: var(--border-color, #E0E0E0);
            --shadow-sm: 0 2px 4px rgba(0, 0, 0, 0.1);
            --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.15);
            --border-radius: 8px;
            --transition: all 0.3s ease;
        }

        /* --- DARK MODE ATIVADO --- */
        [data-theme="dark"] {
            --text-primary: #e0e0e0;
            --text-secondary: #94a3b8;
            --text-muted: #64748b;
            
            --bg-light: var(--bg-body, #020617); /* Fundo Geral Escuro */
            --bg-white: var(--bg-card, #0f172a); /* Fundo Cards Escuro - Herda customização */
            
            --border-color: var(--border-color, #1e293b);
            --shadow-sm: 0 2px 4px rgba(0, 0, 0, 0.5);
        }

        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Montserrat', sans-serif; }
        
        body { 
            background-color: var(--bg-light); 
            color: var(--text-primary); 
            transition: var(--transition); 
        }
        
        .container { max-width: 800px; margin: 0 auto; padding: 20px; }
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
        .page-title { font-size: 24px; font-weight: 600; color: var(--text-primary); display: flex; align-items: center; gap: 12px; }
        
        .status-card { 
            background-color: var(--bg-white); border-radius: var(--border-radius); padding: 20px; 
            box-shadow: var(--shadow-sm); border: 1px solid var(--border-color); margin-bottom: 24px; 
            display: flex; align-items: center; gap: 16px; 
        }
        .status-icon { width: 48px; height: 48px; border-radius: var(--border-radius); display: flex; align-items: center; justify-content: center; font-size: 20px; }
        .status-icon.configurado { background-color: rgba(76, 175, 80, 0.1); color: var(--success-color); }
        .status-icon.nao-configurado { background-color: rgba(255, 193, 7, 0.1); color: var(--warning-color); }
        .status-info h3 { font-size: 18px; font-weight: 600; color: var(--text-primary); margin-bottom: 4px; }
        .status-info p { font-size: 14px; color: var(--text-secondary); }

        .form-container { background-color: var(--bg-white); border-radius: var(--border-radius); padding: 24px; box-shadow: var(--shadow-sm); border: 1px solid var(--border-color); }
        .form-header { display: flex; align-items: center; gap: 12px; margin-bottom: 24px; padding-bottom: 16px; border-bottom: 1px solid var(--border-color); }
        .form-header h3 { font-size: 18px; font-weight: 600; color: var(--text-primary); }
        .form-group { margin-bottom: 20px; }
        .form-label { display: block; margin-bottom: 8px; font-size: 14px; color: var(--text-secondary); font-weight: 500; display: flex; align-items: center; gap: 8px; }
        
        .form-input { 
            width: 100%; padding: 12px 14px; border: 1px solid var(--border-color); 
            border-radius: var(--border-radius); font-size: 14px; color: var(--text-primary); 
            background-color: var(--bg-white); transition: var(--transition); 
            font-family: 'Courier New', monospace; 
        }
        
        /* Ajuste do fundo do input no dark mode */
        [data-theme="dark"] .form-input { background-color: #1e293b; }

        .form-input:focus { outline: none; border-color: var(--primary-color); box-shadow: 0 0 0 3px rgba(0, 152, 70, 0.1); }
        .input-help { font-size: 12px; color: var(--text-muted); margin-top: 4px; display: flex; align-items: center; gap: 6px; }
        
        .btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; padding: 12px 24px; font-size: 14px; font-weight: 500; background-color: var(--primary-color); color: white; border: none; border-radius: var(--border-radius); cursor: pointer; transition: var(--transition); width: 100%; }
        .btn:hover { background-color: var(--primary-dark); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 152, 70, 0.2); }
        
        .success-message { background-color: rgba(76, 175, 80, 0.1); border: 1px solid var(--success-color); border-radius: var(--border-radius); padding: 16px; margin-bottom: 24px; display: flex; align-items: center; gap: 12px; color: var(--success-color); animation: slideIn 0.3s ease; }
        @keyframes slideIn { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
        
        .info-card { background-color: rgba(33, 150, 243, 0.05); border: 1px solid rgba(33, 150, 243, 0.2); border-radius: var(--border-radius); padding: 16px; margin-bottom: 24px; }
        .info-card h4 { color: var(--info-color); font-size: 14px; font-weight: 600; margin-bottom: 8px; display: flex; align-items: center; gap: 8px; }
        .info-card p { color: var(--text-secondary); font-size: 13px; line-height: 1.5; margin-bottom: 8px; }
        .info-card ul { margin-left: 16px; color: var(--text-secondary); font-size: 13px; }
        .info-card li { margin-bottom: 4px; }
        
        .security-indicator { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--success-color); margin-top: 4px; font-weight: 600;}
        .btn.loading { opacity: 0.7; cursor: not-allowed; }
    </style>
</head>
<body>

<div class="container">
    <div class="page-header">
        <h1 class="page-title"><i class="fas fa-key"></i> Credenciais de Pagamento</h1>
    </div>

    <?php if ($credenciaisAtualizadas): ?>
        <div class="success-message">
            <i class="fas fa-check-circle"></i>
            <span>Credenciais atualizadas com sucesso!</span>
        </div>
    <?php endif; ?>

    <div class="status-card">
        <div class="status-icon <?= $credenciaisExistem ? 'configurado' : 'nao-configurado'; ?>">
            <i class="fas fa-<?= $credenciaisExistem ? 'shield-alt' : 'exclamation-triangle'; ?>"></i>
        </div>
        <div class="status-info">
            <h3><?= $credenciaisExistem ? 'Credenciais Configuradas' : 'Aguardando Configuração'; ?></h3>
            <p><?= $credenciaisExistem ? 'Seu sistema está pronto para processar pagamentos.' : 'Preencha os campos abaixo para ativar os pagamentos.'; ?></p>
        </div>
    </div>

    <div class="info-card">
        <h4><i class="fas fa-info-circle"></i> Segurança das Credenciais</h4>
        <p>Por segurança, as credenciais salvas não são exibidas nos campos abaixo.</p>
        <ul>
            <li>Para <strong>manter</strong> a credencial atual, deixe o campo em branco.</li>
            <li>Para <strong>atualizar</strong>, apague e digite a nova credencial.</li>
        </ul>
    </div>

    <div class="form-container">
        <div class="form-header">
            <i class="fas fa-cog"></i>
            <h3>Configurar Mercado Pago</h3>
        </div>

        <form method="POST" id="credentialsForm">
            <div class="form-group">
                <label for="access_token" class="form-label">
                    <i class="fas fa-user-secret"></i> Access Token
                </label>
                <input type="password" 
                       id="access_token" 
                       name="access_token" 
                       class="form-input"
                       placeholder="<?= ($credenciaisExistem && !empty($credenciais['access_token'])) ? '•••••••••••••••••••••••••••••• (Salvo e Oculto)' : 'Cole seu Access Token aqui'; ?>">
                
                <?php if ($credenciais && !empty($credenciais['access_token'])): ?>
                    <div class="security-indicator">
                        <i class="fas fa-lock"></i> Token Ativo e Protegido
                    </div>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label for="public_key" class="form-label">
                    <i class="fas fa-key"></i> Public Key
                </label>
                <input type="password" 
                       id="public_key" 
                       name="public_key" 
                       class="form-input"
                       placeholder="<?= ($credenciaisExistem && !empty($credenciais['public_key'])) ? '•••••••••••••••••••••••••••••• (Salvo e Oculto)' : 'Cole sua Public Key aqui'; ?>">
                
                <?php if ($credenciais && !empty($credenciais['public_key'])): ?>
                    <div class="security-indicator">
                        <i class="fas fa-lock"></i> Chave Ativa e Protegida
                    </div>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
                    <input type="checkbox" name="mercadopago_enabled" value="1" 
                           <?= (isset($mercadopago_config['enabled']) && $mercadopago_config['enabled'] == '1') ? 'checked' : ''; ?>
                           style="width: 20px; height: 20px; cursor: pointer;">
                    <span>Ativar Mercado Pago</span>
                </label>
            </div>

            <button type="submit" class="btn" id="submitBtn">
                <i class="fas fa-save"></i> Salvar Alterações
            </button>
        </form>
    </div>

    <!-- Seção Stripe -->
    <div class="form-container" style="margin-top: 30px;">
        <div class="form-header">
            <i class="fab fa-stripe"></i>
            <h3>Configurar Stripe</h3>
        </div>

        <form method="POST" id="stripeForm">
            <div class="form-group">
                <label for="stripe_public_key" class="form-label">
                    <i class="fas fa-key"></i> Public Key
                </label>
                <input type="password" 
                       id="stripe_public_key" 
                       name="stripe_public_key" 
                       class="form-input"
                       placeholder="<?= (!empty($stripe_config['public_key'])) ? '•••••••••••••••••••••••••••••• (Salvo e Oculto)' : 'Cole sua Stripe Public Key aqui'; ?>">
                
                <?php if (!empty($stripe_config['public_key'])): ?>
                    <div class="security-indicator">
                        <i class="fas fa-lock"></i> Chave Ativa e Protegida
                    </div>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label for="stripe_secret_key" class="form-label">
                    <i class="fas fa-user-secret"></i> Secret Key
                </label>
                <input type="password" 
                       id="stripe_secret_key" 
                       name="stripe_secret_key" 
                       class="form-input"
                       placeholder="<?= (!empty($stripe_config['secret_key'])) ? '•••••••••••••••••••••••••••••• (Salvo e Oculto)' : 'Cole sua Stripe Secret Key aqui'; ?>">
                
                <?php if (!empty($stripe_config['secret_key'])): ?>
                    <div class="security-indicator">
                        <i class="fas fa-lock"></i> Chave Ativa e Protegida
                    </div>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
                    <input type="checkbox" name="stripe_enabled" value="1" 
                           <?= (isset($stripe_config['enabled']) && $stripe_config['enabled'] == '1') ? 'checked' : ''; ?>
                           style="width: 20px; height: 20px; cursor: pointer;">
                    <span>Ativar Stripe</span>
                </label>
            </div>

            <button type="submit" class="btn">
                <i class="fas fa-save"></i> Salvar Configurações Stripe
            </button>
        </form>
    </div>

    <!-- Seção PayPal -->
    <div class="form-container" style="margin-top: 30px;">
        <div class="form-header">
            <i class="fab fa-paypal"></i>
            <h3>Configurar PayPal</h3>
        </div>

        <form method="POST" id="paypalForm">
            <div class="form-group">
                <label for="paypal_client_id" class="form-label">
                    <i class="fas fa-id-card"></i> Client ID
                </label>
                <input type="password" 
                       id="paypal_client_id" 
                       name="paypal_client_id" 
                       class="form-input"
                       placeholder="<?= (!empty($paypal_config['client_id'])) ? '•••••••••••••••••••••••••••••• (Salvo e Oculto)' : 'Cole seu PayPal Client ID aqui'; ?>">
                
                <?php if (!empty($paypal_config['client_id'])): ?>
                    <div class="security-indicator">
                        <i class="fas fa-lock"></i> Client ID Ativo e Protegido
                    </div>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label for="paypal_client_secret" class="form-label">
                    <i class="fas fa-user-secret"></i> Client Secret
                </label>
                <input type="password" 
                       id="paypal_client_secret" 
                       name="paypal_client_secret" 
                       class="form-input"
                       placeholder="<?= (!empty($paypal_config['client_secret'])) ? '•••••••••••••••••••••••••••••• (Salvo e Oculto)' : 'Cole seu PayPal Client Secret aqui'; ?>">
                
                <?php if (!empty($paypal_config['client_secret'])): ?>
                    <div class="security-indicator">
                        <i class="fas fa-lock"></i> Client Secret Ativo e Protegido
                    </div>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label for="paypal_mode" class="form-label">
                    <i class="fas fa-cog"></i> Mode
                </label>
                <select id="paypal_mode" name="paypal_mode" class="form-input">
                    <option value="sandbox" <?= (isset($paypal_config['mode']) && $paypal_config['mode'] == 'sandbox') ? 'selected' : ''; ?>>Sandbox (Teste)</option>
                    <option value="live" <?= (isset($paypal_config['mode']) && $paypal_config['mode'] == 'live') ? 'selected' : ''; ?>>Live (Produção)</option>
                </select>
            </div>

            <div class="form-group">
                <label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
                    <input type="checkbox" name="paypal_enabled" value="1" 
                           <?= (isset($paypal_config['enabled']) && $paypal_config['enabled'] == '1') ? 'checked' : ''; ?>
                           style="width: 20px; height: 20px; cursor: pointer;">
                    <span>Ativar PayPal</span>
                </label>
            </div>

            <button type="submit" class="btn">
                <i class="fas fa-save"></i> Salvar Configurações PayPal
            </button>
        </form>
    </div>

    <!-- ============================================================
         PAGAR.ME
         ============================================================ -->
    <div class="form-card">
        <div class="form-header">
            <i class="fas fa-credit-card"></i>
            <h3>Configurar Pagar.me</h3>
        </div>

        <form method="POST" id="pagarmeForm">
            <div class="form-group">
                <label for="pagarme_api_key" class="form-label">
                    <i class="fas fa-key"></i> API Key
                </label>
                <input type="password" 
                       id="pagarme_api_key" 
                       name="pagarme_api_key" 
                       class="form-input"
                       placeholder="<?= (!empty($pagarme_config['api_key'])) ? '•••••••••••••••••••••••••••••• (Salvo e Oculto)' : 'Cole sua Pagar.me API Key aqui'; ?>">
                
                <?php if (!empty($pagarme_config['api_key'])): ?>
                    <div class="security-indicator">
                        <i class="fas fa-lock"></i> API Key Ativa e Protegida
                    </div>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label for="pagarme_encryption_key" class="form-label">
                    <i class="fas fa-user-secret"></i> Encryption Key
                </label>
                <input type="password" 
                       id="pagarme_encryption_key" 
                       name="pagarme_encryption_key" 
                       class="form-input"
                       placeholder="<?= (!empty($pagarme_config['encryption_key'])) ? '•••••••••••••••••••••••••••••• (Salvo e Oculto)' : 'Cole sua Pagar.me Encryption Key aqui'; ?>">
                
                <?php if (!empty($pagarme_config['encryption_key'])): ?>
                    <div class="security-indicator">
                        <i class="fas fa-lock"></i> Encryption Key Ativa e Protegida
                    </div>
                <?php endif; ?>
            </div>

            <div class="form-group">
                <label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
                    <input type="checkbox" name="pagarme_enabled" value="1" 
                           <?= (isset($pagarme_config['enabled']) && $pagarme_config['enabled'] == '1') ? 'checked' : ''; ?>
                           style="width: 20px; height: 20px; cursor: pointer;">
                    <span>Ativar Pagar.me</span>
                </label>
            </div>

            <button type="submit" class="btn">
                <i class="fas fa-save"></i> Salvar Configurações Pagar.me
            </button>
        </form>
    </div>
</div>

<script>
    // JS para loading do botão
    document.getElementById('credentialsForm').addEventListener('submit', function(e) {
        const submitBtn = document.getElementById('submitBtn');
        submitBtn.classList.add('loading');
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processando...';
    });

    // JS para ocultar mensagem de sucesso
    const successMessage = document.querySelector('.success-message');
    if (successMessage) {
        setTimeout(() => {
            successMessage.style.opacity = '0';
            successMessage.style.transform = 'translateY(-10px)';
            setTimeout(() => { successMessage.style.display = 'none'; }, 300);
        }, 4000);
    }

    // SCRIPT DE SINCRONIZAÇÃO COM O DARK MODE DO INDEX.PHP
    (function() {
        const html = document.documentElement;
        
        // 1. Verifica tema inicial
        const savedTheme = localStorage.getItem('theme');
        if (savedTheme === 'dark') {
            html.setAttribute('data-theme', 'dark');
        }

        // 2. Escuta o clique no botão do menu principal (index.php)
        const mainThemeBtn = window.parent.document.getElementById('themeBtn') || document.getElementById('themeBtn');
        
        if(mainThemeBtn) {
            mainThemeBtn.addEventListener('click', function() {
                setTimeout(() => {
                    const currentTheme = localStorage.getItem('theme');
                    if (currentTheme === 'dark') {
                        html.setAttribute('data-theme', 'dark');
                    } else {
                        html.removeAttribute('data-theme');
                    }
                }, 50);
            });
        }
    })();
</script>

</body>
</html>