<?php
// 1. INCLUIR ARCHIVOS DE CONEXIÓN Y SEGURIDAD
include 'files/guardiankey.php'; 
include 'db/db_connection.php'; // Conexión a la base de datos

// 2. OBTENER DATOS DE LA TABLA website_config
$company_name_from_db = ''; // Valor por defecto
$phone_from_db = ''; // Valor por defecto
$website_from_db = ''; // Valor por defecto

try {
    $stmt = $pdo->query("SELECT company_name, phone_primary, website_url FROM website_config WHERE id = 1 LIMIT 1");
    $config = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($config) {
        $company_name_from_db = $config['company_name'] ?? $company_name_from_db;
        $phone_from_db = $config['phone_primary'] ?? $phone_from_db;
        $website_from_db = $config['website_url'] ?? $website_from_db;
    }
} catch (PDOException $e) {
    // En caso de error, la página usará los valores por defecto sin romperse.
    error_log("Error fetching website_config: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LocalCRM ToolKit | Generador De Anuncios Publicitarios</title>

    <script src="https://cdn.tailwindcss.com"></script>
    <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=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
</head>
<body data-page-title="Generador De Anuncios"
      data-page-subtitle="Crea Textos Publicitarios Que Venden Para Tus Servicios"
      data-page-icon="file-pen">

<div class="relative min-h-screen md:flex">
    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>

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

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8">
            <section id="ad-generator" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">

                    <div class="lg:col-span-3">
                        <form id="ad-generator-form" class="space-y-8 bg-white p-8 rounded-xl shadow-md">
                            <div>
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                        <i class="fas fa-briefcase mr-3 text-[var(--color-secondary)]"></i>
                                        <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> DEFINE TU NEGOCIO
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa los datos de tu empresa y servicio a promocionar.</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                        <div>
                                            <label for="business_name" class="block font-bold text-gray-700 mb-2">Nombre De Tu Negocio</label>
                                            <input type="text" id="business_name" class="w-full p-3 bg-gray-100 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($company_name_from_db); ?>" readonly>
                                        </div>
                                        <div>
                                            <label for="phone" class="block font-bold text-gray-700 mb-2">Teléfono / WhatsApp</label>
                                            <input type="text" id="phone" class="w-full p-3 bg-gray-100 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($phone_from_db); ?>" readonly>
                                        </div>
                                    </div>
                                    <div>
                                        <label for="website" class="block font-bold text-gray-700 mb-2">Página Web o Facebook (Opcional)</label>
                                        <input type="text" id="website" class="w-full p-3 bg-gray-100 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($website_from_db); ?>" readonly>
                                    </div>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 pt-4">
                                        <div>
                                            <label for="service" class="block font-bold text-gray-700 mb-2">Servicio A Promocionar</label>
                                            <input type="text" id="service" placeholder="Ej: Deep Cleaning" class="w-full p-3 bg-white border border-gray-300 rounded-lg" required>
                                        </div>
                                        <div>
                                            <label for="zone" class="block font-bold text-gray-700 mb-2">Zona De Servicio</label>
                                            <input type="text" id="zone" placeholder="Ej: Seattle WA" class="w-full p-3 bg-white border border-gray-300 rounded-lg" required>
                                        </div>
                                    </div>
                                    <div>
                                        <label for="problem" class="block font-bold text-gray-700 mb-2">Problema Urgente Del Cliente</label>
                                        <textarea id="problem" placeholder="Ej: No tiene tiempo para limpiar" class="w-full p-3 bg-white border border-gray-300 rounded-lg" rows="3" required></textarea>
                                    </div>
                                    <div>
                                        <label for="desire" class="block font-bold text-gray-700 mb-2">Deseo Profundo Del Cliente</label>
                                        <textarea id="desire" placeholder="Ej: Quiere llegar a casa y encontrarla impecable para relajarse" class="w-full p-3 bg-white border border-gray-300 rounded-lg" rows="3" required></textarea>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                    <div class="lg:col-span-2 space-y-8">
                        <div class="bg-white rounded-xl shadow-md">
                            <div class="native-video-wrapper" id="videoWrapper">
                                <div class="play-overlay" id="playOverlay">
                                    <img src="https://placehold.co/600x337/07162d/ffc857?text=VIDEO" alt="Imagen de previsualización del video" class="absolute inset-0 w-full h-full object-cover rounded-xl">
                                    <i class="fas fa-play play-icon"></i>
                                </div>
                                <video class="w-full h-full object-cover" id="videoPlayer" controlslist="nodownload nofullscreen" preload="metadata">
                                    <source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
                                    Tu navegador no soporta la etiqueta de video.
                                </video>
                            </div>
                        </div>
                        <div class="bg-white text-brand-dark p-6 md:p-8 rounded-xl shadow-md">
                            <div class="step-header">
                                <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase justify-center md:justify-start">
                                    <i class="fas fa-book mr-3 text-[var(--color-highlight)]"></i> 
                                    INSTRUCCIONES
                                </h2>
                               <p class="step-subtitle text-center md:text-left uppercase">REVISA ESTOS PUNTOS DETALLADAMENTE</p>
                            </div>
                            <div class="border-b border-gray-200 pb-4 mb-6"></div>
                            <ul class="space-y-4 text-gray-700">
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-lightbulb"></i></span><div><strong class="text-brand-dark">Sé Específico:</strong> Cuanto más detalles des sobre el problema y el deseo de tu cliente, más persuasivos serán los anuncios.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-cogs"></i></span><div><strong class="text-brand-dark">Genera Las Opciones:</strong> Haz clic en 'Generar Anuncios' para que la IA cree 3 versiones distintas para tu campaña.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-copy"></i></span><div><strong class="text-brand-dark">Copia y Pega:</strong> Elige el anuncio que más te guste, cópialo con un solo clic y úsalo en tus campañas.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-sync-alt"></i></span><div><strong class="text-brand-dark">Prueba y Optimiza:</strong> No dudes en generar varias veces con pequeñas variaciones para encontrar el texto perfecto.</div></li>
                            </ul>
                        </div>
                    </div>

                    <div class="lg:col-span-5 bg-white p-6 md:p-8 rounded-xl shadow-md mt-6">
                        <div class="step-header">
                             <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                <i class="fas fa-magic-wand-sparkles mr-3 text-[var(--color-secondary)]"></i>
                                <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> CREAR ANUNCIOS
                            </h2>
                            <p class="step-subtitle uppercase">Genera 3 anuncios persuasivos en español e inglés con un solo clic.</p>
                        </div>
                        <div class="border-b border-gray-200 pb-4 mb-6"></div>
                         <div class="flex flex-col md:flex-row items-center md:justify-between gap-4">
<p class="text-lg text-center md:text-left text-gray-700 md:flex-1 md:pr-4 mb-0">Para crear anuncios efectivos, es <b>crucial que los datos sobre tu negocio y cliente ideal sean precisos</b>. Basado en esta información, <strong class="font-black">CLIENT3 IA</strong>, nuestra Inteligencia Artificial, generará <b>3 textos de anuncio únicos</b> y completamente personalizados, listos para captar la atención y vender tus servicios.</p>                               <button id="generateBtn" type="submit" form="ad-generator-form" class="w-full md:w-auto bg-[var(--color-highlight)] text-brand-dark font-bold py-4 px-6 rounded-lg hover:scale-105 transition-transform shadow-lg text-lg flex items-center justify-center uppercase">
                                    <i class="fas fa-brain mr-3"></i>
                                    <span id="btn-text">GENERAR ANUNCIOS</span>
                                    <div id="loader-container" class="hidden ml-3"></div>
                                </button>
                        </div>
                    </div>

                    <div id="result-container" class="lg:col-span-5 mt-8"></div>
                </div>
            </section>
        </div>
    </main>
</div>

<script src="files/header-manager.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();

    // --- Lógica del Video Player ---
    const videoPlayer = document.getElementById('videoPlayer');
    const playOverlay = document.getElementById('playOverlay');
    if (videoPlayer && playOverlay) {
        videoPlayer.controls = false;
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.controls = true;
            videoPlayer.play().catch(e => console.error("Error al reproducir video:", e));
        });
        videoPlayer.addEventListener('ended', () => {
            playOverlay.style.display = 'flex';
            videoPlayer.controls = false;
        });
    }

    // --- Lógica del Generador ---
    const form = document.getElementById('ad-generator-form');
    const resultContainer = document.getElementById('result-container');
    const generateBtn = document.getElementById('generateBtn');
    const btnText = document.getElementById('btn-text');
    const loaderContainer = document.getElementById('loader-container');

    form.addEventListener('submit', async function(event) {
        event.preventDefault();
        btnText.textContent = 'Generando...';
        loaderContainer.innerHTML = '<div class="w-6 h-6 border-4 border-t-transparent border-[var(--color-primary)] rounded-full animate-spin"></div>';
        loaderContainer.classList.remove('hidden');
        generateBtn.disabled = true;
        resultContainer.innerHTML = '';

        const formData = {
            business_name: document.getElementById('business_name').value,
            phone: document.getElementById('phone').value,
            website: document.getElementById('website').value,
            service: document.getElementById('service').value,
            zone: document.getElementById('zone').value,
            problem: document.getElementById('problem').value,
            desire: document.getElementById('desire').value
        };

        try {
            const response = await fetch('api/API-Generador-De-Anuncios-Publicitarios.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });

            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`El servidor respondió con un error ${response.status}. Detalle: ${errorText}`);
            }

            const data = await response.json();
            if(data.error) {
                throw new Error(data.error);
            }
            displayResults(data.anuncios);

        } catch (error) {
            console.error("Error:", error);
            let errorMessage = "No se pudieron generar los anuncios. Por favor, revisa los datos e inténtalo de nuevo.";

            try {
                const jsonStartIndex = error.message.indexOf('{');
                if (jsonStartIndex !== -1) {
                    const errorJsonString = error.message.substring(jsonStartIndex);
                    const errorDetails = JSON.parse(errorJsonString);
                    if (errorDetails.error && errorDetails.error.code === 503) {
                        errorMessage = "LO SENTIMOS En Este Momento, Nuestra Inteligencia Artificial Está Saturada. Por favor, Inténtalo De Nuevo En Unos Minutos.";
                    } else {
                        errorMessage += ` Detalles: ${error.message}`;
                    }
                } else {
                    errorMessage += ` Detalles: ${error.message}`;
                }
            } catch (parseError) {
                errorMessage += ` Detalles: ${error.message}`;
            }
            resultContainer.innerHTML = `<div class="bg-red-100 text-center p-4 text-red-700 rounded-lg border border-red-300"><p><strong>Error:</strong> ${errorMessage}</p></div>`;
        } finally {
            btnText.textContent = 'GENERAR ANUNCIOS';
            loaderContainer.classList.add('hidden');
            generateBtn.disabled = false;
        }
    });

    function displayResults(anuncios) {
        resultContainer.innerHTML = '';
        anuncios.forEach((anuncio, index) => {
            const adCard = createAdCard(anuncio, index);
            resultContainer.appendChild(adCard);
        });

        resultContainer.addEventListener('click', function(e) {
            const button = e.target.closest('.copy-btn');
            if (button) {
                const textToCopy = decodeURIComponent(button.dataset.copytext);
                navigator.clipboard.writeText(textToCopy).then(() => {
                    const originalContent = button.innerHTML;
                    button.innerHTML = '<i class="fas fa-check"></i> Copiado';
                    button.classList.add('copied');
                    setTimeout(() => {
                        button.innerHTML = originalContent;
                        button.classList.remove('copied');
                    }, 2000);
                });
            }
        });
    }

    function createAdCard(anuncio, index) {
        const container = document.createElement('div');
        container.className = 'ad-result-wrapper bg-white p-6 rounded-xl shadow-lg mb-8';
        container.style.animationDelay = `${index * 150}ms`;

        const full_es_text = `${anuncio.es.gancho}\n\n${anuncio.es.solucion}\n\n${anuncio.es.cta}`;
        const full_en_text = `${anuncio.en.gancho}\n\n${anuncio.en.solucion}\n\n${anuncio.en.cta}`;

        container.innerHTML = `
            <h3 class="text-xl font-bold text-gray-800 mb-4">${anuncio.titulo}</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
                <div class="ad-card bg-gray-50 p-4 rounded-lg border border-gray-200">
                    <div class="ad-card-header flex justify-between items-center mb-3">
                        <h4 class="text-lg font-semibold text-gray-700">🇪🇸 Español</h4>
                        <button class="copy-btn bg-[var(--color-primary)] text-white px-3 py-1 rounded-md text-sm hover:opacity-90 transition-opacity" data-copytext="${encodeURIComponent(full_es_text)}"><i class="fas fa-copy mr-1"></i>COPIAR TEXTO</button>
                    </div>
                    <div class="ad-card-body">
                        <div class="ad-part mb-3"><strong class="ad-part-title text-base font-extrabold text-[var(--color-secondary)] block mb-1">Gancho:</strong><p class="text-gray-800 leading-relaxed">${anuncio.es.gancho}</p></div>
                        <div class="ad-part mb-3"><strong class="ad-part-title text-base font-extrabold text-[var(--color-secondary)] block mb-1">Solución:</strong><p class="text-gray-800 leading-relaxed">${anuncio.es.solucion.replace(/\n/g, '<br>')}</p></div>
                        <div class="ad-part"><strong class="ad-part-title text-base font-extrabold text-[var(--color-secondary)] block mb-1">Llamada a la Acción:</strong><p class="text-gray-800 leading-relaxed">${anuncio.es.cta}</p></div>
                    </div>
                </div>
                <div class="ad-card bg-gray-50 p-4 rounded-lg border border-gray-200">
                    <div class="ad-card-header flex justify-between items-center mb-3">
                        <h4 class="ad-language-title text-lg font-semibold text-gray-700">🇺🇸 English</h4>
                        <button class="copy-btn bg-[var(--color-primary)] text-white px-3 py-1 rounded-md text-sm hover:opacity-90 transition-opacity" data-copytext="${encodeURIComponent(full_en_text)}"><i class="fas fa-copy mr-1"></i>COPIAR TEXTO</button>
                    </div>
                    <div class="ad-card-body">
                        <div class="ad-part mb-3"><strong class="ad-part-title text-base font-extrabold text-[var(--color-secondary)] block mb-1">Hook:</strong><p class="text-gray-800 leading-relaxed">${anuncio.en.gancho}</p></div>
                        <div class="ad-part mb-3"><strong class="ad-part-title text-base font-extrabold text-[var(--color-secondary)] block mb-1">Solution:</strong><p class="text-gray-800 leading-relaxed">${anuncio.en.solucion.replace(/\n/g, '<br>')}</p></div>
                        <div class="ad-part"><strong class="ad-part-title text-base font-extrabold text-[var(--color-secondary)] block mb-1">Call to Action:</strong><p class="text-gray-800 leading-relaxed">${anuncio.en.cta}</p></div>
                    </div>
                </div>
            </div>`;
        return container;
    }
});
</script>

</body>
</html>