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

function formatPhoneNumberUSA(?string $number): ?string {
    if (!$number) {
        return null;
    }
    $numeric_only = preg_replace('/\D/', '', $number);

    if (strlen($numeric_only) === 10) {
        return '(' . substr($numeric_only, 0, 3) . ') ' . substr($numeric_only, 3, 3) . '-' . substr($numeric_only, 6);
    }

    return $numeric_only;
}


function fetchLoyalClients($pdo) {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                c.id, 
                c.first_name, 
                c.last_name, 
                c.email, 
                c.phone, 
                c.mobile,
                c.created_at,
                c.is_recurring,
                c.frequency,
                -- c.birthday, -- NO existe en tu esquema de `clients`, se usa placeholder.
                (SELECT SUM(total_amount) FROM invoices WHERE client_id = c.id AND status = 'pagada') AS total_value,
                                (
                    SELECT 
                        GREATEST(
                            COALESCE((SELECT MAX(STR_TO_DATE(CONCAT(appointment_date, ' ', appointment_time), '%Y-%m-%d %H:%i:%s')) FROM unique_appointments WHERE client_id = c.id AND status IN ('confirmed', 'completed')), '0000-00-00 00:00:00'),
                            COALESCE((SELECT MAX(end_date) FROM agenda WHERE client_id = c.id AND status = 'completed'), '0000-00-00 00:00:00')
                        )
                ) AS last_appointment_raw
            FROM 
                clients c
            WHERE 
                c.is_recurring = 1
            ORDER BY 
                c.last_name ASC
        ");
        $stmt->execute();
        $clients_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $clients_formatted = [];
        $today = new DateTime();

        foreach ($clients_raw as $row) {
            $name = trim($row['first_name'] . ' ' . $row['last_name']);
            
            // Formatear Teléfono
            $formatted_phone = formatPhoneNumberUSA($row['phone'] ?? $row['mobile']);
            
            // Procesar Última Cita
            $last_appointment_raw = $row['last_appointment_raw'];
            $last_appointment_display = 'N/A';
            if ($last_appointment_raw && $last_appointment_raw !== '0000-00-00 00:00:00') {
                $last_appointment_date = new DateTime($last_appointment_raw);
                $last_appointment_display = $last_appointment_date->format('d M Y H:i');
            }

            // Datos de Valor y Frecuencia (Lógica existente)
            $total_value = (float)($row['total_value'] ?? 0);
            $frequency_months = 3; // Lógica simplificada
            $loyalty_level = 'Regular'; 
            if ($total_value > 1000) {
                $loyalty_level = 'VIP';
                $frequency_months = 1;
            } elseif ($total_value < 100) {
                $loyalty_level = 'En Riesgo';
                $frequency_months = 6;
            } 
            $next_follow_up = date('Y-m-d', strtotime("+$frequency_months months")); // Simulación

            // --- NOTAS (AHORA USA client_notes) ---
            $notes_sim = [];
            try {
                 // Busca notas de clientes en la nueva tabla client_notes
                $stmt_notes = $pdo->prepare("SELECT content, created_at FROM client_notes WHERE client_id = ? ORDER BY created_at DESC");
                $stmt_notes->execute([$row['id']]); 
                $notes_raw = $stmt_notes->fetchAll(PDO::FETCH_ASSOC);
                $notes_sim = array_map(function($n) {
                    return ['date' => date('Y-m-d', strtotime($n['created_at'])), 'content' => $n['content']];
                }, $notes_raw);
            } catch (\Exception $e) { /* ignore */ }
            
            $clients_formatted[] = [
                'id' => $row['id'],
                'name' => $name,
                'contact_person' => $name, // Usamos el nombre completo como contacto principal
                'email' => $row['email'],
                'phone' => $formatted_phone, // Formateado
                'birthday' => null, // No existe en clients, se envía null
                'last_purchase_date' => null, // Eliminado por solicitud
                'last_purchase_days_ago' => null, // Eliminado por solicitud
                'total_value' => $total_value,
                'frequency_months' => $frequency_months,
                'loyalty_level' => $loyalty_level,
                'next_follow_up' => $next_follow_up,
                'last_appointment' => $last_appointment_display, // Agregado
                'notes' => $notes_sim,
                'first_name' => $row['first_name'], 
                'last_name' => $row['last_name'], 
            ];
        }
        return $clients_formatted;

    } catch (PDOException $e) {
        error_log("Error al cargar clientes recurrentes: " . $e->getMessage());
        return [];
    }
}

