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

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';

// 1. Obtener clientes de la tabla 'clients'
$clients_data_from_db = [];
// Inicializar contadores y variables para el filtro mensual
$total_clients_count = 0;
$monthly_clients_count = 0;
$selected_year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$selected_month = isset($_GET['month']) ? (int)$_GET['month'] : date('m');
$months_with_clients_data = [];

// Array para nombres de meses en español (para la visualización PHP inicial)
$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"
];
// Formato para la visualización inicial del periodo mensual
$initial_monthly_period_display = $month_names_php[(int)$selected_month] . ' ' . $selected_year;

$db_error_message = null; // Variable para capturar errores de DB en PHP

try {
    // Consulta principal para cargar todos los clientes (SIN SERVICIOS)
    $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
        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'],
            'telefono_display' => ($row['mobile'] ? $row['mobile'] : '') . ($row['phone'] ? ($row['mobile'] ? ' | ' : '') . $row['phone'] : ''),
            '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']
        ];
    }
    $total_clients_count = count($clients_data_from_db); // Actualizar el contador total
} catch (PDOException $e) {
    error_log("Error al cargar clientes desde la DB: " . $e->getMessage());
    $db_error_message = 'Error al cargar clientes: ' . $e->getMessage();
}

// Lógica para el filtro y conteo de clientes mensuales
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");
    while ($row = $stmt_months->fetch(PDO::FETCH_ASSOC)) {
        $months_with_clients_data[] = $row;
    }
} catch (PDOException $e) {
    error_log("Error al cargar meses para el filtro de clientes desde la DB: " . $e->getMessage());
}

// Contar clientes creados en el mes y año SELECCIONADOS
try {
    $stmt_monthly = $pdo->prepare("SELECT COUNT(id) AS count FROM clients WHERE YEAR(created_at) = :year AND MONTH(created_at) = :month");
    $stmt_monthly->bindValue(':year', $selected_year);
    $stmt_monthly->bindValue(':month', (int)$selected_month);
    $stmt_monthly->execute();
    $result_monthly = $stmt_monthly->fetch(PDO::FETCH_ASSOC);
    $monthly_clients_count = $result_monthly['count'];

} catch (PDOException $e) {
    error_log("Error al contar clientes mensuales filtrados desde la DB: " . $e->getMessage());
}


// 2. Obtener prospectos de la tabla 'leads' (para el autocomplete)
$prospects_data_for_autocomplete = [];
try {
    $stmt = $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");
    $db_prospects_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($db_prospects_rows as $row) {
        $prospects_data_for_autocomplete[$row['id']] = [
            'id' => $row['id'],
            'nombre' => $row['first_name'],
            'apellido' => $row['last_name'],
            'empresa' => $row['company'],
            'email' => $row['email'],
            'phone' => $row['phone'],
            'mobile' => $row['mobile'] ?? null,
            'fuente' => $row['source'],
            'estado' => $row['status'],
            'direccion_calle' => $row['street_address'],
            'ciudad' => $row['city'],
            'state_province' => $row['state_province'],
            'zip_code' => $row['zip_code']
        ];
    }
} catch (PDOException | Exception $e) {
    error_log("Error al cargar prospectos para autocomplete desde la DB: " . $e->getMessage());
}

// Convertir los arrays PHP a formato JSON para que JavaScript los pueda usar
$clients_json = json_encode($clients_data_from_db);
$prospects_json = json_encode($prospects_data_for_autocomplete);
$months_with_clients_json = json_encode($months_with_clients_data);

// Pasar los contadores y el mes/año seleccionado a JavaScript
$total_clients_count_json = json_encode($total_clients_count);
$monthly_clients_count_json = json_encode($monthly_clients_count);
$selected_month_js = json_encode((int)$selected_month);
$selected_year_js = json_encode((int)$selected_year);

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 FlowCMS™  De OrozDesign Powered By OrozCO</title>
  <meta name="robots" content="noindex, nofollow">

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

    <?php include 'files/gtm-head.php'; ?>

    <script src="https://cdn.tailwindcss.com"></script>

    <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>
    <script src="https://unpkg.com/imask"></script>

    <link rel="stylesheet" href="style.css">
    <script src="files/header-manager.js"></script>
    
<style>

/* --- Ocultar títulos grandes debajo del header en móvil --- */
@media (max-width: 768px) {
  .page-header-container, #page-title, #page-subtitle { display: none !important; }
  /* aire inicial para el primer bloque bajo header */
  .dashboard-section:first-of-type,
  #inicio:first-of-type,
  main .dashboard-section:first-child,
  main section:first-of-type,
  .clients-section:first-of-type { margin-top: calc(var(--header-height) + 12px) !important; }
}

/* --- Evitar que el header tape anclas/headers --- */
:is(h1,h2,h3,h4,h5,h6,.section-title,[data-section]) { scroll-margin-top: var(--header-height); }

/* --- Tarjetas y stats (sin cambiar desktop) --- */
.stat-card { display:flex; align-items:center; gap:1rem; box-shadow:0 10px 25px rgba(0,0,0,.06); border-left-width:4px; }
.stat-card p.text-5xl { line-height:1; }
.client-card, .card, .panel, .box { border-radius: 14px; box-shadow: 0 10px 22px rgba(0,0,0,.06); }

