<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/format.php';
require_once __DIR__ . '/_customer_quick_fields.php';
require_once '../../services/crm/CrmService.php';

require_login();
require_permission('module.customers');

$page_title = 'Clientes';

$crm = new CrmService();
$customers = $crm->getCustomers();

$q = isset($_GET['q']) ? trim($_GET['q']) : '';
$restock_filter = isset($_GET['restock_filter']) ? trim($_GET['restock_filter']) : ''; 
$has_opps = isset($_GET['has_opps']) ? trim($_GET['has_opps']) : ''; 
$country_filter = isset($_GET['country']) ? trim((string) $_GET['country']) : '';
$region_filter = isset($_GET['region']) ? trim((string) $_GET['region']) : '';

$availableCountries = array();
$availableRegions = array();
foreach ($customers as $customerOption) {
    $optionCountry = trim((string)($customerOption['country'] ?? ''));
    $optionRegion = trim((string)($customerOption['region'] ?? ''));
    if ($optionCountry !== '') $availableCountries[$optionCountry] = $optionCountry;
    if ($optionRegion !== '') $availableRegions[$optionRegion] = $optionRegion;
}
asort($availableCountries);
asort($availableRegions);

$filteredCustomers = array();

foreach ($customers as $customer) {
    // 1. Búsqueda por texto
    $searchText = strtolower(
        ($customer['customer_name'] ?? '') . ' ' .
        ($customer['commercial_name'] ?? '') . ' ' .
        ($customer['legal_name'] ?? '') . ' ' .
        ($customer['customer_tax_id'] ?? '') . ' ' .
        ($customer['email'] ?? '') . ' ' .
        ($customer['city'] ?? '') . ' ' .
        ($customer['district'] ?? '') . ' ' .
        ($customer['region'] ?? '') . ' ' .
        ($customer['country'] ?? '')
    );

    if ($q !== '' && strpos($searchText, strtolower($q)) === false) {
        continue;
    }

    // 2. Lógica del Semáforo de Reposición (Cálculo previo)
    $nextRestock = $customer['next_restock_date'] ?? null;
    $daysLeft = null;
    $statusCat = 'none'; // Gris por defecto

    if ($nextRestock) {
        $today = new DateTime();
        $today->setTime(0, 0, 0); 
        $targetDate = new DateTime($nextRestock);
        $targetDate->setTime(0, 0, 0);
        $diff = $today->diff($targetDate);
        $daysLeft = (int)$diff->format('%R%a'); 

        if ($daysLeft < 0) {
            $statusCat = 'overdue'; 
        } elseif ($daysLeft <= 10) {
            $statusCat = 'soon'; 
        } else {
            $statusCat = 'ok'; 
        }
    }

    // 3. Aplicar Filtros
    if ($restock_filter !== '' && $restock_filter !== $statusCat) continue;
    
    $openOpps = isset($customer['open_opportunities']) ? (int) $customer['open_opportunities'] : 0;
    if ($has_opps === 'yes' && $openOpps === 0) continue;
    if ($has_opps === 'no' && $openOpps > 0) continue;

    if ($country_filter !== '' && trim((string)($customer['country'] ?? '')) !== $country_filter) continue;
    if ($region_filter !== '' && trim((string)($customer['region'] ?? '')) !== $region_filter) continue;

    $customer['calc_has_coordinates'] = !empty($customer['latitude']) && !empty($customer['longitude']) && is_numeric($customer['latitude']) && is_numeric($customer['longitude']);
    $customer['calc_status_cat'] = $statusCat;
    $customer['calc_days_left'] = $daysLeft;

    $filteredCustomers[] = $customer;
}

require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';

?>