$loyal_clients = fetchLoyalClients($pdo);
$total_loyal_clients = count($loyal_clients);

// --- CÁLCULOS PARA KPIs ---
$average_frequency = 0;
$average_value = 0;
if ($total_loyal_clients > 0) {
    $total_frequency = array_sum(array_column($loyal_clients, 'frequency_months'));
    $total_overall_value = array_sum(array_column($loyal_clients, 'total_value'));
    $average_frequency = round($total_frequency / $total_loyal_clients, 1);
    $average_value = round($total_overall_value / $total_loyal_clients, 2);
}

// Mapeo de Niveles de Lealtad a Estilos
$loyalty_styles = [
    'VIP' => ['icon' => 'gem', 'color' => 'text-black', 'bg' => 'bg-[var(--color-highlight)]'],
    'Regular' => ['icon' => 'star', 'color' => 'text-white', 'bg' => 'bg-[var(--color-primary)]'],
    'En Riesgo' => ['icon' => 'alert-triangle', 'color' => 'text-white', 'bg' => '[var(--color-secondary)]'],
];

// Pasar datos de clientes a JS para el panel lateral (Indexado por ID)
$clients_js_data = json_encode(array_column($loyal_clients, null, 'id'));

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clientes Fidelizados - FlowCRM™</title>
    <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 class="font-barlow"
    data-page-title="Centro De Clientes Fidelizados"
    data-page-subtitle="Gestiona Y Potencia Tus Relaciones Comerciales Más Valiosas"
    data-page-icon="shield-user">

    <div id="toast-container" class="toast-container"></div>
    
    <?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">
    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <?php include 'menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white p-4 flex justify-between items-center sticky top-0 z-20 shadow-sm">
               <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 bg-[var(--color-background)] space-y-8">

               <div>
     <div class="grid grid-cols-1 md:grid-cols-3 gap-6">

         <div class="bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-primary)]">
             <i data-lucide="users" class="w-12 h-12 text-gray-700"></i>
             <div>
                 <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">Clientes Recurrentes</h3>
                 <p class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $total_loyal_clients; ?></p>
             </div>
         </div>

         <div class="bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
             <i data-lucide="refresh-cw" class="w-12 h-12 text-gray-700"></i>
             <div>
                 <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">Frecuencia Prom. (Meses)</h3>
                 <p class="text-5xl font-bold text-[var(--color-primary)]"><?php echo $average_frequency; ?></p>
             </div>
         </div>

         <div class="bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-primary)]">
             <i data-lucide="wallet" class="w-12 h-12 text-gray-700"></i>
             <div>
                 <h3 class="text-lg font-extrabold text-gray-500 mb-1 uppercase">Valor Prom. Cliente</h3>
                 <p class="text-5xl font-bold text-[var(--color-primary)]">$<?php echo number_format($average_value, 2); ?></p>
             </div>
         </div>

     </div>
