<?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_first_name = 'Propietario';

try {
    // MITIGACIÓN SQLI: Uso de Sentencia Preparada para business_info
    $stmt_config = $pdo->prepare("SELECT full_name, company_name FROM business_info WHERE id = :id");
    $stmt_config->execute([':id' => 1]); 
    $config = $stmt_config->fetch(PDO::FETCH_ASSOC);
    
    if ($config) {
        $company_name = htmlspecialchars($config['company_name'] ?? 'Su Negocio Local');
        $first_name_parts = explode(' ', htmlspecialchars($config['full_name'] ?? 'Propietario'));
        $owner_first_name = $first_name_parts[0];
    }
} catch (Exception $e) {
    error_log("Error al cargar config del dashboard: " . $e->getMessage());
}

$classes_completed = array_filter($adn_progress['class_status'], fn($status) => $status === 'completed');
$total_classes = TOTAL_ADN_CLASSES;
$completion_percentage = ($total_classes > 0) ? round((count($classes_completed) / $total_classes) * 100) : 0;

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>Dashboard Programa De Negocios 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>
        .adn-card { background-color: white; border-radius: 0.75rem; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); transition: transform 0.2s; }
        .adn-card:hover { transform: translateY(-3px); }
        .locked-overlay { background: rgba(7, 22, 45, 0.85); backdrop-filter: blur(4px); } 
        .progress-bar-bg { background-color: #e2e8f0; }
        .progress-bar-fill { width: <?php echo $completion_percentage; ?>%; background-color: var(--color-secondary); }
        .locked-icon { color: #94a3b8; }
        .unlocked-icon { color: var(--color-highlight); }
        .completed-icon { color: var(--color-green); }

        .adn-class-image-card {
            min-height: 350px;
            overflow: hidden;
            border-radius: 0.75rem;
            position: relative;
            cursor: pointer;
            box-shadow: 0 10px 15px -3px rgba(0,0,0,0.3);
            transition: transform 0.3s ease-in-out;
        }
        .adn-class-image-card:hover { transform: translateY(-5px); }
        .adn-class-image-card .background-image {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-size: cover;
            background-position: center;
            opacity: 0.9; 
            transition: transform 0.4s ease-in-out;
            filter: grayscale(40%);
        }
        .adn-class-image-card:hover .background-image { transform: scale(1.05); filter: grayscale(0%); }
        .adn-class-image-card .content-overlay {
            position: relative;
            z-index: 10;
            height: 100%;
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            justify-content: flex-end;
            background: linear-gradient(to top, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.5) 40%, transparent 100%);
        }
        .adn-class-image-card .title { line-height: 1.0; color: white; }
        .adn-class-image-card .subtitle { color: var(--color-highlight); font-size: 0.9rem; }
        .locked-overlay-hover { 
            background: rgba(7, 22, 45, 0.95); 
            backdrop-filter: blur(4px);
            opacity: 0;
            transition: opacity 0.3s ease-in-out;
            pointer-events: none; 
        }
        .adn-class-image-card:hover .locked-overlay-hover { opacity: 1; }

        #notificationModal {
            animation: fadeIn 0.3s ease-out;
        }
        #notificationModal > 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; }
        }
    </style>

