<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');

$average_frequency = 0;
$average_value = 0;
$clients_js_data = "[]";
$loyal_clients = [];
$total_loyal_clients = 0;
$csrf_token = $_SESSION['csrf_token'] ?? ''; // Fase V: Obtener token CSRF de la sesión

// Función Helper para formateo
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;
}

/**
 * Crea la parte dinámica de la cláusula IN para consultas PDO.
 * @param array $ids Array de IDs a incluir.
 * @return string Una string de marcadores de posición (ej: "?, ?, ?").
 */
function create_in_clause(array $ids): string {
    // Maneja array vacío para evitar error de sintaxis SQL
    if (empty($ids)) return 'NULL'; 
    return implode(',', array_fill(0, count($ids), '?'));
}

// <<-- INICIO DEL BLOQUE TRY (Corrección de Parse Error)
try {

    // 1. OBTENER CLIENTES RECURRENTES (Seguro: usa sentencia preparada sin input)
    $sql_clients = "
        SELECT id, first_name, last_name, email, phone, mobile, created_at, is_recurring, frequency 
        FROM clients 
        WHERE is_recurring = 1 
        ORDER BY last_name ASC";
    
    $stmt = $pdo->prepare($sql_clients);
    $stmt->execute();
    $raw_clients = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 2. PREPARACIÓN DE DATOS POR LOTES (Batch Processing)
    $client_ids = array_column($raw_clients, 'id');
    
    $map_invoices = [];
    $map_appointments = [];
    $map_notes = [];

    if (!empty($client_ids)) {
        // Fase II: Generar placeholders para consultas dinámicas
        $in_clause = create_in_clause($client_ids); 

        // A. Calcular Totales de Facturación (Fase II: CORREGIDO - usa placeholders)
        $sql_inv = "SELECT client_id, SUM(total_amount) as total
                    FROM invoices 
                    WHERE status = 'pagada' AND client_id IN ({$in_clause}) 
                    GROUP BY client_id";
        $stmt_inv = $pdo->prepare($sql_inv);
        // Fase II: Ejecutar con el array de IDs
        $stmt_inv->execute($client_ids); 
        $map_invoices = $stmt_inv->fetchAll(PDO::FETCH_KEY_PAIR);

        // B. Encontrar Última Actividad (Fase II: CORREGIDO - usa placeholders)
        // Requiere duplicar el array de IDs para cada set de placeholders en la UNION
        $sql_dates = "
            SELECT client_id, MAX(event_date) as last_date FROM (
                SELECT client_id, CAST(CONCAT(appointment_date, ' ', appointment_time) AS DATETIME) as event_date 
                FROM unique_appointments 
                WHERE client_id IN ({$in_clause}) AND status IN ('confirmed', 'completed')
                UNION ALL
                SELECT client_id, end_date as event_date 
                FROM agenda 
                WHERE client_id IN ({$in_clause}) AND status = 'completed'
            ) as combined_dates GROUP BY client_id
        ";
        $stmt_dates = $pdo->prepare($sql_dates);
        // Fase II: Ejecutar con el array de IDs duplicado
        $stmt_dates->execute(array_merge($client_ids, $client_ids)); 
        $map_appointments = $stmt_dates->fetchAll(PDO::FETCH_KEY_PAIR);

        // C. Obtener TODAS las notas de una vez (Fase II: CORREGIDO - usa placeholders)
        $sql_notes = "SELECT client_id, content, created_at
                      FROM client_notes
                      WHERE client_id IN ({$in_clause})
                      ORDER BY created_at DESC";
        $stmt_notes = $pdo->prepare($sql_notes);
        // Fase II: Ejecutar con el array de IDs
        $stmt_notes->execute($client_ids); 
        while ($note = $stmt_notes->fetch(PDO::FETCH_ASSOC)) {
            $map_notes[$note['client_id']][] = [
                'date' => date('Y-m-d', strtotime($note['created_at'])),
                'content' => $note['content']
            ];
        }
    }

    // 3. ENSAMBLADO DE DATOS (En Memoria PHP)
    foreach ($raw_clients as $row) {
        $cid = $row['id'];
        $name = trim($row['first_name'] . ' ' . $row['last_name']);
        // Usamos el teléfono primario si existe, sino el móvil. formatPhoneNumberUSA es seguro.
        $formatted_phone = formatPhoneNumberUSA($row['phone'] ?? $row['mobile']); 

        $total_value = isset($map_invoices[$cid]) ? (float)$map_invoices[$cid] : 0.00;
        
        $last_appt_raw = isset($map_appointments[$cid]) ? $map_appointments[$cid] : null;
        $last_appointment_display = 'N/A';
        if ($last_appt_raw) {
            // Asegura que la fecha se formateó correctamente del DATETIME
            $last_appointment_display = date('d M Y H:i', strtotime($last_appt_raw));
        }

        // Lógica de Negocio (Loyalty Logic)
        $frequency_months = 3;
        $loyalty_level = 'Regular';
        
        if ($total_value > 3000) {
            $loyalty_level = 'Alto Valor';
            $frequency_months = 1;
        } elseif ($total_value < 500) {
            $loyalty_level = 'En Riesgo';
            $frequency_months = 6;
        }
        
        // Determina la fecha de seguimiento basada en la lógica de frecuencia
        $next_follow_up = date('Y-m-d', strtotime("+$frequency_months months"));
        
        $client_notes = isset($map_notes[$cid]) ? $map_notes[$cid] : [];

        $loyal_clients[] = [
            'id' => $cid, 'name' => $name, 'contact_person' => $name, 'email' => $row['email'],
            'phone' => $formatted_phone, 'birthday' => null, 'last_purchase_date' => null,
            'last_purchase_days_ago' => null, 'total_value' => $total_value,
            'frequency_months' => $frequency_months, 'loyalty_level' => $loyalty_level,
            'next_follow_up' => $next_follow_up, 'last_appointment' => $last_appointment_display,
            'notes' => $client_notes, 'first_name' => $row['first_name'], 'last_name' => $row['last_name'],
        ];
    }

    // 4. CÁLCULOS GLOBALES
    $total_loyal_clients = count($loyal_clients);
    if ($total_loyal_clients > 0) {
        $total_freq = array_sum(array_column($loyal_clients, 'frequency_months'));
        $total_val = array_sum(array_column($loyal_clients, 'total_value'));
        $average_frequency = round($total_freq / $total_loyal_clients, 1);
        $average_value = round($total_val / $total_loyal_clients, 2);
    }

    // Codificación segura a JSON (Fase IV)
    $clients_js_data = json_encode(array_column($loyal_clients, null, 'id'), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);

// <<-- FIN DEL BLOQUE TRY
} catch (Exception $e) {
    error_log("Error crítico en recurring_clients.php: " . $e->getMessage());
}

