<?php include 'files/guardiankey.php'; ?>
<?php
ob_start();
session_start();

// Configuración de errores
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

include_once 'db/db_connection.php';

$clients_data_from_db = [];
$db_error_message = null;

try {
    $stmt = $pdo->query("
        SELECT
            c.id, c.first_name, c.last_name, c.email, c.phone, c.mobile,
            c.street_address, c.city, c.state_province, c.zip_code, c.created_at, c.is_recurring, c.access_code,
            (SELECT GROUP_CONCAT(s.name SEPARATOR ', ') FROM services s JOIN client_services cs ON s.id = cs.service_id WHERE cs.client_id = c.id) AS services_list,
            (SELECT GROUP_CONCAT(cs.service_id SEPARATOR ',') FROM client_services cs WHERE cs.client_id = c.id) AS service_ids,
            (SELECT COUNT(*) FROM unique_appointments ua WHERE ua.client_id = c.id AND ua.appointment_date >= CURDATE() AND ua.status IN ('pending', 'confirmed')) as upcoming_appointments,
            (SELECT COUNT(*) FROM tasks t WHERE t.client_id = c.id AND t.status = 'pending') as pending_tasks,
            (SELECT COUNT(*) FROM invoices i WHERE i.client_id = c.id AND i.status IN ('pendiente', 'vencida', 'enviada')) as pending_invoices,
            (SELECT COUNT(*) FROM estimates e WHERE e.client_id = c.id AND e.status IN ('enviado', 'aprobado', 'pendiente')) as sent_estimates
        FROM clients c ORDER BY c.created_at DESC");

    $db_clients_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($db_clients_rows as $row) {
        $clients_data_from_db[$row['id']] = [
            'id' => $row['id'],
            'nombre' => $row['first_name'],
            'apellido' => $row['last_name'],
            'email' => $row['email'],
            'phone' => $row['phone'],
            'mobile' => $row['mobile'],
            'servicios' => $row['services_list'],
            'service_ids' => !empty($row['service_ids']) ? array_map('intval', explode(',', $row['service_ids'])) : [],
            'direccion_calle' => $row['street_address'],
            'ciudad' => $row['city'],
            'state_province' => $row['state_province'],
            'zip_code' => $row['zip_code'],
            'created_at' => $row['created_at'],
            'is_recurring' => (bool)$row['is_recurring'],
            'access_code' => $row['access_code'],
            'upcoming_appointments' => (int)$row['upcoming_appointments'],
            'pending_tasks' => (int)$row['pending_tasks'],
            'pending_invoices' => (int)$row['pending_invoices'],
            'sent_estimates' => (int)$row['sent_estimates'],
        ];
    }
} catch (PDOException $e) {
    error_log("Error al cargar clientes desde la DB: " . $e->getMessage());
    $db_error_message = 'Error al cargar clientes: ' . $e->getMessage();
}

$prospects_data_for_autocomplete = [];
try {
    $stmt_prospects = $pdo->query("SELECT id, first_name, last_name, company, email, phone, mobile, source, status, street_address, city, state_province, zip_code FROM leads ORDER BY id DESC");
    foreach ($stmt_prospects->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $prospects_data_for_autocomplete[$row['id']] = $row;
    }
} catch (PDOException $e) { error_log("Error al cargar prospectos: " . $e->getMessage()); }

$available_services_data = [];
try {
    $stmt_services = $pdo->query("SELECT id, name FROM services");
    foreach ($stmt_services->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $available_services_data[] = ['id' => (int)$row['id'], 'name' => $row['name']];
    }
} catch (PDOException $e) { error_log("Error al cargar servicios: " . $e->getMessage()); }

$total_clients_count = count($clients_data_from_db);
$selected_year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$selected_month = isset($_GET['month']) ? (int)$_GET['month'] : date('m');
$month_names_php = [1 => "ENERO", 2 => "FEBRERO", 3 => "MARZO", 4 => "ABRIL", 5 => "MAYO", 6 => "JUNIO", 7 => "JULIO", 8 => "AGOSTO", 9 => "SEPTIEMBRE", 10 => "OCTUBRE", 11 => "NOVIEMBRE", 12 => "DICIEMBRE"];
$initial_monthly_period_display = $month_names_php[(int)$selected_month] . ' ' . $selected_year;

$months_with_clients_data = [];
try {
    $stmt_months = $pdo->query("SELECT DISTINCT YEAR(created_at) AS year, MONTH(created_at) AS month FROM clients ORDER BY year DESC, month DESC");
    $months_with_clients_data = $stmt_months->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { error_log("Error al cargar meses para el filtro: " . $e->getMessage()); }

$monthly_clients_count = 0;
try {
    $stmt_monthly = $pdo->prepare("SELECT COUNT(id) AS count FROM clients WHERE YEAR(created_at) = :year AND MONTH(created_at) = :month");
    $stmt_monthly->execute([':year' => $selected_year, ':month' => $selected_month]);
    $monthly_clients_count = $stmt_monthly->fetchColumn();
} catch (PDOException $e) { error_log("Error al contar clientes mensuales: " . $e->getMessage()); }

$clients_json = json_encode($clients_data_from_db);
$prospects_json = json_encode($prospects_data_for_autocomplete);
$available_services_json = json_encode($available_services_data);
$months_with_clients_json = json_encode($months_with_clients_data);

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>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>
    
    <style>
        .activity-summary { display: grid; grid-template-columns: repeat(2, 1fr); gap: 0.5rem; width: 100%; margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #e5e7eb; }
        .activity-item { display: flex; align-items: center; justify-content: center; text-align: center; gap: 0.5rem; background-color: #f3f4f6; padding: 0.5rem; border-radius: 0.5rem; font-size: 0.75rem; color: #4b5563; }
        .activity-item.has-pending { background-color: #fef9c3; color: #854d0e; font-weight: 600; }
        .activity-item .font-bold { margin-right: 0.25rem; }
        .compact-activity-summary { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap; }
        
        /* --- INICIO DE ESTILOS AÑADIDOS --- */
        @media (max-width: 767px) {
            .main-action-buttons {
                flex-direction: column;
            }
        }
        @media (max-width: 480px) {
            .stat-card {
                padding: 14px !important;
                border-radius: 14px !important;
            }
            .stat-card [data-lucide] {
                width: 32px !important;
                height: 32px !important;
            }
            .stat-card h3 {
                font-size: .95rem !important;
                line-height: 1.15 !important;
                margin-bottom: .25rem !important;
            }
            .stat-card .text-5xl {
                font-size: 2.25rem !important;
                line-height: 1 !important;
            }
        }
    </style>
</head>

<body
data-page-title="Centro De Clientes Empresariales"
data-page-subtitle="Información De Clientes Activos Del Negocio"
data-page-icon="users">
    
        <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 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 id="clientes" class="dashboard-section">
                <div class="bg-white p-6 rounded-xl shadow-md">
                    <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                        <div>
                            <h3 class="text-2xl font-extrabold text-gray-800 flex items-center gap-2"><i data-lucide="user-check" class="w-7 h-7 text-[var(--color-secondary)]"></i> BASE DE DATOS DE CLIENTES</h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">Ficha, actividad y servicios de cada cliente.</p>
                        </div>
                        <div class="flex items-center gap-4 w-full md:w-auto main-action-buttons">
                            <button class="btn-secondary font-bold py-2 px-4 rounded-lg flex items-center w-full md:w-auto justify-center uppercase" onclick="openPanel('addClientePanel')"><i data-lucide="plus" class="w-5 h-5 mr-2"></i> AGREGAR CLIENTE</button>
                            <button id="download-clientes-btn" class="btn-primary font-bold py-2 px-4 rounded-lg flex items-center w-full md:w-auto justify-center uppercase text-sm"><i data-lucide="download" class="w-4 h-4 mr-2"></i> DESCARGAR</button>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                        <div class="stat-card bg-white p-6 rounded-xl 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">TOTAL DE CLIENTES</h3><p id="total-clients-count" class="text-5xl font-bold text-[var(--color-secondary)]"><?php echo $total_clients_count; ?></p><p class="text-sm text-gray-400 mt-1">ACTIVOS EN LA BASE DE DATOS</p></div></div>
                        <div class="stat-card bg-white p-6 rounded-xl flex items-center space-x-4 border-l-4 border-[var(--color-secondary)]"><i data-lucide="user-plus" class="w-12 h-12 text-gray-700"></i><div><h3 class="text-lg font-extrabold text-gray-500 mb-1">CLIENTES NUEVOS EN <span id="monthly-period-display"><?php echo htmlspecialchars($initial_monthly_period_display); ?></span></h3><p id="monthly-clients-count" class="text-5xl font-bold text-[var(--color-secondary)]"><?php echo $monthly_clients_count; ?></p></div></div>
                    </div>
                    <div class="flex flex-col md:flex-row gap-4 mb-6 pt-4 border-t">
                        <div class="relative flex-grow"><input type="text" id="client-search" placeholder="Buscar por Nombre o Servicio..." class="w-full p-3 pl-10 border border-gray-300 rounded-lg"><i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400"></i></div>
                        <select id="client-filter-apellido-letter" class="w-full md:w-48 p-3 border border-gray-300 rounded-lg bg-white"></select>
                        <select id="client-filter-service" class="w-full md:w-48 p-3 border border-gray-300 rounded-lg bg-white"></select>
                        <select id="monthly-filter-select" class="w-full md:w-64 p-3 border border-gray-300 rounded-lg bg-white"></select>
                        <div class="view-toggle inline-flex bg-gray-200 rounded-lg p-1"><button id="grid-view-btn" class="px-3 py-1 rounded-md text-sm font-semibold active" title="Vista de Tarjetas"><i data-lucide="layout-grid" class="w-5 h-5"></i></button><button id="list-view-btn" class="px-3 py-1 rounded-md text-sm font-semibold" title="Vista de Lista"><i data-lucide="list" class="w-5 h-5"></i></button></div>
                    </div>
                    <div id="client-grid-view" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"></div>
                    <div id="client-list-view" class="overflow-x-auto hidden">
                        <table class="min-w-full bg-white responsive-stack"><thead class="bg-gray-50"><tr class="text-left text-gray-500 uppercase text-sm"><th class="py-3 px-6 font-semibold">Nombre</th><th class="py-3 px-6 font-semibold hidden md:table-cell">Contacto</th><th class="py-3 px-6 font-semibold">Servicios</th><th class="py-3 px-6 font-semibold">Actividad Pendiente</th><th class="py-3 px-6 font-semibold text-center">Acciones</th></tr></thead><tbody id="clientsTableBody"></tbody></table>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<div id="addClientePanel" class="fixed inset-y-0 right-0 w-full md:w-1/3 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto"><div class="flex flex-col h-full"><div class="bg-slate-800 text-white p-6 flex justify-between items-center flex-shrink-0"><div class="flex items-center"><i data-lucide="user-plus" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i><h3 class="text-xl font-bold uppercase">Agregar Nuevo Cliente</h3></div><button onclick="closePanel('addClientePanel')" class="text-gray-400 hover:text-gray-200"><i data-lucide="x" class="w-6 h-6"></i></button></div><form id="add-cliente-form" class="p-8 flex-grow overflow-y-auto space-y-4"><div class="relative"><label for="cliente-prospecto-search" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Seleccionar Desde Prospectos</label><input type="text" id="cliente-prospecto-search" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="Buscar Prospecto..."><input type="hidden" id="cliente-selected-prospect-id"><div id="prospect-search-results" class="absolute z-10 w-full bg-white border rounded-lg shadow-lg mt-1 max-h-60 overflow-y-auto hidden"></div></div><div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label for="cliente-first-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Nombre</label><input type="text" id="cliente-first-name" class="w-full p-3 border border-gray-300 rounded-lg" required></div><div><label for="cliente-last-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Apellido</label><input type="text" id="cliente-last-name" class="w-full p-3 border border-gray-300 rounded-lg"></div></div><div><label for="cliente-email" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Email</label><input type="email" id="cliente-email" class="w-full p-3 border border-gray-300 rounded-lg"></div><div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label for="cliente-phone" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Teléfono Fijo</label><input type="tel" id="cliente-phone" class="w-full p-3 border border-gray-300 rounded-lg"></div><div><label for="cliente-mobile" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Celular</label><input type="tel" id="cliente-mobile" class="w-full p-3 border border-gray-300 rounded-lg"></div></div><div><label for="cliente-servicio-search" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Añadir Servicio</label><div class="relative"><input type="text" id="cliente-servicio-search" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="Buscar Servicio..."><div id="service-search-results" class="absolute z-10 w-full bg-white border rounded-lg shadow-lg mt-1 max-h-40 overflow-y-auto hidden"></div></div><div id="selected-services-container" class="mt-2 flex flex-wrap gap-2"></div><input type="hidden" id="cliente-servicios"></div><div class="flex items-center"><input type="checkbox" id="cliente-is-recurring" class="h-5 w-5 text-[var(--color-primary)] border-gray-300 rounded mr-2"><label for="cliente-is-recurring" class="text-gray-700 text-sm font-bold uppercase">Cliente Recurrente</label></div><div><label for="cliente-direccion-calle" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Dirección</label><input type="text" id="cliente-direccion-calle" class="w-full p-3 border border-gray-300 rounded-lg"></div><div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label for="cliente-ciudad" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Ciudad</label><input type="text" id="cliente-ciudad" class="w-full p-3 border border-gray-300 rounded-lg"></div><div><label for="cliente-estado-field" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Estado/Provincia</label><input type="text" id="cliente-estado-field" class="w-full p-3 border border-gray-300 rounded-lg"></div></div><div><label for="cliente-codigo-postal" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Código Postal</label><input type="text" id="cliente-codigo-postal" class="w-full p-3 border border-gray-300 rounded-lg"></div></form><div class="flex justify-end space-x-4 p-4 border-t bg-white flex-shrink-0"><button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closePanel('addClientePanel')">Cancelar</button><button type="submit" form="add-cliente-form" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase">Guardar Cliente</button></div></div></div>
<div id="viewClienteReadOnlyPanel" class="fixed inset-y-0 right-0 w-full md:w-1/3 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto"><div class="flex flex-col h-full"><div class="bg-slate-800 text-white p-6 flex justify-between items-center flex-shrink-0"><div class="flex items-center"><i data-lucide="user-circle" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i><h3 class="text-3xl font-black uppercase">Ficha del Cliente</h3></div><button onclick="closePanel('viewClienteReadOnlyPanel')" class="text-gray-400 hover:text-gray-200"><i data-lucide="x" class="w-6 h-6"></i></button></div><div class="p-8 flex-grow overflow-y-auto space-y-6"><div class="text-center"><h2 id="readonly-cliente-full-name" class="text-3xl font-extrabold text-gray-900"></h2><div id="readonly-cliente-recurring-tag" class="mt-2 hidden"><span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-semibold bg-purple-100 text-purple-800"><i data-lucide="repeat" class="w-4 h-4 mr-1"></i> Cliente Recurrente</span></div></div><div class="bg-gray-50 p-6 rounded-lg"><h3 class="text-lg font-bold text-gray-700 mb-4 flex items-center gap-2 uppercase"><i data-lucide="contact" class="w-6 h-6 text-[var(--color-primary)]"></i> Contacto</h3><div class="space-y-2"><div id="readonly-cliente-email-group" class="flex items-center text-gray-700"><i data-lucide="mail" class="w-5 h-5 text-gray-500 mr-3"></i><p id="readonly-cliente-email" class="font-medium break-all"></p></div><div id="readonly-cliente-phone-group" class="flex items-center text-gray-700"><i data-lucide="phone" class="w-5 h-5 text-gray-500 mr-3"></i><p id="readonly-cliente-phone" class="font-medium"></p></div><div id="readonly-cliente-mobile-group" class="flex items-center text-gray-700"><i data-lucide="smartphone" class="w-5 h-5 text-gray-500 mr-3"></i><p id="readonly-cliente-mobile" class="font-medium"></p></div><div id="readonly-cliente-address-group" class="flex items-start text-gray-700"><i data-lucide="map-pin" class="w-5 h-5 text-gray-500 mr-3 mt-1"></i><p id="readonly-cliente-full-address" class="font-medium"></p></div></div></div><div class="bg-blue-50 border-l-4 border-blue-500 p-4 rounded-lg"><h3 class="text-lg font-bold text-blue-800 mb-2 uppercase">Portal del Cliente</h3><p class="text-sm text-blue-700 mb-3">Código de acceso único para el cliente.</p><div class="relative bg-white p-2 rounded-md shadow-sm"><input type="password" id="readonly-access-code" class="w-full font-mono text-lg text-gray-700 bg-transparent border-none focus:ring-0 p-0 pr-36" readonly><div class="absolute inset-y-0 right-0 flex items-center pr-2"><button id="toggle-access-code-btn" class="p-2 text-gray-500 hover:bg-gray-100 rounded-md" title="Mostrar/Ocultar código"><i data-lucide="eye" class="w-5 h-5"></i></button><button id="copy-access-code-btn" class="p-2 text-gray-500 hover:bg-gray-100 rounded-md" title="Copiar código"><i data-lucide="copy" class="w-5 h-5"></i></button><button id="generate-access-code-btn" class="p-2 text-green-500 hover:bg-green-100 rounded-md" title="Generar nuevo código"><i data-lucide="refresh-cw" class="w-5 h-5"></i></button><button id="delete-access-code-btn" class="p-2 text-[var(--color-secondary)] hover:bg-[var(--color-secondary)] rounded-md" title="Eliminar código"><i data-lucide="trash-2" class="w-5 h-5"></i></button></div></div></div><div class="bg-gray-50 p-6 rounded-lg"><h3 class="text-lg font-bold text-gray-700 mb-4 flex items-center gap-2 uppercase"><i data-lucide="package" class="w-6 h-6 text-[var(--color-primary)]"></i> Servicios Contratados</h3><div id="readonly-cliente-services-display" class="flex flex-wrap gap-2"></div></div></div><div class="flex justify-end space-x-4 p-4 border-t bg-white flex-shrink-0"><button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closePanel('viewClienteReadOnlyPanel')">Cerrar</button><button type="button" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase" id="edit-client-from-readonly-btn">Editar Cliente</button></div></div></div>
<div id="viewClientePanel" class="fixed inset-y-0 right-0 w-full md:w-1/3 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto"><div class="flex flex-col h-full"><div class="bg-slate-800 text-white p-6 flex justify-between items-center flex-shrink-0"><div class="flex items-center"><i data-lucide="user-cog" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i><h3 class="text-xl font-bold uppercase">Editar Cliente</h3></div><button onclick="closePanel('viewClientePanel')" class="text-gray-400 hover:text-gray-200"><i data-lucide="x" class="w-6 h-6"></i></button></div><form id="view-cliente-form" class="p-8 flex-grow overflow-y-auto space-y-4"><input type="hidden" id="view-cliente-id"><div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label for="view-cliente-first-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Nombre</label><input type="text" id="view-cliente-first-name" class="w-full p-3 border border-gray-300 rounded-lg"></div><div><label for="view-cliente-last-name" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Apellido</label><input type="text" id="view-cliente-last-name" class="w-full p-3 border border-gray-300 rounded-lg"></div></div><div><label for="view-cliente-email" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Email</label><input type="email" id="view-cliente-email" class="w-full p-3 border border-gray-300 rounded-lg"></div><div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label for="view-cliente-phone" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Teléfono Fijo</label><input type="tel" id="view-cliente-phone" class="w-full p-3 border border-gray-300 rounded-lg"></div><div><label for="view-cliente-mobile" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Celular</label><input type="tel" id="view-cliente-mobile" class="w-full p-3 border border-gray-300 rounded-lg"></div></div><div><label for="view-cliente-servicio-search" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Editar Servicios</label><div class="relative"><input type="text" id="view-cliente-servicio-search" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="Buscar Servicio..."><div id="view-service-search-results" class="absolute z-10 w-full bg-white border mt-1 rounded-lg shadow-lg max-h-40 overflow-y-auto hidden"></div></div><div id="view-selected-services-container" class="mt-2 flex flex-wrap gap-2"></div><input type="hidden" id="view-cliente-servicios"></div><div class="flex items-center"><input type="checkbox" id="view-cliente-is-recurring" class="h-5 w-5 text-[var(--color-primary)] border-gray-300 rounded mr-2"><label for="view-cliente-is-recurring" class="text-gray-700 text-sm font-bold uppercase">Cliente Recurrente</label></div><div><label for="view-cliente-direccion-calle" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Dirección</label><input type="text" id="view-cliente-direccion-calle" class="w-full p-3 border border-gray-300 rounded-lg"></div><div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label for="view-cliente-ciudad" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Ciudad</label><input type="text" id="view-cliente-ciudad" class="w-full p-3 border border-gray-300 rounded-lg"></div><div><label for="view-cliente-estado-field" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Estado/Provincia</label><input type="text" id="view-cliente-estado-field" class="w-full p-3 border border-gray-300 rounded-lg"></div></div><div><label for="view-cliente-codigo-postal" class="block text-gray-700 text-sm font-bold mb-2 uppercase">Código Postal</label><input type="text" id="view-cliente-codigo-postal" class="w-full p-3 border border-gray-300 rounded-lg"></div></form><div class="flex justify-end space-x-4 p-4 border-t bg-white flex-shrink-0"><button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closePanel('viewClientePanel')">Cancelar</button><button type="submit" form="view-cliente-form" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase">Guardar Cambios</button></div></div></div>

<div id="confirmDeleteModal" class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center hidden z-50">
    <div class="bg-white p-8 rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        <div class="flex justify-center mb-4">
            <i id="confirm-modal-icon" data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
        </div>
        <h3 id="confirm-modal-title" class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase"></h3>
        <p id="confirm-modal-message" class="text-gray-700 mb-6 uppercase"></p>
        <div class="flex justify-center space-x-4">
            <button type="button" class="bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-4 rounded-lg uppercase" onclick="closeModal('confirmDeleteModal')">CANCELAR</button>
            <button type="button" class="btn-secondary font-bold py-2 px-4 rounded-lg uppercase" id="confirm-delete-button">CONFIRMAR</button>
        </div>
    </div>
</div>
<script>
    // --- INICIO DEL CÓDIGO JS RESTAURADO Y MEJORADO ---
    let clientsFromDB = <?php echo $clients_json; ?>;
    let prospectsFromDB = <?php echo $prospects_json; ?>;
    let availableServices = <?php echo $available_services_json; ?>;
    const monthsWithClients = <?php echo $months_with_clients_json; ?>;
    let selectedMonth = <?php echo $selected_month; ?>;
    let selectedYear = <?php echo $selected_year; ?>;

    let currentClientView = 'grid';
    let selectedServiceIds = new Set();
    let viewSelectedServiceIds = new Set();
    let currentReadOnlyClientId = null;
    
    // --- Panel & Modal Management ---
    const panelOverlay = document.createElement('div');
    panelOverlay.className = 'fixed inset-0 bg-gray-900 bg-opacity-75 z-40 hidden';
    document.body.appendChild(panelOverlay);

    window.openPanel = (panelId) => {
        const panel = document.getElementById(panelId);
        if (!panel) return;
        if (panelId === 'addClientePanel') {
            document.getElementById('add-cliente-form').reset();
            selectedServiceIds.clear();
            renderSelectedServices(selectedServiceIds, document.getElementById('selected-services-container'), document.getElementById('cliente-servicios'));
        }
        panel.classList.remove('translate-x-full');
        panelOverlay.classList.remove('hidden');
        lucide.createIcons();
    };

    window.closePanel = (panelId) => {
        document.getElementById(panelId)?.classList.add('translate-x-full');
        const anyPanelOpen = Array.from(document.querySelectorAll('.fixed.inset-y-0')).some(p => !p.classList.contains('translate-x-full'));
        if (!anyPanelOpen) panelOverlay.classList.add('hidden');
    };
    
    window.openModal = (modalId) => {
        const modal = document.getElementById(modalId);
        if (!modal) return;
        const modalContent = modal.querySelector('div:first-child');
        modal.classList.remove('hidden');
        setTimeout(() => modalContent.classList.remove('scale-95', 'opacity-0'), 50);
        panelOverlay.classList.remove('hidden');
        lucide.createIcons();
    };

    window.closeModal = (modalId) => {
        const modal = document.getElementById(modalId);
        if (!modal) return;
        const modalContent = modal.querySelector('div:first-child');
        modalContent.classList.add('scale-95', 'opacity-0');
        setTimeout(() => {
            modal.classList.add('hidden');
            const anyPanelOpen = Array.from(document.querySelectorAll('.fixed.inset-y-0')).some(p => !p.classList.contains('translate-x-full'));
            if (!anyPanelOpen) panelOverlay.classList.add('hidden');
        }, 300);
    };

    const openConfirmationModal = (title, message, confirmAction, icon = 'alert-triangle', iconColor = 'text-[var(--color-secondary)]') => {
        document.getElementById('confirm-modal-title').textContent = title;
        document.getElementById('confirm-modal-message').innerHTML = message;
        
        const modalIcon = document.getElementById('confirm-modal-icon');
        modalIcon.setAttribute('data-lucide', icon);
        modalIcon.className = `w-16 h-16 ${iconColor}`;

        document.getElementById('confirm-delete-button').onclick = () => confirmAction();
        openModal('confirmDeleteModal');
    };

    panelOverlay.addEventListener('click', () => {
        closePanel('addClientePanel');
        closePanel('viewClientePanel');
        closePanel('viewClienteReadOnlyPanel');
        closeModal('confirmDeleteModal');
    });

    // --- Funciones de Utilidad y Formato ---
    const getServiceTagColors = (serviceName) => {
        const serviceTagColors = ['blue', 'green', 'purple', 'yellow', 'pink', 'indigo', 'red', 'gray'].map(c => ({ bg: `bg-${c}-100`, text: `text-${c}-800` }));
        let hash = 0;
        for (let i = 0; i < (serviceName || '').length; i++) { hash = serviceName.charCodeAt(i) + ((hash << 5) - hash); }
        return serviceTagColors[Math.abs(hash) % serviceTagColors.length];
    };
    
    const formatPhoneNumber = (value) => {
        if (!value) return '';
        const cleaned = ('' + value).replace(/\D/g, '');
        const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
        return match ? `(${match[1]}) ${match[2]}-${match[3]}` : value;
    };
    
    const renderActivitySummary = (client, isCompact = false) => {
        const items = [
            { icon: 'calendar', count: client.upcoming_appointments, label: 'Citas' },
            { icon: 'check-square', count: client.pending_tasks, label: 'Tareas' },
            { icon: 'file-text', count: client.pending_invoices, label: 'Facturas' },
            { icon: 'file-bar-chart-2', count: client.sent_estimates, label: 'Cotizaciones' }
        ];

        if (isCompact) {
            const pendingItems = items.filter(item => item.count > 0);
            if (pendingItems.length === 0) return '<span class="text-xs text-gray-400">Sin actividad pendiente</span>';
            return `<div class="compact-activity-summary">${pendingItems.map(item => `
                <div class="flex items-center gap-1 text-xs text-yellow-800 bg-yellow-100 px-2 py-0.5 rounded-full" title="${item.count} ${item.label} pendiente(s)">
                    <i data-lucide="${item.icon}" class="w-3 h-3"></i><span class="font-bold">${item.count}</span>
                </div>`).join('')}</div>`;
        }

        return `<div class="activity-summary">${items.map(item => `
            <div class="activity-item ${item.count > 0 ? 'has-pending' : ''}">
                <i data-lucide="${item.icon}" class="w-4 h-4"></i><span class="font-bold">${item.count}</span><span>${item.label}</span>
            </div>`).join('')}</div>`;
    };

    // --- Funciones de Renderizado (Restauradas y Mejoradas) ---
    const renderClientCard = (client) => {
        const fullName = `${client.nombre || ''} ${client.apellido || ''}`.trim();
        const initial = (client.nombre || 'C').charAt(0).toUpperCase();
        const servicesHtml = client.servicios ? client.servicios.split(', ').map(s => `<span class="inline-block ${getServiceTagColors(s).bg} ${getServiceTagColors(s).text} py-0.5 px-2 rounded-full text-xs font-semibold mr-1 mb-1">${s}</span>`).join('') : '<p class="text-gray-500 text-sm italic">SIN SERVICIOS</p>';
        const recurringTag = client.is_recurring ? `<span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800 ml-2"><i data-lucide="repeat" class="w-3 h-3 mr-1"></i> Recurrente</span>` : '';

        return `<div class="client-card bg-white rounded-xl p-4 flex flex-col items-center text-center shadow-sm">
            <div class="client-avatar rounded-full flex items-center justify-center mb-4"><span>${initial}</span></div>
            <h4 class="font-black text-2xl text-gray-800">${fullName}<br />${recurringTag}</h4>
            <p class="text-xs text-gray-500 mb-2">${client.email || 'N/A'}</p>
            <div class="mb-4 flex flex-wrap justify-center min-h-[24px]">${servicesHtml}</div>
            ${renderActivitySummary(client, false)} 
            <div class="flex space-x-2 mt-4 w-full">
                <button class="flex-1 btn-secondary font-bold py-2 px-3 rounded-lg text-xs uppercase edit-client-btn" data-client-id="${client.id}">Ver Detalles</button>
                <button class="p-2 bg-[var(--color-secondary)] hover:bg-[var(--color-secondary)] text-white rounded-lg delete-btn" data-item-id="${client.id}" title="Eliminar Cliente"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
            </div>
        </div>`;
    };

    const renderClientTableRow = (client) => {
        const fullName = `${client.nombre || ''} ${client.apellido || ''}`.trim();
        const recurringTag = client.is_recurring ? `<span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800 ml-2"><i data-lucide="repeat" class="w-3 h-3 mr-1"></i> Recurrente</span>` : '';
        const contactInfo = `${client.email || ''}<br>${formatPhoneNumber(client.mobile) || formatPhoneNumber(client.phone) || ''}`.trim();
        const servicesHtml = client.servicios ? client.servicios.split(', ').map(s => `<span class="inline-block ${getServiceTagColors(s).bg} ${getServiceTagColors(s).text} py-0.5 px-2 rounded-full text-xs font-semibold mr-1 mb-1">${s}</span>`).join('') : '<p class="text-gray-500 text-sm italic">SIN SERVICIOS</p>';

        return `<tr class="border-b border-gray-200 hover:bg-gray-50">
            <td data-label="Nombre"><span class="font-semibold text-blue-600 cursor-pointer edit-client-btn" data-client-id="${client.id}">${fullName}</span>${recurringTag}</td>
            <td class="hidden md:table-cell" data-label="Contacto">${contactInfo}</td>
            <td data-label="Servicios">${servicesHtml}</td>
            <td data-label="Actividad Pendiente">${renderActivitySummary(client, true)}</td>
            <td class="text-center" data-label="Acciones"><div class="flex justify-center items-center gap-2">
                <button class="text-blue-600 hover:text-blue-800 edit-client-btn" data-client-id="${client.id}" title="Ver Detalles"><i data-lucide="eye" class="w-5 h-5"></i></button>
                <button class="text-[var(--color-secondary)] hover:text-[var(--color-secondary)] delete-btn" data-item-id="${client.id}" title="Eliminar Cliente"><i data-lucide="trash-2" class="w-5 h-5"></i></button>
            </div></td>
        </tr>`;
    };

    window.openClientDetailsModal = (clientId) => {
        const client = clientsFromDB[clientId];
        if (!client) return;
        currentReadOnlyClientId = clientId;
        document.getElementById('readonly-cliente-full-name').textContent = `${client.nombre || ''} ${client.apellido || ''}`.trim();
        document.getElementById('readonly-cliente-recurring-tag').classList.toggle('hidden', !client.is_recurring);
        document.getElementById('readonly-cliente-email').textContent = client.email || 'N/A';
        document.getElementById('readonly-cliente-phone').textContent = formatPhoneNumber(client.phone) || 'N/A';
        document.getElementById('readonly-cliente-mobile').textContent = formatPhoneNumber(client.mobile) || 'N/A';
        document.getElementById('readonly-cliente-full-address').textContent = [client.direccion_calle, client.ciudad, client.state_province, client.zip_code].filter(Boolean).join(', ');
        
        const accessCodeInput = document.getElementById('readonly-access-code');
        accessCodeInput.value = client.access_code || 'N/A';
        // Reset to password type when opening
        accessCodeInput.type = 'password';
        const toggleIcon = document.querySelector('#toggle-access-code-btn i');
        if (toggleIcon) {
            toggleIcon.setAttribute('data-lucide', 'eye');
        }

        document.getElementById('readonly-cliente-services-display').innerHTML = client.servicios ? client.servicios.split(', ').map(s => `<span class="inline-block ${getServiceTagColors(s).bg} ${getServiceTagColors(s).text} py-0.5 px-2 rounded-full text-sm font-semibold">${s}</span>`).join('') : '<p class="text-gray-500 text-sm italic">Sin servicios</p>';
        openPanel('viewClienteReadOnlyPanel');
    };

    window.openEditClienteModal = (clientId) => {
        const client = clientsFromDB[clientId];
        if (!client) return;
        document.getElementById('view-cliente-id').value = client.id;
        document.getElementById('view-cliente-first-name').value = client.nombre || '';
        document.getElementById('view-cliente-last-name').value = client.apellido || '';
        document.getElementById('view-cliente-email').value = client.email || '';
        document.getElementById('view-cliente-phone').value = client.phone || '';
        document.getElementById('view-cliente-mobile').value = client.mobile || '';
        document.getElementById('view-cliente-direccion-calle').value = client.direccion_calle || '';
        document.getElementById('view-cliente-ciudad').value = client.ciudad || '';
        document.getElementById('view-cliente-estado-field').value = client.state_province || '';
        document.getElementById('view-cliente-codigo-postal').value = client.zip_code || '';
        document.getElementById('view-cliente-is-recurring').checked = client.is_recurring;
        viewSelectedServiceIds.clear();
        (client.service_ids || []).forEach(id => viewSelectedServiceIds.add(id));
        renderSelectedServices(viewSelectedServiceIds, document.getElementById('view-selected-services-container'), document.getElementById('view-cliente-servicios'));
        closePanel('viewClienteReadOnlyPanel');
        openPanel('viewClientePanel');
    };

    const renderClients = () => {
        const DOMElements = { clientSearch: document.getElementById('client-search'), clientFilterApellidoLetter: document.getElementById('client-filter-apellido-letter'), clientFilterService: document.getElementById('client-filter-service'), clientGridView: document.getElementById('client-grid-view'), clientListView: document.getElementById('client-list-view'), clientsTableBody: document.getElementById('clientsTableBody'), gridViewBtn: document.getElementById('grid-view-btn'), listViewBtn: document.getElementById('list-view-btn') };
        const searchTerm = DOMElements.clientSearch.value.toLowerCase();
        const selectedLetter = DOMElements.clientFilterApellidoLetter.value;
        const selectedServiceId = parseInt(DOMElements.clientFilterService.value);
        const filteredClients = Object.values(clientsFromDB).filter(c => {
            const fullName = `${c.nombre || ''} ${c.apellido || ''}`.trim().toLowerCase();
            const initial = (c.apellido || c.nombre || ' ').charAt(0).toUpperCase();
            const matchesSearch = fullName.includes(searchTerm) || (c.servicios || '').toLowerCase().includes(searchTerm);
            const matchesLetter = selectedLetter === 'all' || initial === selectedLetter;
            const matchesService = isNaN(selectedServiceId) || selectedServiceId === 0 || (c.service_ids || []).includes(selectedServiceId);
            return matchesSearch && matchesLetter && matchesService;
        });

        const content = filteredClients.length > 0 ? filteredClients.map(currentClientView === 'grid' ? renderClientCard : renderClientTableRow).join('') : currentClientView === 'list' ? `<tr><td colspan="5" class="text-center py-8 text-gray-500">No se encontraron clientes</td></tr>` : `<p class="text-center py-8 text-gray-500 md:col-span-3">No se encontraron clientes</p>`;
        if (currentClientView === 'grid') DOMElements.clientGridView.innerHTML = content; else DOMElements.clientsTableBody.innerHTML = content;
        DOMElements.clientGridView.classList.toggle('hidden', currentClientView !== 'grid');
        DOMElements.clientListView.classList.toggle('hidden', currentClientView !== 'list');
        DOMElements.gridViewBtn.classList.toggle('active', currentClientView === 'grid');
        DOMElements.listViewBtn.classList.toggle('active', currentClientView !== 'list');
        lucide.createIcons();
    };

    const populateFilters = () => {
        const initials = [...new Set(Object.values(clientsFromDB).map(c => (c.apellido || c.nombre || ' ').charAt(0).toUpperCase()))].sort();
        document.getElementById('client-filter-apellido-letter').innerHTML = `<option value="all">Todas las Letras</option>${initials.map(i => `<option value="${i}">${i}</option>`).join('')}`;
        document.getElementById('client-filter-service').innerHTML = `<option value="0">Todos los Servicios</option>${availableServices.map(s => `<option value="${s.id}">${s.name}</option>`).join('')}`;
        const monthNames = ["", "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
        const uniqueMonths = [...new Set(monthsWithClients.map(m => `${m.year}-${m.month}`))].sort((a, b) => b.localeCompare(a));
        document.getElementById('monthly-filter-select').innerHTML = uniqueMonths.map(val => {
            const [y, m] = val.split('-');
            return `<option value="${y}-${m}" ${y == selectedYear && m == selectedMonth ? 'selected' : ''}>${monthNames[parseInt(m)]} ${y}</option>`;
        }).join('');
    };
    
    const renderSelectedServices = (selectedIdsSet, container, hiddenInput) => {
        const servicesArray = Array.from(selectedIdsSet);
        hiddenInput.value = servicesArray.join(',');
        if (servicesArray.length === 0) {
            container.innerHTML = '<p class="text-gray-500 text-sm italic">NINGÚN SERVICIO SELECCIONADO</p>';
        } else {
            container.innerHTML = servicesArray.map(id => {
                const service = availableServices.find(s => s.id == id);
                return service ? `<span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-[var(--color-primary)] text-white gap-1"><span>${service.name.toUpperCase()}</span><button type="button" class="remove-service-btn" data-service-id="${id}"><i data-lucide="x" class="w-4 h-4"></i></button></span>` : '';
            }).join('');
        }
        lucide.createIcons();
    };

    const setupServiceSearch = (input, resultsDiv, selectedIds, container, hiddenInput) => {
        input.addEventListener('input', e => {
            const query = e.target.value.toLowerCase();
            if (query.length < 1) { resultsDiv.classList.add('hidden'); return; }
            const filtered = availableServices.filter(s => s.name.toLowerCase().includes(query) && !selectedIds.has(s.id));
            resultsDiv.innerHTML = filtered.length > 0 ? filtered.map(s => `<div class="p-2 cursor-pointer hover:bg-gray-100" data-service-id="${s.id}">${s.name}</div>`).join('') : '<div class="p-2 text-gray-500">No hay resultados</div>';
            resultsDiv.classList.remove('hidden');
        });
        resultsDiv.addEventListener('mousedown', e => {
            if (e.target.dataset.serviceId) {
                const id = parseInt(e.target.dataset.serviceId);
                selectedIds.add(id);
                renderSelectedServices(selectedIds, container, hiddenInput);
                input.value = '';
                resultsDiv.classList.add('hidden');
            }
        });
        container.addEventListener('click', e => {
            const btn = e.target.closest('.remove-service-btn');
            if(btn) {
                selectedIds.delete(parseInt(btn.dataset.serviceId));
                renderSelectedServices(selectedIds, container, hiddenInput);
            }
        });
        document.addEventListener('click', e => { if (!input.contains(e.target) && !resultsDiv.contains(e.target)) resultsDiv.classList.add('hidden'); });
    };

    const setupProspectSearch = () => { 
        const input = document.getElementById('cliente-prospecto-search');
        const resultsDiv = document.getElementById('prospect-search-results');
        input.addEventListener('input', e => {
            const query = e.target.value.toLowerCase();
            if (query.length < 2) { resultsDiv.classList.add('hidden'); return; }
            const filtered = Object.values(prospectsFromDB).filter(p => `${p.first_name} ${p.last_name}`.toLowerCase().includes(query) || p.email.toLowerCase().includes(query));
            resultsDiv.innerHTML = filtered.length > 0 ? filtered.map(p => `<div class="p-2 cursor-pointer hover:bg-gray-100" data-prospect-id="${p.id}">${p.first_name} ${p.last_name} (${p.email})</div>`).join('') : '<div class="p-2 text-gray-500">No hay resultados</div>';
            resultsDiv.classList.remove('hidden');
        });
        resultsDiv.addEventListener('mousedown', e => {
            if(e.target.dataset.prospectId) {
                const prospect = prospectsFromDB[e.target.dataset.prospectId];
                if (prospect) {
                    document.getElementById('cliente-first-name').value = prospect.first_name;
                    document.getElementById('cliente-last-name').value = prospect.last_name;
                    document.getElementById('cliente-email').value = prospect.email;
                    document.getElementById('cliente-phone').value = prospect.phone;
                    document.getElementById('cliente-mobile').value = prospect.mobile;
                    document.getElementById('cliente-direccion-calle').value = prospect.street_address;
                    document.getElementById('cliente-ciudad').value = prospect.city;
                    document.getElementById('cliente-estado-field').value = prospect.state_province;
                    document.getElementById('cliente-codigo-postal').value = prospect.zip_code;
                    document.getElementById('cliente-selected-prospect-id').value = prospect.id;
                    input.value = `${prospect.first_name} ${prospect.last_name}`;
                    resultsDiv.classList.add('hidden');
                }
            }
        });
        document.addEventListener('click', e => { if (!input.contains(e.target) && !resultsDiv.contains(e.target)) resultsDiv.classList.add('hidden'); });
    };

    document.addEventListener('DOMContentLoaded', () => {
        populateFilters();
        renderClients();
        
        document.getElementById('client-search').addEventListener('input', renderClients);
        document.getElementById('client-filter-apellido-letter').addEventListener('change', renderClients);
        document.getElementById('client-filter-service').addEventListener('change', renderClients);
        document.getElementById('monthly-filter-select').addEventListener('change', e => {
            const [year, month] = e.target.value.split('-');
            window.location.href = `clients.php?year=${year}&month=${month}`;
        });
        document.getElementById('grid-view-btn').addEventListener('click', () => { currentClientView = 'grid'; renderClients(); });
        document.getElementById('list-view-btn').addEventListener('click', () => { currentClientView = 'list'; renderClients(); });
        
        const contentArea = document.getElementById('content-area');
        contentArea.addEventListener('click', e => {
            const editBtn = e.target.closest('.edit-client-btn');
            if (editBtn) openClientDetailsModal(editBtn.dataset.clientId);
            
            const deleteBtn = e.target.closest('.delete-btn');
            if (deleteBtn) {
                const clientId = deleteBtn.dataset.itemId;
                const confirmAction = async () => {
                    // Lógica para borrar cliente
                    const response = await fetch('db/clients-delete.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({ id: clientId })
                    });
                  const result = await response.json();
                  if (result.success) { 
                location.reload(); 
            } else { 
                openConfirmationModal(
                    'ERROR AL GUARDAR',
                    result.message,
                    () => closeModal('confirmDeleteModal'),
                    'alert-triangle', 
                    'text-red-500' 
                );
                document.getElementById('confirm-delete-button').textContent = 'ENTENDIDO';
            }
                };
                openConfirmationModal(
                    'CONFIRMAR ELIMINACIÓN',
                    '¿ESTÁS SEGURO DE QUE DESEAS ELIMINAR ESTE CLIENTE? ESTA ACCIÓN NO SE PUEDE DESHACER.',
                    confirmAction
                );
            }
        });

        document.getElementById('edit-client-from-readonly-btn').addEventListener('click', () => {
            if (currentReadOnlyClientId) openEditClienteModal(currentReadOnlyClientId);
        });

        // --- INICIO DE NUEVA FUNCIONALIDAD PARA PORTAL DEL CLIENTE ---
        const accessCodeInput = document.getElementById('readonly-access-code');
        const toggleBtn = document.getElementById('toggle-access-code-btn');
        const copyBtn = document.getElementById('copy-access-code-btn');
        const generateBtn = document.getElementById('generate-access-code-btn');
        const deleteCodeBtn = document.getElementById('delete-access-code-btn');

        toggleBtn.addEventListener('click', () => {
            const icon = toggleBtn.querySelector('i');
            if (accessCodeInput.type === 'password') {
                accessCodeInput.type = 'text';
                icon.setAttribute('data-lucide', 'eye-off');
            } else {
                accessCodeInput.type = 'password';
                icon.setAttribute('data-lucide', 'eye');
            }
            lucide.createIcons();
        });
        
        copyBtn.addEventListener('click', (e) => {
            const isPassword = accessCodeInput.type === 'password';
            if (isPassword) accessCodeInput.type = 'text';
            
            accessCodeInput.select();
            document.execCommand('copy');
            
            if (isPassword) accessCodeInput.type = 'password';

            const icon = e.currentTarget.querySelector('i');
            icon.setAttribute('data-lucide', 'check');
            lucide.createIcons();
            setTimeout(() => {
                icon.setAttribute('data-lucide', 'copy');
                lucide.createIcons();
            }, 1500);
        });
        
        generateBtn.addEventListener('click', () => {
            if (!currentReadOnlyClientId) return;
            const confirmAction = async () => {
                const response = await fetch('db/clients-generate-code.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ client_id: currentReadOnlyClientId })
                });
                const result = await response.json();
                if (result.success) {
                    accessCodeInput.value = result.new_code;
                    clientsFromDB[currentReadOnlyClientId].access_code = result.new_code;
                    closeModal('confirmDeleteModal');
                } else {
                    alert('Error al generar el código: ' + result.message);
                    closeModal('confirmDeleteModal');
                }
            };

            openConfirmationModal(
                'GENERAR NUEVO CÓDIGO',
                '¿ESTÁS SEGURO? EL CÓDIGO ANTERIOR SERÁ REEMPLAZADO PERMANENTEMENTE.',
                confirmAction,
                'refresh-cw',
                'text-green-500'
            );
        });

        deleteCodeBtn.addEventListener('click', () => {
            if (!currentReadOnlyClientId) return;
            const confirmAction = async () => {
                const response = await fetch('db/clients-delete-code.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ client_id: currentReadOnlyClientId })
                });
                const result = await response.json();
                if (result.success) {
                    accessCodeInput.value = 'N/A';
                    clientsFromDB[currentReadOnlyClientId].access_code = null;
                    closeModal('confirmDeleteModal');
                } else {
                    alert('Error al eliminar el código: ' + result.message);
                    closeModal('confirmDeleteModal');
                }
            };

            openConfirmationModal(
                'ELIMINAR CÓDIGO',
                '¿ESTÁS SEGURO? EL CLIENTE NO PODRÁ ACCEDER AL PORTAL HASTA QUE SE GENERE UN NUEVO CÓDIGO.',
                confirmAction
            );
        });
        // --- FIN DE NUEVA FUNCIONALIDAD ---
        
        setupProspectSearch();
        setupServiceSearch(document.getElementById('cliente-servicio-search'), document.getElementById('service-search-results'), selectedServiceIds, document.getElementById('selected-services-container'), document.getElementById('cliente-servicios'));
        setupServiceSearch(document.getElementById('view-cliente-servicio-search'), document.getElementById('view-service-search-results'), viewSelectedServiceIds, document.getElementById('view-selected-services-container'), document.getElementById('view-cliente-servicios'));
        
        document.getElementById('add-cliente-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = {
                first_name: document.getElementById('cliente-first-name').value,
                last_name: document.getElementById('cliente-last-name').value,
                email: document.getElementById('cliente-email').value,
                phone: document.getElementById('cliente-phone').value,
                mobile: document.getElementById('cliente-mobile').value,
                street_address: document.getElementById('cliente-direccion-calle').value,
                city: document.getElementById('cliente-ciudad').value,
                state_province: document.getElementById('cliente-estado-field').value,
                zip_code: document.getElementById('cliente-codigo-postal').value,
                assigned_service_ids: Array.from(selectedServiceIds),
                prospect_id: document.getElementById('cliente-selected-prospect-id').value,
                is_recurring: document.getElementById('cliente-is-recurring').checked
            };
            const response = await fetch('db/clients-create.php', {
                method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(formData)
            });
            const result = await response.json();
            if (result.success) { location.reload(); } else { alert('Error: ' + result.message); }
        });
        
        document.getElementById('view-cliente-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = {
                id: document.getElementById('view-cliente-id').value,
                first_name: document.getElementById('view-cliente-first-name').value,
                last_name: document.getElementById('view-cliente-last-name').value,
                email: document.getElementById('view-cliente-email').value,
                phone: document.getElementById('view-cliente-phone').value,
                mobile: document.getElementById('view-cliente-mobile').value,
                street_address: document.getElementById('view-cliente-direccion-calle').value,
                city: document.getElementById('view-cliente-ciudad').value,
                state_province: document.getElementById('view-cliente-estado-field').value,
                zip_code: document.getElementById('view-cliente-codigo-postal').value,
                assigned_service_ids: Array.from(viewSelectedServiceIds),
                is_recurring: document.getElementById('view-cliente-is-recurring').checked
            };
            // NECESITAS CREAR db/clients-update.php PARA ESTA PARTE
            const response = await fetch('db/clients-update.php', { 
                method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(formData)
            });
            const result = await response.json();
            if (result.success) { location.reload(); } else { alert('Error: ' + result.message); }
        });
    });
</script>
</body>
</html>