</head>
<body data-page-title="Dashboard Programa De Negocios ADN" 
      data-page-subtitle="Tu Centro de Progreso del Acelerador de Negocios" 
      data-page-icon="bar-chart-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>
    <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-10">
        
        <section class="p-6 md:p-10 video-widget" id="welcome-adn-video">
            <div class="blob bl1"></div><div class="blob bl2"></div>
            <div class="relative grid grid-cols-1 lg:grid-cols-2 gap-8 items-center">
                <div class="lg:col-span-1">
                    <span class="chip"><i data-lucide="award" class="w-4 h-4"></i> Bienvenido Al Programa De Negocios ADN</span>
                    <h2 class="mt-3 text-2xl md:text-5xl font-black uppercase leading-tight text-[var(--color-highlight)]">¡Aquí Empieza Tu Viaje De Crecimiento Empresarial!</h2>
                    <p class="mt-2 text-white/90 max-w-xl text-lg"><?php echo $owner_first_name; ?> este programa es tu GPS para convertir <b><?php echo $company_name; ?></b> en una máquina de adquisición de clientes potenciales</p>
                </div>
                <div class="lg:col-span-1">
                    <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="welcomeAdnVideoPlayer" controls 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 id="playOverlayAdn" class="absolute inset-0 flex justify-center items-center cursor-pointer group">
                                    <img src="img/VideoLeccion-IAMarketing.jpg" alt="Video Placeholder - ADN Welcome" 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 De Bienvenida
                                </span>
                                <button class="hide-widget-btn inline-flex items-center gap-2 text-xs font-black text-[var(--color-highlight)] hover:text-white transition-colors py-1 px-2 rounded-md" 
                                        data-widget-id="welcome-adn-video" 
                                        title="Ocultar el video de bienvenida">
                                    OCULTAR VIDEO
                                    <i data-lucide="square-x" class="w-4 h-4"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <section class="adn-card p-6 border-l-4 border-[var(--color-secondary)]">
            <h1 class="text-3xl font-black text-[var(--color-primary)] uppercase flex items-center gap-2">
                <i data-lucide="award" class="w-7 h-7 text-[var(--color-highlight)]"></i>
                Tu Progreso De Implementación Del Programa ADN
            </h1>
            <p class="text-lg uppercase text-gray-700 mt-2"><?php echo $owner_first_name; ?> Has completado <b><?php echo count($classes_completed); ?> de <?php echo $total_classes; ?></b> clases del programa</p>
            <div class="mt-4">
                <div class="progress-bar-bg h-3 rounded-full overflow-hidden">
                    <div class="progress-bar-fill h-full rounded-full transition-all duration-500"></div>
                </div>
                <p class="text-sm font-bold text-gray-600 mt-1"><?php echo $completion_percentage; ?>% Completado</p>
            </div>
        </section>

        <section>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <?php foreach ($adn_classes as $id => $class): 
                    $status = $adn_progress['class_status'][$id] ?? 'locked';
                    $is_locked = $status === 'locked';
                    // El enlace siempre va a la página del video
                    $url = 'adn-masterclass.php?class=' . $id; 
                ?>
                <a href="<?php echo $url; ?>" class="adn-class-image-card group <?php echo $is_locked ? 'is-locked' : ''; ?>">
                    <div class="background-image" style="background-image: url('<?php echo htmlspecialchars($class['image_url']); ?>');"></div>
                    
                    <div class="content-overlay">
                        <div class="absolute top-4 right-4 p-2 rounded-full bg-black/50">
                            <?php if ($status === 'completed'): ?>
                                <i data-lucide="check-circle" class="w-6 h-6 completed-icon text-white"></i>
                            <?php elseif ($is_locked): ?>
                                <i data-lucide="lock" class="w-6 h-6 locked-icon text-white/50"></i>
                            <?php else: ?>
                                <i data-lucide="unlock" class="w-6 h-6 unlocked-icon text-white"></i>
                            <?php endif; ?>
                        </div>

                      <span class="w-fit inline-flex items-center gap-1.5 text-xs font-extrabold uppercase px-2 py-1 rounded bg-[var(--color-highlight)] text-black mb-2 transition-opacity duration-300 <?php echo $is_locked ? 'group-hover:opacity-0' : ''; ?>">
                         <i data-lucide="calendar" class="w-3 h-3"></i>
                            SEMANA <?php echo $id; ?>
                      </span>
                      <h3 class="text-3xl title font-black uppercase mt-1 transition-opacity duration-300 <?php echo $is_locked ? 'group-hover:opacity-0' : ''; ?>"><?php echo htmlspecialchars($class['title']); ?></h3>
                        <p class="subtitle font-black mt-1 transition-opacity duration-300 <?php echo $is_locked ? 'group-hover:opacity-0' : ''; ?>"><?php echo htmlspecialchars($class['subtitle']); ?></p>
                    </div>

                    <?php if ($is_locked): ?>
                        <div class="locked-overlay-hover absolute inset-0 flex flex-col items-center justify-center text-white p-4 text-center">
                            <i data-lucide="lock" class="w-8 h-8 mb-2"></i>
                            <span class="font-bold text-xl uppercase">Bloqueado</span>
                            <span class="text-sm text-gray-300 uppercase">Completa la clase anterior</span>
                        </div>
                    <?php endif; ?>
                </a>
                <?php endforeach; ?>
            </div>
        </section>
        
    </div>
    </main>