/* --- Compactar en móviles pequeños --- */
@media (max-width: 480px) {
  .dashboard-section .grid, .clients-section .grid { gap: 12px !important; }
  .stat-card, .client-card, .card, .panel, .box {
    padding: 14px !important;
    border-radius: 14px !important;
    box-shadow: 0 10px 22px rgba(0,0,0,.06) !important;
  }
  .stat-card [data-lucide], .client-card [data-lucide], .card [data-lucide] { width: 32px !important; height: 32px !important; }
  .stat-card h3, .client-card h3, .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; }
  .stat-card .text-sm, .client-card .text-sm, .card .text-sm { font-size: .75rem !important; }
}

/* =========================
   BOTONES APILADOS (MÓVIL)
   ========================= */
@media (max-width: 767.98px) {
  /* Grupos genéricos */
  .btn-group, .buttons, .actions, .action-row, .toolbar, .card-actions, .header-actions,
  [class*="btn-group"], [class*="buttons"], [class*="actions"], [class*="toolbar"] {
    display: flex !important;
    flex-direction: column !important;
    align-items: stretch !important;
    gap: 10px !important;
  }
  /* Si el grupo es .flex (Tailwind), forzar columna */
  .flex.header-actions, .flex.card-actions, .flex.action-row, .flex.actions, .flex.buttons, .flex.btn-group {
    flex-direction: column !important; align-items: stretch !important;
  }
  /* Botones/enlaces internos 100% ancho */
  .btn-group > a, .btn-group > button,
  .buttons   > a, .buttons   > button,
  .actions   > a, .actions   > button,
  .action-row> a, .action-row> button,
  .toolbar   > a, .toolbar   > button,
  .card-actions > a, .card-actions > button,
  .header-actions > a, .header-actions > button,
  [class*="btn-group"] > a, [class*="btn-group"] > button,
  [class*="buttons"]   > a, [class*="buttons"]   > button,
  [class*="actions"]   > a, [class*="actions"]   > button,
  [class*="toolbar"]   > a, [class*="toolbar"]   > button {
    display: block !important; width: 100% !important; margin: 0 !important; text-align: center !important;
  }
  /* Casos comunes .flex con gap */
  .flex.gap-2,  .flex.gap-4 { flex-direction: column !important; align-items: stretch !important; }
  .flex.gap-2 > a, .flex.gap-2 > button,
  .flex.gap-4 > a, .flex.gap-4 > button { width: 100% !important; }

  /* Acciones en tablas (última columna) */
  table td:last-child .flex { flex-direction: column !important; gap: 8px !important; align-items: stretch !important; }
  table td:last-child .flex > a, table td:last-child .flex > button { width: 100% !important; }

  /* Modales / SweetAlert footers */
  .swal2-actions, .modal-actions, .modal-footer, .dialog-actions, [role="dialog"] .actions {
    display: flex !important; flex-direction: column !important; gap: 12px !important; align-items: stretch !important; width: 100%;
  }
  .swal2-actions .swal2-styled,
  .modal-actions button, .modal-footer button, .dialog-actions button, [role="dialog"] .actions button {
    width: 100% !important; display: block !important;
  }
}

/* =========================
   MAYÚSCULAS (scoped)
   ========================= */
/* Títulos en normal */
:is(h1,h2,h3,h4,h5,h6){ text-transform:none !important; letter-spacing:normal !important; }
/* Nombres (tarjeta + lista) en normal */
.client-card h3, .client-card h4, #client-list-view td:first-child a {
  text-transform: none !important; letter-spacing: normal !important;
}
/* Emails en minúsculas (tarjeta + lista) */
.client-card .client-email, .client-card p.email, #client-list-view td.email, a[href^="mailto:"] {
  text-transform: lowercase !important;
}
/* Chips/etiquetas (servicios) SÍ en mayúsculas */
.client-card .chip, .client-card .badge, .client-card .tag, .client-card .label, .client-card .service-badge {
  text-transform: uppercase !important; letter-spacing: .02em !important;
}

/* =========================
   TABLAS → TARJETAS EN MÓVIL
   ========================= */
@media (max-width: 640px) {
  /* Cualquier tabla de clientes/lista */
  .clients-section table, #client-list-view table, table.clients, table.responsive-stack {
    width: 100% !important; border-collapse: collapse; display: block;
  }
  .clients-section table thead, #client-list-view table thead, table.clients thead, table.responsive-stack thead {
    display: none !important;
  }
  .clients-section table tbody, #client-list-view table tbody, table.clients tbody, table.responsive-stack tbody {
    display: block; width: 100%;
  }
  .clients-section table tbody tr, #client-list-view table tbody tr, table.clients tbody tr, table.responsive-stack tbody tr {
    display: block; background: #fff; border-radius: 12px; margin: 10px 0; box-shadow: 0 8px 18px rgba(0,0,0,.06); overflow: hidden;
  }
  .clients-section table tbody td, #client-list-view table tbody td, table.clients tbody td, table.responsive-stack tbody td {
    display: grid; grid-template-columns: 42% 1fr; gap: 8px; padding: 10px 12px;
    border-bottom: 1px solid rgba(0,0,0,.06); align-items: start; white-space: normal;
  }
  .clients-section table tbody td:last-child, #client-list-view table tbody td:last-child, table.clients tbody td:last-child, table.responsive-stack tbody td:last-child {
    border-bottom: none;
  }
  /* Etiqueta de celda (rellenada por JS con data-label) */
  .clients-section table tbody td::before,
  #client-list-view table tbody td::before,
  table.clients tbody td::before,
  table.responsive-stack tbody td::before {
    content: attr(data-label);
    font-weight: 800; font-size: .72rem; letter-spacing: .02em; text-transform: uppercase; color: #6B7280;
  }
}

/* =========================
   Filtro mensual roto → ocultar UI (sin borrar nodos)
   ========================= */