<main class="app-main" id="customers-main">

    <style>
    /* ==========================================================================
       Clientes - layout estricto con scroll interno de tabla
       ========================================================================== */
    #customers-main {
        height: 100vh;
        height: 100dvh;
        max-height: 100dvh;
        overflow: hidden !important;
        display: flex;
        flex-direction: column;
    }

    #customers-main .content {
        flex: 1 1 0% !important;
        display: flex !important;
        flex-direction: column !important;
        overflow: hidden !important;
        min-height: 0 !important;
        padding-bottom: 12px;
    }

    #customers-main .card-table-container {
        flex: 1 1 0% !important;
        display: flex !important;
        flex-direction: column !important;
        overflow: hidden !important;
        min-height: 0 !important;
        margin-bottom: 0 !important;
    }

    #customers-main .table-container-scroll {
        flex: 1 1 auto !important;
        overflow-y: auto !important;
        overflow-x: auto !important;
        min-height: 0 !important;
    }

    #customers-main .table-container-scroll thead th {
        position: sticky;
        top: 0;
        z-index: 10;
        background: var(--surface-2);
        box-shadow: 0 1px 0 var(--border-subtle);
    }

    /* ==========================================================================
       Modal crear cliente
       ========================================================================== */
    .product-modal-backdrop {
        position: fixed;
        inset: 0;
        background: rgba(0,0,0,0.6);
        backdrop-filter: blur(4px);
        z-index: var(--z-modal);
        display: none;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity var(--motion-base);
    }

    .product-modal-backdrop.show { opacity: 1; }

    .product-modal-box {
        background: var(--surface-1);
        width: 980px;
        max-width: min(96vw, 980px);
        max-height: 90vh;
        border: 1px solid var(--border-default);
        border-radius: var(--radius-xl);
        box-shadow: var(--shadow-lg);
        display: flex;
        flex-direction: column;
        transform: translateY(20px);
        transition: transform var(--motion-base);
    }

    .product-modal-backdrop.show .product-modal-box { transform: translateY(0); }
    .product-modal-header { padding: var(--space-5); border-bottom: 1px solid var(--border-subtle); display: flex; justify-content: space-between; align-items: flex-start; }
    .product-modal-body { padding: var(--space-5); overflow-y: auto; flex: 1; }
    .product-modal-footer { padding: var(--space-4) var(--space-5); border-top: 1px solid var(--border-subtle); display: flex; justify-content: flex-end; gap: var(--space-3); background: var(--surface-0); border-radius: 0 0 var(--radius-xl) var(--radius-xl); }

    /* ==========================================================================
       P8.1 - Filtros clientes: escritorio ordenado + móvil colapsable
       ========================================================================== */
    #customers-main .customer-filter-card {
        flex-shrink: 0;
        margin-bottom: 10px !important;
    }

    #customers-main .customer-filter-card .card-body {
        padding: 14px 16px !important;
    }

    #customers-main .customer-filters-compact {
        display: grid !important;
        grid-template-columns: minmax(300px, 380px) minmax(0, 1fr) !important;
        gap: 12px !important;
        align-items: center !important;
        width: 100% !important;
        margin: 0 !important;
    }

    #customers-main .customer-filter-main-row {
        display: grid !important;
        grid-template-columns: minmax(0, 1fr) !important;
        gap: 10px !important;
        align-items: stretch !important;
        width: 100% !important;
        min-width: 0 !important;
    }

    #customers-main .customer-filter-search-field {
        min-width: 0 !important;
        width: 100% !important;
    }

    #customers-main .customer-filter-search-field .input {
        width: 100% !important;
    }

    #customers-main .customer-filter-toggle {
        display: none !important;
    }

    #customers-main .customer-filter-panel {
        display: grid !important;
        grid-template-columns: repeat(4, minmax(128px, 1fr)) minmax(96px, auto) minmax(90px, auto) !important;
        gap: 10px !important;
        align-items: stretch !important;
        min-width: 0 !important;
        width: 100% !important;
    }

    #customers-main .customer-filter-panel .form-field {
        min-width: 0 !important;
        width: 100% !important;
    }

    #customers-main .customer-filter-panel .select,
    #customers-main .customer-filter-panel .btn {
        width: 100% !important;
        height: 42px !important;
        min-height: 42px !important;
    }

    #customers-main .customer-filter-apply,
    #customers-main .customer-filter-clear {
        white-space: nowrap !important;
        justify-content: center !important;
    }

    @media (max-width: 1180px) and (min-width: 761px) {
        #customers-main .customer-filters-compact {
            grid-template-columns: 1fr !important;
        }

        #customers-main .customer-filter-main-row {
            max-width: 420px !important;
        }

        #customers-main .customer-filter-panel {
            grid-template-columns: repeat(4, minmax(130px, 1fr)) auto auto !important;
        }
    }

    /* ==========================================================================
       Móvil
       ========================================================================== */
    @media (max-width: 760px) {
        #customers-main .content {
            padding-bottom: 8px !important;
        }

        #customers-main .page-header {
            display: flex !important;
            flex-direction: row !important;
            flex-wrap: nowrap !important;
            justify-content: space-between !important;
            align-items: flex-start !important;
            margin-bottom: 10px !important;
        }

        #customers-main .page-header-content {
            flex: 1;
            min-width: 0;
            padding-right: 12px;
        }

        #customers-main .page-header-content h1 {
            font-size: 1.35rem !important;
            line-height: 1.2 !important;
            margin-bottom: 4px !important;
            word-break: break-word;
        }

        #customers-main .page-header-content p {
            display: none !important;
        }

        #customers-main .actions-cluster {
            flex-shrink: 0;
            display: flex !important;
            gap: 8px !important;
        }

        #customers-main .mobile-hidden {
            display: none !important;
        }

        #customers-main .icon-btn-mobile {
            padding: 0 !important;
            width: 44px;
            height: 44px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #customers-main .customer-filter-card {
            margin-bottom: 8px !important;
        }

        #customers-main .customer-filter-card .card-body {
            padding: 10px !important;
        }

        #customers-main .customer-filters-compact {
            display: grid !important;
            grid-template-columns: 1fr !important;
            gap: 8px !important;
            width: 100% !important;
        }

        #customers-main .customer-filter-main-row {
            display: grid !important;
            grid-template-columns: minmax(0, 1fr) 46px !important;
            gap: 8px !important;
            width: 100% !important;
            max-width: none !important;
        }

        #customers-main .customer-filter-search-field .input {
            width: 100% !important;
            height: 46px !important;
            min-height: 46px !important;
            padding-left: 14px !important;
            padding-right: 12px !important;
            font-size: 0.92rem !important;
        }

        #customers-main .customer-filter-toggle {
            display: inline-flex !important;
            width: 46px !important;
            min-width: 46px !important;
            height: 46px !important;
            min-height: 46px !important;
            padding: 0 !important;
            align-items: center !important;
            justify-content: center !important;
            border-radius: 14px !important;
        }

        #customers-main .customer-filter-toggle svg {
            width: 19px !important;
            height: 19px !important;
        }

        #customers-main .customer-filter-toggle span,
        #customers-main .customer-filter-toggle strong {
            display: none !important;
        }

        #customers-main .customer-filter-panel {
            display: none !important;
            grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
            gap: 8px !important;
            width: 100% !important;
            padding-top: 8px !important;
            margin-top: 2px !important;
            border-top: 1px solid var(--border-subtle) !important;
        }

        #customers-main .customer-filters-compact.is-expanded .customer-filter-panel {
            display: grid !important;
        }

        #customers-main .customer-filter-panel > .form-field {
            grid-column: auto !important;
            width: 100% !important;
            min-width: 0 !important;
        }

        #customers-main .customer-filter-panel .select {
            height: 42px !important;
            min-height: 42px !important;
            width: 100% !important;
            font-size: 0.82rem !important;
            padding-left: 10px !important;
            padding-right: 26px !important;
        }

        #customers-main .customer-filter-apply {
            grid-column: 1 / -1 !important;
            width: 100% !important;
            height: 44px !important;
            min-height: 44px !important;
            justify-content: center !important;
            margin-top: 2px !important;
        }

        #customers-main .customer-filter-clear {
            grid-column: 1 / -1 !important;
            width: 100% !important;
            height: 42px !important;
            min-height: 42px !important;
            justify-content: center !important;
        }

        #customers-main .card-table-container {
            flex: 1 1 0% !important;
            min-height: 0 !important;
        }

        #customers-main .card-table-container .card-header {
            padding-top: 10px !important;
            padding-bottom: 6px !important;
        }

        #customers-main .table-container-scroll {
            flex: 1 1 auto !important;
            min-height: 0 !important;
        }

        #customers-main .table-mobile-compact {
            min-width: 100% !important;
            table-layout: fixed;
        }

        #customers-main .table-mobile-compact th.col-cliente { width: 58% !important; }
        #customers-main .table-mobile-compact th.col-opps { width: 24% !important; padding-left: 4px; padding-right: 4px; }
        #customers-main .table-mobile-compact th.col-action { width: 18% !important; }
        #customers-main .table-mobile-compact td.cell-opps { white-space: normal !important; font-size: 0.75rem; line-height: 1.2; }

        .product-modal-footer {
            display: flex !important;
            flex-direction: row !important;
            justify-content: flex-end !important;
            align-items: center !important;
            gap: 8px !important;
            padding: var(--space-3) var(--space-4) !important;
        }

        .modal-footer-actions-right {
            display: flex !important;
            gap: 8px !important;
            justify-content: flex-end !important;
            flex: 1;
        }

        .modal-footer-actions-right .btn {
            padding: 0 var(--space-3) !important;
            height: 42px !important;
            font-size: 0.85rem !important;
            white-space: nowrap !important;
        }
    }


    /* ==========================================================================
       P8.1.1 - Customer filters full-width correction
       ========================================================================== */

    #customers-main .customer-filter-card {
        width: 100% !important;
        max-width: none !important;
        flex-shrink: 0 !important;
    }

    #customers-main .customer-filter-card .card-body {
        width: 100% !important;
        max-width: none !important;
        padding: 16px 13px !important;
    }

    #customers-main .customer-filters-compact {
        width: 100% !important;
        max-width: none !important;
        margin: 0 !important;
        display: grid !important;
        grid-template-columns: minmax(360px, 1.1fr) minmax(0, 2.9fr) !important;
        gap: 16px !important;
        align-items: center !important;
    }

    #customers-main .customer-filter-main-row {
        width: 100% !important;
        max-width: none !important;
        min-width: 0 !important;
        display: grid !important;
        grid-template-columns: minmax(0, 1fr) !important;
        gap: 10px !important;
        align-items: stretch !important;
    }

    #customers-main .customer-filter-search-field,
    #customers-main .customer-filter-search-field .input {
        width: 100% !important;
        max-width: none !important;
        min-width: 0 !important;
    }

    #customers-main .customer-filter-panel {
        width: 100% !important;
        max-width: none !important;
        min-width: 0 !important;
        display: grid !important;
        grid-template-columns:
            minmax(132px, 1fr)
            minmax(132px, 1fr)
            minmax(132px, 1fr)
            minmax(132px, 1fr)
            minmax(164px, auto)
            minmax(112px, auto) !important;
        gap: 10px !important;
        align-items: stretch !important;
    }

    #customers-main .customer-filter-panel > .form-field,
    #customers-main .customer-filter-panel .select {
        width: 100% !important;
        max-width: none !important;
        min-width: 0 !important;
    }

    #customers-main .customer-filter-apply,
    #customers-main .customer-filter-clear {
        width: 100% !important;
        justify-content: center !important;
        white-space: nowrap !important;
    }

    #customers-main .customer-filter-apply {
        min-width: 164px !important;
    }

    #customers-main .customer-filter-clear {
        min-width: 112px !important;
    }

    @media (min-width: 1360px) {
        #customers-main .customer-filters-compact {
            grid-template-columns: minmax(430px, 1.15fr) minmax(0, 2.85fr) !important;
        }
    }

    @media (max-width: 1180px) and (min-width: 761px) {
        #customers-main .customer-filters-compact {
            grid-template-columns: 1fr !important;
            gap: 12px !important;
        }

        #customers-main .customer-filter-main-row {
            max-width: none !important;
        }

        #customers-main .customer-filter-panel {
            grid-template-columns:
                repeat(4, minmax(0, 1fr))
                minmax(150px, auto)
                minmax(110px, auto) !important;
        }
    }

    @media (max-width: 760px) {
        #customers-main .customer-filter-card .card-body {
            padding: 10px !important;
        }

        #customers-main .customer-filters-compact {
            display: flex !important;
            flex-direction: column !important;
            width: 100% !important;
            max-width: none !important;
            gap: 10px !important;
        }

        #customers-main .customer-filter-main-row {
            display: grid !important;
            grid-template-columns: minmax(0, 1fr) 46px !important;
            gap: 8px !important;
            width: 100% !important;
            max-width: none !important;
        }

        #customers-main .customer-filter-toggle {
            display: inline-flex !important;
            width: 46px !important;
            min-width: 46px !important;
            height: 46px !important;
            min-height: 46px !important;
            padding: 0 !important;
            align-items: center !important;
            justify-content: center !important;
            border-radius: 14px !important;
        }

        #customers-main .customer-filter-main-row .input {
            width: 100% !important;
            max-width: none !important;
            height: 46px !important;
            min-height: 46px !important;
        }

        #customers-main .customer-filter-panel {
            display: none !important;
            width: 100% !important;
            max-width: none !important;
            grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
            gap: 8px !important;
            padding-top: 10px !important;
            border-top: 1px solid var(--border-subtle) !important;
        }

        #customers-main .customer-filters-compact.is-expanded .customer-filter-panel {
            display: grid !important;
        }

        #customers-main .customer-filter-panel > .form-field {
            width: 100% !important;
            min-width: 0 !important;
        }

        #customers-main .customer-filter-panel .select {
            width: 100% !important;
            height: 42px !important;
            min-height: 42px !important;
            font-size: 0.82rem !important;
        }

        #customers-main .customer-filter-apply {
            grid-column: 1 / -1 !important;
            width: 100% !important;
            min-width: 0 !important;
            height: 44px !important;
            min-height: 44px !important;
        }

        #customers-main .customer-filter-clear {
            grid-column: 1 / -1 !important;
            width: 100% !important;
            min-width: 0 !important;
            height: 42px !important;
            min-height: 42px !important;
        }
    }



    /* =========================================================
       P23 - Clientes: modales homologados a Cotizaciones final
       Referencia: quotesModalBackdrop / quotes-modal-box.
       Header/footer fijos; body con scroll interno; footer estable.
       ========================================================= */
    #customers-main #customerModal.product-modal-backdrop {
        position: fixed !important;
        inset: 0 !important;
        display: none;
        align-items: center !important;
        justify-content: center !important;
        padding: 24px !important;
        overflow: hidden !important;
        background: rgba(0, 0, 0, 0.68) !important;
        backdrop-filter: blur(5px) !important;
        z-index: 1050 !important;
        opacity: 0;
        transition: opacity 0.2s ease !important;
    }

    #customers-main #customerModal.product-modal-backdrop.show {
        display: flex !important;
        opacity: 1 !important;
    }

    #customers-main #customerModal > .product-modal-box {
        width: min(980px, calc(100vw - 48px)) !important;
        max-width: calc(100vw - 48px) !important;
        height: min(700px, calc(100dvh - 100px)) !important;
        min-height: min(700px, calc(100dvh - 100px)) !important;
        max-height: calc(100dvh - 100px) !important;
        display: flex !important;
        flex-direction: column !important;
        overflow: hidden !important;
        border-radius: var(--radius-xl) !important;
        background: var(--surface-1) !important;
        border: 1px solid var(--border-default) !important;
        box-shadow: var(--shadow-lg) !important;
    }

    #customers-main #customerModal .product-modal-header {
        flex: 0 0 auto !important;
        min-height: 78px !important;
        padding: 20px 24px !important;
        display: flex !important;
        flex-direction: row !important;
        align-items: flex-start !important;
        justify-content: space-between !important;
        gap: 14px !important;
        border-bottom: 1px solid var(--border-subtle) !important;
        background: var(--surface-1) !important;
    }

    #customers-main #customerModal .product-modal-body {
        flex: 1 1 auto !important;
        min-height: 0 !important;
        max-height: none !important;
        padding: 20px 24px !important;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        -webkit-overflow-scrolling: touch !important;
        overscroll-behavior: contain !important;
    }

    #customers-main #customerModal .product-modal-footer {
        flex: 0 0 auto !important;
        min-height: 76px !important;
        height: auto !important;
        max-height: none !important;
        padding: 14px 20px !important;
        display: flex !important;
        flex-direction: row !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 12px !important;
        flex-wrap: nowrap !important;
        background: var(--surface-0) !important;
        border-top: 1px solid var(--border-subtle) !important;
        border-radius: 0 0 var(--radius-xl) var(--radius-xl) !important;
        overflow: visible !important;
    }

    #customers-main #customerModal .modal-footer-actions-right {
        flex: 0 1 auto !important;
        width: auto !important;
        min-width: 0 !important;
        margin-left: auto !important;
        display: flex !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 12px !important;
        overflow: visible !important;
        flex-wrap: nowrap !important;
    }

    #customers-main #customerModal .product-modal-footer .btn {
        width: auto !important;
        min-width: 118px !important;
        max-width: none !important;
        height: 48px !important;
        min-height: 48px !important;
        padding: 0 18px !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        gap: 8px !important;
        flex: 0 0 auto !important;
        white-space: nowrap !important;
        text-align: center !important;
        overflow: visible !important;
        text-overflow: clip !important;
        border-radius: var(--radius-lg) !important;
    }

    #customers-main #customerModal .product-modal-footer .btn-primary {
        min-width: 178px !important;
    }

    #customers-main #customerModal .product-modal-footer .btn span {
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        min-width: 0 !important;
        max-width: none !important;
        overflow: visible !important;
        text-overflow: clip !important;
        white-space: nowrap !important;
        text-align: center !important;
    }

    @media (max-width: 760px) {
        #customers-main #customerModal.product-modal-backdrop {
            align-items: center !important;
            justify-content: center !important;
            padding: 12px !important;
        }

        #customers-main #customerModal > .product-modal-box {
            width: calc(100vw - 24px) !important;
            max-width: calc(100vw - 24px) !important;
            height: calc(100dvh - 200px) !important;
            min-height: 0 !important;
            max-height: calc(100dvh - 200px) !important;
            border-radius: 18px !important;
        }

        #customers-main #customerModal .product-modal-header {
            min-height: 64px !important;
            padding: 14px !important;
            align-items: flex-start !important;
            gap: 10px !important;
        }

        #customers-main #customerModal .product-modal-header .h3,
        #customers-main #customerModal .product-modal-header h2 {
            font-size: 1.05rem !important;
            line-height: 1.14 !important;
            margin-bottom: 2px !important;
        }

        #customers-main #customerModal .product-modal-header .text-sm {
            font-size: 0.78rem !important;
            line-height: 1.15 !important;
        }

        #customers-main #customerModal .product-modal-body {
            padding: 14px !important;
        }

        #customers-main #customerModal .product-modal-footer {
            min-height: 68px !important;
            padding: 10px 12px calc(10px + env(safe-area-inset-bottom)) !important;
            gap: 10px !important;
            overflow: visible !important;
        }

        #customers-main #customerModal .modal-footer-actions-right {
            gap: 10px !important;
            flex: 0 1 auto !important;
            min-width: 0 !important;
        }

        #customers-main #customerModal .product-modal-footer .btn {
            height: 44px !important;
            min-height: 44px !important;
            min-width: 106px !important;
            max-width: none !important;
            padding: 0 14px !important;
            font-size: 0.94rem !important;
            flex: 0 0 auto !important;
        }

        #customers-main #customerModal .product-modal-footer .btn-primary {
            min-width: 124px !important;
        }

        #customers-main #customerModal .product-modal-footer .btn span {
            display: inline-flex !important;
            overflow: visible !important;
            text-overflow: clip !important;
            max-width: none !important;
        }
    }


    </style>

    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content">

        <div class="page-header">
            <div class="page-header-content">
                <span class="label">Comercial</span>
                <h1>Clientes</h1>
                <p class="text-secondary">Agenda comercial de clientes y oportunidades.</p>
            </div>

            <div class="cluster actions-cluster">
                <a class="btn btn-outline icon-btn-mobile" href="/modules/customers/territory.php" title="Mapa y territorio">
                    <i data-lucide="map"></i>
                    <span class="mobile-hidden">Territorio</span>
                </a>
                <button type="button" class="btn btn-primary icon-btn-mobile" onclick="openCustomerModal()" title="Crear Cliente">
                    <i data-lucide="plus"></i>
                    <span class="mobile-hidden">Crear Cliente</span>
                </button>
            </div>
        </div>

        <?php $hasAdvancedFilters = ($restock_filter !== '' || $has_opps !== '' || $country_filter !== '' || $region_filter !== ''); ?>
        <section class="card mb-3 customer-filter-card" style="flex-shrink: 0;">
            <div class="card-body">
                <form method="GET" class="customer-filters-compact <?php echo $hasAdvancedFilters ? 'is-expanded' : ''; ?>" id="customerFiltersForm" style="margin-bottom: 0;">
                    <div class="customer-filter-main-row">
                        <div class="form-field customer-filter-search-field">
                            <input
                                type="text"
                                id="customerLiveSearch"
                                name="q"
                                class="input"
                                placeholder="Buscar cliente, RUT, email, ciudad..."
                                value="<?php echo safe_text($q); ?>"
                                autocomplete="off"
                            >
                        </div>

                        <button
                            type="button"
                            class="btn btn-outline customer-filter-toggle"
                            id="customerFiltersToggle"
                            aria-expanded="<?php echo $hasAdvancedFilters ? 'true' : 'false'; ?>"
                            aria-controls="customerAdvancedFilters"
                            title="Mostrar filtros"
                        >
                            <i data-lucide="sliders-horizontal"></i>
                            <span>Filtros</span>
                            <?php if ($hasAdvancedFilters): ?>
                                <strong><?php echo (int) (($restock_filter !== '' ? 1 : 0) + ($has_opps !== '' ? 1 : 0) + ($country_filter !== '' ? 1 : 0) + ($region_filter !== '' ? 1 : 0)); ?></strong>
                            <?php endif; ?>
                        </button>
                    </div>

                    <div class="customer-filter-panel" id="customerAdvancedFilters">
                        <div class="form-field">
                            <select name="restock_filter" class="select">
                                <option value="">Reposición: todos</option>
                                <option value="overdue" <?php echo $restock_filter === 'overdue' ? 'selected' : ''; ?>>Atrasados</option>
                                <option value="soon" <?php echo $restock_filter === 'soon' ? 'selected' : ''; ?>>Próximos 10 días</option>
                                <option value="ok" <?php echo $restock_filter === 'ok' ? 'selected' : ''; ?>>Al día</option>
                                <option value="none" <?php echo $restock_filter === 'none' ? 'selected' : ''; ?>>Sin ciclo definido</option>
                            </select>
                        </div>

                        <div class="form-field">
                            <select name="has_opps" class="select">
                                <option value="">Oportunidades: todas</option>
                                <option value="yes" <?php echo $has_opps === 'yes' ? 'selected' : ''; ?>>Con oportunidades</option>
                                <option value="no" <?php echo $has_opps === 'no' ? 'selected' : ''; ?>>Sin oportunidades</option>
                            </select>
                        </div>

                        <div class="form-field">
                            <select name="country" class="select">
                                <option value="">País: todos</option>
                                <?php foreach ($availableCountries as $countryOption): ?>
                                    <option value="<?php echo safe_text($countryOption); ?>" <?php echo $country_filter === $countryOption ? 'selected' : ''; ?>><?php echo safe_text($countryOption); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-field">
                            <select name="region" class="select">
                                <option value="">Región: todas</option>
                                <?php foreach ($availableRegions as $regionOption): ?>
                                    <option value="<?php echo safe_text($regionOption); ?>" <?php echo $region_filter === $regionOption ? 'selected' : ''; ?>><?php echo safe_text($regionOption); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <button type="submit" class="btn btn-primary customer-filter-apply">Aplicar filtros</button>
                        <?php if ($q !== '' || $hasAdvancedFilters): ?>
                            <a href="/modules/customers/index.php" class="btn btn-outline customer-filter-clear">Limpiar</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </section>

        <section class="card card-table-container">
            <div class="card-header" style="padding-bottom: 0; border-bottom: 0; flex-shrink: 0;">
                <span class="text-secondary text-sm"><span id="customersFoundCount"><?php echo count($filteredCustomers); ?></span> clientes encontrados</span>
            </div>

            <div class="table-wrap table-container-scroll" style="margin-top: 12px; border: 0; border-top: 1px solid var(--border-default); border-radius: 0;">
                <table class="table table-mobile-compact">
                    <thead>
                        <tr>
                            <th class="col-cliente" style="width: 35%;">Cliente</th>
                            <th class="mobile-hidden" style="width: 18%;">Ciudad / País</th>
                            <th class="mobile-hidden" style="width: 18%;">Última compra</th>
                            <th class="col-opps" style="width: 15%; text-align: center;">Oportunidades</th>
                            <th class="col-action text-right" style="width: 10%;">Acción</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php foreach ($filteredCustomers as $customer): ?>
                            <?php
                                $customerName = !empty($customer['commercial_name']) ? $customer['commercial_name'] : $customer['customer_name'];
                                $legalName = !empty($customer['legal_name']) ? $customer['legal_name'] : '';
                                $lastPurchase = !empty($customer['last_purchase_date']) ? $customer['last_purchase_date'] : '';
                                $openOpps = isset($customer['open_opportunities']) ? (int) $customer['open_opportunities'] : 0;
                                $initial = mb_substr($customerName, 0, 1, 'UTF-8');
                                
                                $statusCat = $customer['calc_status_cat'];
                                $daysLeft = $customer['calc_days_left'];

                                $dotColor = 'var(--surface-4)';
                                $dotTitle = 'Sin fecha calculada';
                                $avatarBg = '';
                                $avatarColor = '';

                                if ($statusCat === 'overdue') {
                                    $dotColor = 'var(--color-error)';
                                    $dotTitle = '¡Atrasado por ' . abs($daysLeft) . ' días!';
                                    $avatarBg = 'rgba(255, 77, 79, 0.18)'; 
                                    $avatarColor = 'var(--color-error)';   
                                } elseif ($statusCat === 'soon') {
                                    $dotColor = 'var(--color-warning)';
                                    $dotTitle = 'Llamar pronto (' . $daysLeft . ' días)';
                                    $avatarBg = 'rgba(244, 180, 0, 0.18)'; 
                                    $avatarColor = 'var(--color-warning)';
                                } elseif ($statusCat === 'ok') {
                                    $dotColor = 'var(--color-success)';
                                    $dotTitle = 'Próxima en ' . $daysLeft . ' días';
                                    $avatarBg = 'rgba(0, 255, 48, 0.15)'; 
                                    $avatarColor = 'var(--color-success)';
                                }

                                $avatarStyle = $avatarBg !== '' ? "background-color: {$avatarBg}; color: {$avatarColor}; border: 1px solid {$avatarColor};" : "";
                            ?>

                            <?php
                                $rowSearch = mb_strtolower(trim(implode(' ', array_filter(array(
                                    $customer['commercial_name'] ?? '',
                                    $customer['customer_name'] ?? '',
                                    $customerName,
                                    $legalName,
                                    $customer['customer_tax_id'] ?? '',
                                    $customer['email'] ?? '',
                                    $customer['phone'] ?? '',
                                    $customer['address'] ?? '',
                                    $customer['district'] ?? '',
                                    $customer['city'] ?? '',
                                    $customer['region'] ?? '',
                                    $customer['country'] ?? '',
                                    $customer['geocode_status'] ?? ''
                                )))), 'UTF-8');
                            ?>
                            <tr data-customer-row="1" data-customer-search="<?php echo safe_text($rowSearch); ?>" data-country="<?php echo safe_text($customer['country'] ?? ''); ?>" data-region="<?php echo safe_text($customer['region'] ?? ''); ?>">
                                <td>
                                    <a class="customer-cell" href="/modules/customers/view.php?id=<?php echo (int) $customer['id']; ?>">
                                        
                                        <span class="customer-avatar-mini" style="<?php echo $avatarStyle; ?>">
                                            <?php echo safe_text(strtoupper($initial)); ?>
                                        </span>

                                        <span class="customer-cell-text">
                                            <strong><?php echo safe_text($customerName); ?></strong>
                                            <?php if ($legalName !== ''): ?>
                                                <small><?php echo safe_text($legalName); ?></small>
                                            <?php endif; ?>
                                        </span>
                                    </a>
                                </td>

                                <td class="mobile-hidden">
                                    <?php echo !empty($customer['city']) ? safe_text($customer['city']) : '—'; ?>
                                    <?php if (!empty($customer['country'])): ?>
                                        <small class="table-subtext"><?php echo safe_text(trim(($customer['region'] ?? '') . ' · ' . ($customer['country'] ?? ''), ' ·')); ?></small>
                                    <?php endif; ?>
                                </td>

                                <td class="mobile-hidden">
                                    <?php if ($lastPurchase !== ''): ?>
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <span><?php echo safe_text($lastPurchase); ?></span>
                                            <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background-color: <?php echo $dotColor; ?>; <?php echo $dotColor !== 'var(--surface-4)' ? 'box-shadow: 0 0 6px ' . str_replace(')', ', 0.5)', str_replace('rgb', 'rgba', $dotColor)) . ';' : ''; ?>" title="<?php echo safe_text($dotTitle); ?>"></span>
                                        </div>
                                    <?php else: ?>
                                        <span class="pill-muted">Sin compras</span>
                                    <?php endif; ?>
                                </td>

                                <td class="cell-opps" style="text-align: center;">
                                    <?php if ($openOpps > 0): ?>
                                        <span class="customer-opps is-open">
                                            <?php echo $openOpps; ?> abierta<?php echo $openOpps > 1 ? 's' : ''; ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="customer-opps">0</span>
                                    <?php endif; ?>
                                </td>

                                <td class="text-right">
                                    <a class="btn btn-sm btn-outline" href="/modules/customers/view.php?id=<?php echo (int) $customer['id']; ?>">
                                        <i data-lucide="chevron-right"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>

                        <?php if (empty($filteredCustomers)): ?>
                            <tr>
                                <td colspan="5" class="text-center text-secondary py-8">
                                    <p class="mt-4">No hay clientes que coincidan con los filtros.</p>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>

    </section>

    <div id="customerModal" class="product-modal-backdrop">
        <div class="product-modal-box">
            
            <div class="product-modal-header">
                <div>
                    <h2 class="h3">Crear Nuevo Cliente</h2>
                    <span class="text-secondary text-sm">Completa los datos mínimos para agregar a tu agenda</span>
                </div>
                <button type="button" class="icon-btn" onclick="closeCustomerModal()"><i data-lucide="x"></i></button>
            </div>
            
            <div class="product-modal-body">
                <form id="form-create-customer" action="/modules/customers/customer_store.php" method="POST" data-no-spa="true" style="margin: 0;">
                    
                    <button type="submit" style="display: none;" aria-hidden="true"></button>

                    <?php icylab_render_customer_quick_fields(array(
                        'name_field' => 'customer_name',
                        'tax_field' => 'customer_tax_id',
                        'tax_id' => 'modalCustomerTaxId',
                        'phone_prefix_id' => 'create_phone_prefix',
                        'phone_number_id' => 'create_phone_number',
                        'phone_hidden_id' => 'create_real_phone_input',
                        'values' => array('country' => 'Chile'),
                        'required' => array('customer_name', 'country', 'address', 'district', 'city', 'region')
                    )); ?>
                </form>
            </div>

            <div class="product-modal-footer" style="justify-content: flex-end;">
                <div class="modal-footer-actions-right">
                    <button type="button" class="btn btn-outline" onclick="closeCustomerModal()">Cancelar</button>
                    <button type="submit" form="form-create-customer" class="btn btn-primary">
                        <i data-lucide="save"></i>
                        <span>Guardar&nbsp;<span class="mobile-hidden">Cliente</span></span>
                    </button>
                </div>
            </div>

        </div>
    </div>

    <script src="/assets/js/customer-location.js?v=p8_1"></script>
    <script>
    function openCustomerModal() {
        var modal = document.getElementById('customerModal');
        var form = document.getElementById('form-create-customer');

        if (modal) {
            if (form) form.reset();

            var realPhone = document.getElementById('create_real_phone_input');
            if (realPhone) realPhone.value = '';

            modal.style.display = 'flex';
            setTimeout(function () { modal.classList.add('show'); }, 10);
        }
    }

    function closeCustomerModal() {
        var modal = document.getElementById('customerModal');
        if (modal) {
            modal.classList.remove('show');
            setTimeout(function () { modal.style.display = 'none'; }, 200);
        }
    }

    document.addEventListener('click', function (e) {
        var modal = document.getElementById('customerModal');
        if (modal && e.target === modal) closeCustomerModal();
    });

    var cPrefixSelect = document.getElementById('create_phone_prefix');
    var cNumberInput = document.getElementById('create_phone_number');
    var cRealPhone = document.getElementById('create_real_phone_input');

    if (cPrefixSelect && cNumberInput && cRealPhone) {
        function updateCreatePhone() {
            var num = cNumberInput.value.replace(/[^0-9\s-]/g, '');
            cNumberInput.value = num;

            if (num.replace(/[^0-9]/g, '').length > 0) {
                cRealPhone.value = cPrefixSelect.value + ' ' + num;
            } else {
                cRealPhone.value = '';
            }
        }

        cPrefixSelect.addEventListener('change', updateCreatePhone);
        cNumberInput.addEventListener('input', updateCreatePhone);
    }

    var rutInput = document.getElementById('modalCustomerTaxId');
    if (rutInput) {
        rutInput.addEventListener('input', function (e) {
            if (window.ICY_CUSTOMER_LOCATION && window.ICY_CUSTOMER_LOCATION.countryCode(e.target.closest('form')) !== 'cl') return;

            var value = e.target.value.replace(/[^0-9kK]/g, '');
            if (!value) {
                e.target.value = '';
                return;
            }

            if (value.length === 1) {
                e.target.value = value.toUpperCase();
                return;
            }

            var body = value.slice(0, -1);
            var dv = value.slice(-1).toUpperCase();
            body = body.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
            e.target.value = body + '-' + dv;
        });
    }

    function normalizeCustomerSearchText(value) {
        if (window.ICY_NORMALIZE_SEARCH) return window.ICY_NORMALIZE_SEARCH(value);
        return String(value || '').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim();
    }

    function normalizeCustomerRutText(value) {
        if (window.ICY_NORMALIZE_RUT_SEARCH) return window.ICY_NORMALIZE_RUT_SEARCH(value);
        return normalizeCustomerSearchText(value).replace(/[^0-9k]/g, '');
    }

    function applyCustomerLiveFilter() {
        var input = document.getElementById('customerLiveSearch');
        var rows = document.querySelectorAll('#customers-main tr[data-customer-row="1"]');
        var counter = document.getElementById('customersFoundCount');
        var rawQuery = input ? input.value : '';
        var query = normalizeCustomerSearchText(rawQuery);
        var rutQuery = normalizeCustomerRutText(rawQuery);
        var visible = 0;

        rows.forEach(function (row) {
            var rawHaystack = row.getAttribute('data-customer-search') || '';
            var haystack = normalizeCustomerSearchText(rawHaystack);
            var rutHaystack = normalizeCustomerRutText(rawHaystack);
            var show = query === '' || haystack.indexOf(query) !== -1 || (rutQuery.length >= 2 && rutHaystack.indexOf(rutQuery) !== -1);
            row.style.display = show ? '' : 'none';
            if (show) visible++;
        });

        if (counter) counter.textContent = visible;
    }

    function initCustomerFiltersUi() {
        var toggle = document.getElementById('customerFiltersToggle');
        var form = document.getElementById('customerFiltersForm');
        var panel = document.getElementById('customerAdvancedFilters');

        if (!toggle || !form || !panel || toggle.dataset.bound === '1') return;

        toggle.dataset.bound = '1';
        toggle.addEventListener('click', function () {
            var expanded = form.classList.toggle('is-expanded');
            toggle.setAttribute('aria-expanded', expanded ? 'true' : 'false');
        });
    }

    var customerLiveSearchInput = document.getElementById('customerLiveSearch');
    if (customerLiveSearchInput && customerLiveSearchInput.dataset.liveBound !== '1') {
        customerLiveSearchInput.dataset.liveBound = '1';
        customerLiveSearchInput.addEventListener('input', applyCustomerLiveFilter);
        customerLiveSearchInput.addEventListener('keydown', function (event) {
            if (event.key === 'Enter') event.preventDefault();
        });
        applyCustomerLiveFilter();
    }

    initCustomerFiltersUi();

    if (window.ICY_CUSTOMER_LOCATION) {
        window.ICY_CUSTOMER_LOCATION.init(document.getElementById('customers-main') || document);
    }
    </script>
</main>

<?php require_once '../../layouts/footer.php'; ?>