<?php
// Conexão com o banco de dados
// Nota: Autenticação já verificada em dashboard/index.php
require_once __DIR__ . '/../../config/config_db.php';
// Inicialização das variáveis de controle
$pixelAtualizado = false;
$pixelExiste = false;
$message = '';


// Busca o ID do Pixel salvo
$sql = "SELECT * FROM configuracoes WHERE chave = 'facebook_pixel_id'";
$stmt = $pdo->query($sql);
$config = $stmt->fetch(PDO::FETCH_ASSOC);
$pixel_id_atual = $config ? $config['valor'] : '';

if ($config && !empty($pixel_id_atual)) {
    $pixelExiste = true;
}

// Atualiza ou remove o ID do Pixel caso o formulário seja enviado
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pixel_id = trim($_POST['pixel_id']);

    if (empty($pixel_id)) {
        // Se o campo estiver vazio, remove o ID do Pixel do banco de dados
        if ($config) {
            $sql = "DELETE FROM configuracoes WHERE chave = 'facebook_pixel_id'";
            $stmt = $pdo->prepare($sql);
            $stmt->execute();
            $message = "ID do Pixel removido com sucesso!";
            $pixelExiste = false;
            $pixel_id_atual = '';
        }
    } else {
        if ($config) {
            // Atualiza o ID do Pixel existente
            $sql = "UPDATE configuracoes SET valor = :valor WHERE chave = 'facebook_pixel_id'";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':valor' => $pixel_id]);
            $message = "ID do Pixel atualizado com sucesso!";
        } else {
            // Insere um novo ID do Pixel
            $sql = "INSERT INTO configuracoes (chave, valor) VALUES ('facebook_pixel_id', :valor)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([':valor' => $pixel_id]);
            $message = "ID do Pixel salvo com sucesso!";
        }
        
        $pixelExiste = true;
        $pixel_id_atual = $pixel_id;
    }

    $pixelAtualizado = true;
}
?>

<!-- Página incluída no dashboard/index.php - não precisa de tags HTML completas -->
<style>
        /* ==========================================================
           2. ESTILOS CSS (COM SUPORTE A DARK MODE)
           ========================================================== */
        :root {
            /* Cores Padrão (Light Mode) */
            --primary-color: #1877F2;
            --primary-light: #42A5F5;
            --primary-dark: #1565C0;
            --secondary-color: #009846;
            --success-color: #4CAF50;
            --warning-color: #FFC107;
            --danger-color: #F44336;
            --info-color: #2196F3;
            --facebook-blue: #1877F2;
            
            --text-primary: #212121;
            --text-secondary: #757575;
            --text-muted: #9E9E9E;
            
            --bg-light: #f4f4f4;
            --bg-white: var(--bg-card, #FFFFFF);
            --bg-input: 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 */
            --bg-input: var(--bg-card, #1e293b); /* Inputs Escuros */
            
            --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;
        }

        .page-title .fab.fa-facebook {
            color: var(--facebook-blue);
        }

        /* Status card */
        .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(24, 119, 242, 0.1);
            color: var(--facebook-blue);
        }

        .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 */
        .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-header .fab.fa-facebook {
            color: var(--facebook-blue);
        }

        .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-input); /* Ajustado para Dark Mode */
            transition: var(--transition);
            font-family: 'Courier New', monospace;
        }

        .form-input:focus {
            outline: none;
            border-color: var(--facebook-blue);
            box-shadow: 0 0 0 3px rgba(24, 119, 242, 0.1);
        }

        .form-input::placeholder {
            color: var(--text-muted);
            font-family: 'Montserrat', sans-serif;
        }

        .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(--secondary-color);
            color: white;
            text-align: center;
            border: none;
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: var(--transition);
            width: 100%;
        }

        .btn:hover {
            background-color: #007635;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 152, 70, 0.3);
        }

        .btn:active {
            transform: translateY(0);
        }

        /* Success message */
        .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);
            }
        }

        .success-message i {
            font-size: 20px;
        }

        /* Info card */
        .info-card {
            background-color: rgba(24, 119, 242, 0.05);
            border: 1px solid rgba(24, 119, 242, 0.2);
            border-radius: var(--border-radius);
            padding: 16px;
            margin-bottom: 24px;
        }

        .info-card h4 {
            color: var(--facebook-blue);
            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;
        }

        /* Loading state */
        .btn.loading {
            opacity: 0.7;
            cursor: not-allowed;
        }

        .btn.loading:hover {
            transform: none;
            box-shadow: none;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 16px;
            }

            .status-card {
                flex-direction: column;
                text-align: center;
            }

            .form-container {
                padding: 20px;
            }
        }

        /* Security indicator */
        .security-indicator {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            color: var(--facebook-blue);
            margin-top: 4px;
        }

        .security-indicator.warning {
            color: var(--warning-color);
        }

        /* Pixel ID preview */
        .pixel-preview {
            background-color: rgba(24, 119, 242, 0.05);
            border: 1px solid rgba(24, 119, 242, 0.2);
            border-radius: var(--border-radius);
            padding: 12px;
            margin-top: 8px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            color: var(--text-secondary);
        }
    </style>