</div>

               <div>
                     <h3 class="text-4xl font-black text-[var(--color-primary)] uppercase mb-4 flex items-center"><i data-lucide="list" class="w-6 h-6 mr-2"></i>Listado de Clientes Recurrentes</h3>
                     <?php if (empty($loyal_clients)): ?>
                           <p class="text-center text-gray-500 italic bg-white p-6 rounded-xl shadow">Aún no tienes clientes marcados como recurrentes.</p>
                     <?php else: ?>
                          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="loyal-clients-grid">
                                 <?php foreach ($loyal_clients as $client):
                                      $level_style = $loyalty_styles[$client['loyalty_level']] ?? ['icon' => 'star', 'color' => 'text-gray-500', 'bg' => 'bg-gray-100'];
                                      $follow_up_soon = false;
                                      // Verifica si hay próximo seguimiento y si está en los próximos 7 días
                                      if ($client['next_follow_up']) { 
                                          $next_follow_up_date = new DateTime($client['next_follow_up']); 
                                          $today_dt = new DateTime(); 
                                          $diff = $today_dt->diff($next_follow_up_date); 
                                          // $diff->invert es 0 si la fecha es futura o el mismo día
                                          if ($diff->days <= 7 && !$diff->invert) { $follow_up_soon = true; } 
                                      }
                                 ?>
                                 <div class="loyal-client-card bg-white rounded-xl shadow-lg transition-all duration-300 ease-in-out hover:shadow-xl hover:-translate-y-0.5 border-l-4 border-[var(--color-primary)] p-4 flex flex-col justify-between">
                                     <div>
                                         <div class="flex justify-between items-start mb-2 pb-2 border-b"> 
                                             <div> 
                                                 <h4 class="text-lg font-black text-[var(--color-primary)]"><?php echo htmlspecialchars($client['name']); ?></h4> 
                                                 <?php if ($client['contact_person']): ?> 
                                                     <p class="text-xs text-gray-500 font-medium">Contacto: <?php echo htmlspecialchars($client['contact_person']); ?></p> 
                                                 <?php endif; ?> 
                                             </div> 
                                             <span class="text-xs font-bold uppercase px-2 py-1 rounded-full flex items-center <?php echo $level_style['bg'] . ' ' . $level_style['color']; ?>"> 
                                                 <i data-lucide="<?php echo $level_style['icon']; ?>" class="w-3 h-3 mr-1"></i> 
                                                 <?php echo htmlspecialchars($client['loyalty_level']); ?> 
                                             </span> 
                                         </div>
                                         <div class="space-y-1.5 text-sm text-gray-700 mb-4">
                                             
                                              <p class="flex flex-col items-start bg-[var(--color-primary)] p-2 rounded-lg"><span class="flex items-center text-xs font-semibold text-gray-600 mb-1"><i data-lucide="wallet" class="w-3 h-3 mr-1.5 text-[var(--color-primary)]"></i> VALOR TOTAL:</span> <span class="text-3xl font-black text-[var(--color-primary)]">$<?php echo number_format($client['total_value'], 2); ?></span></p>

                                              <p class="flex items-center"><i data-lucide="calendar-clock" class="w-4 h-4 mr-2 text-gray-400"></i>Última Cita: <span class="font-semibold ml-1"><?php echo $client['last_appointment']; ?></span></p>
                                              <p class="flex items-center"><i data-lucide="refresh-cw" class="w-4 h-4 mr-2 text-gray-400"></i>Frecuencia: <span class="font-semibold ml-1">Cada ~<?php echo $client['frequency_months']; ?> meses</span></p>
                                              
                                              <?php if ($client['next_follow_up']): ?>
                                                  <p class="flex items-center <?php echo $follow_up_soon ? 'text-[var(--color-highlight)] font-bold animate-pulse' : ''; ?>"> <i data-lucide="calendar-check" class="w-4 h-4 mr-2 <?php echo $follow_up_soon ? 'text-[var(--color-highlight)]' : 'text-gray-400'; ?>"></i> Próx. Seguimiento: <span class="font-semibold ml-1"><?php echo date('d M Y', strtotime($client['next_follow_up'])); ?></span> </p>
                                              <?php endif; ?>
                                         </div>
                                     </div>
                                     <div class="mt-auto pt-3 border-t text-right">
                                           <button onclick="openClientDetailPanel(<?php echo $client['id']; ?>)" class="inline-flex items-center text-xs font-bold uppercase text-white bg-[var(--color-secondary)] py-1.5 px-3 rounded-lg shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200 ease-in-out hover:opacity-90" title="Ver Detalles">
                                                <i data-lucide="edit" class="w-4 h-4 mr-1.5"></i> Ver Detalles
                                            </button>
                                     </div>
                                 </div>
                                 <?php endforeach; ?>
                           </div>
                     <?php endif; ?>
               </div>
        </div>
    </main>
</div>

