<?php
include 'files/guardiankey.php';
require_once('db/db_connection.php');

include 'db/fetch-daily-summary.php';
$daily_summary = fetchDailySummary($pdo);

// ***************************************************************
// Usamos getUserFullName que se añadió en fetch-daily-summary.php
$full_name = getUserFullName($pdo);
// Separamos el nombre para un saludo más personal (ej: "Hola Leandro!")
$user_first_name_parts = explode(' ', $full_name);
$user_first_name = $user_first_name_parts[0];
$greeting_name = htmlspecialchars($user_first_name);
// ***************************************************************

$formatter = new IntlDateFormatter('es_ES', IntlDateFormatter::FULL, IntlDateFormatter::NONE, 'America/Los_Angeles', IntlDateFormatter::GREGORIAN, 'EEEE, dd \'de\' MMMM');
$today_name = $formatter->format(new DateTime());

// Contar las tareas totales para el checklist (Tareas de DB/Emergencia + Leads de Seguimiento + Tarea Estratégica)
$total_checklist_items = count($daily_summary['tasks']) + $daily_summary['follow_up_clients'] + 1; // +1 por la tarea estratégica

?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>FlowCRM™ Tu Centro De Control Empresarial Powered By OrozCO</title>
  <meta name="description" content="La Plataforma Todo En Uno Para Impulsar Tu Negocio">
  <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="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'; ?>

    <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-bold text-2xl md:text-3xl text-[var(--color-primary)] mb-1">
                            ¡Hola <?php echo $greeting_name; ?>! hoy es <span class="text-[var(--color-secondary)]"><?php echo $today_name; ?></span>
                        </h1>
                        <p class="text-gray-600 text-lg">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-2 md:grid-cols-2 gap-4 mb-6"> 
                            
                                <div class="flex items-center gap-4 bg-white p-6 rounded-xl shadow-lg border-l-4 border-[var(--color-highlight)] transition-all duration-300 ease-in-out hover:-translate-y-0.5 hover:shadow-xl">
                                    <i data-lucide="user-plus" class="w-12 h-12 text-gray-700"></i>
                                    <div>
                                        <h3 class="font-black uppercase text-black mb-1 text-lg leading-tight">FACTURAS VENCIDAS</h3>
                                        <p class="main-value font-bold text-[var(--color-secondary)] mt-1 text-4xl leading-none"><?php echo $daily_summary['invoices_overdue']; ?></p>
                                        <p class="text-sm text-gray-400 mt-1 uppercase">ENVIAR AL CLIENTE</p>
                                    </div>
                                </div>
                                
                                <div class="flex items-center gap-4 bg-white p-6 rounded-xl shadow-lg border-l-4 border-[var(--color-secondary)] transition-all duration-300 ease-in-out hover:-translate-y-0.5 hover:shadow-xl">
                                    <i data-lucide="calendar-check" class="w-12 h-12 text-[var(--color-secondary)]"></i>
                                    <div>
                                        <h3 class="font-black uppercase text-black mb-1 text-lg leading-tight">CITAS PENDIENTES</h3>
                                        <p class="main-value font-bold text-[var(--color-secondary)] mt-1 text-4xl leading-none"><?php echo count($daily_summary['appointments']); ?></p>
                                        <p class="text-sm text-gray-400 mt-1 uppercase">AGENDA DIARIA</p>
                                    </div>
                                </div>
                                
                                <div class="flex items-center gap-4 bg-white p-6 rounded-xl shadow-lg border-l-4 border-[var(--color-secondary)] transition-all duration-300 ease-in-out hover:-translate-y-0.5 hover:shadow-xl">
                                    <i data-lucide="users" class="w-12 h-12 text-[var(--color-secondary)]"></i>
                                    <div>
                                        <h3 class="font-black uppercase text-black mb-1 text-lg leading-tight">SEGUIMIENTO LEADS</h3>
                                        <p class="main-value font-bold text-[var(--color-secondary)] mt-1 text-4xl leading-none"><?php echo $daily_summary['follow_up_clients']; ?></p>
                                        <p class="text-sm text-gray-400 mt-1 uppercase">ENVIAR RECORDATORIOS</p>
                                    </div>
                                </div>
                                
                                <div class="flex items-center gap-4 bg-white p-6 rounded-xl shadow-lg border-l-4 border-[var(--color-primary)] transition-all duration-300 ease-in-out hover:-translate-y-0.5 hover:shadow-xl">
                                    <i data-lucide="check-square" class="w-12 h-12 text-[var(--color-primary)]"></i>
                                    <div>
                                        <h3 class="font-black uppercase text-black mb-1 text-lg leading-tight">TAREAS PENDIENTES</h3>
                                        <p class="main-value font-bold text-[var(--color-primary)] mt-1 text-4xl leading-none"><?php echo count($daily_summary['tasks']); ?></p>
                                        <p class="text-sm text-gray-400 mt-1 uppercase">COSAS POR HACER</p>
                                    </div>
                                </div>
                            </div>