<div class="container">
    <div class="page-header">
        <h1 class="page-title">
            <i class="fab fa-facebook"></i> Facebook Pixel
        </h1>
    </div>

    <?php if ($pixelAtualizado && !empty($message)): ?>
        <div class="success-message">
            <i class="fas fa-check-circle"></i>
            <span><?= $message; ?></span>
        </div>
    <?php endif; ?>

    <div class="status-card">
        <div class="status-icon <?= $pixelExiste ? 'configurado' : 'nao-configurado'; ?>">
            <i class="fab fa-<?= $pixelExiste ? 'facebook' : 'facebook'; ?>"></i>
        </div>
        <div class="status-info">
            <h3>
                <?= $pixelExiste ? 'Facebook Pixel Configurado' : 'Facebook Pixel Não Configurado'; ?>
            </h3>
            <p>
                <?= $pixelExiste 
                    ? 'Seu Facebook Pixel está ativo e rastreando conversões.' 
                    : 'Configure seu Facebook Pixel para rastrear conversões e otimizar campanhas.'; ?>
            </p>
            <?php if ($pixelExiste): ?>
                <div class="pixel-preview">
                    ID do Pixel: <?= htmlspecialchars($pixel_id_atual); ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="info-card">
        <h4>
            <i class="fas fa-info-circle"></i>
            Como Obter seu Facebook Pixel ID
        </h4>
        <p>Para encontrar o ID do seu Facebook Pixel, siga estes passos:</p>
        <ul>
            <li>Acesse o <strong>Facebook Business Manager</strong></li>
            <li>Vá para <strong>Ferramentas de Eventos</strong> → <strong>Pixels</strong></li>
            <li>Selecione seu pixel ou crie um novo</li>
            <li>Copie o <strong>ID do Pixel</strong> (sequência numérica de 15-16 dígitos)</li>
            <li>Cole o ID no campo abaixo para ativar o rastreamento</li>
            <li>Deixe o campo vazio para desativar o pixel</li>
        </ul>
    </div>

    <div class="form-container">
        <div class="form-header">
            <i class="fab fa-facebook"></i>
            <h3>Configurar Facebook Pixel</h3>
        </div>

        <form method="POST" id="pixelForm">
            <div class="form-group">
                <label for="pixel_id" class="form-label">
                    <i class="fas fa-hashtag"></i>
                    ID do Facebook Pixel
                </label>
                <input type="text" 
                       id="pixel_id" 
                       name="pixel_id" 
                       class="form-input"
                       placeholder="Ex: 123456789012345"
                       value="<?= htmlspecialchars($pixel_id_atual); ?>"
                       pattern="[0-9]{15,16}"
                       title="ID do Pixel deve conter 15-16 dígitos">
                <div class="input-help">
                    <i class="fas fa-lightbulb"></i>
                    Sequência numérica de 15-16 dígitos encontrada no Facebook Business Manager
                </div>
                <?php if ($pixelExiste): ?>
                    <div class="security-indicator">
                        <i class="fas fa-check-circle"></i>
                        Pixel ativo e rastreando
                    </div>
                <?php endif; ?>
            </div>

            <button type="submit" class="btn" id="submitBtn">
                <i class="fas fa-save"></i>
                <?= $pixelExiste ? 'Atualizar Pixel' : 'Salvar Pixel'; ?>
            </button>
        </form>
    </div>
</div>

<script>
    // SCRIPT DE SINCRONIZAÇÃO COM O DARK MODE DO INDEX.PHP
    (function() {
        const html = document.documentElement;
        // Tenta pegar o botão do index.php
        const mainThemeBtn = window.parent.document.getElementById('themeBtn') || document.getElementById('themeBtn');

        function syncTheme() {
            const savedTheme = localStorage.getItem('theme');
            if (savedTheme === 'dark') {
                html.setAttribute('data-theme', 'dark');
            } else {
                html.removeAttribute('data-theme');
            }
        }

        // Aplica ao carregar
        syncTheme();

        // Ouve o clique no botão do menu principal
        if(mainThemeBtn) {
            mainThemeBtn.addEventListener('click', function() {
                setTimeout(syncTheme, 50);
            });
        }
    })();

    // Validação do ID do Pixel em tempo real
    const pixelInput = document.getElementById('pixel_id');
    const submitBtn = document.getElementById('submitBtn');

    if(pixelInput) {
        pixelInput.addEventListener('input', function() {
            const value = this.value.trim();
            const isValid = /^[0-9]{15,16}$/.test(value) || value === '';
            
            if (value !== '' && !isValid) {
                this.style.borderColor = 'var(--danger-color)';
                this.style.boxShadow = '0 0 0 3px rgba(244, 67, 54, 0.1)';
            } else {
                this.style.borderColor = '';
                this.style.boxShadow = '';
            }
        });

        // Formatação automática (apenas números)
        pixelInput.addEventListener('keypress', function(e) {
            if (!/[0-9]/.test(e.key) && !['Backspace', 'Delete', 'Tab', 'Enter'].includes(e.key)) {
                e.preventDefault();
            }
        });
    }

    // Form submission com loading state
    document.getElementById('pixelForm').addEventListener('submit', function(e) {
        const pixelId = pixelInput.value.trim();
        
        // Validação adicional
        if (pixelId !== '' && !/^[0-9]{15,16}$/.test(pixelId)) {
            e.preventDefault();
            alert('Por favor, insira um ID válido do Facebook Pixel (15-16 dígitos).');
            return;
        }
        
        // Loading state
        submitBtn.classList.add('loading');
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Salvando...';
        submitBtn.disabled = true;
    });

    // Auto-hide success message
    const successMessage = document.querySelector('.success-message');
    if (successMessage) {
        setTimeout(() => {
            successMessage.style.opacity = '0';
            successMessage.style.transform = 'translateY(-10px)';
            setTimeout(() => {
                successMessage.style.display = 'none';
            }, 300);
        }, 5000);
    }
</script>