$loyalty_styles = [
    'Alto Valor' => ['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' => 'bg-[var(--color-secondary)]'],
];

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

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    
    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>


</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>
    <div id="task-panel-overlay" class="fixed inset-0 bg-black/60 z-40 hidden transition-opacity duration-300"></div>  
    
    <?php include 'menu.php'; ?>
    
    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

    <div id="content-area" class="p-4 md:p-8 bg-[var(--color-background)] space-y-8">

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

         <div class="stat-card bg-white p-6 rounded-xl shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-highlight)]">
             <i data-lucide="users" class="w-12 h-12 text-[var(--color-secondary)]"></i>
             <div>
                 <h3 class="text-lg font-black 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="stat-card 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-[var(--color-secondary)]"></i>
             <div>
                 <h3 class="text-lg font-black text-gray-500 mb-1 uppercase">Frecuencia Prom. (Meses)</h3>
                 <p class="text-4xl font-bold text-[var(--color-primary)]"><?php echo $average_frequency; ?></p>
             </div>
         </div>

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

     </div>
</div>

               <div class="bg-white p-6 rounded-xl shadow-md">
                     <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-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 (LTV):</span> <span class="text-3xl font-black text-[var(--color-secondary)]">$<?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 btn-primary py-1.5 px-3 rounded-lg shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200 ease-in-out" 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 shadow-2xl">
    
    <div class="flex flex-col h-full">
        <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
            <h3 class="text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase">
                <i data-lucide="user-check" class="w-8 h-8 mr-2 text-white"></i>
                DETALLES DEL CLIENTE
            </h3>
            <button class="bg-[var(--color-secondary)] text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200" onclick="closeClientDetailPanel()">
                <i data-lucide="x" class="w-8 h-8"></i>
            </button>
        </div>

        <div class="flex-grow overflow-y-auto p-4 space-y-6 relative">
            
            <div class="bg-white p-4 rounded-xl shadow-md transition duration-300 space-y-4">
                <div class="border-b pb-3 mb-2">
                    <div class="flex justify-between items-start mb-1">
                        <h4 class="text-2xl font-black text-[var(--color-secondary)] uppercase 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 bg-yellow-100 text-yellow-800 border border-yellow-200" 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 font-bold text-gray-400 text-right uppercase">ID Cliente: <span id="panel-client-id"></span></p>
                </div>

                <div class="space-y-3">
                    <div>
                        <label for="panel-client-contact-person-input" class="block text-md font-bold 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-md font-bold 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 class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label for="panel-client-phone-input" class="block text-md font-bold 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-md font-bold text-gray-600 mb-1 uppercase">Cumpleaños</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>
            </div>

            <div class="bg-white p-4 rounded-xl shadow-md transition duration-300 border-l-4 border-[var(--color-highlight)]">
                <h5 class="text-lg font-black text-[var(--color-primary)] border-b border-gray-100 pb-2 mb-3 uppercase flex items-center">
                    <i data-lucide="bar-chart-2" class="w-5 h-5 mr-2"></i> Métricas Clave
                </h5>
                
                <div class="bg-gray-50 p-3 rounded-lg mb-4 text-center border border-gray-100">
                    <span class="block text-xs font-bold text-gray-500 uppercase mb-1">
                        <i data-lucide="trending-up" class="w-3 h-3 inline mr-1"></i> Valor Total Invertido
                    </span>
                    <strong id="panel-client-total-value" class="text-4xl font-black text-[var(--color-primary)] tracking-tight"></strong>
                </div>
                
                <div class="grid grid-cols-2 gap-4 text-sm">
                    <div class="bg-gray-50 p-2 rounded border border-gray-100">
                        <span class="block text-xs font-bold text-gray-400 uppercase mb-1">Última Cita</span>
                        <strong id="panel-client-last-appointment" class="text-gray-800"></strong>
                    </div>
                    <div class="bg-gray-50 p-2 rounded border border-gray-100">
                        <span class="block text-xs font-bold text-gray-400 uppercase mb-1">Frecuencia (Meses)</span>
                        <strong id="panel-client-frequency" class="text-gray-800"></strong>
                    </div>
                </div>
            </div>

            <div class="bg-white p-4 rounded-xl shadow-md transition duration-300">
                <div class="border-b pb-3 mb-4">
                    <h5 class="text-lg font-black text-[var(--color-secondary)] uppercase flex items-center">
                        <i data-lucide="calendar-check" class="w-5 h-5 mr-2"></i> Seguimiento
                    </h5>
                </div>

                <div class="space-y-4">
                    <div>
                        <label for="panel-client-next-followup-input" class="block text-md font-bold text-gray-600 mb-1 uppercase">
                            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>
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">
                            Añadir Nueva Nota
                        </label>
                        <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..."></textarea>
                    </div>

                    <div class="border-t pt-4">
                        <h5 class="text-xs font-bold text-gray-500 uppercase mb-2 flex items-center">
                            <i data-lucide="history" class="w-3 h-3 mr-1"></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 custom-scrollbar bg-gray-50 p-2 rounded border border-gray-100">
                            </div>
                    </div>
                </div>
            </div>

        </div>

        <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
            <div class="grid grid-cols-2 gap-3">
                <button onclick="closeClientDetailPanel()" class="w-full btn-cancel uppercase flex items-center justify-center gap-2">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                <button onclick="saveClientDetails()" class="w-full btn-confirm uppercase flex items-center justify-center gap-2">
                    <i data-lucide="save" class="w-5 h-5"></i> GUARDAR CAMBIOS
                </button>
            </div>
        </div>
    </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';

    document.getElementById('panel-client-total-value').textContent = `$${parseFloat(client.total_value || 0).toLocaleString('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
    
    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 (LTV):</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 btn-primary py-1.5 px-3 rounded-lg shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200 ease-in-out" 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>
<script src="files/toast.js"></script>
</body>
</html>