<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');
include 'db/adn-status-logic.php';

$company_name = 'Su Negocio Local';
$owner_name = 'Propietario';

try {
    // Mitigación SQLi: Uso de sentencia preparada.
    $stmt_config = $pdo->prepare("SELECT full_name, company_name FROM business_info WHERE id = 1");
    $stmt_config->execute();
    $config = $stmt_config->fetch(PDO::FETCH_ASSOC);

    if ($config) {
        $company_name = htmlspecialchars($config['company_name'] ?? 'Su Negocio Local', ENT_QUOTES, 'UTF-8');
        $owner_name = htmlspecialchars($config['full_name'] ?? 'Propietario', ENT_QUOTES, 'UTF-8');
        $first_name_parts = explode(' ', $owner_name);
        $owner_first_name = $first_name_parts[0];
    } else {
        $owner_first_name = 'Propietario';
    }
    
} catch (Exception $e) {
    error_log("Error general al cargar configuración para Masterclass: " . $e->getMessage());
    $owner_first_name = 'Propietario'; 
}

// Validación y acceso de la clase (Lógica de negocio esencial)
$current_class_id = isset($_GET['class']) ? (int)$_GET['class'] : 1;
if (!isset($adn_classes[$current_class_id])) {
    header('Location: adn-dashboard.php');
    exit;
}
$user_class_status = $adn_progress['class_status'][$current_class_id] ?? 'locked';
$current_class = $adn_classes[$current_class_id];
$total_classes = TOTAL_ADN_CLASSES;
$next_class_id = ($current_class_id < $total_classes) ? $current_class_id + 1 : null;
$prev_class_id = ($current_class_id > 1) ? $current_class_id - 1 : null;

// Lógica de navegación (ajuste por status de clase)
if ($prev_class_id !== null && ($adn_progress['class_status'][$prev_class_id] ?? 'locked') === 'locked') {
    $prev_class_id = null;
}
if ($next_class_id !== null && ($adn_progress['class_status'][$next_class_id] ?? 'locked') === 'locked') {
    $next_class_id = null;
}
$instructor_name = "Nestor Orozco";
$instructor_title = "CEO & Fundador Of OrozCO FlowCRM™";
$instructor_bio = "Experto en optimización de negocios locales con más de 10 años de experiencia, enfocado en sistemas de conversión y automatización para la industria de servicios.";
$quiz_url = "adn-quiz.php?unlock_id=" . ($current_class_id + 1);
$next_video_url = $next_class_id ? "adn-video-semana.php?class=" . $next_class_id : "#";
$prev_video_url = $prev_class_id ? "adn-video-semana.php?class=" . $prev_class_id : "#";