#monthly-filter-select,
.month-filter select,
.clients-section .filter-month,
#recent-clients-filter .filter-month,
#recent-clients-filter select[name="month"] {
  display: none !important;
}
/* colapsar contenedor si queda espacio */
#recent-clients-filter, .clients-section .filters, .clients-section .filters .flex.items-center.justify-end {
  min-height: 0 !important; height: auto !important;
}

/* ===== CONFIRM DELETE MODAL: apilar botones en móvil ===== */
@media (max-width: 768px) {
  /* 1) Fuerza columna y elimina el espacio horizontal de Tailwind */
  #confirmDeleteModal .flex.justify-center.space-x-4 {
    display: flex !important;
    flex-direction: column !important;
    align-items: stretch !important;
    gap: 12px !important;       /* reemplaza space-x-* por gap vertical */
  }
  /* Tailwind space-x-* añade margin-left al 2º+ hijo; anúlalo */
  #confirmDeleteModal .flex.justify-center.space-x-4 > :not([hidden]) ~ :not([hidden]) {
    margin-left: 0 !important;
  }

  /* 2) Botones a 100% de ancho, bloque completo */
  #confirmDeleteModal .flex.justify-center.space-x-4 > button,
  #confirmDeleteModal .flex.justify-center.space-x-4 > a {
    width: 100% !important;
    display: block !important;
    text-align: center !important;
  }

  /* 3) Ajuste del cuadro para pantallas pequeñas (opcional) */
  #confirmDeleteModal .bg-white {
    max-width: 92vw !important;
    margin: 16px !important;
  }
}

</style>


</head>
<body data-page-title="Panel De Gestión De Clientes Actuales"
      data-page-subtitle="Registro E Información De Contacto De Tus Clientes Activos"
      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>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    
    <?php include 'cms-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 ACTIVOS
                            </h3>
                            <p class="text-gray-500 text-sm mt-1 uppercase">ACCESO RÁPIDO A FICHA Y DATOS DE CONTACTO.</p>
                        </div>
                        <div class="flex items-center gap-4 w-full md:w-auto">
                            <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 shadow-md flex items-center space-x-4 border-l-4 border-[var(--color-primary)]">
        <i data-lucide="users" class="w-12 h-12 text-gray-700"></i>
        <div>
            <h3 class="text-lg font-extrabold text-gray-500 mb-1">TOTAL DE CLIENTES</h3>
            <p id="total-clients-count" class="text-5xl font-bold text-[var(--color-secondary)]">0</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 shadow-md flex items-center space-x-4 border-l-4 border-red-500">
        <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 $initial_monthly_period_display; ?></span></h3>
            <p id="monthly-clients-count" class="text-5xl font-bold text-red-700">0</p>
            <p class="text-sm text-gray-400 mt-1 uppercase">CLIENTES AGREGADOS EN EL PERIODO SELECCIONADO</p>
        </div>
    </div>
    