<div id="client-detail-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 transition-opacity duration-300 opacity-0 pointer-events-none" onclick="closeClientDetailPanel()"></div>
<aside id="client-detail-panel" class="fixed top-0 right-0 h-full w-full lg:w-1/3 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out flex flex-col shadow-2xl">
    <div class="p-4 bg-[var(--color-primary)] border-b border-gray-200 flex-shrink-0 flex justify-between items-center "> <h3 class="text-xl font-black text-[var(--color-highlight)] flex items-center"> <i data-lucide="user-check" class="w-5 h-5 mr-2 text-[var(--color-highlight)]"></i> DETALLES DEL CLIENTE FIDELIZADO </h3> <button class="text-gray-400 hover:text-[var(--color-secondary)] p-1 rounded-full transition-colors duration-200" onclick="closeClientDetailPanel()"> <i data-lucide="x" class="w-6 h-6"></i> </button> </div>
    <div class="p-4 overflow-y-auto flex-grow space-y-5">
        <div class="bg-white p-4 rounded-xl shadow-lg border-l-4 border-[var(--color-primary)] space-y-4">
             <div class="border-b pb-3 mb-4"> <div class="flex justify-between items-start mb-1"> <h4 class="text-lg font-black text-[var(--color-primary)] flex items-center"> <i data-lucide="building" class="w-5 h-5 mr-2"></i> <span id="panel-client-name"></span> </h4> <span class="text-xs font-bold uppercase px-2 py-1 rounded-full flex items-center" id="panel-client-loyalty-badge"> <i data-lucide="star" class="w-3 h-3 mr-1" id="panel-client-loyalty-icon"></i> <span id="panel-client-loyalty-text"></span> </span> </div> <p class="text-xs text-gray-400 text-right">ID Cliente: <span id="panel-client-id"></span></p> </div>
             
             <div> <label for="panel-client-contact-person-input" class="block text-xs font-semibold text-gray-600 mb-1 uppercase">Contacto Principal</label> <input type="text" id="panel-client-contact-person-input" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="Nombre del contacto"> </div>
             <div> <label for="panel-client-email-input" class="block text-xs font-semibold text-gray-600 mb-1 uppercase">Email</label> <input type="email" id="panel-client-email-input" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="correo@ejemplo.com"> </div>
             <div> <label for="panel-client-phone-input" class="block text-xs font-semibold text-gray-600 mb-1 uppercase">Teléfono Principal</label> <input type="tel" id="panel-client-phone-input" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm" placeholder="55 1234 5678"> </div>
             <div> <label for="panel-client-birthday-input" class="block text-xs font-semibold text-gray-600 mb-1 uppercase">Fecha de Nacimiento (Contacto)</label> <input type="date" id="panel-client-birthday-input" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm"> </div>
          </div>
          <div class="bg-white p-4 rounded-xl shadow-lg border-l-4 border-[var(--color-highlight)] space-y-3"> 
             <h5 class="text-md font-bold text-[var(--color-primary)] border-b pb-1 mb-2">Métricas Clave</h5> 
             
             <p class="flex flex-col items-start bg-white p-2 rounded-lg mb-4"><span class="flex items-center text-xs font-semibold text-gray-600 mb-1"><i data-lucide="trending-up" class="w-4 h-4 mr-1.5 text-[var(--color-primary)]"></i> VALOR TOTAL INVERTIDO</span> <strong id="panel-client-total-value" class="text-4xl font-black text-[var(--color-primary)]"></strong></p>
             
             <p class="text-sm text-gray-700 flex justify-between items-center"><span class="flex items-center"><i data-lucide="calendar-clock" class="w-4 h-4 mr-1.5 text-gray-400"></i>Última Cita:</span> <strong id="panel-client-last-appointment"></strong></p> 
             <p class="text-sm text-gray-700 flex justify-between items-center"><span class="flex items-center"><i data-lucide="refresh-cw" class="w-4 h-4 mr-1.5 text-gray-400"></i>Frecuencia (Meses):</span> <strong id="panel-client-frequency"></strong></p> 
          </div>
          <div class="bg-white p-4 rounded-xl shadow-lg border-l-4 border-gray-300">
              <div> <label for="panel-client-next-followup-input" class="block text-xs font-semibold text-gray-600 mb-1 uppercase flex items-center"> <i data-lucide="calendar-plus" class="w-4 h-4 mr-1.5 text-[var(--color-secondary)]"></i> Programar Próximo Seguimiento</label> <input type="date" id="panel-client-next-followup-input" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-highlight)] focus:ring-[var(--color-highlight)] focus:ring-1 transition duration-150 text-sm"> </div>
              
              <div class="mt-4"> <h5 class="text-md font-bold text-[var(--color-primary)] mb-2 flex items-center"><i data-lucide="message-square-plus" class="w-4 h-4 mr-1.5"></i>Añadir Nueva Nota</h5> <textarea id="panel-client-new-note" class="w-full p-2 border border-gray-300 rounded-lg focus:border-[var(--color-secondary)] focus:ring-[var(--color-secondary)] focus:ring-1 transition duration-150 text-sm" rows="3" placeholder="Escriba aquí el resumen de la interacción o la tarea de seguimiento..."></textarea> </div>
              
              <div class="mt-4"> <h5 class="text-md font-bold text-[var(--color-primary)] border-b pb-1 mb-2 flex items-center"><i data-lucide="history" class="w-4 h-4 mr-1.5"></i>Historial de Notas</h5> <div id="panel-client-notes" class="space-y-2 text-xs text-gray-600 max-h-40 overflow-y-auto pr-2"> </div> </div>
          </div>
    </div>
    <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0"> <button onclick="saveClientDetails()" class="w-full bg-[var(--color-secondary)] text-white font-black py-2.5 uppercase px-4 rounded-lg shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all duration-300 ease-in-out hover:bg-[var(--color-secondary)]"> <i data-lucide="save" class="w-5 h-5 mr-2 inline-block"></i> Guardar Cambios </button> </div>