if (ob_get_level() > 0) { ob_end_clean(); }
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Masterclass Programa Empresarial ADN <?php echo htmlspecialchars($branding['full_title']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">
  
  <?php include 'files/gtm-head.php'; ?>

  <script src="https://unpkg.com/lucide@latest"></script>
  <link rel="stylesheet" href="style.css"> 
  <script src="files/header-manager.js"></script>

    <style>
        /* (Tus mismos estilos de antes) */
        .vip-content-bg { background-color: white; color: var(--color-text-dark); }
        .class-header-bar { background-color: var(--color-primary); color: var(--color-text-light); }
        .video-container { position: relative; height: 0; overflow: hidden; }
        .video-container iframe, .video-container video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border-radius: 12px;
        }
        .class-list-item {
            background-color: var(--color-background); 
            color: var(--color-text-dark);
            transition: background-color 0.15s ease-in-out;
            border-left: 3px solid transparent;
        }
        .class-list-item:hover { background-color: #e5e7eb; }
        .class-list-item.active {
            background-color: var(--color-highlight); 
            color: var(--color-primary);
            font-weight: 700;
            border-left-color: var(--color-secondary);
        }
        .class-list-item.active .text-gray-400 { color: var(--color-primary); }

        /* ESTILO PARA EL BOTÓN DESHABILITADO */
        .btn-disabled {
            background-color: #9ca3af; /* Gris de Tailwind */
            color: #e5e7eb;
            cursor: not-allowed;
            opacity: 0.7;
            box-shadow: none;
        }
        .btn-disabled:hover {
            background-color: #9ca3af;
            transform: none;
        }

        /* ESTILOS PARA EL MODAL */
        #videoCompleteModal {
            animation: fadeIn 0.3s ease-out;
        }
        #videoCompleteModal > div {
             animation: zoomIn 0.3s ease-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        @keyframes zoomIn {
            from { transform: scale(0.9); opacity: 0; }
            to { transform: scale(1); opacity: 1; }
        }
        .btn-modal-primary { 
            background-color: var(--color-secondary); 
            color: var(--color-text-light); 
            transition: all 0.2s;
        }
        .btn-modal-primary:hover { background-color: #7c1020; }
    </style>

</head>
<body data-page-title="Programa ADN Acelerador De Negocios" 
      data-page-subtitle="Sistema Ejecutivo: El GPS de Crecimiento Empresarial" 
      data-page-icon="graduation-cap">
    
    <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>
    <div id="task-panel-overlay" class="fixed inset-0 bg-black/60 z-40 hidden transition-opacity duration-300"></div>  
    
    <?php include 'adn-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 space-y-8">

        
        <?php if ($user_class_status !== 'locked'): ?>
        
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <div class="lg:col-span-2 space-y-6">
                    
                    <div class="p-4 rounded-xl class-header-bar shadow-md flex items-center gap-4">
                        <div class="flex-shrink-0">
                            <i data-lucide="graduation-cap" class="w-10 h-10 text-[var(--color-highlight)]"></i>
                        </div>
                        <div class="flex-grow min-w-0">
                            <span class="text-sm font-semibold uppercase text-white/80">SEMANA <?php echo $current_class_id; ?> DE <?php echo $total_classes; ?></span>
                            <h2 class="text-3xl font-black uppercase text-white mt-1 leading-tight truncate">
                                <?php echo htmlspecialchars($current_class['title']); ?>
                            </h2>
                            <p class="text-xl uppercase text-[var(--color-highlight)] font-bold">
                                <?php echo htmlspecialchars($current_class['subtitle']); ?>
                            </p>
                        </div>
                    </div>
    
    
                 <div class="w-full">
                    <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden">
                        <div class="relative w-full" style="padding-bottom: 56.25%;">
                            <video class="absolute top-0 left-0 w-full h-full object-cover" id="videoPlayer" controls controlslist="nodownload" preload="metadata" poster="<?php echo htmlspecialchars($current_class['poster_image']); ?>">
                                <source src="<?php echo htmlspecialchars($current_class['video_url']); ?>" type="video/mp4">
                                TU NAVEGADOR NO SOPORTA LA ETIQUETA DE VIDEO
                            </video>
                            <div id="playOverlay" class="absolute inset-0 flex justify-center items-center cursor-pointer group" style="display: flex;">
                                <img src="<?php echo htmlspecialchars($current_class['poster_image']); ?>" alt="VideoLeccion - <?php echo htmlspecialchars($current_class['title']); ?>" class="absolute inset-0 w-full h-full object-cover">
                                <div class="absolute inset-0 w-full h-full bg-black/40 transition-colors group-hover:bg-black/60"></div>
                                <i data-lucide="play" class="relative w-16 h-16 text-white opacity-80 group-hover:opacity-100 transition-opacity"></i>
                            </div>
                        </div>
                        <div class="p-4 text-white/90 text-sm flex items-center justify-between">
                            <span class="inline-flex items-center gap-2">
                                <i data-lucide="play-circle" class="w-4 h-4"></i>
                                Video Presentación
                            </span>
    
                            <span class="text-sm font-semibold uppercase text-white/80">SEMANA <?php echo $current_class_id; ?></span>
                        </div>
                    </div>
                </div>
    
                    <div class="flex justify-between items-center bg-white p-4 rounded-xl shadow-md border border-gray-200">
                        <a href="<?php echo $prev_video_url; ?>" 
                           class="btn-primary font-bold py-3 px-4 rounded-lg flex items-center uppercase transition-all duration-200 <?php echo $prev_class_id ? '' : 'opacity-50 pointer-events-none'; ?>">
                            <i data-lucide="chevron-left" class="w-5 h-5 mr-2"></i> ANTERIOR
                        </a>
                        
                        <a href="<?php echo $quiz_url; ?>"
                           id="quiz-btn" 
                           class="bg-[var(--color-highlight)] hover:bg-yellow-400 text-[var(--color-primary)] font-black py-3 px-4 rounded-lg flex items-center uppercase transition-all duration-200 shadow-lg btn-disabled pointer-events-none">
                            <i data-lucide="check-circle" class="w-5 h-5 mr-2"></i> REALIZAR PRUEBA
                        </a>
                        <a href="<?php echo $next_video_url; ?>" 
                           class="btn-primary font-bold py-3 px-4 rounded-lg flex items-center uppercase transition-all duration-200 <?php echo $next_class_id ? '' : 'opacity-50 pointer-events-none'; ?>">
                            SIGUIENTE <i data-lucide="chevron-right" class="w-5 h-5 ml-2"></i>
                        </a>
                    </div>
    
                    <div class="vip-content-bg p-6 rounded-xl space-y-6 shadow-md border border-gray-200">
                        <h3 class="text-4xl font-black text-[var(--color-secondary)] flex items-center gap-2 uppercase">
                            <i data-lucide="file-text" class="w-6 h-6"></i> RESUMEN DE LA CLASE
                        </h3>
                        <p class="text-gray-700"><?php echo nl2br(htmlspecialchars($current_class['description'])); ?></p>
    
                        <a href="<?php echo htmlspecialchars($current_class['workbook_url']); ?>" download 
                           class="bg-gray-700 hover:bg-gray-900 text-white font-black py-3 px-6 rounded-lg flex items-center justify-center uppercase text-lg transition-all duration-200 shadow-lg">
                            <i data-lucide="book-down" class="w-6 h-6 mr-3"></i>
                            Descargar Workbook
                        </a>
                    </div>
                </div>
    
                <div class="lg:col-span-1 space-y-6">
                    <div class="vip-content-bg p-4 rounded-xl shadow-md border border-gray-200">
                        <h3 class="text-xl font-black text-[var(--color-primary)] mb-4 flex items-center gap-2 uppercase">
                            <i data-lucide="list-ordered" class="w-5 h-5 text-[var(--color-secondary)]"></i>
                            Módulos Del Programa ADN
                        </h3>
                        <ul class="space-y-2 text-sm max-h-96 overflow-y-auto pr-2">
                            <?php 
                            foreach ($adn_classes as $id => $class): 
                                $status = $adn_progress['class_status'][$id] ?? 'locked';
                                $is_locked = $status === 'locked';
                                $url = 'adn-video-semana.php?class=' . $id;
                            ?>
                                <li>
                                    <a href="<?php echo $url; ?>" 
                                       class="class-list-item flex flex-col p-3 rounded-lg shadow-sm border border-gray-100 cursor-pointer 
                                               <?php echo ($id === $current_class_id) ? 'active' : ''; ?>
                                               <?php echo $is_locked ? 'opacity-60' : ''; ?>">
                                        <span class="font-bold flex items-center gap-2">
                                            <?php if($status === 'completed'): ?>
                                                <i data-lucide="check-circle" class="w-4 h-4 mr-1 text-green-600"></i>
                                            <?php elseif($is_locked): ?>
                                                <i data-lucide="lock" class="w-4 h-4 mr-1 text-gray-400"></i>
                                            <?php else: // unlocked ?>
                                                <i data-lucide="chevron-right" class="w-4 h-4 mr-1"></i>
                                            <?php endif; ?>
                                            
                                            SEM. <?php echo $id; ?>: <?php echo htmlspecialchars($class['title']); ?>
                                            <?php if ($id === $current_class_id): ?>
                                                <span class="text-xs font-semibold px-2 py-0.5 rounded-full bg-[var(--color-primary)] text-white ml-auto">VIENDO</span>
                                            <?php endif; ?>
                                        </span>
                                        <span class="text-xs ml-6 text-gray-400"><?php echo htmlspecialchars($class['subtitle']); ?></span>
                                    </a>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                    
                    <div class="vip-content-bg p-6 rounded-xl text-center shadow-md border border-gray-200">
                        <h3 class="text-2xl font-black text-[var(--color-primary)] mb-4 uppercase">INSTRUCTOR ESTRATEGA</h3>
                        <div class="flex flex-col items-center">
                            <img src="https://orozdesign.com/NestorOrozcoCasualCuadrada.webp" alt="Instructor <?php echo $instructor_name; ?>" class="w-24 h-24 rounded-full border-4 border-[var(--color-secondary)] mb-4">
                            <h4 class="text-xl font-black text-[var(--color-secondary)]"><?php echo $instructor_name; ?></h4>
                            <p class="text-md text-gray-500 font-semibold mb-3"><?php echo $instructor_title; ?></p>
                            <p class="text-sm text-gray-700">"El ADN es un programa diseñado para que dueños de negocios como usted, <b><?php echo $owner_first_name; ?></b>, logren un crecimiento predecible y sistemático."</p>
                        </div>
                    </div>
    
                </div>
            </div>
            <?php else: ?>

            <div class="bg-white p-6 md:p-10 rounded-xl shadow-md border-l-4 border-[var(--color-secondary)] text-center">
                <i data-lucide="lock" class="w-20 h-20 text-[var(--color-secondary)] mx-auto mb-4"></i>
                <h1 class="text-4xl font-black uppercase text-[var(--color-primary)]">Clase Bloqueada</h1>
                
                <h2 class="text-6xl font-black uppercase text-[var(--color-secondary)] mt-2"><?php echo htmlspecialchars($current_class['title']); ?></h2>
                
                <p class="text-lg text-gray-700 max-w-2xl mx-auto mt-4">
                    Esta clase todavía no está disponible. Debes completar la clase anterior
                    <?php if($prev_class_id !== null): ?>
                        (<b>Semana <?php echo $prev_class_id; ?>: <?php echo htmlspecialchars($adn_classes[$prev_class_id]['title']); ?></b>) 
                    <?php endif; ?>
                    y aprobar su cuestionario para desbloquear este contenido.
                </p>
                <div class="mt-8 flex flex-col sm:flex-row justify-center gap-4">
                    <?php if($prev_class_id !== null): ?>
                    <a href="adn-video-semana.php?class=<?php echo $prev_class_id; ?>" class="btn-secondary font-bold py-3 px-6 rounded-lg flex items-center uppercase transition-all duration-200 shadow-lg mx-auto w-fit">
                        <i data-lucide="arrow-left" class="w-5 h-5 mr-2"></i>
                        Ir a la Clase Anterior
                    </a>
                    <?php endif; ?>
                    <a href="adn-dashboard.php" class="btn-primary font-bold py-3 px-6 rounded-lg flex items-center uppercase transition-all duration-200 shadow-lg mx-auto w-fit">
                        <i data-lucide="layout-dashboard" class="w-5 h-5 mr-2"></i>
                        Volver al Progreso
                    </a>
                </div>
            </div>
            <?php endif; ?>

    </div>
    </main>
</div>

<div id="videoCompleteModal" class="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center p-4 z-[999] hidden">
    <div class="bg-white rounded-xl shadow-2xl p-6 md:p-8 max-w-lg w-full text-center">
        <i data-lucide="party-popper" class="w-16 h-16 text-green-500 mx-auto mb-4"></i>
        <h2 class="text-3xl font-black uppercase text-[var(--color-primary)]">¡Video Completado!</h2>
        <p class="text-lg text-gray-700 my-4">
            ¡Excelente! Has completado esta lección. Estás listo(a) para validar lo que has aprendido y desbloquear la siguiente lección
        </p>
        <div class="flex flex-col sm:flex-row-reverse gap-4 justify-center">
            
            <a href="<?php echo $quiz_url; ?>" id="modalQuizButton" class="btn-modal-primary font-bold py-3 px-6 rounded-lg uppercase transition-all duration-200 shadow-lg w-full sm:w-auto">
                Realizar Prueba 
            </a>
            
            <button id="closeVideoModalButton" type="button" class="py-3 px-6 rounded-lg font-bold uppercase text-gray-600 hover:bg-gray-100 w-full sm:w-auto">
                Cerrar
            </button>

        </div>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        if (typeof lucide !== 'undefined') {
            lucide.createIcons();
        }

        // --- Lógica del Menú (sin cambios) ---
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        const sidebar = document.getElementById('sidebar');
        const sidebarOverlay = document.getElementById('sidebar-overlay');
        if (mobileMenuButton && sidebar && sidebarOverlay) { 
            mobileMenuButton.addEventListener('click', () => { 
                sidebar.classList.toggle('-translate-x-full'); 
                sidebarOverlay.classList.toggle('hidden'); 
            }); 
            sidebarOverlay.addEventListener('click', () => { 
                sidebar.classList.add('-translate-x-full'); 
                sidebarOverlay.classList.add('hidden'); 
            }); 
        }

        // --- Lógica del Video (sin cambios) ---
        const videoElement = document.getElementById('videoPlayer');
        const playOverlay = document.getElementById('playOverlay');

        if (videoElement && playOverlay) {
            videoElement.removeAttribute('controls');
            playOverlay.style.display = 'flex'; 

            playOverlay.addEventListener('click', () => {
                playOverlay.style.display = 'none';
                videoElement.setAttribute('controls', 'true');
                videoElement.play();
            });

            const resetVideoState = () => {
                if (!videoElement.ended) {
                    playOverlay.style.display = 'flex';
                    videoElement.removeAttribute('controls');
                }
            };
            
            videoElement.addEventListener('pause', resetVideoState);
        }
        
        // --- ¡NUEVA LÓGICA! MODAL + LOCALSTORAGE ---
        
        // Solo ejecutar esta lógica si el video existe (si la clase no está bloqueada)
        const quizBtn = document.getElementById('quiz-btn');
        const videoCompleteModal = document.getElementById('videoCompleteModal');
        const closeVideoModalButton = document.getElementById('closeVideoModalButton');
        
        if (videoElement && quizBtn && videoCompleteModal && closeVideoModalButton) {
            
            // Definir una clave única para esta clase en localStorage
            const classId = <?php echo $current_class_id; ?>;
            const storageKey = `video_completed_${classId}`;

            // --- Función para HABILITAR el botón del quiz ---
            function enableQuizButton() {
                quizBtn.classList.remove('btn-disabled', 'pointer-events-none');
            }
            
            // --- Función para MOSTRAR el modal ---
            function showVideoCompleteModal() {
                videoCompleteModal.classList.remove('hidden');
                videoCompleteModal.classList.add('flex');
                if (typeof lucide !== 'undefined') {
                    lucide.createIcons(); // Renderizar el ícono del modal
                }
            }
            
            // --- Función para CERRAR el modal ---
            function closeVideoCompleteModal() {
                videoCompleteModal.classList.add('hidden');
                videoCompleteModal.classList.remove('flex');
                // Al cerrar, el botón de la barra (que ya está habilitado) es visible.
            }

            // --- 1. Al Cargar la Página ---
            // Revisar si el video ya se había completado antes
            if (localStorage.getItem(storageKey) === 'true') {
                enableQuizButton(); // Habilitar el botón de la barra inmediatamente
            }

            // --- 2. Al Terminar el Video ---
            videoElement.addEventListener('ended', () => {
                const alreadyCompleted = localStorage.getItem(storageKey) === 'true';

                // Habilitar el botón de la barra en CUALQUIER CASO
                enableQuizButton();
                
                // Guardar en localStorage que ya se completó
                localStorage.setItem(storageKey, 'true');

                // Solo mostrar el modal la PRIMERA VEZ que se completa
                if (!alreadyCompleted) {
                    showVideoCompleteModal();
                }
            });

            // --- 3. Al Cerrar el Modal ---
            closeVideoModalButton.addEventListener('click', closeVideoCompleteModal);
        }

    });
</script>
<script src="files/toast.js"></script>
</body>
</html>