</div>

                    <div class="flex justify-end mb-6">
                        <select id="monthly-filter-select" class="w-full md:w-64 p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                            </select>
                    </div>

                    <h3 class="text-xl font-extrabold text-gray-800 mb-4 flex items-center gap-2 mt-8">
                        <i data-lucide="history" class="w-6 h-6 text-[var(--color-secondary)]"></i> ÚLTIMOS CLIENTES
                    </h3>
                    <div id="recent-clients-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                    </div>

                    <div class="flex flex-col md:flex-row gap-4 mb-6">
                        <div class="relative flex-grow">
                            <input type="text" id="client-search" placeholder="Buscar Por Nombre..." class="w-full p-3 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                            <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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)] bg-white">
                            <option value="all">TODAS LAS LETRAS</option>
                            </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 transition-colors duration-200 active uppercase" title="Vista de Cuadrícula">
                                <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 transition-colors duration-200 uppercase" 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">
                            <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">EMAIL</th>
                                    <th class="py-3 px-6 font-semibold hidden lg:table-cell">TELÉFONO</th>
                                    <th class="py-3 px-6 font-semibold text-center">ACCIONES</th>
                                </tr>
                            </thead>
                            <tbody class="text-gray-700 text-sm" 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/2 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="p-8 flex flex-col h-full">
        <div class="flex justify-between items-center mb-6 flex-shrink-0">
            <h3 class="text-2xl font-bold text-[var(--color-primary)]">AGREGAR NUEVO CLIENTE</h3>
            <button onclick="closePanel('addClientePanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <form id="add-cliente-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
            <div class="mb-4 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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Buscar Prospecto...">
                <input type="hidden" id="cliente-selected-prospect-id" value="">
                <div id="prospect-search-results" class="absolute z-10 w-full bg-white border border-gray-300 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-x-6 gap-y-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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Primer Nombre" 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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Apellido" required>
                </div>
                <div class="md:col-span-2">
                    <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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="email@ejemplo.com">
                </div>
                <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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                </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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                </div>

                <div class="md:col-span-2 flex items-center pt-2 mb-4">
                    <input type="checkbox" id="cliente-is-recurring" class="h-5 w-5 text-[var(--color-primary)] focus:ring-[var(--color-highlight)] 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 class="md:col-span-2">
                    <label for="cliente-direccion-calle" class="block text-gray-700 text-sm font-bold mb-2 uppercase">DIRECCIÓN (CALLE Y NÚMERO)</label>
                    <input type="text" id="cliente-direccion-calle" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 123 Main St">
                </div>
                <div class="col-span-1">
                    <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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Springfield">
                </div>
                <div class="col-span-1">
                    <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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. IL">
                </div>
                <div class="md:col-span-2">
                    <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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 62701">
                </div>
            </div>
        </form>
        <div class="flex justify-end space-x-4 pt-6 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/2 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50">
    <div class="p-8 flex flex-col h-full">
        <div class="flex justify-between items-center mb-6 flex-shrink-0">
            <h3 class="text-2xl font-bold text-[var(--color-primary)] text-center w-full flex items-center justify-center gap-2 uppercase">
                <i data-lucide="user-circle" class="w-6 h-6 text-[var(--color-primary)]"></i> FICHA DEL CLIENTE
            </h3>
            <button onclick="closePanel('viewClienteReadOnlyPanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>

        <div class="flex-grow overflow-y-auto pr-2 -mr-2">
            <h2 id="readonly-cliente-full-name" class="text-4xl font-extrabold text-gray-900 mb-6 text-center uppercase"></h2>
            
            <div id="readonly-cliente-recurring-tag" class="text-center mb-4 hidden">
                <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-semibold bg-purple-100 text-purple-800 uppercase">
                    <i data-lucide="repeat" class="w-4 h-4 mr-1"></i> Cliente Recurrente
                </span>
            </div>

            <div class="bg-gray-50 p-6 rounded-lg mb-6">
                <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> INFORMACIÓN DE CONTACTO
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div id="readonly-cliente-email-group" class="flex items-center text-gray-700 text-base">
                        <i data-lucide="mail" class="w-5 h-5 text-gray-500 mr-2 flex-shrink-0"></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 text-base">
                        <i data-lucide="phone" class="w-5 h-5 text-gray-500 mr-2 flex-shrink-0"></i>
                        <p id="readonly-cliente-phone" class="font-medium"></p>
                    </div>
                    <div id="readonly-cliente-mobile-group" class="flex items-center text-gray-700 text-base">
                        <i data-lucide="smartphone" class="w-5 h-5 text-gray-500 mr-2 flex-shrink-0"></i>
                        <p id="readonly-cliente-mobile" class="font-medium"></p>
                    </div>
                    <div id="readonly-cliente-address-group" class="md:col-span-2 flex items-start text-gray-700 text-base">
                        <i data-lucide="map-pin" class="w-5 h-5 text-gray-500 mr-2 flex-shrink-0 mt-1"></i>
                        <p id="readonly-cliente-full-address" class="font-medium"></p>
                    </div>
                </div>
            </div>
            <div class="h-4"></div> 
        </div>

        <div class="flex justify-end space-x-4 pt-4 border-t border-gray-200 mt-6 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" id="edit-client-from-readonly-btn">EDITAR CLIENTE</button>
            <button type="button" class="btn-primary font-bold py-2 px-4 rounded-lg uppercase" onclick="closePanel('viewClienteReadOnlyPanel')">CERRAR</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 data-lucide="alert-triangle" class="w-16 h-16 text-red-500"></i>
        </div>
        <h3 class="text-2xl font-bold text-[var(--color-primary)] mb-4 uppercase">CONFIRMAR ELIMINACIÓN</h3>
        <p class="text-gray-700 mb-6 uppercase">¿ESTÁS SEGURO DE QUE DESEAS ELIMINAR ESTE <span id="confirm-item-type" class="font-semibold">ELEMENTO</span>? ESTA ACCIÓN NO SE PUEDE DESHACER.</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>

<div id="viewClientePanel" class="fixed inset-y-0 right-0 w-full md:w-1/2 bg-white shadow-lg transform translate-x-full transition-transform duration-300 ease-in-out z-50 overflow-y-auto">
    <div class="p-8 flex flex-col h-full">
        <div class="flex justify-between items-center mb-6 flex-shrink-0">
            <h3 class="text-2xl font-bold text-[var(--color-primary)]">EDITAR CLIENTE</h3>
            <button onclick="closePanel('viewClientePanel')" class="text-gray-400 hover:text-gray-600"><i data-lucide="x" class="w-6 h-6"></i></button>
        </div>
        <form id="view-cliente-form" class="flex-grow overflow-y-auto pr-2 -mr-2">
            <input type="hidden" id="view-cliente-id">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Primer Nombre">
                </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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Apellido">
                </div>
                <div class="md:col-span-2">
                    <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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="email@ejemplo.com">
                </div>
                <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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                </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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="(XXX) XXX-XXXX">
                </div>

                <div class="md:col-span-2 flex items-center pt-2 mb-4">
                    <input type="checkbox" id="view-cliente-is-recurring" class="h-5 w-5 text-[var(--color-primary)] focus:ring-[var(--color-highlight)] 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 class="md:col-span-2">
                    <label for="view-cliente-direccion-calle" class="block text-gray-700 text-sm font-bold mb-2 uppercase">DIRECCIÓN (CALLE Y NÚMERO)</label>
                    <input type="text" id="view-cliente-direccion-calle" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 123 Main St">
                </div>
                <div class="col-span-1">
                    <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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. Springfield">
                </div>
                <div class="col-span-1">
                    <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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. IL">
                </div>
                <div class="md:col-span-2">
                    <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 focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]" placeholder="Ej. 62701">
                </div>
            </div>
            <div class="h-4"></div>
        </form>
        <div class="flex justify-end space-x-4 pt-4 border-t border-gray-200 mt-6 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-primary font-bold py-2 px-4 rounded-lg uppercase">GUARDAR CAMBIOS</button>
        </div>
    </div>
</div>