<div class="bg-white p-6 rounded-xl shadow-xl space-y-6 border-t-4 border-t-gray-100 transition-all duration-300 ease-in-out hover:shadow-2xl">
    
    <div class="border-b pb-4">
        <h3 class="text-3xl font-black uppercase text-black mb-4 flex items-center gap-2">
            <i data-lucide="calendar" class="w-6 h-6 mr-3 text-[var(--color-primary)]"></i> Citas y Reuniones
        </h3>
        <?php if (!empty($daily_summary['appointments'])): ?>
            <ul class="list-none space-y-2 ml-4">
                <?php foreach ($daily_summary['appointments'] as $appt): ?>
                    <li class="text-gray-800 text-base font-medium border-l-4 border-[var(--color-secondary)] pl-3 p-1 rounded-sm transition-colors hover:bg-gray-50">
                        <span class="inline-block w-20 text-brand-primary font-extrabold mr-3"><?php echo htmlspecialchars($appt['time']); ?></span>
                        <?php echo htmlspecialchars($appt['title']); ?>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php else: ?>
            <p class="text-base text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg">No Hay Citas Confirmadas Para Hoy. ¡Día Libre De Reuniones!</p>
        <?php endif; ?>
    </div>
    
    <div class="border-b pb-4">
        <h3 class="text-3xl font-black uppercase text-black mb-4 flex items-center gap-2">
            <i data-lucide="map-pin" class="w-6 h-6 mr-3 text-[var(--color-primary)]"></i> Ruta del Día
        </h3>
        <?php if (!empty($daily_summary['today_route'])): ?>
            <?php $route = $daily_summary['today_route']; ?>
            <p class="text-lg font-bold text-[var(--color-secondary)] ml-4 mb-3">Ruta Asignada: <?php echo htmlspecialchars($route['name']); ?> (<?php echo count($route['clients']); ?> Clientes)</p>
            <ol class="list-decimal space-y-3 ml-8">
                <?php foreach ($route['clients'] as $index => $client): ?>
                    <li class="text-gray-800 text-base font-medium border-l-4 border-[var(--color-highlight)] pl-3 p-1 rounded-sm transition-colors hover:bg-yellow-50">
                        <span class="font-extrabold text-[var(--color-primary)] mr-2"><?php echo $index + 1; ?>.</span> 
                        <?php echo htmlspecialchars($client['client_name']); ?>
                        <p class="text-sm text-gray-500 italic mt-0.5 ml-6"><?php echo htmlspecialchars($client['street_address'] . ', ' . $client['city']); ?></p>
                    </li>
                <?php endforeach; ?>
            </ol>
        <?php else: ?>
            <p class="text-base text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg">No Hay Una Ruta De clientes Asignada Para Hoy</p>
        <? endif; ?>
    </div>
        
    <div class="border-b pb-4">
        <h3 class="text-3xl font-black uppercase text-black mb-4 flex items-center gap-2">
            <i data-lucide="list-checks" class="w-6 h-6 mr-3 text-[var(--color-primary)]"></i> Tareas Clave Pendientes (<?php echo count($daily_summary['tasks']); ?>)
        </h3>
        <?php if (!empty($daily_summary['tasks'])): ?>
            <ul class="list-disc space-y-2 ml-8 text-gray-800 text-base font-medium">
                <?php foreach ($daily_summary['tasks'] as $task): 
                    $is_emergency = $task['is_emergency'] ?? false;
                    $border_color_class = $is_emergency ? 'border-[var(--color-secondary)]' : 'border-[var(--color-highlight)]'; 
                    $icon_color_class = $is_emergency ? 'text-[var(--color-secondary)]' : 'text-gray-400'; 
                    $text_color_class = $is_emergency ? 'text-[var(--color-secondary)] font-bold' : 'text-gray-800';
                ?>
                    <li class="flex items-start border-l-4 pl-3 p-1 rounded-sm transition-colors hover:bg-gray-50 <?php echo $border_color_class; ?>">
                        <?php echo $is_emergency ? '<i data-lucide="zap" class="w-5 h-5 mr-2 flex-shrink-0 mt-1 '.$icon_color_class.'"></i>' : '<i data-lucide="chevrons-right" class="w-5 h-5 mr-2 text-gray-400 flex-shrink-0 mt-1"></i>'; ?>
                        <span class="<?php echo $text_color_class; ?>">
                            <?php echo $task['title'];  ?>
                        </span>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php else: ?>
            <p class="text-base text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg">No Hay Tareas Pendientes Asignadas Para Hoy</p>
        <?php endif; ?>
    </div>

    <div class="border-b pb-4">
        <h3 class="text-3xl font-black uppercase text-black mb-4 flex items-center gap-2">
            <i data-lucide="bell" class="w-6 h-6 mr-3 text-[var(--color-primary)]"></i> Prospectos para Seguimiento (<?php echo $daily_summary['follow_up_clients']; ?>)
            <a href="leads.php" class="ml-auto text-xs text-white bg-[var(--color-primary)] font-bold py-2 px-4 rounded-lg shadow-md hover:shadow-lg transition-all duration-300 ease-in-out hover:-translate-y-0.5">
            VER TODOS <i data-lucide="chevron-right" class="w-4 h-4 inline-block ml-1"></i>
        </a>
        </h3>
        <?php if (!empty($daily_summary['follow_up_list'])): ?>
            <p class="text-sm text-gray-500 ml-4 mb-2">Se Recomienda Contactar Hoy A Estos Prospectos:</p>
            <ul class="list-none space-y-2 ml-4">
                <?php foreach ($daily_summary['follow_up_list'] as $lead): 
                    $contact_info_display = htmlspecialchars($lead['mobile'] ?? $lead['phone'] ?? 'Sin Teléfono (Revisar Lead)');
                    $has_phone = !empty($lead['mobile']) || !empty($lead['phone']);
                    $contact_class = $has_phone ? 'text-gray-600' : 'text-[var(--color-secondary)] font-semibold';
                ?>
                    <li class="flex justify-between items-center text-gray-800 text-base font-medium border-l-4 border-[var(--color-secondary)] pl-3 p-2 rounded-sm transition-colors hover:bg-gray-50">
                        
                        <div class="flex-1 min-w-0">
                            <span class="font-bold mr-2 truncate block"><?php echo htmlspecialchars($lead['name'] ?? 'N/A'); ?></span>
                            <span class="text-sm italic <?php echo $contact_class; ?>">(<?php echo $contact_info_display; ?>)</span>
                        </div>

                        <a href="leads.php?id=<?php echo htmlspecialchars($lead['id'] ?? ''); ?>" 
                           class="flex-shrink-0 bg-[var(--color-secondary)] text-white text-xs font-bold uppercase px-3 py-1.5 rounded-lg shadow-md transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5">
                            <i data-lucide="eye" class="w-4 h-4 inline-block mr-1"></i> VER PROSPECTO
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php else: ?>
            <p class="text-base text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg">No Hay Prospectos Para Seguimiento Urgente Hoy</p>
        <?php endif; ?>
    </div>

    <div class="border-b pb-4">
        <h3 class="text-3xl font-black uppercase text-black mb-4 flex items-center gap-2">
            <i data-lucide="alert-triangle" class="w-6 h-6 mr-3 text-[var(--color-primary)]"></i> Quejas Activas (<?php echo count($daily_summary['active_complaints']); ?>)
        </h3>
        <?php if (!empty($daily_summary['active_complaints'])): ?>
            <p class="text-sm text-gray-500 ml-4 mb-2">Requieren Tu Atención Inmediata:</p>
            <ul class="list-none space-y-2 ml-4">
                <?php foreach ($daily_summary['active_complaints'] as $complaint): ?>
                    <li class="flex justify-between items-center text-gray-800 text-base font-medium border-l-4 border-[var(--color-secondary)] pl-3 p-2 rounded-sm transition-colors hover:bg-gray-50">
                        <span class="font-bold mr-2 truncate block">
                            <?php echo htmlspecialchars($complaint['title']); ?> 
                            <span class="text-xs text-[var(--color-secondary)] font-semibold">(Cliente: <?php echo htmlspecialchars($complaint['first_name'] . ' ' . $complaint['last_name']); ?>)</span>
                        </span>
                        <a href="complaints.php?id=<?php echo htmlspecialchars($complaint['id'] ?? ''); ?>"
                           class="flex-shrink-0 text-white bg-[var(--color-secondary)] text-xs font-bold uppercase px-3 py-1.5 rounded-lg shadow-md transition-all duration-300 ease-in-out hover:shadow-lg hover:-translate-y-0.5">
                           <i data-lucide="chevrons-right" class="w-4 h-4 inline-block"></i> RESOLVER
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php else: ?>
            <p class="text-base text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg">¡Excelente! No Hay Quejas Activas O Pendientes De Acción</p>
        <?php endif; ?>
    </div>

    <div class="border-b pb-4">
        <h3 class="text-3xl font-black uppercase text-black mb-4 flex items-center gap-2">
            <i data-lucide="construction" class="w-6 h-6 mr-3 text-[var(--color-primary)]"></i> Proyectos En Curso (<?php echo count($daily_summary['active_projects']); ?>)
        </h3>
        <?php if (!empty($daily_summary['active_projects'])): ?>
            <p class="text-sm text-gray-500 ml-4 mb-2">Prioriza Las Fechas De Entrega Próximas:</p>
            <ul class="list-none space-y-2 ml-4">
                <?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 = $days_left < 7 ? 'text-[var(--color-secondary)] font-bold' : 'text-green-600';
                ?>
                    <li class="flex justify-between items-center text-gray-800 text-base font-medium border-l-4 border-[var(--color-secondary)] pl-3 p-2 rounded-sm transition-colors hover:bg-gray-50">
                        <span class="font-bold mr-2 truncate block">
                            <?php echo htmlspecialchars($project['name']); ?> 
                            <span class="text-xs text-gray-500 font-medium">(Cliente: <?php echo htmlspecialchars($project['client_name']); ?>)</span>
                        </span>
                        <div class="flex-shrink-0 text-right">
                           <span class="text-sm <?php echo $date_color; ?>">
                                Vence: <?php echo date('M d', strtotime($project['due_date'])); ?>
                           </span>