</aside>

<script>
// Datos JS pasados desde PHP
const loyalClientsData = <?php echo $clients_js_data; ?>;
const loyaltyStylesJS = <?php echo json_encode($loyalty_styles); ?>;
let currentClientId = null; // Variable global

// --- Funciones de Utilidad (Aseguramos que existan) ---

function showToast(message, type = 'info') {
    const toastContainer = document.getElementById('toast-container');
    if (!toastContainer) return;
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    let icon = 'info';
    if (type === 'success') icon = 'check-circle';
    if (type === 'error') icon = 'alert-circle';
    if (type === 'warning') icon = 'alert-triangle';
    toast.innerHTML = `<i data-lucide="${icon}" class="w-5 h-5"></i><span>${message}</span>`;
    toastContainer.appendChild(toast);
    lucide.createIcons({ container: toast });
    setTimeout(() => toast.classList.add('show'), 100);
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toastContainer.removeChild(toast), 500);
    }, 4000);
}

// --- Funciones del Panel Lateral de Detalles del Cliente ---
const detailPanel = document.getElementById('client-detail-panel');
const detailOverlay = document.getElementById('client-detail-panel-overlay');

function openClientDetailPanel(clientId) {
    const client = loyalClientsData[clientId];
    if (!client) {
        console.error("Cliente no encontrado:", clientId);
        showToast("Error: No se pudo cargar la información del cliente.", 'error');
        return;
    }
    currentClientId = clientId;

    document.getElementById('panel-client-name').textContent = client.name || 'N/A';
    document.getElementById('panel-client-id').textContent = client.id;
    document.getElementById('panel-client-contact-person-input').value = client.contact_person || '';
    document.getElementById('panel-client-email-input').value = client.email || '';
    
    // El teléfono ya viene formateado de PHP
    document.getElementById('panel-client-phone-input').value = client.phone || ''; 
    
    // Campo de fecha de nacimiento (placeholder, ya que no existe en DB)
    document.getElementById('panel-client-birthday-input').value = client.birthday || ''; 
    
    document.getElementById('panel-client-next-followup-input').value = client.next_follow_up || '';

    const loyaltyBadge = document.getElementById('panel-client-loyalty-badge');
    const loyaltyIcon = document.getElementById('panel-client-loyalty-icon');
    const loyaltyText = document.getElementById('panel-client-loyalty-text');
    const style = loyaltyStylesJS[client.loyalty_level] || loyaltyStylesJS['Regular'];
    loyaltyBadge.className = `text-xs font-bold uppercase px-2 py-1 rounded-full flex items-center ${style.bg} ${style.color}`;
    loyaltyIcon.setAttribute('data-lucide', style.icon);
    loyaltyText.textContent = client.loyalty_level || 'N/A';

    // Mostrar Valor Total en grande
    document.getElementById('panel-client-total-value').textContent = `$${parseFloat(client.total_value || 0).toLocaleString('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
    
    // Mostrar Última Cita en el panel
    document.getElementById('panel-client-last-appointment').textContent = client.last_appointment || 'N/A';
    document.getElementById('panel-client-frequency').textContent = `~${client.frequency_months} meses`;

    renderClientNotes(client.notes || []);
    document.getElementById('panel-client-new-note').value = '';

    detailPanel.classList.remove('translate-x-full');
    detailOverlay.classList.remove('opacity-0', 'pointer-events-none');
    detailOverlay.classList.add('opacity-100');
    lucide.createIcons();
}

function closeClientDetailPanel() {
    detailPanel.classList.add('translate-x-full');
    detailOverlay.classList.remove('opacity-100');
    detailOverlay.classList.add('opacity-0', 'pointer-events-none');
    currentClientId = null;
}

function renderClientNotes(notes) {
    const notesContainer = document.getElementById('panel-client-notes');
    notesContainer.innerHTML = '';
    if (!notes || notes.length === 0) {
        notesContainer.innerHTML = '<p class="italic text-gray-500 text-xs">No hay notas registradas.</p>';
        return;
    }
    // Se invierte el orden aquí para mostrar la más reciente primero
    notes.sort((a, b) => new Date(b.date) - new Date(a.date)).forEach(note => { 
        const noteDiv = document.createElement('div');
        noteDiv.className = 'bg-gray-50 p-2 rounded border-l-4 border-gray-300 text-xs';
        noteDiv.innerHTML = `
            <p class="text-gray-800">${note.content}</p>
            <p class="text-gray-500 font-medium mt-1 text-right">${new Date(note.date).toLocaleDateString('es-ES', { day: 'numeric', month: 'short', year: 'numeric' })}</p>
        `;
        notesContainer.appendChild(noteDiv);
    });
}

// Función JS para forzar el formato de teléfono (simulación)
function formatPhoneForDisplay(number) {
    if (!number) return 'N/A';
    const numeric_only = number.toString().replace(/\D/g, '');
    if (numeric_only.length === 10) {
        return `(${numeric_only.substring(0, 3)}) ${numeric_only.substring(3, 6)}-${numeric_only.substring(6, 10)}`;
    }
    return number; // Retorna sin formato si no es de 10 dígitos
}


async function saveClientDetails() {
    if (!currentClientId) return;
    
    const client = loyalClientsData[currentClientId];
    const newNoteContent = document.getElementById('panel-client-new-note').value.trim();
    
    // --- 1. Preparar datos de actualización de cliente (Simulación) ---
    const rawPhoneNumber = document.getElementById('panel-client-phone-input').value.trim();
    
    const clientUpdateData = {
        id: currentClientId,
        contact_person: document.getElementById('panel-client-contact-person-input').value.trim(),
        email: document.getElementById('panel-client-email-input').value.trim(),
        phone: formatPhoneForDisplay(rawPhoneNumber), 
        birthday: document.getElementById('panel-client-birthday-input').value || null,
        next_follow_up: document.getElementById('panel-client-next-followup-input').value || null,
    };

    if (newNoteContent) {
        showToast("Guardando nota...", "info");
        try {
            const noteResponse = await fetch('db/recurring-client-note.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ client_id: currentClientId, content: newNoteContent })
            });

            const result = await noteResponse.json();

            if (noteResponse.ok && result.success) {
                // Simular inserción local y actualizar panel
                const newNote = result.note;
                if (!client.notes) client.notes = [];
                client.notes.push(newNote);
                document.getElementById('panel-client-new-note').value = '';
                renderClientNotes(client.notes); // Re-renderizar notas
                showToast("Nota guardada con éxito.", "success");
            } else {
                showToast(`Error al guardar nota: ${result.message}`, "error");
            }
        } catch (e) {
            showToast("Error de conexión al guardar la nota. Asegúrate que la tabla 'client_notes' exista.", "error");
            console.error("Note Save error:", e);
        }
    }
    
    // --- 3. Aplicar y re-renderizar cambios de datos del cliente (Simulación) ---
    // Aunque solo se actualizó en el lado del cliente (JS), esto asegura que la vista esté fresca.
    client.contact_person = clientUpdateData.contact_person;
    client.email = clientUpdateData.email;
    client.phone = clientUpdateData.phone; 
    client.birthday = clientUpdateData.birthday;
    client.next_follow_up = clientUpdateData.next_follow_up;
    
    // Si no se agregó nota, solo mostramos el toast de guardado si se hicieron otros cambios
    if (!newNoteContent) {
         showToast("Cambios guardados con éxito.", "success");
    }

    closeClientDetailPanel();
    renderAllCards(); // Re-renderizar tarjetas para reflejar cambios
}


// Función para renderizar/actualizar las tarjetas de cliente
function renderAllCards() {
    const container = document.getElementById('loyal-clients-grid');
    if (!container) return;
    container.innerHTML = ''; // Limpiar contenedor

    // Iterar sobre los datos JS actualizados
    Object.values(loyalClientsData).forEach(clientData => {
        const level_style_js = loyaltyStylesJS[clientData.loyalty_level] || loyaltyStylesJS['Regular'];
        let follow_up_soon_js = false;
        let followUpHTML = '';
        if (clientData.next_follow_up) {
            const nextFollowUpDateJS = new Date(clientData.next_follow_up + 'T00:00:00');
            const todayJS = new Date(); todayJS.setHours(0,0,0,0);
            const diffTime = nextFollowUpDateJS - todayJS;
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            if (diffDays >= 0 && diffDays <= 7) { follow_up_soon_js = true; }
            const formattedFollowUpDate = nextFollowUpDateJS.toLocaleDateString('es-ES', { day: 'numeric', month: 'short', year: 'numeric' });
            followUpHTML = `
                <p class="flex items-center text-sm ${follow_up_soon_js ? 'text-[var(--color-highlight)] font-bold animate-pulse' : 'text-gray-700'}">
                    <i data-lucide="calendar-check" class="w-4 h-4 mr-2 ${follow_up_soon_js ? 'text-[var(--color-highlight)]' : 'text-gray-400'}"></i>
                    Próx. Seguimiento: <span class="font-semibold ml-1">${formattedFollowUpDate}</span>
                </p>`;
        }

        const totalValueFormatted = `$${parseFloat(clientData.total_value || 0).toLocaleString('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
        
        const cardHTML = `
            <div class="loyal-client-card bg-white rounded-xl shadow-lg transition-all duration-300 ease-in-out hover:shadow-xl hover:-translate-y-0.5 border-l-4 border-[var(--color-primary)] p-4 flex flex-col justify-between">
                <div>
                    <div class="flex justify-between items-start mb-2 pb-2 border-b">
                        <div>
                            <h4 class="text-lg font-black text-[var(--color-primary)]">${clientData.name}</h4>
                            ${clientData.contact_person ? `<p class="text-xs text-gray-500 font-medium">Contacto: ${clientData.contact_person}</p>` : ''}
                        </div>
                        <span class="text-xs font-bold uppercase px-2 py-1 rounded-full flex items-center ${level_style_js.bg} ${level_style_js.color}">
                            <i data-lucide="${level_style_js.icon}" class="w-3 h-3 mr-1"></i>
                            ${clientData.loyalty_level}
                        </span>
                    </div>
                    <div class="space-y-1.5 text-sm text-gray-700 mb-4">
                        <p class="flex flex-col items-start bg-white p-2 rounded-lg"><span class="flex items-center text-xs font-semibold text-gray-600 mb-1"><i data-lucide="wallet" class="w-3 h-3 mr-1.5 text-[var(--color-secondary)]"></i> VALOR TOTAL:</span> <span class="text-3xl font-black text-[var(--color-secondary)]">${totalValueFormatted}</span></p>

                        <p class="flex items-center"><i data-lucide="calendar-clock" class="w-4 h-4 mr-2 text-gray-400"></i>Última Cita: <span class="font-semibold ml-1">${clientData.last_appointment}</span></p>
                        <p class="flex items-center"><i data-lucide="refresh-cw" class="w-4 h-4 mr-2 text-gray-400"></i>Frecuencia: <span class="font-semibold ml-1">Cada ~${clientData.frequency_months} meses</span></p>
                        ${followUpHTML}
                    </div>
                </div>
                <div class="mt-auto pt-3 border-t text-right">
                    <button onclick="openClientDetailPanel(${clientData.id})" class="inline-flex items-center text-xs font-bold uppercase text-white bg-[var(--color-secondary)] py-1.5 px-3 rounded-lg shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200 ease-in-out hover:opacity-90" title="Ver Detalles">
                        <i data-lucide="edit" class="w-4 h-4 mr-1.5"></i> Ver Detalles
                    </button>
                </div>
            </div>`;
        container.insertAdjacentHTML('beforeend', cardHTML);
    });
    lucide.createIcons(); // Re-render icons
}


document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();
    // Lógica menú móvil
    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'); }); }
    // Renderizado inicial de tarjetas
    renderAllCards();
});
</script>
</body>
</html>