<?php
declare(strict_types=1);

require_once(__DIR__ . '/core/init.php');
require_once(__DIR__ . '/db/fetch-daily-summary.php');


// 4. FUNCIONES HELPER (VISTA)
function formatPhoneNumberUSA(string $number): string
{
    $number = preg_replace('/[^0-9]/', '', $number);
    if (strlen($number) === 10) {
        return '(' . substr($number, 0, 3) . ') ' . substr($number, 3, 3) . '-' . substr($number, 6);
    }
    return htmlspecialchars($number, ENT_QUOTES, 'UTF-8');
}

// Lógica de traducción para las frases estratégicas (Debe estar en el frontend)
function translateStrategicRoute(string $route): string
{
    // Cadenas que vienen del backend (fetch-daily-summary.php) y deben ser traducidas en el frontend.
    // **Las claves deben ser EXACTAS a las cadenas generadas en el backend, incluyendo los espacios.**
    $translations = [
        // STRATEGIC ROUTE DYNAMIC MESSAGES
        "RED_ALERT: Resolve the " => "ALERTA ROJA: Resuelve las ", 
        " open complaints NOW." => " quejas abiertas YA.",
        "CRITICAL_CASHFLOW: " => "FLUJO DE CAJA CRÍTICO: ",
        " overdue invoices." => " facturas vencidas.",
        "SALES_CLOSE: " => "CIERRE DE VENTAS: ",
        " pending quotes." => " estimados pendientes.",

        // STRATEGIC ROUTE STATIC MESSAGES
        "EXECUTION: Focus on the assigned route." => "EJECUCIÓN: Concéntrate en la ruta asignada.",
        "LASER_FOCUS: Finish tasks one by one." => "ENFOQUE LÁSER: Termina tus tareas una por una.",
        "MAINTENANCE: Total quality in appointments." => "MANTENIMIENTO: Calidad total en tus citas.",
        "HUNTER_MODE: Your schedule is light. Fill empty slots." => "MODO CAZADOR: Tu agenda está ligera. Llena los espacios vacíos.",
        "ORGANIZATION_MODE: Use the calm to organize your finances." => "MODO ORGANIZACIÓN: Aprovecha la calma para organizar tus finanzas.",
        "VISIBILITY_MODE: Do marketing today." => "MODO VISIBILIDAD: Haz marketing hoy.",
        
        // APPOINTMENTS
        "Appointment: " => "Cita: ", 
        "General Appointment" => "Cita General",
        
        // TASKS (These come from the default array in this same file, so we just map them to themselves)
        'CRECIMIENTO: Llama a 3 clientes antiguos inactivos para ofrecer una promoción de reactivación.' => 'CRECIMIENTO: Llama a 3 clientes antiguos inactivos para ofrecer una promoción de reactivación.',
        'MARKETING: Graba y sube 1 Historia o Reel mostrando un resultado "Antes y Después".' => 'MARKETING: Graba y sube 1 Historia o Reel mostrando un resultado "Antes y Después".',
        'MANTENIMIENTO: Revisa inventario y limpieza de herramientas para estar listo mañana.' => 'MANTENIMIENTO: Revisa inventario y limpieza de herramientas para estar listo mañana.',
        'FIDELIZACIÓN: Envía mensajes personales de agradecimiento a los últimos 5 clientes.' => 'FIDELIZACIÓN: Envía mensajes personales de agradecimiento a los últimos 5 clientes.',
        'ESTRATEGIA: Investiga 2 competidores locales y anota qué ofertas están promocionando.' => 'ESTRATEGIA: Investiga 2 competidores locales y anota qué ofertas están promocionando.',
        'REPUTACIÓN: Contacta a tu último cliente satisfecho y pídele una reseña en Google Maps.' => 'REPUTACIÓN: Contacta a tu último cliente satisfecho y pídele una reseña en Google Maps.',
        'VISIBILIDAD: Publica las mejores fotos de tu semana en tus redes sociales.' => 'VISIBILIDAD: Publica las mejores fotos de tu semana en tus redes sociales.',
        'VENTAS: Revisa cotizaciones antiguas (hace 30 días) y haz una llamada de seguimiento final.' => 'VENTAS: Revisa cotizaciones antiguas (hace 30 días) y haz una llamada de seguimiento final.',
        'ALIANZAS: Contacta a un negocio local para explorar una colaboración que puedan trabajar juntos.' => 'ALIANZAS: Contacta a un negocio local para explorar una colaboración que puedan trabajar juntos.',
        'Define tu estrategia de crecimiento hoy.' => 'Define tu estrategia de crecimiento hoy.'
    ];

    // Simplemente usamos str_replace para reemplazar todas las cadenas conocidas.
    // Esto funciona para cadenas dinámicas (reemplazando el prefijo y el sufijo) y estáticas (reemplazando la cadena completa).
    $translated = str_replace(array_keys($translations), array_values($translations), $route);
    
    return $translated;
}