<a href="projects.php?id=<?php echo htmlspecialchars($project['id'] ?? ''); ?>" 
       class="ml-2 inline-flex items-center text-xs font-bold text-white bg-[var(--color-primary)] py-1 px-2 rounded-full shadow-sm hover:shadow-md transition-all duration-300 ease-in-out hover:bg-[var(--color-secondary)]">
        VER <i data-lucide="chevron-right" class="w-3 h-3 ml-1"></i>
    </a>                        </div>
                    </li>
                <?php endforeach; ?>
            </ul>
        <?php else: ?>
            <p class="text-base text-gray-500 ml-4 italic p-2 bg-gray-50 rounded-lg">No Hay Proyectos Activos. ¡Busca El Siguiente Trabajo!</p>
        <?php endif; ?>
    </div>

    <div class="border-b pb-4">
        <h3 class="text-3xl font-black uppercase text-black mb-4 flex items-center gap-2">
            <i data-lucide="wallet" class="w-6 h-6 mr-3 text-[var(--color-primary)]"></i> Flujo de Efectivo Pendiente
        </h3>
        <ul class="list-none space-y-2 ml-4 text-gray-800 text-base font-medium">
            <li class="flex justify-between border-l-4 border-green-500 pl-3 p-1 rounded-sm">
                <span>Facturas Enviadas Pendientes De Cobro:</span>
                <span class="font-bold text-green-600"><?php echo $daily_summary['invoices_sent_pending']; ?></span>
            </li>
            <li class="flex justify-between border-l-4 border-yellow-500 pl-3 p-1 rounded-sm">
                <span>Estimados Para Aprobación:</span>
                <span class="font-bold text-yellow-600"><?php echo $daily_summary['estimates_pending']; ?></span>
            </li>
        </ul>
    </div>
    
    <div>
        <h3 class="text-4xl font-black uppercase text-black mb-4 flex items-center gap-2">
            <i data-lucide="megaphone" class="w-6 h-6 mr-3 text-[var(--color-primary)]"></i> Plan De Acción De Hoy
        </h3>
        <p class="text-gray-700 text-base font-medium italic border-l-4 border-[var(--color-secondary)] pl-4 ml-4 bg-gray-50 p-3 rounded-lg">
            <?php echo $daily_summary['strategic_route']; ?>
        </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-[0_25px_50px_-12px_rgba(0,0,0,0.25)]">