<script>
    let clientsFromDB = <?php echo $clients_json; ?>;
    let prospectsFromDB = <?php echo $prospects_json; ?>;
    let totalClientsCount = <?php echo $total_clients_count_json; ?>;
    let monthlyClientsCount = <?php echo $monthly_clients_count_json; ?>;
    const monthsWithClients = <?php echo $months_with_clients_json; ?>;
    let selectedMonth = <?php echo $selected_month_js; ?>;
    let selectedYear = <?php echo $selected_year_js; ?>;

    // =================================================================
    // VARIABLES Y CACHÉ DE ELEMENTOS DEL DOM
    // =================================================================
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    const clientSearch = document.getElementById('client-search');
    const clientFilterApellidoLetter = document.getElementById('client-filter-apellido-letter');
    const recentClientsGrid = document.getElementById('recent-clients-grid');
    const clientGridView = document.getElementById('client-grid-view');
    const clientListView = document.getElementById('client-list-view');
    const clientsTableBody = document.getElementById('clientsTableBody');
    const gridViewBtn = document.getElementById('grid-view-btn');
    const listViewBtn = document.getElementById('list-view-btn');
    const downloadClientesBtn = document.getElementById('download-clientes-btn');
    const confirmDeleteButton = document.getElementById('confirm-delete-button');
    const confirmItemTypeSpan = document.getElementById('confirm-item-type');
    const viewClienteReadOnlyPanel = document.getElementById('viewClienteReadOnlyPanel');
    const addClienteForm = document.getElementById('add-cliente-form');
    const viewClienteForm = document.getElementById('view-cliente-form');
    const editClientFromReadonlyBtn = document.getElementById('edit-client-from-readonly-btn');
    const clienteProspectoSearchInput = document.getElementById('cliente-prospecto-search');
    const clienteSelectedProspectIdInput = document.getElementById('cliente-selected-prospect-id');
    const prospectSearchResultsDiv = document.getElementById('prospect-search-results');
    const totalClientsCountElement = document.getElementById('total-clients-count');
    const monthlyClientsCountElement = document.getElementById('monthly-clients-count');
    const monthlyPeriodDisplay = document.getElementById('monthly-period-display');
    const monthlyFilterSelect = document.getElementById('monthly-filter-select');
    const clienteIsRecurringCheckbox = document.getElementById('cliente-is-recurring');
    const viewClienteIsRecurringCheckbox = document.getElementById('view-cliente-is-recurring');
    const readonlyClienteRecurringTag = document.getElementById('readonly-cliente-recurring-tag');

    // Estado local
    let currentClientView = 'grid';
    let currentReadOnlyClientId = null;

    const panelOverlay = document.createElement('div');
    panelOverlay.id = 'panel-overlay';
    panelOverlay.className = 'fixed inset-0 bg-gray-900 bg-opacity-75 z-40 hidden';
    document.body.appendChild(panelOverlay);

    // =================================================================
    // FUNCIONES DE UTILIDAD
    // =================================================================

    window.openPanel = (panelId) => {
        const panel = document.getElementById(panelId);
        if (!panel) return;
        if (panelId === 'addClientePanel') {
            addClienteForm.reset();
            clienteProspectoSearchInput.value = '';
            clienteSelectedProspectIdInput.value = '';
            prospectSearchResultsDiv.innerHTML = '';
            prospectSearchResultsDiv.classList.add('hidden');
            clienteIsRecurringCheckbox.checked = false;
            applyPhoneFormatToInputs();
        }
        panel.classList.remove('translate-x-full');
        panelOverlay.classList.remove('hidden');
        lucide.createIcons();
    };

    window.closePanel = (panelId) => {
        const panel = document.getElementById(panelId);
        if (panel) {
            panel.classList.add('translate-x-full');
            panelOverlay.classList.add('hidden');
        }
    };

    window.openModal = (modalId) => {
        const modal = document.getElementById(modalId);
        if (modal) {
            const modalBox = modal.querySelector('div:first-of-type');
            modal.classList.remove('hidden');
            setTimeout(() => modalBox.classList.remove('scale-95', 'opacity-0'), 50);
            lucide.createIcons();
        }
    };

    window.closeModal = (modalId) => {
        const modal = document.getElementById(modalId);
        if (modal) {
            const modalBox = modal.querySelector('div:first-of-type');
            modalBox.classList.add('scale-95', 'opacity-0');
            setTimeout(() => modal.classList.add('hidden'), 300);
        }
    };

    window.openConfirmDeleteModal = (itemId, itemType) => {
        confirmDeleteButton.dataset.itemId = itemId;
        confirmDeleteButton.dataset.itemType = itemType;
        confirmItemTypeSpan.textContent = itemType.toUpperCase();
        openModal('confirmDeleteModal');
    };

    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 ?? '';
        viewClienteIsRecurringCheckbox.checked = client.is_recurring || false;

        closePanel('viewClienteReadOnlyPanel');
        openPanel('viewClientePanel');
        setTimeout(applyPhoneFormatToInputs, 100);
    };

    window.openClientDetailsModal = (clientId) => {
        const client = clientsFromDB[clientId];
        if (!client) return;
        currentReadOnlyClientId = clientId;

        document.getElementById('readonly-cliente-full-name').textContent = `${client.nombre ?? ''} ${client.apellido ?? ''}`.trim().toUpperCase();
        readonlyClienteRecurringTag.classList.toggle('hidden', !client.is_recurring);

        const emailGroup = document.getElementById('readonly-cliente-email-group');
        const emailEl = document.getElementById('readonly-cliente-email');
        emailGroup.classList.toggle('hidden', !client.email);
        emailEl.textContent = client.email ?? '';

        const phoneGroup = document.getElementById('readonly-cliente-phone-group');
        const phoneEl = document.getElementById('readonly-cliente-phone');
        const formattedPhone = formatPhoneNumber(client.phone);
        phoneGroup.classList.toggle('hidden', !formattedPhone);
        phoneEl.textContent = formattedPhone;

        const mobileGroup = document.getElementById('readonly-cliente-mobile-group');
        const mobileEl = document.getElementById('readonly-cliente-mobile');
        const formattedMobile = formatPhoneNumber(client.mobile);
        mobileGroup.classList.toggle('hidden', !formattedMobile);
        mobileEl.textContent = formattedMobile;

        const addressGroup = document.getElementById('readonly-cliente-address-group');
        const addressEl = document.getElementById('readonly-cliente-full-address');
        const addressParts = [client.direccion_calle, client.ciudad, client.state_province, client.zip_code].filter(Boolean);
        addressGroup.classList.toggle('hidden', addressParts.length === 0);
        addressEl.textContent = addressParts.join(', ').toUpperCase();

        lucide.createIcons();
        openPanel('viewClienteReadOnlyPanel');
    };

    const toggleSidebar = () => {
        sidebar?.classList.toggle('-translate-x-full');
        sidebarOverlay?.classList.toggle('hidden');
    };

    const renderClientCard = (client) => {
        const initial = (client.nombre?.charAt(0) || '').toUpperCase();
        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>` : '';

        return `<div class="client-card bg-white rounded-xl p-6 flex flex-col items-center text-center shadow-sm" data-client-id="${client.id}">
            <div class="client-avatar rounded-full flex items-center justify-center mb-4">
                <span>${initial}</span>
            </div>
            <h4 class="font-bold text-lg text-gray-800 uppercase">${fullName}${recurringTag}</h4>
            <p class="text-xs text-gray-500 mb-4 uppercase">${client.email ?? 'N/A'}</p>
            <div class="flex space-x-3 mt-auto w-full">
                <button class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 font-bold py-2 px-3 rounded-lg text-xs edit-client-btn uppercase" data-client-id="${client.id}">VER DETALLES</button>
                <button class="p-2 bg-red-100 hover:bg-red-200 text-red-600 rounded-lg delete-btn" data-item-type="cliente" 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 displayPhone = formatPhoneNumber(client.phone) || formatPhoneNumber(client.mobile) || 'N/A';
        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 `<tr class="border-b border-gray-200 hover:bg-gray-50" data-client-id="${client.id}">
            <td class="py-4 px-6 whitespace-nowrap">
                <span class="text-blue-600 hover:text-blue-800 cursor-pointer font-semibold uppercase client-name-link" data-client-id="${client.id}">${fullName}${recurringTag}</span>
            </td>
            <td class="py-4 px-6 hidden md:table-cell uppercase">${client.email ?? 'N/A'}</td>
            <td class="py-4 px-6 hidden lg:table-cell uppercase">${displayPhone}</td>
            <td class="py-4 px-6 text-center">
                <button class="text-blue-600 hover:text-blue-800 mr-3 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-red-600 hover:text-red-800 delete-btn" data-item-type="cliente" data-item-id="${client.id}" title="ELIMINAR CLIENTE"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
            </td>
        </tr>`;
    };

    const populateApellidoLetterFilter = () => {
        const initials = new Set(Object.values(clientsFromDB).map(c => (c.apellido?.charAt(0) || c.nombre?.charAt(0))?.toUpperCase()).filter(Boolean));
        const sortedInitials = Array.from(initials).sort();
        clientFilterApellidoLetter.innerHTML = '<option value="all">TODAS LAS LETRAS</option>' + sortedInitials.map(i => `<option value="${i}">${i}</option>`).join('');
    };

    const updateTotalClientsDisplay = () => totalClientsCountElement.textContent = totalClientsCount.toString();

    const updateMonthlyClientsDisplay = () => {
        monthlyClientsCountElement.textContent = monthlyClientsCount.toString();
        const monthNames = ["ENERO", "FEBRERO", "MARZO", "ABRIL", "MAYO", "JUNIO", "JULIO", "AGOSTO", "SEPTIEMBRE", "OCTUBRE", "NOVIEMBRE", "DICIEMBRE"];
        monthlyPeriodDisplay.textContent = selectedMonth >= 1 && selectedMonth <= 12 ? `${monthNames[selectedMonth - 1]} ${selectedYear}` : `PERIODO DESCONOCIDO`;
    };

    const populateMonthlyFilter = () => {
        const uniqueMonths = new Set(monthsWithClients.map(d => `${d.year}-${String(d.month).padStart(2, '0')}`));
        const now = new Date();
        uniqueMonths.add(`${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`);
        
        const sortedMonths = Array.from(uniqueMonths).map(dateStr => {
            const [year, month] = dateStr.split('-').map(Number);
            return { year, month, dateObj: new Date(year, month - 1, 1) };
        }).sort((a, b) => b.dateObj - a.dateObj);

        const monthNames = ["ENERO", "FEBRERO", "MARZO", "ABRIL", "MAYO", "JUNIO", "JULIO", "AGOSTO", "SEPTIEMBRE", "OCTUBRE", "NOVIEMBRE", "DICIEMBRE"];
        monthlyFilterSelect.innerHTML = sortedMonths.map(data =>
            `<option value="${data.year}-${String(data.month).padStart(2, '0')}" ${data.year === selectedYear && data.month === selectedMonth ? 'selected' : ''}>
                ${monthNames[data.month - 1]} ${data.year}
            </option>`
        ).join('');
    };

    const renderClients = (viewType = currentClientView) => {
        const searchTerm = clientSearch.value.toLowerCase();
        const selectedLetter = clientFilterApellidoLetter.value;
        const allClientsArray = Object.values(clientsFromDB);

        recentClientsGrid.innerHTML = allClientsArray.sort((a, b) => new Date(b.created_at) - new Date(a.created_at)).slice(0, 4)
            .map(renderClientCard).join('') || `<p class="text-gray-500 col-span-full text-center uppercase">NO HAY CLIENTES RECIENTES.</p>`;

        const filteredClients = allClientsArray.filter(c => {
            const fullName = `${c.nombre ?? ''} ${c.apellido ?? ''}`.trim().toLowerCase();
            const email = (c.email ?? '').toLowerCase();
            const matchesSearch = fullName.includes(searchTerm) || email.includes(searchTerm);
            const matchesLetter = selectedLetter === 'all' || (c.apellido || c.nombre || '').charAt(0).toUpperCase() === selectedLetter;
            return matchesSearch && matchesLetter;
        });

        if (viewType === 'grid') {
            clientGridView.innerHTML = filteredClients.map(renderClientCard).join('') || `<p class="text-gray-500 md:col-span-3 text-center uppercase">NO SE ENCONTRARON CLIENTES.</p>`;
        } else {
            clientsTableBody.innerHTML = filteredClients.map(renderClientTableRow).join('') || `<tr><td colspan="4" class="py-4 px-6 text-center text-gray-500 uppercase">NO SE ENCONTRARON CLIENTES.</td></tr>`;
        }

        clientGridView.classList.toggle('hidden', viewType !== 'grid');
        clientListView.classList.toggle('hidden', viewType !== 'list');
        gridViewBtn.classList.toggle('active', viewType === 'grid');
        listViewBtn.classList.toggle('active', viewType === 'list');
        lucide.createIcons();
    };

    const setupProspectSearch = () => {
        const fillClientForm = (prospect) => {
            document.getElementById('cliente-first-name').value = prospect.nombre ?? '';
            document.getElementById('cliente-last-name').value = prospect.apellido ?? '';
            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.direccion_calle ?? '';
            document.getElementById('cliente-ciudad').value = prospect.ciudad ?? '';
            document.getElementById('cliente-estado-field').value = prospect.state_province ?? '';
            document.getElementById('cliente-codigo-postal').value = prospect.zip_code ?? '';
            clienteSelectedProspectIdInput.value = prospect.id;
            clienteIsRecurringCheckbox.checked = false;
            applyPhoneFormatToInputs();
        };

        const searchProspects = (query) => {
            if (query.length < 2) {
                prospectSearchResultsDiv.classList.add('hidden');
                return;
            }
            const lowerCaseQuery = query.toLowerCase();
            const filteredResults = Object.values(prospectsFromDB).filter(p =>
                `${p.nombre ?? ''} ${p.apellido ?? ''}`.trim().toLowerCase().includes(lowerCaseQuery) ||
                (p.email ?? '').toLowerCase().includes(lowerCaseQuery)
            );
            if (filteredResults.length > 0) {
                prospectSearchResultsDiv.innerHTML = filteredResults.map(p => `<div class="p-2 cursor-pointer hover:bg-gray-100 uppercase text-sm" data-prospect-id="${p.id}">${p.nombre} ${p.apellido}</div>`).join('');
            } else {
                prospectSearchResultsDiv.innerHTML = `<div class="p-2 text-gray-500 text-sm italic">No se encontraron prospectos.</div>`;
            }
            prospectSearchResultsDiv.classList.remove('hidden');
        };

        clienteProspectoSearchInput.addEventListener('input', e => searchProspects(e.target.value));
        clienteProspectoSearchInput.addEventListener('focus', e => searchProspects(e.target.value));
        clienteProspectoSearchInput.addEventListener('blur', () => setTimeout(() => prospectSearchResultsDiv.classList.add('hidden'), 150));
        prospectSearchResultsDiv.addEventListener('mousedown', e => {
            const prospectItem = e.target.closest('[data-prospect-id]');
            if (prospectItem) {
                const prospect = prospectsFromDB[prospectItem.dataset.prospectId];
                if (prospect) {
                    fillClientForm(prospect);
                    clienteProspectoSearchInput.value = `${prospect.nombre ?? ''} ${prospect.apellido ?? ''}`.trim();
                    prospectSearchResultsDiv.classList.add('hidden');
                }
            }
        });
    };

    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]}` : cleaned;
    };

    const applyPhoneFormatToInputs = () => {
        ['cliente-phone', 'cliente-mobile', 'view-cliente-phone', 'view-cliente-mobile'].forEach(id => {
            const input = document.getElementById(id);
            if (input) {
                input.value = formatPhoneNumber(input.value);
                input.addEventListener('input', e => e.target.value = formatPhoneNumber(e.target.value.replace(/\D/g, '')));
            }
        });
    };
    
    const downloadCSV = (data, filename) => {
        if (data.length === 0) return;
        const headers = Object.keys(data[0]);
        const csvRows = [headers.join(',')];
        for (const row of data) {
            const values = headers.map(header => `"${(row[header] ?? '').toString().replace(/"/g, '""')}"`);
            csvRows.push(values.join(','));
        }
        const blob = new Blob(["\uFEFF" + csvRows.join('\n')], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    // =================================================================
    // INICIALIZACIÓN Y EVENTOS
    // =================================================================
    document.addEventListener('DOMContentLoaded', () => {
        <?php if ($db_error_message): ?>
            console.error("[clients.php] Error PHP: <?php echo addslashes($db_error_message); ?>");
        <?php endif; ?>

        mobileMenuButton.addEventListener('click', toggleSidebar);
        sidebarOverlay.addEventListener('click', toggleSidebar);
        panelOverlay.addEventListener('click', () => {
            closePanel('addClientePanel');
            closePanel('viewClientePanel');
            closePanel('viewClienteReadOnlyPanel');
        });

        populateApellidoLetterFilter();
        updateTotalClientsDisplay();
        populateMonthlyFilter();
        updateMonthlyClientsDisplay();
        renderClients(currentClientView);

        clientSearch.addEventListener('input', () => renderClients(currentClientView));
        clientFilterApellidoLetter.addEventListener('change', () => renderClients(currentClientView));
        monthlyFilterSelect.addEventListener('change', e => window.location.href = `cms-clients.php?year=${e.target.value.split('-')[0]}&month=${e.target.value.split('-')[1]}`);
        gridViewBtn.addEventListener('click', () => { currentClientView = 'grid'; renderClients('grid'); });
        listViewBtn.addEventListener('click', () => { currentClientView = 'list'; renderClients('list'); });

        const handleClientsContainerClick = e => {
            const deleteBtn = e.target.closest('.delete-btn');
            if (deleteBtn) {
                openConfirmDeleteModal(deleteBtn.dataset.itemId, deleteBtn.dataset.itemType);
                return;
            }
            const editBtn = e.target.closest('.edit-client-btn, .client-name-link');
            if (editBtn) openClientDetailsModal(editBtn.dataset.clientId);
        };
        recentClientsGrid.addEventListener('click', handleClientsContainerClick);
        clientGridView.addEventListener('click', handleClientsContainerClick);
        clientsTableBody.addEventListener('click', handleClientsContainerClick);

        setupProspectSearch();

        addClienteForm.addEventListener('submit', async e => {
            e.preventDefault();
            const newClientData = {
                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.replace(/\D/g, '') || null,
                mobile: document.getElementById('cliente-mobile').value.replace(/\D/g, '') || null,
                street_address: document.getElementById('cliente-direccion-calle').value || null,
                city: document.getElementById('cliente-ciudad').value || null,
                state_province: document.getElementById('cliente-estado-field').value || null,
                zip_code: document.getElementById('cliente-codigo-postal').value || null,
                prospect_id: clienteSelectedProspectIdInput.value,
                is_recurring: clienteIsRecurringCheckbox.checked
            };
            const response = await fetch('db/clients-create.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newClientData) });
            const result = await response.json();
            if (result.success) location.reload(); else console.error('Error:', result.message);
        });

        viewClienteForm.addEventListener('submit', async e => {
            e.preventDefault();
            const updatedClientData = {
                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.replace(/\D/g, '') || null,
                mobile: document.getElementById('view-cliente-mobile').value.replace(/\D/g, '') || null,
                street_address: document.getElementById('view-cliente-direccion-calle').value || null,
                city: document.getElementById('view-cliente-ciudad').value || null,
                state_province: document.getElementById('view-cliente-estado-field').value || null,
                zip_code: document.getElementById('view-cliente-codigo-postal').value || null,
                is_recurring: viewClienteIsRecurringCheckbox.checked
            };
            const response = await fetch('db/clients-update.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updatedClientData) });
            const result = await response.json();
            if (result.success) location.reload(); else console.error('Error:', result.message);
        });

        editClientFromReadonlyBtn.addEventListener('click', () => {
            if (currentReadOnlyClientId) openEditClienteModal(currentReadOnlyClientId);
        });

        downloadClientesBtn.addEventListener('click', () => {
            const dataToExport = Object.values(clientsFromDB).map(c => ({
                'ID': c.id, 'Nombre': c.nombre, 'Apellido': c.apellido, 'Email': c.email, 'Teléfono Fijo': c.phone,
                'Teléfono Móvil': c.mobile, 'Dirección': c.direccion_calle, 'Ciudad': c.ciudad, 'Estado': c.state_province,
                'Código Postal': c.zip_code, 'Recurrente': c.is_recurring ? 'Sí' : 'No', 'Fecha de Creación': c.created_at
            }));
            downloadCSV(dataToExport, 'clientes.csv');
        });
        
        confirmDeleteButton.addEventListener('click', async () => {
            const itemId = confirmDeleteButton.dataset.itemId;
            const response = await fetch('db/clients-delete.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: itemId }) });
            const result = await response.json();
            if (result.success) location.reload(); else console.error('Error:', result.message);
        });

        applyPhoneFormatToInputs();
        lucide.createIcons();
    });
</script>

<script>
(function(){
  function enhanceTables(ctx){
    (ctx || document).querySelectorAll('.clients-section table, table.responsive-stack').forEach(function(tb){
      tb.classList.add('responsive-stack');
      var heads = Array.from(tb.querySelectorAll('thead th')).map(function(th){ return (th.textContent||'').trim(); });
      tb.querySelectorAll('tbody tr').forEach(function(tr){
        Array.from(tr.children).forEach(function(td, i){
          if (!td.hasAttribute('data-label')) td.setAttribute('data-label', heads[i] || '');
        });
      });
    });
  }
  enhanceTables(document);
  var mo = new MutationObserver(function(muts){
    muts.forEach(function(m){ m.addedNodes.forEach(function(n){ if(n.nodeType===1 && n.querySelector('table')) enhanceTables(n); }); });
  });
  try { mo.observe(document.body, {childList: true, subtree: true}); } catch(e) {}
  try { if (window.lucide) window.lucide.createIcons(); } catch(e){}
})();
</script>

</body>
</html>