// 5. INICIALIZACIÓN DE VARIABLES
$daily_summary = [];
$greeting_name = 'Usuario';
$today_name = 'Hoy';
$daily_growth_challenge = [];
$csrf_token = htmlspecialchars($_SESSION['csrf_token'] ?? '', ENT_QUOTES, 'UTF-8');


    // A. Configuración de Zona Horaria
    $stmt_tz = $pdo->prepare("SELECT timezone FROM business_info WHERE id = :id LIMIT 1");
    $stmt_tz->execute([':id' => 1]);
    $timezone = ($stmt_tz->fetch(PDO::FETCH_ASSOC))['timezone'] ?? '';
    date_default_timezone_set($timezone);

    // B. Obtención de Datos del Usuario
    $stmt_user = $pdo->prepare("SELECT full_name FROM users WHERE user_id = :user_id LIMIT 1");
    // FIX: Cambiado $user_id a $user_id_session (definido en core/init.php)
    $stmt_user->execute([':user_id' => $user_id_session]);
    $full_name = $stmt_user->fetchColumn();
    $user_first_name = $full_name ? explode(' ', $full_name)[0] : 'Usuario';
    $greeting_name = htmlspecialchars($user_first_name, ENT_QUOTES, 'UTF-8');

    // C. Formateo de Fecha
    $formatter = new IntlDateFormatter('es_ES', IntlDateFormatter::FULL, IntlDateFormatter::NONE, $timezone, IntlDateFormatter::GREGORIAN, 'EEEE, dd \'de\' MMMM');
    $today_name = $formatter->format(new DateTime());

    // D. Obtención del Resumen Diario (Lógica de Negocio)
    // FIX: Cambiado $user_id a $user_id_session
    $daily_summary = fetchDailySummary($pdo, $user_id_session);

    // E. Lógica del "Reto de Crecimiento"
    $growth_strategies = [
        ['title' => 'CRECIMIENTO: Llama a 3 clientes antiguos inactivos para ofrecer una promoción de reactivación.', 'is_emergency' => true],
        ['title' => 'MARKETING: Graba y sube 1 Historia o Reel mostrando un resultado "Antes y Después".', 'is_emergency' => true],
        ['title' => 'MANTENIMIENTO: Revisa inventario y limpieza de herramientas para estar listo mañana.', 'is_emergency' => false],
        ['title' => 'FIDELIZACIÓN: Envía mensajes personales de agradecimiento a los últimos 5 clientes.', 'is_emergency' => true],
        ['title' => 'ESTRATEGIA: Investiga 2 competidores locales y anota qué ofertas están promocionando.', 'is_emergency' => false],
        ['title' => 'REPUTACIÓN: Contacta a tu último cliente satisfecho y pídele una reseña en Google Maps.', 'is_emergency' => true],
        ['title' => 'VISIBILIDAD: Publica las mejores fotos de tu semana en tus redes sociales.', 'is_emergency' => false],
        ['title' => 'VENTAS: Revisa cotizaciones antiguas (hace 30 días) y haz una llamada de seguimiento final.', 'is_emergency' => true],
        ['title' => 'ALIANZAS: Contacta a un negocio local para explorar una colaboración que puedan trabajar juntos.', 'is_emergency' => false]
    ];
    
    if (!empty($growth_strategies)) {
        // Selección determinista basada en la fecha (todos los usuarios ven lo mismo el mismo día)
        $seed_integer = crc32(date('Y-m-d'));
        $strategy_index = abs($seed_integer) % count($growth_strategies);
        $daily_growth_challenge = $growth_strategies[$strategy_index];
    } else {
        $daily_growth_challenge = ['title' => 'Define tu estrategia de crecimiento hoy.', 'is_emergency' => false];
    }

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Un Día Productivo <?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>
    <script src="https://unpkg.com/imask"></script>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