</div>

<div id="notificationModal" 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="lock" class="w-16 h-16 text-[var(--color-secondary)] mx-auto mb-4"></i>
        <h2 class="text-3xl font-black uppercase text-[var(--color-primary)]">Clase Bloqueada</h2>
        <p id="modalMessage" class="text-lg text-gray-700 my-4">
            </p>
        <button id="closeModalButton" class="btn-primary font-bold py-3 px-6 rounded-lg uppercase transition-all duration-200 shadow-lg">
            Entendido
        </button>
    </div>
</div>
<script>
    const toggleWidgetVisibility = (widgetId, isHidden) => {
        // (Lógica del widget de bienvenida sin cambios)
        const widget = document.getElementById(widgetId);
        const showContainer = document.querySelector(`#show-welcome-adn-container`);
        const videoPlayer = widget ? widget.querySelector('video') : null;
        if (!widget || !showContainer) return; 
        if (isHidden) {
            widget.classList.add('hidden');
            showContainer.classList.remove('hidden');
            if (videoPlayer) videoPlayer.pause(); 
        } else {
            widget.classList.remove('hidden');
            showContainer.classList.add('hidden');
        }
        localStorage.setItem(`hide_${widgetId}`, isHidden ? 'true' : 'false');
    };

    document.addEventListener('DOMContentLoaded', () => {
        if (typeof lucide !== 'undefined') { lucide.createIcons(); }
        
        // --- Lógica del Video de Bienvenida (sin cambios) ---
        const videoPlayer = document.getElementById('welcomeAdnVideoPlayer');
        const playOverlay = document.getElementById('playOverlayAdn');
        if (videoPlayer && playOverlay) {
            playOverlay.addEventListener('click', () => {
                playOverlay.classList.add('hidden');
                videoPlayer.play();
            });
            videoPlayer.addEventListener('pause', () => {
                 if (videoPlayer.currentTime < videoPlayer.duration) {
                    playOverlay.classList.remove('hidden');
                }
            });
             videoPlayer.addEventListener('ended', () => {
                 playOverlay.classList.remove('hidden');
            });
        }
        
        // --- Lógica del Menú y Ocultar/Mostrar (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');
            });
        }
        document.querySelector('.hide-widget-btn[data-widget-id="welcome-adn-video"]')?.addEventListener('click', (e) => toggleWidgetVisibility('welcome-adn-video', true));
        document.querySelector('.show-widget-btn[data-widget-id="welcome-adn-video"]')?.addEventListener('click', (e) => toggleWidgetVisibility('welcome-adn-video', false));
        const isHidden = localStorage.getItem(`hide_welcome-adn-video`) === 'true';
        toggleWidgetVisibility('welcome-adn-video', isHidden);


        // --- ========= ¡NUEVA LÓGICA DEL MODAL! ========= ---
        
        const modal = document.getElementById('notificationModal');
        const closeModalButton = document.getElementById('closeModalButton');
        const modalMessage = document.getElementById('modalMessage');

        // Función para MOSTRAR el modal
        function showModal(message) {
            if (!modal || !modalMessage) return;
            modalMessage.textContent = message;
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            if (typeof lucide !== 'undefined') {
                lucide.createIcons();
            }
        }

        // Función para CERRAR el modal
        function closeModal() {
            if (!modal) return;
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        }

        // Asignar el evento al botón de cerrar
        if (closeModalButton) {
            closeModalButton.addEventListener('click', closeModal);
        }
        
        document.querySelectorAll('.adn-class-image-card.is-locked').forEach(card => {
            card.addEventListener('click', (e) => {
                e.preventDefault(); 
                
                showModal('Debes completar la clase anterior y aprobar el cuestionario para desbloquear esta.');
            });
        });
    });
</script>
<script src="files/toast.js"></script>
</body>
</html>