<h3 class="text-3xl font-extrabold uppercase mb-6 border-b pb-4 border-white/20 flex items-center">
    <i data-lucide="target" class="w-7 h-7 mr-3 text-[var(--color-highlight)]"></i> TU ENFOQUE DIARIO
</h3>
    
    <ul id="daily-focus-checklist" class="space-y-4">
        
        <?php if (!empty($daily_summary['today_route'])): ?>
            <li class="border-t pt-4 mt-4 border-white/20">
                <p class="text-sm font-bold text-[var(--color-highlight)] uppercase mb-2">RUTA DE SERVICIO:</p>
            </li>
            <?php 
            foreach ($daily_summary['today_route']['clients'] as $index => $client): 
                $task_id = 'task-appt-' . $appt['id'];
                $task_title = 'Completar Servicio: ' . htmlspecialchars($client['client_name']);
            ?>
                <li class="flex items-start">
                    <input type="checkbox" id="<?php echo $task_id; ?>" 
                           data-task-title="<?php echo $task_title; ?>"
                           class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded transition-colors duration-200 mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)] focus:ring-4 focus:ring-[var(--color-highlight)]/50">
                    <label for="<?php echo $task_id; ?>" 
                           class="text-base transition-colors cursor-pointer flex-1 text-white font-medium">
                        <?php echo $task_title; ?>
                    </label>
                </li>
            <?php endforeach; ?>
        <?php endif; ?>

        <?php if (!empty($daily_summary['appointments'])): ?>
            <li class="border-t pt-4 mt-4 border-white/20">
                <p class="text-sm font-bold text-[var(--color-highlight)] uppercase mb-2">CITAS DE HOY:</p>
            </li>
            <?php 
            foreach ($daily_summary['appointments'] as $index => $appt): 
                $task_id = 'task-appt-' . $appt['id'];
                $task_title = htmlspecialchars($appt['time']) . ' ' . htmlspecialchars($appt['title']);
            ?>
                <li class="flex items-start">
                    <input type="checkbox" id="<?php echo $task_id; ?>" 
                           data-task-title="<?php echo $task_title; ?>"
                           class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded transition-colors duration-200 mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)] focus:ring-4 focus:ring-[var(--color-highlight)]/50">
                    <label for="<?php echo $task_id; ?>" 
                           class="text-base transition-colors cursor-pointer flex-1 text-white font-medium">
                        <?php echo $task_title; ?>
                    </label>
                </li>
            <?php endforeach; ?>
        <?php endif; ?>
        
        <?php if (!empty($daily_summary['tasks'])): ?>
            <li class="border-t pt-4 mt-4 border-white/20">
                <p class="text-sm font-bold text-[var(--color-highlight)] uppercase mb-2">TAREAS ASIGNADAS:</p>
            </li>
            <?php 
            foreach ($daily_summary['tasks'] as $index => $task): 
                $task_id = 'task-core-' . $task['id'];
                $is_emergency = $task['is_emergency'] ?? false;
                $prefix = $is_emergency ? ' ' : '';
                $text_color_class = $is_emergency ? 'text-white font-extrabold is-urgent-task' : 'text-white font-medium';
            ?>
                <li class="flex items-start">
                    <input type="checkbox" id="<?php echo $task_id; ?>" 
                           data-task-title="<?php echo htmlspecialchars($task['title']); ?>"
                           class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded transition-colors duration-200 mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)] focus:ring-4 focus:ring-[var(--color-highlight)]/50">
                    <label for="<?php echo $task_id; ?>" 
                           class="text-base transition-colors cursor-pointer flex-1 <?php echo $text_color_class; ?>">
                        <?php echo $prefix; ?><?php echo $task['title'];  ?>
                    </label>
                </li>
            <?php endforeach; ?>
        <?php endif; ?>

        <?php if ($daily_summary['invoices_overdue'] > 0 || !empty($daily_summary['active_complaints'])): ?>
            <li class="border-t pt-4 mt-4 border-white/20">
                <p class="text-sm font-bold text-[var(--color-highlight)] uppercase mb-2">RIESGOS HOY (COBRO/REPUTACIÓN):</p>
            </li>
            
            <?php if ($daily_summary['invoices_overdue'] > 0): 
                $task_id_inv = 'task-inv-overdue-today';
            ?>
                <li class="flex items-start">
                    <input type="checkbox" id="<?php echo $task_id_inv; ?>" 
                           data-task-title="Cobrar: <?php echo $daily_summary['invoices_overdue']; ?> Facturas Vencidas"
                           class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded transition-colors duration-200 mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)] focus:ring-4 focus:ring-[var(--color-highlight)]/50">
                    <label for="<?php echo $task_id_inv; ?>" 
                           class="text-base transition-colors cursor-pointer flex-1 text-[var(--color-secondary)] font-extrabold is-urgent-task">
                        Cobrar: <?php echo $daily_summary['invoices_overdue']; ?> Facturas Vencidas.
                    </label>
                </li>
            <?php endif; ?>

            <?php foreach ($daily_summary['active_complaints'] as $index => $complaint): 
                $task_id_comp = 'task-comp-' . $complaint['id'];
            ?>
                <li class="flex items-start">
                    <input type="checkbox" id="<?php echo $task_id_comp; ?>" 
                           data-task-title="Resolver Queja: <?php echo htmlspecialchars($complaint['title']); ?>"
                           class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded transition-colors duration-200 mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)] focus:ring-4 focus:ring-[var(--color-highlight)]/50">
                    <label for="<?php echo $task_id_comp; ?>" 
                           class="text-base transition-colors cursor-pointer flex-1 text-[var(--color-secondary)] font-extrabold is-urgent-task">
                        Resolver Queja: <?php echo htmlspecialchars($complaint['title']); ?>.
                    </label>
                </li>
            <?php endforeach; ?>
        <?php endif; ?>

        <?php if (!empty($daily_summary['follow_up_list']) || $daily_summary['estimates_pending'] > 0): ?>
            <li class="border-t pt-4 mt-4 border-white/20">
                <p class="text-sm font-bold text-[var(--color-highlight)] uppercase mb-2">TAREAS DE VENTA/SEGUIMIENTO:</p>
            </li>

            <?php foreach ($daily_summary['follow_up_list'] as $index => $lead): 
                $task_id = 'task-follow-' . $lead['id'];
                $lead_name = htmlspecialchars($lead['name'] ?? 'Cliente Potencial');
                $task_title = 'Contactar A ' . $lead_name . ' Para Seguimiento.';
            ?>
                <li class="flex items-start">
                    <input type="checkbox" id="<?php echo $task_id; ?>" 
                           data-task-title="<?php echo $task_title; ?>"
                           class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded transition-colors duration-200 mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)] focus:ring-4 focus:ring-[var(--color-highlight)]/50">
                    <label for="<?php echo $task_id; ?>" 
                           class="text-base transition-colors cursor-pointer flex-1 text-white font-medium">
                        <?php echo $task_title; ?>
                    </label>
                </li>
            <?php endforeach; ?>

            <?php if ($daily_summary['estimates_pending'] > 0): 
                $task_id_est = 'task-est-pend-today';
            ?>
                <li class="flex items-start">
                    <input type="checkbox" id="<?php echo $task_id_est; ?>" 
                           data-task-title="Revisar <?php echo $daily_summary['estimates_pending']; ?> Estimados Enviados"
                           class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded transition-colors duration-200 mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)] focus:ring-4 focus:ring-[var(--color-highlight)]/50">
                    <label for="<?php echo $task_id_est; ?>" 
                           class="text-base transition-colors cursor-pointer flex-1 text-white font-medium">
                        Revisar estado de <?php echo $daily_summary['estimates_pending']; ?> Estimados/Cotizaciones.
                    </label>
                </li>
            <?php endif; ?>
        <?php endif; ?>

        <li class="flex items-start border-t pt-4 mt-4 border-white/20">
            <input type="checkbox" id="task-strategy" 
                   data-task-title="Ruta Estratégica"
                   class="focus-checklist-checkbox w-5 h-5 bg-gray-600 border-gray-400 rounded transition-colors duration-200 mt-1 mr-3 cursor-pointer checked:bg-[var(--color-secondary)] checked:border-[var(--color-secondary)] focus:ring-4 focus:ring-[var(--color-highlight)]/50">
            <label for="task-strategy" 
                   class="text-white text-base font-medium transition-colors cursor-pointer flex-1">
                <?php echo htmlspecialchars(strip_tags($daily_summary['strategic_route'])); ?>
            </label>
        </li>
        
        <?php 
        $total_action_items = count($daily_summary['appointments']) + count($daily_summary['tasks']) + 
                              $daily_summary['invoices_overdue'] + count($daily_summary['active_complaints']) + 
                              count($daily_summary['follow_up_list']) + ($daily_summary['estimates_pending'] > 0 ? 1 : 0) +
                                (!empty($daily_summary['today_route']) ? count($daily_summary['today_route']['clients']) : 0); // Sumar clientes de ruta
                                
        // Re-calculate $total_action_items for the checklist section, as the previous one was missing route clients
        $total_checklist_items = $total_action_items + 1; // +1 for the strategic route itself

        if ($total_action_items === 0): 
        ?>
             <li class="pt-2">
                 <p class="text-sm text-gray-300 italic p-2 bg-white/10 rounded">¡Todo está al día! Enfócate 100% en la Ruta Estratégica.</p>
             </li>
        <?php endif; ?>
    </ul>

    <div class="pt-4 border-t mt-6 border-white/20">
        <p class="text-lg font-bold text-gray-300 mb-2 uppercase flex items-center justify-between">
            <span>PROGRESO DE IMPACTO</span> 
            <span id="progress-percentage" style="font-size: 3rem; line-height: 1; color: var(--color-highlight);" class="font-extrabold transition-colors duration-500">0%</span>
        </p>
        <div class="w-full bg-white/10 rounded-full h-5 shadow-inner">
            <div id="progress-bar" class="h-5 rounded-full transition-all duration-500 shadow-lg" style="width: 0%; background-color: var(--color-secondary);"></div>
        </div>
    </div> 