</head>
<body data-page-title="Tu Día Productivo De Acción Diaria" 
      data-page-subtitle="Tu Plan De Acción Diario Y Resumen De Pendientes" 
      data-page-icon="handshake">
    
    <div id="toast-container" class="toast-container"></div>
    
    <?php include 'files/gtm-body.php'; ?>
    
    <input type="hidden" id="csrf-token-php" value="<?= $csrf_token ?>">
    
    <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 bg-[var(--color-background)]">
            <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">
                <section class="dashboard-section">
                    
                    <div class="mb-6">
                        <h1 class="font-black uppercase text-3xl md:text-4xl text-[var(--color-primary)] mb-1">
                            ¡Hola <?= $greeting_name ?>! <br />hoy es <span class="text-[var(--color-secondary)]"><?= htmlspecialchars($today_name) ?></span>
                        </h1>
                        <p class="text-gray-600 font-bold text-lg uppercase">Tu Resumen Y Plan De Acción Para Maximizar Tu Impacto.</p>
                    </div>

                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <div class="lg:col-span-2 space-y-6">
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-2 gap-4 mb-6 stat-cards-grid"> 
                                
                                <div class="stat-card bg-white p-3 lg:p-6 rounded-xl shadow-md flex items-center border-l-4 border-[var(--color-highlight)]">
                                    <i data-lucide="user-plus" class="w-8 h-8 lg:w-12 lg:h-12 text-[var(--color-secondary)] shrink-0"></i>
                                    <div class="flex-1 flex justify-between items-center ml-3 lg:ml-4">
                                        <h3 class="text-md lg:text-lg font-black text-gray-500 leading-tight uppercase">FACTURAS VENCIDAS</h3>
                                        <p class="text-5xl lg:text-5xl font-black text-[var(--color-primary)]"><?= (int)($daily_summary['invoices_overdue'] ?? 0) ?></p>
                                    </div>
                                </div>

                                <div class="stat-card bg-white p-3 lg:p-6 rounded-xl shadow-md flex items-center border-l-4 border-[var(--color-highlight)]">
                                    <i data-lucide="calendar-check" class="w-8 h-8 lg:w-12 lg:h-12 text-[var(--color-secondary)] shrink-0"></i>
                                    <div class="flex-1 flex justify-between items-center ml-3 lg:ml-4">
                                        <h3 class="text-md lg:text-lg font-black text-gray-500 leading-tight uppercase">CITAS PENDIENTES</h3>
                                        <p class="text-5xl lg:text-5xl font-black text-[var(--color-primary)]"><?= count($daily_summary['appointments'] ?? []) ?></p>
                                    </div>
                                </div>

                                <div class="stat-card bg-white p-3 lg:p-6 rounded-xl shadow-md flex items-center border-l-4 border-[var(--color-highlight)]">
                                    <i data-lucide="users" class="w-8 h-8 lg:w-12 lg:h-12 text-[var(--color-secondary)] shrink-0"></i>
                                    <div class="flex-1 flex justify-between items-center ml-3 lg:ml-4">
                                        <h3 class="text-md lg:text-lg font-black text-gray-500 leading-tight uppercase">SEGUIMIENTO LEADS</h3>
                                        <p class="text-5xl lg:text-5xl font-black text-[var(--color-primary)]"><?= (int)($daily_summary['follow_up_clients'] ?? 0) ?></p>
                                    </div>
                                </div>

                                <div class="stat-card bg-white p-3 lg:p-6 rounded-xl shadow-md flex items-center border-l-4 border-[var(--color-highlight)]">
                                    <i data-lucide="check-square" class="w-8 h-8 lg:w-12 lg:h-12 text-[var(--color-secondary)] shrink-0"></i>
                                    <div class="flex-1 flex justify-between items-center ml-3 lg:ml-4">
                                        <h3 class="text-md lg:text-lg font-black text-gray-500 leading-tight uppercase">TAREAS PENDIENTES</h3>
                                        <p class="text-5xl lg:text-5xl font-black text-[var(--color-primary)]"><?= count($daily_summary['tasks'] ?? []) ?></p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="bg-white p-6 rounded-xl shadow-md space-y-8">
                                
                                <div class="border-b border-gray-100 pb-6">
                                    <h3 class="text-2xl font-black uppercase text-[var(--color-primary)] mb-4 flex items-center gap-2">
                                        <i data-lucide="calendar" class="w-6 h-6 mr-2 text-[var(--color-secondary)]"></i> Citas y Reuniones
                                    </h3>
                                    <?php if (!empty($daily_summary['appointments'])): ?>
                                        <ul class="list-none space-y-2 ml-2 appointments-list">
                                            <?php foreach ($daily_summary['appointments'] as $appt): ?>
                                                <li class="text-gray-700 text-sm font-medium border-l-4 border-[var(--color-secondary)] pl-3 p-2 rounded-r-md transition-colors hover:bg-gray-50 flex items-center appointment-item">
                                                    <span class="inline-block w-20 text-[var(--color-primary)] font-black mr-3 uppercase appointment-time"><?= htmlspecialchars($appt['time'], ENT_QUOTES, 'UTF-8') ?></span>
                                                    <span class="appointment-title uppercase"><?= htmlspecialchars(translateStrategicRoute($appt['title']), ENT_QUOTES, 'UTF-8') ?></span>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php else: ?>
                                        <p class="text-sm text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg uppercase">No Hay Citas Confirmadas Para Hoy. ¡Día Libre De Reuniones!</p>
                                    <?php endif; ?>
                                </div>

                                <div class="border-b border-gray-100 pb-6">
                                    <h3 class="text-2xl font-black uppercase text-[var(--color-primary)] mb-4 flex items-center gap-2">
                                        <i data-lucide="map-pin" class="w-6 h-6 mr-2 text-[var(--color-secondary)]"></i> Ruta del Día
                                    </h3>
                                    <?php if (!empty($daily_summary['today_route'])): ?>
                                        <?php $route = $daily_summary['today_route']; ?>
                                        <p class="text-md font-bold text-[var(--color-secondary)] ml-2 mb-3 uppercase">Ruta Asignada: <?= htmlspecialchars($route['name'], ENT_QUOTES, 'UTF-8') ?> (<?= count($route['clients']) ?> Clientes)</p>
                                        <ol class="list-decimal space-y-3 ml-6 route-list">
                                            <?php foreach ($route['clients'] as $index => $client): ?>
                                                <li class="text-gray-700 text-sm font-medium border-l-4 border-[var(--color-highlight)] pl-3 p-2 rounded-r-md transition-colors hover:bg-yellow-50 route-item">
                                                    <span class="font-black text-[var(--color-primary)] mr-2 route-step-number"><?= $index + 1 ?>.</span> 
                                                    <span class="route-client-name uppercase font-bold"><?= htmlspecialchars($client['client_name'], ENT_QUOTES, 'UTF-8') ?></span>
                                                    <p class="text-xs text-gray-500 italic mt-0.5 ml-6 route-address uppercase"><?= htmlspecialchars($client['street_address'] . ', ' . $client['city'], ENT_QUOTES, 'UTF-8') ?></p>
                                                </li>
                                            <?php endforeach; ?>
                                        </ol>
                                    <?php else: ?>
                                        <p class="text-sm text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg uppercase">No Hay Una Ruta De clientes Asignada Para Hoy</p>
                                    <?php endif; ?>
                                </div>

                                <div class="border-b border-gray-100 pb-6">
                                    <h3 class="text-2xl font-black uppercase text-[var(--color-primary)] mb-4 flex items-center gap-2">
                                        <i data-lucide="list-checks" class="w-6 h-6 mr-2 text-[var(--color-secondary)]"></i> Tareas Clave (<?= count($daily_summary['tasks'] ?? []) ?>)
                                    </h3>
                                    <?php if (!empty($daily_summary['tasks'])): ?>
                                        <ul class="list-none space-y-2 ml-2 text-gray-700 text-sm font-medium tasks-list">
                                            <?php foreach ($daily_summary['tasks'] as $task): 
                                                $is_emergency = $task['is_emergency'] ?? false;
                                                $border_color_class = $is_emergency ? 'border-red-500' : 'border-[var(--color-highlight)]'; 
                                                $icon_color_class = $is_emergency ? 'text-red-500' : 'text-gray-400'; 
                                                $text_color_class = $is_emergency ? 'text-[var(--color-secondary)] font-black' : 'text-gray-800';
                                            ?>
                                                <li class="flex items-start border-l-4 pl-3 p-2 rounded-r-md transition-colors hover:bg-gray-50 <?= htmlspecialchars($border_color_class) ?>">
                                                    <?= $is_emergency ? '<i data-lucide="zap" class="w-5 h-5 mr-2 flex-shrink-0 mt-0.5 ' . htmlspecialchars($icon_color_class) . '"></i>' : '<i data-lucide="chevrons-right" class="w-5 h-5 mr-2 text-gray-400 flex-shrink-0 mt-0.5"></i>' ?>
                                                    <span class="<?= htmlspecialchars($text_color_class) ?> uppercase"><?= htmlspecialchars(translateStrategicRoute($task['title']), ENT_QUOTES, 'UTF-8') ?></span>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php else: ?>
                                        <p class="text-sm text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg uppercase">No Hay Tareas Pendientes Asignadas Para Hoy</p>
                                    <?php endif; ?>
                                </div>

                                <div class="border-b border-gray-100 pb-6">
                                    <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center mb-4 gap-4">
                                        <h3 class="text-2xl font-black uppercase text-[var(--color-primary)] flex items-center gap-2">
                                            <i data-lucide="bell" class="w-6 h-6 mr-2 text-[var(--color-secondary)]"></i> Prospectos (<?= (int)($daily_summary['follow_up_clients'] ?? 0) ?>)
                                        </h3>
                                        <a href="leads.php" class="bg-[var(--color-primary)] hover:opacity-90 text-white font-black py-2 px-4 rounded-lg uppercase text-xs flex items-center justify-center gap-2 btn-view-all-leads">
                                            VER TODOS <i data-lucide="chevron-right" class="w-4 h-4"></i>
                                        </a>
                                    </div>

                                    <?php if (!empty($daily_summary['follow_up_list'])): ?>
                                        <p class="text-xs text-gray-500 ml-2 mb-2 uppercase font-bold">Se Recomienda Contactar Hoy:</p>
                                        <ul class="list-none space-y-3 ml-2 follow-up-list">
                                            <?php foreach ($daily_summary['follow_up_list'] as $lead): 
                                                $contact_info_display = formatPhoneNumberUSA($lead['mobile'] ?? $lead['phone'] ?? 'Sin Teléfono');
                                                $has_phone = !empty($lead['mobile']) || !empty($lead['phone']);
                                                $contact_class = $has_phone ? 'text-gray-600' : 'text-[var(--color-secondary)] font-semibold';
                                            ?>
                                                <li class="flex flex-col sm:flex-row justify-between items-start sm:items-center text-gray-700 text-sm font-medium border-l-4 border-[var(--color-secondary)] pl-3 p-2 rounded-r-md transition-colors hover:bg-gray-50 lead-item gap-3">
                                                    <div class="flex-1 min-w-0">
                                                        <span class="font-bold mr-2 truncate block lead-name uppercase text-[var(--color-primary)]"><?= htmlspecialchars($lead['name'] ?? 'N/A', ENT_QUOTES, 'UTF-8') ?></span>
                                                        <span class="text-xs italic <?= htmlspecialchars($contact_class) ?> lead-contact"><?= $contact_info_display ?></span>
                                                    </div>
                                                    <a href="leads.php?id=<?= htmlspecialchars((string)($lead['id'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" class="w-full sm:w-auto bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-1.5 px-3 rounded-lg uppercase text-xs flex items-center justify-center gap-2 btn-view-lead">
                                                        <i data-lucide="eye" class="w-3 h-3"></i> VER PROSPECTO
                                                    </a>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php else: ?>
                                        <p class="text-sm text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg uppercase">No Hay Prospectos Para Seguimiento Urgente Hoy</p>
                                    <?php endif; ?>
                                </div>

                                <div class="border-b border-gray-100 pb-6">
                                    <h3 class="text-2xl font-black uppercase text-[var(--color-primary)] mb-4 flex items-center gap-2">
                                        <i data-lucide="alert-triangle" class="w-6 h-6 mr-2 text-[var(--color-secondary)]"></i> Quejas Activas (<?= count($daily_summary['active_complaints'] ?? []) ?>)
                                    </h3>
                                    <?php if (!empty($daily_summary['active_complaints'])): ?>
                                        <p class="text-xs text-gray-500 ml-2 mb-2 uppercase font-bold">Requieren Tu Atención Inmediata:</p>
                                        <ul class="list-none space-y-2 ml-2 complaints-list">
                                            <?php foreach ($daily_summary['active_complaints'] as $complaint): ?>
                                                <li class="flex flex-col sm:flex-row justify-between items-start sm:items-center text-gray-700 text-sm font-medium border-l-4 border-[var(--color-secondary)] pl-3 p-2 rounded-r-md transition-colors hover:bg-gray-50 complaint-item gap-3">
                                                    <span class="font-bold mr-2 truncate block uppercase text-red-700">
                                                        <?= htmlspecialchars($complaint['title'], ENT_QUOTES, 'UTF-8') ?> 
                                                        <span class="text-xs text-gray-500 font-semibold block sm:inline">(Cliente: <?= htmlspecialchars($complaint['first_name'] . ' ' . $complaint['last_name'], ENT_QUOTES, 'UTF-8') ?>)</span>
                                                    </span>
                                                    <a href="complaints.php?id=<?= htmlspecialchars((string)($complaint['id'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" class="w-full sm:w-auto bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-1.5 px-3 rounded-lg uppercase text-xs flex items-center justify-center gap-2 btn-resolve-complaint">
                                                        <i data-lucide="chevrons-right" class="w-3 h-3"></i> RESOLVER
                                                    </a>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php else: ?>
                                        <p class="text-sm text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg uppercase">¡Excelente! No Hay Quejas Activas O Pendientes De Acción</p>
                                    <?php endif; ?>
                                </div>

                                <div class="border-b border-gray-100 pb-6">
                                    <h3 class="text-2xl font-black uppercase text-[var(--color-primary)] mb-4 flex items-center gap-2">
                                        <i data-lucide="construction" class="w-6 h-6 mr-2 text-[var(--color-secondary)]"></i> Proyectos En Curso (<?= count($daily_summary['active_projects'] ?? []) ?>)
                                    </h3>
                                    <?php if (!empty($daily_summary['active_projects'])): ?>
                                        <p class="text-xs text-gray-500 ml-2 mb-2 uppercase font-bold">Prioriza Las Fechas De Entrega:</p>
                                        <ul class="list-none space-y-2 ml-2 projects-list">
                                            <?php foreach ($daily_summary['active_projects'] as $project): 
                                                $due_date = new DateTime($project['due_date']);
                                                $days_left = (new DateTime())->diff($due_date)->days;
                                                $date_color_class = $days_left < 7 ? 'text-[var(--color-secondary)] font-black' : 'text-green-600 font-bold';
                                            ?>
                                                <li class="flex flex-col sm:flex-row justify-between items-start sm:items-center text-gray-700 text-sm font-medium border-l-4 border-[var(--color-secondary)] pl-3 p-2 rounded-r-md transition-colors hover:bg-gray-50 project-item gap-3">
                                                    <span class="font-bold mr-2 truncate block uppercase text-[var(--color-primary)]">
                                                        <?= htmlspecialchars($project['name'], ENT_QUOTES, 'UTF-8') ?> 
                                                        <span class="text-xs text-gray-500 font-medium block sm:inline">(Cliente: <?= htmlspecialchars($project['client_name'], ENT_QUOTES, 'UTF-8') ?>)</span>
                                                    </span>
                                                    <div class="flex items-center gap-3 w-full sm:w-auto justify-between sm:justify-end project-due-date-container">
                                                        <span class="text-xs <?= htmlspecialchars($date_color_class) ?> uppercase project-due-date-text">
                                                            Vence: <?= date('M d', strtotime($project['due_date'])) ?>
                                                        </span>
                                                        <a href="projects.php?id=<?= htmlspecialchars((string)($project['id'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" class="bg-[var(--color-primary)] hover:opacity-90 text-white font-black py-1 px-3 rounded-full uppercase text-[10px] flex items-center justify-center gap-1 btn-view-project">
                                                            VER <i data-lucide="chevron-right" class="w-3 h-3"></i>
                                                        </a> 
                                                    </div>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php else: ?>
                                        <p class="text-sm text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg uppercase">No Hay Proyectos Activos.</p>
                                    <?php endif; ?>
                                </div>

                                <div class="border-b border-gray-100 pb-6">
                                    <h3 class="text-2xl font-black uppercase text-[var(--color-primary)] mb-4 flex items-center gap-2">
                                        <i data-lucide="wallet" class="w-6 h-6 mr-2 text-[var(--color-secondary)]"></i> Flujo de Efectivo
                                    </h3>
                                    <ul class="list-none space-y-2 ml-2 text-gray-700 text-sm font-medium">
                                        <li class="flex justify-between border-l-4 border-green-500 pl-3 p-2 rounded-r-md bg-green-50/50">
                                            <span class="uppercase font-bold">Facturas Enviadas Pendientes:</span>
                                            <span class="font-black text-green-700"><?= (int)($daily_summary['invoices_sent_pending'] ?? 0) ?></span>
                                        </li>
                                        <li class="flex justify-between border-l-4 border-yellow-500 pl-3 p-2 rounded-r-md bg-yellow-50/50">
                                            <span class="uppercase font-bold">Estimados Para Aprobación:</span>
                                            <span class="font-black text-yellow-700"><?= (int)($daily_summary['quotes_pending'] ?? 0) ?></span>
                                        </li>
                                    </ul>
                                </div>

                                <div>
                                    <h3 class="text-2xl font-black uppercase text-[var(--color-primary)] mb-4 flex items-center gap-2">
                                        <i data-lucide="megaphone" class="w-6 h-6 mr-2 text-[var(--color-secondary)]"></i> Plan De Acción
                                    </h3>
                                    <p class="text-gray-700 text-sm font-medium italic border-l-4 border-[var(--color-secondary)] pl-4 ml-2 bg-gray-50 p-3 rounded-r-md strategic-route-box">
                                        <?= htmlspecialchars(translateStrategicRoute(strip_tags($daily_summary['strategic_route'] ?? 'Sin plan estratégico definido.')), ENT_QUOTES, 'UTF-8') ?>
                                    </p>
                                </div>
                            </div>
                            
                            <div class="bg-gradient-to-br from-[var(--color-secondary)] to-[var(--color-primary)] rounded-xl shadow-xl text-white relative overflow-hidden border-4 border-white/50 hover:shadow-2xl transition-all duration-300 growth-challenge-card">
                                <div class="absolute top-0 right-0 p-4 opacity-10">
                                    <i data-lucide="trending-up" class="w-32 h-32 transform rotate-12"></i>
                                </div>
                                <div class="p-6 relative z-10">
                                    <h3 class="text-2xl font-black uppercase mb-3 flex items-center gap-2 text-white">
                                        <i data-lucide="rocket" class="w-8 h-8 text-[var(--color-highlight)]"></i> Plan De Crecimiento
                                    </h3>
                                    <div class="bg-white/10 backdrop-blur-sm p-4 rounded-lg border border-white/20">
                                        <p class="text-lg font-bold uppercase text-white shadow-black drop-shadow-md">
                                            <?= htmlspecialchars(translateStrategicRoute($daily_growth_challenge['title']), ENT_QUOTES, 'UTF-8') ?>
                                        </p>
                                    </div>
                                    <p class="mt-3 text-sm font-medium text-white/80 flex items-center uppercase">
                                        <i data-lucide="award" class="w-4 h-4 mr-2"></i> Sal De Tu Zona De Confort
                                    </p>
                                </div>
                            </div>

                        </div>
                        
                        <div>
                            <div class="bg-[var(--color-primary)] text-white rounded-xl shadow-2xl border-l-4 border-[var(--color-highlight)] min-h-[300px] p-6 space-y-6 transition-all duration-300 ease-in-out hover:shadow-lg daily-focus-container sticky top-24">
                                <h3 class="text-2xl font-black uppercase mb-6 border-b pb-4 border-white/20 flex items-center text-[var(--color-highlight)]">
                                    <i data-lucide="target" class="w-7 h-7 mr-3 text-white"></i> TU ENFOQUE DIARIO
                                </h3>
                                <ul id="daily-focus-checklist" class="space-y-4">
                                    
                                    <?php if (!empty($daily_summary['active_complaints'])): ?>
                                        <li class="border-t pt-4 mt-4 border-white/20 checklist-section-title">
                                            <p class="text-sm font-black text-red-400 uppercase mb-2 animate-pulse flex items-center gap-2">
                                                <i data-lucide="alert-triangle" class="w-4 h-4"></i> ATENCIÓN URGENTE (QUEJAS):
                                            </p>
                                        </li>
                                        <?php foreach ($daily_summary['active_complaints'] as $idx => $comp): ?>
                                            <li class="flex items-start">
                                                <input type="checkbox" id="check-complaint-<?= $comp['id'] ?>" data-task-title="Resolver Queja: <?= htmlspecialchars($comp['title']) ?>" class="focus-checklist-checkbox w-5 h-5 bg-red-600 border-red-400 rounded mt-1 mr-3 cursor-pointer checked:bg-white checked:border-white">
                                                <label for="check-complaint-<?= $comp['id'] ?>" class="text-sm font-bold text-white cursor-pointer flex-1 focus-checklist-label uppercase">
                                                    Resolver: <?= htmlspecialchars($comp['title']) ?> (<?= htmlspecialchars($comp['first_name']) ?>)
                                                </label>
                                            </li>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                    <?php if (!empty($daily_summary['invoices_overdue_list'])): ?>
                                        <li class="border-t pt-4 mt-4 border-white/20 checklist-section-title">
                                            <p class="text-sm font-black text-[var(--color-highlight)] uppercase mb-2 flex items-center gap-2">
                                                <i data-lucide="dollar-sign" class="w-4 h-4"></i> COBROS URGENTES:
                                            </p>
                                        </li>
                                        <?php foreach ($daily_summary['invoices_overdue_list'] as $inv): ?>
                                            <li class="flex items-start">
                                                <input type="checkbox" id="check-inv-<?= $inv['id'] ?>" data-task-title="Cobrar Factura <?= htmlspecialchars($inv['external_id']) ?>" class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)]">
                                                <label for="check-inv-<?= $inv['id'] ?>" class="text-sm text-white cursor-pointer flex-1 focus-checklist-label">
                                                    Cobrar Factura #<?= htmlspecialchars($inv['external_id']) ?> ($<?= number_format((float)$inv['total_amount'], 2) ?>) - <?= htmlspecialchars($inv['client_name']) ?>
                                                </label>
                                            </li>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                    <?php if (!empty($daily_summary['today_route']['clients'])): ?>
                                        <li class="border-t pt-4 mt-4 border-white/20 checklist-section-title">
                                            <p class="text-sm font-black text-[var(--color-highlight)] uppercase mb-2 flex items-center gap-2">
                                                <i data-lucide="truck" class="w-4 h-4"></i> RUTA DE HOY:
                                            </p>
                                        </li>
                                        <?php foreach ($daily_summary['today_route']['clients'] as $index => $client): ?>
                                            <li class="flex items-start">
                                                <input type="checkbox" id="task-route-<?= $index ?>" data-task-title="Servicio: <?= htmlspecialchars($client['client_name']) ?>" class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)]">
                                                <label for="task-route-<?= $index ?>" class="text-sm text-white cursor-pointer flex-1 focus-checklist-label">
                                                    Visitar: <?= htmlspecialchars($client['client_name']) ?>
                                                </label>
                                            </li>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                    <?php if (!empty($daily_summary['appointments'])): ?>
                                        <li class="border-t pt-4 mt-4 border-white/20 checklist-section-title">
                                            <p class="text-sm font-black text-[var(--color-highlight)] uppercase mb-2 flex items-center gap-2">
                                                <i data-lucide="calendar" class="w-4 h-4"></i> CITAS:
                                            </p>
                                        </li>
                                        <?php foreach ($daily_summary['appointments'] as $appt): ?>
                                            <li class="flex items-start">
                                                <input type="checkbox" id="task-appt-<?= $appt['id'] ?>" class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)]">
                                                <label for="task-appt-<?= $appt['id'] ?>" class="text-sm text-white cursor-pointer flex-1 focus-checklist-label">
                                                    <?= htmlspecialchars(translateStrategicRoute($appt['time'] . ' ' . $appt['title'])) ?>
                                                </label>
                                            </li>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                    <?php if (!empty($daily_summary['quotes_pending_list'])): ?>
                                        <li class="border-t pt-4 mt-4 border-white/20 checklist-section-title">
                                            <p class="text-sm font-black text-[var(--color-highlight)] uppercase mb-2 flex items-center gap-2">
                                                <i data-lucide="handshake" class="w-4 h-4"></i> CIERRE DE VENTAS:
                                            </p>
                                        </li>
                                        <?php foreach ($daily_summary['quotes_pending_list'] as $est): ?>
                                            <li class="flex items-start">
                                                <input type="checkbox" id="check-est-<?= $est['id'] ?>" class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)]">
                                                <label for="check-est-<?= $est['id'] ?>" class="text-sm text-white cursor-pointer flex-1 focus-checklist-label">
                                                    Cerrar Estimado #<?= htmlspecialchars($est['external_id']) ?> (<?= htmlspecialchars($est['client_name']) ?>)
                                                </label>
                                            </li>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                    <?php if (!empty($daily_summary['follow_up_list'])): ?>
                                        <li class="border-t pt-4 mt-4 border-white/20 checklist-section-title">
                                            <p class="text-sm font-black text-[var(--color-highlight)] uppercase mb-2 flex items-center gap-2">
                                                <i data-lucide="phone" class="w-4 h-4"></i> LLAMADAS DE SEGUIMIENTO:
                                            </p>
                                        </li>
                                        <?php foreach ($daily_summary['follow_up_list'] as $lead): ?>
                                            <li class="flex items-start">
                                                <input type="checkbox" id="check-lead-<?= $lead['id'] ?>" class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)]">
                                                <label for="check-lead-<?= $lead['id'] ?>" class="text-sm text-white cursor-pointer flex-1 focus-checklist-label">
                                                    Contactar Lead: <?= htmlspecialchars($lead['name']) ?> (<?= htmlspecialchars($lead['status'] ?? 'Pendiente') ?>)
                                                </label>
                                            </li>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                    <?php if (!empty($daily_summary['tasks'])): ?>
                                        <li class="border-t pt-4 mt-4 border-white/20 checklist-section-title">
                                            <p class="text-sm font-black text-[var(--color-highlight)] uppercase mb-2 flex items-center gap-2">
                                                <i data-lucide="check-circle" class="w-4 h-4"></i> TAREAS VARIAS:
                                            </p>
                                        </li>
                                        <?php foreach ($daily_summary['tasks'] as $task): 
                                            $task_id = 'task-core-' . htmlspecialchars((string)$task['id']);
                                            $text_class = ($task['is_emergency'] ?? false) ? 'text-white font-black is-urgent-task' : 'text-white font-medium';
                                        ?>
                                            <li class="flex items-start">
                                                <input type="checkbox" id="<?= $task_id ?>" class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)]">
                                                <label for="<?= $task_id ?>" class="text-sm cursor-pointer flex-1 focus-checklist-label <?= htmlspecialchars($text_class) ?>">
                                                    <?= htmlspecialchars(translateStrategicRoute($task['title'])) ?>
                                                </label>
                                            </li>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                    <li class="flex items-start border-t pt-4 mt-4 border-white/20">
                                        <input type="checkbox" id="task-strategy" class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)]">
                                        <label for="task-strategy" class="text-white text-sm font-medium cursor-pointer flex-1 focus-checklist-label italic">
                                            <?= htmlspecialchars(translateStrategicRoute(strip_tags($daily_summary['strategic_route'] ?? 'Sin plan estratégico definido.')), ENT_QUOTES, 'UTF-8') ?>
                                        </label>
                                    </li>
                                </ul>

                                <div class="pt-4 border-t mt-6 border-white/20">
                                    <p class="text-xl font-black text-gray-300 mb-2 uppercase flex items-center justify-between">
                                        <span>TU PROGRESO</span> 
                                        <span id="progress-percentage" class="progress-percentage-display font-extrabold text-[var(--color-highlight)] transition-colors duration-500">0%</span>
                                    </p>
                                    <div class="w-full bg-white/10 rounded-full h-4 shadow-inner">
                                        <div id="progress-bar" class="h-4 rounded-full bg-[var(--color-secondary)] transition-all duration-500 shadow-lg progress-bar-fill"></div>
                                    </div>
                                </div> 
                            </div> 
                            <?php include 'push.php'; ?>
                        </div>
                    </div>
                </section>
            </div>
        </main>
    </div>
