<?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
$user_name_from_db = ''; // Valor por defecto
$company_name_from_db = ''; // Valor por defecto

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

    if ($config) {
        $user_name_from_db = htmlspecialchars($config['contact_name'] ?? $user_name_from_db);
        $company_name_from_db = htmlspecialchars($config['company_name'] ?? $company_name_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 | Creador De Publicaciones Sociales | OrozDesign Multimedia</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">
    <script src="files/header-manager.js"></script>
        
    <style>
        /* Estilos específicos para los títulos de los pasos (copiados del archivo anterior) */
        .step-header h2 {
            flex-direction: column;
            align-items: flex-start;
            justify-content: flex-start;
            text-align: left;
        }

        .step-header .step-number {
            font-size: 1.25rem;
            font-weight: 900;
            margin-right: 0;
            margin-bottom: 0.25rem;
            display: flex;
            align-items: center;
            color: var(--color-secondary);
            flex-shrink: 0;
            text-align: left;
        }
        .step-header .step-number i {
            margin-right: 0.5rem;
            font-size: 1.5rem;
        }

        .step-header .step-title {
            font-size: 1.4rem;
            font-weight: 900;
            color: #1e293b;
            line-height: 1.2;
            text-transform: uppercase;
            text-align: left;
            width: 100%;
        }

        @media (min-width: 768px) {
            .step-header h2 {
                flex-direction: row;
                align-items: center;
                justify-content: flex-start;
                text-align: left;
            }
            .step-header .step-number {
                font-size: 1.5rem;
                margin-right: 0.5rem;
                margin-bottom: 0;
                text-align: left;
            }
            .step-header .step-number i {
                font-size: 1.8rem;
            }
            .step-header .step-title {
                font-size: 1.5rem;
                width: auto;
                text-align: left;
            }
        }
    </style>
</head>
<body data-page-title="Creador De Publicaciones Sociales"
      data-page-subtitle="Crea Posts Que Abordan El Problema, La Solución Y Tu Servicio"
      data-page-icon="share-2">
    
    <div id="toast-container" class="toast-container"></div>

<?php include 'files/gtm-body.php'; ?>

<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="social-post-creator" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">

                    <div class="lg:col-span-3">
                        <form id="social-post-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">
                                        <span class="step-number"> <i class="fas fa-briefcase mr-3 text-[var(--color-secondary)]"></i>
                                            PASO 1:
                                        </span>
                                        <span class="step-title"> DEFINE TU NEGOCIO
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Ingresa los datos fundamentales de tu negocio</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <label for="business_name_readonly" class="block font-bold text-gray-700 mb-2">Nombre De Tu Negocio</label>
                                        <input type="text" id="business_name_readonly" name="business_name_readonly" value="<?php echo htmlspecialchars($company_name_from_db); ?>" class="w-full p-3 bg-gray-100 border border-gray-300 rounded-lg" readonly>
                                    </div>
                                    <div>
                                        <label for="website_url" class="block font-bold text-gray-700 mb-2">Tu Página Web O Perfil Social Principal (Opcional)</label>
                                        <input type="text" id="website_url" class="w-full p-3 bg-gray-100 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($website_url_from_db); ?>" readonly>
                                    </div>
                                    <div>
                                        <label for="phone_whatsapp" class="block font-bold text-gray-700 mb-2">Tu Teléfono / WhatsApp</label>
                                        <input type="text" id="phone_whatsapp" class="w-full p-3 bg-gray-100 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($contact_phone_from_db); ?>" readonly>
                                    </div>
                                    <div>
                                        <label for="service_zone" class="block font-bold text-gray-700 mb-2">Zona Geográfica De Servicio (Opcional)</label>
                                        <input type="text" id="service_zone" placeholder="Ej: Seattle WA, Madrid España" class="w-full p-3 bg-white border border-gray-300 rounded-lg">
                                    </div>
                                </div>
                            </div>

                            <div class="pt-8">
                                <div class="step-header">
                                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                        <span class="step-number"> <i class="fas fa-lightbulb mr-3 text-[var(--color-highlight)]"></i>
                                            PASO 2:
                                        </span>
                                        <span class="step-title"> DEFINE TU PRODUCTO/SERVICIO Y AUDIENCIA
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Describe qué ofreces y a quién te diriges</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-6">
                                    <div>
                                        <label for="product_service_description" class="block font-bold text-gray-700 mb-2">Descripción Detallada De Tu Producto/Servicio Principal</label>
                                        <textarea id="product_service_description" placeholder="Ej: Ofrecemos servicios de limpieza profunda para hogares y oficinas, utilizando productos ecológicos y personal altamente calificado en el área de Miami." class="w-full p-3 bg-white border border-gray-300 rounded-lg" rows="4" required></textarea>
                                    </div>
                                    <div>
                                        <label for="problem_solved" class="block font-bold text-gray-700 mb-2">Problema Principal Que Resuelve Tu Producto/Servicio</label>
                                        <textarea id="problem_solved" placeholder="Ej: Falta de tiempo para la limpieza, alergias por químicos fuertes, dificultad para encontrar personal de confianza." class="w-full p-3 bg-white border border-gray-300 rounded-lg" rows="3" required></textarea>
                                    </div>
                                    <div>
                                        <label for="desired_outcome" class="block font-bold text-gray-700 mb-2">Deseo O Resultado Ideal Que Tu Cliente Busca</label>
                                        <textarea id="desired_outcome" placeholder="Ej: Un hogar siempre impecable sin esfuerzo, ambiente saludable, paz mental y más tiempo libre." class="w-full p-3 bg-white border border-gray-300 rounded-lg" rows="3" required></textarea>
                                    </div>
                                    <div>
                                        <label for="key_benefits" class="block font-bold text-gray-700 mb-2">Beneficios Clave De Tu Producto/Servicio (Menciona Al Menos 3)</label>
                                        <textarea id="key_benefits" placeholder="Ej: Ahorro de tiempo, resultados profesionales garantizados, productos ecológicos, personal de confianza, flexibilidad de horarios." class="w-full p-3 bg-white border border-gray-300 rounded-lg" rows="3" required></textarea>
                                    </div>
                                    <div>
                                        <label for="communication_tone" class="block font-bold text-gray-700 mb-2">Tono De Comunicación Preferido</label>
                                        <select id="communication_tone" class="w-full p-3 bg-white border border-gray-300 rounded-lg" required>
                                            <option value="Amigable">Amigable</option>
                                            <option value="Profesional">Profesional</option>
                                            <option value="Entusiasta">Entusiasta</option>
                                            <option value="Directo">Directo</option>
                                            <option value="Empático">Empático</option>
                                            <option value="Innovador">Innovador</option>
                                        </select>
                                    </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">
                                    <span class="step-number"> <i class="fas fa-book mr-3 text-[var(--color-highlight)]"></i> 
                                    </span>
                                    <span class="step-title">
                                        INSTRUCCIONES
                                    </span>
                                </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-edit"></i></span><div><strong class="text-brand-dark">DETALLA TU OFERTA:</strong> Cuanto más específico seas con tu producto/servicio, problema y deseo, mejores resultados obtendrás.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-language"></i></span><div><strong class="text-brand-dark">GENERA OFERTA ATRATIVAS:</strong> La herramienta creará posts tanto en español como en inglés para ampliar tu alcance.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i class="fas fa-hashtag"></i></span><div><strong class="text-brand-dark">HASHTAGS INCLUIDOS:</strong> Cada post vendrá con sugerencias de hashtags relevantes para aumentar su visibilidad.</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 PUBLICIA:</strong> Elige el post que más te guste, cópialo con un clic y súbelo directamente a tus redes sociales.</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">
                                <span class="step-number"> <i class="fas fa-share-alt mr-3 text-[var(--color-secondary)]"></i>
                                    PASO 3:
                                </span>
                                <span class="step-title">
                                    CREAR PUBLICACIONES
                                </span>
                            </h2>
                            <p class="step-subtitle text-center md:text-left uppercase">Genera posts atractivos para tus redes sociales 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">Basado en tu información, <strong class="font-black">CLIENT3 IA</strong>, generará <b>varias opciones de publicaciones para redes sociales</b>, cada una con un enfoque estratégico (problema, solución, servicio), listas para captar la atención de tu audiencia y generar interacción. Incluye hashtags y está en dos idiomas.</p>
                            <button id="generateBtn" type="submit" form="social-post-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">Genera Publicaciones Sociales</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>
document.addEventListener('DOMContentLoaded', function() {
    // Inicialización del Toast desde URL parámetros (solo aquí, no en header-manager.js)
    const urlParams = new URLSearchParams(window.location.search);
    const notificationType = urlParams.get('notification_type');
    const notificationMessage = urlParams.get('notification_message');

    if (notificationType && notificationMessage) {
        if (typeof showToast === 'function') {
            showToast(notificationMessage, notificationType);
        } else {
            console.error("showToast function is not defined. Toast notification might not display.");
        }
    }

    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 => showToast("Error al reproducir video: " + e.message, 'error')); // Replaced console.error
        });
        videoPlayer.addEventListener('ended', () => {
            playOverlay.style.display = 'flex';
            videoPlayer.controls = false;
        });
    }

    // --- Lógica del Generador ---
    const form = document.getElementById('social-post-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 Publicaciones Sociales...';
        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 = '';
        resultContainer.style.opacity = '0'; 

        const formData = {
            business_name: document.getElementById('business_name').value, // Corrected ID
            website_url: document.getElementById('website_url').value,
            phone_whatsapp: document.getElementById('phone_whatsapp').value,
            service_zone: document.getElementById('service_zone').value,
            product_service_description: document.getElementById('product_service_description').value,
            problem_solved: document.getElementById('problem_solved').value,
            desired_outcome: document.getElementById('desired_outcome').value,
            key_benefits: document.getElementById('key_benefits').value,
            communication_tone: document.getElementById('communication_tone').value
        };

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

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || `El servidor respondió con un error ${response.status}.`);
            }

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

        } catch (error) {
            let errorMessage = "No se pudieron generar las publicaciones. 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>`;
            resultContainer.style.opacity = '1';
            showToast(errorMessage, 'error'); // Added toast
        } finally {
            btnText.textContent = 'Genera Publicaciones Sociales';
            loaderContainer.classList.add('hidden');
            generateBtn.disabled = false;
        }
    });

    function displayResult(posts) {
        let allPostsHtml = '';
        posts.forEach((post, index) => {
            const postTitle = (post.type === 'problem') ? 'Enfocada En El Problema' :
                               (post.type === 'solution') ? 'Enfocada En La Solución/Deseo' :
                               (post.type === 'service') ? 'Enfocada En El Servicio/Beneficios' :
                               'Publicación General';
            const postIcon = (post.type === 'problem') ? 'fas fa-exclamation-triangle' :
                               (post.type === 'solution') ? 'fas fa-star' :
                               (post.type === 'service') ? 'fas fa-check-circle' :
                               'fas fa-bullhorn';
            // Determine icon color based on post type for better visual distinction
            const postIconClass = (post.type === 'problem') ? 'fas fa-exclamation-triangle text-red-500' :
                                     (post.type === 'solution') ? 'fas fa-star text-yellow-500' :
                                     (post.type === 'service') ? 'fas fa-check-circle text-green-500' :
                                     'fas fa-bullhorn text-gray-500';

            // Format hashtags to include '#' sign
            const formattedEsHashtags = post.es_hashtags.map(tag => `#${tag}`).join(' ');
            const formattedEnHashtags = post.en_hashtags.map(tag => `#${tag}`).join(' ');

            allPostsHtml += `
                <div class="social-post-card bg-white p-6 rounded-xl shadow-lg mb-8">
                    <h3 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
                        <i class="${postIconClass} mr-3"></i>Publicación ${index + 1}: ${postTitle}
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
                        <div class="social-post-lang-card bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <div class="social-post-lang-header flex justify-between items-center mb-3">
                                <h4 class="text-lg font-semibold text-gray-700">🇪🇸 Español</h4>
                                <button class="copy-social-post-btn bg-[var(--color-primary)] text-white px-3 py-1 rounded-md text-sm hover:opacity-90 transition-opacity" data-copy-text="${encodeURIComponent(post.es_copy + '\n\n' + formattedEsHashtags)}"><i class="fas fa-copy mr-1"></i>COPIAR POST</button>
                            </div>
                            <div class="social-post-body">
                                <p class="post-copy text-gray-800 leading-relaxed whitespace-pre-wrap">${post.es_copy.replace(/\n/g, '<br>')}</p>
                                <p class="post-hashtags text-sm text-[var(--color-secondary)] mt-3 font-medium">${formattedEsHashtags}</p>
                            </div>
                        </div>
                        <div class="social-post-lang-card bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <div class="social-post-lang-header flex justify-between items-center mb-3">
                                <h4 class="text-lg font-semibold text-gray-700">🇺🇸 English</h4>
                                <button class="copy-social-post-btn bg-[var(--color-secondary)] text-white px-3 py-1 rounded-md text-sm hover:opacity-90 transition-opacity" data-copy-text="${encodeURIComponent(post.en_copy + '\n\n' + formattedEnHashtags)}"><i class="fas fa-copy mr-1"></i>COPIAR POST</button>
                            </div>
                            <div class="social-post-body">
                                <p class="post-copy text-gray-800 leading-relaxed whitespace-pre-wrap">${post.en_copy.replace(/\n/g, '<br>')}</p>
                                <p class="post-hashtags text-sm text-[var(--color-primary)] mt-3 font-medium">${formattedEnHashtags}</p>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });

        resultContainer.innerHTML = `<div class="ai-response p-6 md:p-8 rounded-xl shadow-md space-y-8">${allPostsHtml}</div>`;
        setTimeout(() => { resultContainer.style.opacity = '1'; resultContainer.style.transform = 'scale(1)'; }, 100);

        resultContainer.querySelectorAll('.copy-btn').forEach(button => {
            button.addEventListener('click', function() {
                const textToCopy = decodeURIComponent(this.dataset.copyText);
                navigator.clipboard.writeText(textToCopy).then(() => {
                    const originalContent = button.innerHTML;
                    button.innerHTML = '<i class="fas fa-check"></i> Copiado';
                    button.classList.add('copied');
                    showToast('Publicación copiada al portapapeles.', 'success'); // Added toast
                    setTimeout(() => {
                        button.innerHTML = originalContent;
                        button.classList.remove('copied');
                    }, 2000);
                }).catch(err => {
                    console.error('Error al copiar el texto: ', err);
                    showToast('Error al copiar el texto.', 'error'); // Added toast
                });
            });
        });
    }
});
</script>

</body>
</html>