</div>                          <?php include 'push.php'; ?>
                        </div>
                </section>

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

<script>
document.addEventListener('DOMContentLoaded', () => {
    // Inicializar iconos de Lucide
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
    // Lógica para el menú móvil y overlay
    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.toggle('-translate-x-full'); 
            sidebarOverlay.classList.toggle('hidden'); 
        });
    }
});

// Lógica de Checklist y Barra de Progreso (Ajustada a la Paleta de Branding Oscura)
function setupDailyChecklist() {
    const checklist = document.getElementById('daily-focus-checklist');
    const progressBar = document.getElementById('progress-bar');
    const progressPercentage = document.getElementById('progress-percentage');

    // Branding: Leer las variables de color directamente del CSS.
    const style = getComputedStyle(document.documentElement);
    const BRAND_ACCENT_COLOR = style.getPropertyValue('--color-secondary').trim() || '#9e1428';
    const BRAND_COMPLETED_COLOR = style.getPropertyValue('--color-highlight').trim() || '#ffc857';
    
    // Colores de texto para los items del checklist
    const TEXT_COMPLETED_COLOR = '#9CA3AF'; // gray-400 de Tailwind
    const TEXT_DEFAULT_COLOR = '#FFFFFF'; // Color blanco
    const TEXT_URGENT_COLOR = BRAND_ACCENT_COLOR; // Rojo/Acento

    if (!checklist) return;

    const todayDate = '<?php echo date('Ymd'); ?>';

    const updateProgress = () => {
        const allCheckboxes = checklist.querySelectorAll('input[type="checkbox"]');
        const totalTasks = allCheckboxes.length;
        const completedTasks = checklist.querySelectorAll('input[type="checkbox"]:checked').length;
        
        if (totalTasks === 0) {
            progressBar.style.width = '0%';
            progressPercentage.textContent = '0%';
            return;
        }

        const percentage = Math.round((completedTasks / totalTasks) * 100);
        
        progressBar.style.width = `${percentage}%`;
        progressPercentage.textContent = `${percentage}%`;
        
        // Branding: Cambiar color de fondo y texto con variables CSS.
        if (percentage === 100) {
            progressBar.style.backgroundColor = BRAND_COMPLETED_COLOR; 
            progressPercentage.style.color = BRAND_COMPLETED_COLOR;
        } else {
            progressBar.style.backgroundColor = BRAND_ACCENT_COLOR;
            progressPercentage.style.color = BRAND_ACCENT_COLOR;
        }
    };

    checklist.addEventListener('change', (e) => {
        if (e.target.classList.contains('focus-checklist-checkbox')) {
            const label = checklist.querySelector(`label[for="${e.target.id}"]`);
            
            // Branding: Detectar urgencia por la CLASE 'is-urgent-task'.
            const isUrgent = label ? label.classList.contains('is-urgent-task') : false;

            if (label) {
                // Aplicar estilo de texto dinámicamente
                label.style.textDecoration = e.target.checked ? 'line-through' : 'none';
                label.style.color = e.target.checked ? TEXT_COMPLETED_COLOR : (isUrgent ? TEXT_URGENT_COLOR : TEXT_DEFAULT_COLOR);
            }
            // Guardar el estado en localStorage
            localStorage.setItem(`daily_task_${e.target.id}_${todayDate}`, e.target.checked);
            updateProgress();
        }
    });

    // Cargar el estado al inicio (persistencia durante el día)
    checklist.querySelectorAll('input[type="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) {
            // Branding: Detectar urgencia por la CLASE 'is-urgent-task'
            const isUrgent = label.classList.contains('is-urgent-task');

            label.style.textDecoration = checkbox.checked ? 'line-through' : 'none';
            label.style.color = checkbox.checked ? TEXT_COMPLETED_COLOR : (isUrgent ? TEXT_URGENT_COLOR : TEXT_DEFAULT_COLOR);
        }
    });

    // Inicializar el progreso al cargar la página
    updateProgress();
}

// Llama a la función después de que el DOM esté cargado
document.addEventListener('DOMContentLoaded', setupDailyChecklist);
</script>
</body>
</html>