</body>

<script>
(function() {
    "use strict";

    /**
     * Configura el checklist diario y su persistencia en LocalStorage
     */
    function setupDailyChecklist() {
        const checklist = document.getElementById('daily-focus-checklist');
        const progressBar = document.getElementById('progress-bar');
        const progressPercentage = document.getElementById('progress-percentage');
        
        if (!checklist || !progressBar || !progressPercentage) return;

        // Clave única por día para reiniciar el checklist diariamente
        const todayDate = '<?php echo date('Ymd'); ?>';

        const updateProgress = () => {
            const allCheckboxes = checklist.querySelectorAll('input.focus-checklist-checkbox');
            const completedCheckboxes = checklist.querySelectorAll('input.focus-checklist-checkbox:checked');
            const total = allCheckboxes.length;
            
            if (total === 0) {
                progressBar.style.width = `0%`;
                progressPercentage.textContent = `0%`;
                return;
            }

            const percentage = Math.round((completedCheckboxes.length / total) * 100);
            progressBar.style.width = `${percentage}%`;
            progressPercentage.textContent = `${percentage}%`;

            if (percentage === 100) {
                progressBar.classList.remove('bg-progress-default');
                progressBar.classList.add('bg-progress-complete');
                progressPercentage.classList.remove('text-progress-default');
                progressPercentage.classList.add('text-progress-complete');
            } else {
                progressBar.classList.remove('bg-progress-complete');
                progressBar.classList.add('bg-progress-default');
                progressPercentage.classList.remove('text-progress-complete');
                progressPercentage.classList.add('text-progress-default');
            }
        };

        // Event Listener para cambios en checkboxes
        checklist.addEventListener('change', (e) => {
            const target = e.target;
            if (!target.classList.contains('focus-checklist-checkbox')) return;

            const label = checklist.querySelector(`label[for="${target.id}"]`);
            if (label) {
                label.classList.toggle('line-through', target.checked);
                label.classList.toggle('text-gray-400', target.checked);
                if (!target.checked) {
                    label.classList.toggle('font-extrabold', label.classList.contains('is-urgent-task'));
                }
            }
            // Guardar estado en LocalStorage
            localStorage.setItem(`daily_task_${target.id}_${todayDate}`, target.checked);
            updateProgress();
        });

        // Inyección de estilos dinámicos para la barra de progreso
        const styleSheet = document.createElement("style");
        styleSheet.innerHTML = `
            .bg-progress-default { background-color: var(--color-secondary); }
            .bg-progress-complete { background-color: var(--color-highlight); }
            .text-progress-default { color: var(--color-highlight); }
            .text-progress-complete { color: white; }
            .progress-bar-fill { background-color: var(--color-highlight); }
        `;
        document.head.appendChild(styleSheet);

        // Inicialización de estado visual
        progressBar.classList.add('bg-progress-default');
        progressPercentage.classList.add('text-progress-default');

        // Restaurar estado desde LocalStorage
        checklist.querySelectorAll('input.focus-checklist-checkbox').forEach(checkbox => {
            const savedState = localStorage.getItem(`daily_task_${checkbox.id}_${todayDate}`);
            checkbox.checked = (savedState === 'true');
            const label = checklist.querySelector(`label[for="${checkbox.id}"]`);
            if(label){
                label.classList.toggle('line-through', checkbox.checked);
                label.classList.toggle('text-gray-400', checkbox.checked);
            }
        });

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