<?php

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

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

$page_title = 'CRM';

PaymentStatusService::processOverdueOpportunities(db());
$crm = new CrmService();
$kpis = $crm->getDashboardKpis();

// Variables para Modal Nueva Oportunidad
$customers = $crm->getCustomers();
$assignableUsers = $crm->getAssignableUsers();
$currentUser = current_user();
$ownerValue = $currentUser['name'] ?? '';

$stages = [
    'nuevo' => 'Nuevo', 'contactado' => 'Contactado', 'cotizando' => 'Cotizando',
    'negociacion' => 'Negociación', 'ganada' => 'Ganada', 'perdida' => 'Perdida', 'facturada' => 'Facturada'
];

$paymentStatusOptions = [
    'no_facturado' => 'No facturado', 'por_cobrar' => 'Por cobrar',
    'pagado' => 'Pagado', 'atrasado' => 'Atrasado', 'incobrable' => 'Incobrable'
];

$sourceOptions = [
    'Instagram' => 'Instagram', 'Web' => 'Web', 'OpenLab' => 'OpenLab',
    'Recomendación' => 'Recomendación', 'Email' => 'Email', 'Llamada' => 'Llamada',
    'Distribuidor' => 'Distribuidor', 'Otro' => 'Otro'
];

$competitorOptions = [
    '' => 'No identificado', 'Abstrax' => 'Abstrax', 'HopBurst' => 'HopBurst',
    'Pellets' => 'Pellets', 'Proveedor tradicional' => 'Proveedor tradicional', 'Otro' => 'Otro'
];

$nextActionOptions = [
    '' => 'Sin acción', 'Llamar' => 'Llamar', 'Enviar cotización' => 'Enviar cotización',
    'Enviar muestra' => 'Enviar muestra', 'Agendar reunión' => 'Agendar reunión',
    'Despachar' => 'Despachar', 'Hacer seguimiento' => 'Hacer seguimiento', 'Esperar respuesta' => 'Esperar respuesta'
];

// Variable de control para auto-abrir modal
$openModalId = isset($_GET['open_modal']) ? (int) $_GET['open_modal'] : 0;

$formErrors = $_SESSION['form_errors'] ?? array();
$formOld = $_SESSION['form_old'] ?? array();
unset($_SESSION['form_errors'], $_SESSION['form_old']);

// LÓGICA DE REPOSICIONES URGENTES
$allCustomers = $crm->getCustomers();
$urgentRestocks = [];

foreach ($allCustomers as $c) {
    if (!empty($c['next_restock_date'])) {
        $today = new DateTime();
        $today->setTime(0, 0, 0);
        $target = new DateTime($c['next_restock_date']);
        $target->setTime(0, 0, 0);
        
        $diff = $today->diff($target);
        $daysLeft = (int)$diff->format('%R%a');

        if ($daysLeft <= 10) {
            $c['days_left'] = $daysLeft;
            $urgentRestocks[] = $c;
        }
    }
}
usort($urgentRestocks, function($a, $b) { return $a['days_left'] <=> $b['days_left']; });
$urgentRestocks = array_slice($urgentRestocks, 0, 20);

// OPORTUNIDADES CALIENTES
$embudo = $crm->getEmbudo();
$hotOpps = array_merge($embudo['cotizando'] ?? [], $embudo['negociacion'] ?? []);
usort($hotOpps, function($a, $b) { return $b['expected_value'] <=> $a['expected_value']; });
$hotOpps = array_slice($hotOpps, 0, 8); 

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

?>

<main id="crm-index-main" class="app-main no-scroll-main">
    
    <style>
    /* =========================================================
       CRM Index - layout móvil/escritorio autocontenido
       Mantiene el patrón correcto: desktop sin scroll de página;
       mobile con scroll del index + scroll interno en tarjetas.
       ========================================================= */
    #crm-index-main {
        min-width: 0 !important;
    }

    @media (min-width: 761px) {
        body #crm-index-main.app-main.no-scroll-main {
            height: 100vh !important;
            height: 100dvh !important;
            min-height: 0 !important;
            overflow: hidden !important;
            display: flex !important;
            flex-direction: column !important;
        }

        body #crm-index-main.app-main.no-scroll-main > .content.flex-content {
            flex: 1 1 0% !important;
            min-height: 0 !important;
            overflow: hidden !important;
            display: flex !important;
            flex-direction: column !important;
            padding-bottom: 24px !important;
        }

        #crm-index-main .scrollable-grid {
            flex: 1 1 0% !important;
            min-height: 0 !important;
            height: auto !important;
            overflow: hidden !important;
            display: grid !important;
            grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
            gap: var(--space-4) !important;
        }

        #crm-index-main .flex-card {
            height: 100% !important;
            min-height: 0 !important;
            display: flex !important;
            flex-direction: column !important;
            overflow: hidden !important;
        }

        #crm-index-main .card-scroll-area {
            flex: 1 1 0% !important;
            min-height: 0 !important;
            padding: 0 !important;
            display: flex !important;
            flex-direction: column !important;
            overflow: hidden !important;
        }

        #crm-index-main .card-scroll-area .table-wrap {
            flex: 1 1 auto !important;
            min-height: 0 !important;
            height: 100% !important;
            max-height: none !important;
            overflow-y: auto !important;
            overflow-x: hidden !important;
        }
    }

    #crm-index-main .card-header {
        flex: 0 0 auto !important;
    }

    #crm-index-main .card-scroll-area .table-wrap {
        scrollbar-width: thin;
        scrollbar-color: var(--border-default) transparent;
        -webkit-overflow-scrolling: touch;
        overscroll-behavior: contain;
    }

    #crm-index-main .card-scroll-area .table-wrap::-webkit-scrollbar { width: 6px; }
    #crm-index-main .card-scroll-area .table-wrap::-webkit-scrollbar-track { background: transparent; }
    #crm-index-main .card-scroll-area .table-wrap::-webkit-scrollbar-thumb { background: var(--border-default); border-radius: 4px; }
    #crm-index-main .card-scroll-area .table-wrap::-webkit-scrollbar-thumb:hover { background: var(--text-muted); }

    #crm-index-main .table-wrap {
        border: none !important;
        border-radius: 0 !important;
        margin: 0 !important;
    }

    #crm-index-main .table-urgent-restocks,
    #crm-index-main .table-hot-opps {
        width: 100% !important;
        min-width: 0 !important;
        max-width: 100% !important;
        table-layout: fixed !important;
        border-collapse: collapse !important;
        margin-bottom: 0 !important;
    }

    #crm-index-main .table-urgent-restocks td,
    #crm-index-main .table-hot-opps td {
        padding: 12px 10px !important;
        vertical-align: middle !important;
        border-bottom: 1px solid var(--border-subtle) !important;
        overflow: visible !important;
        text-overflow: clip !important;
        white-space: normal !important;
    }

    #crm-index-main .table-urgent-restocks td:last-child,
    #crm-index-main .table-hot-opps td:last-child {
        padding-right: 20px !important;
        text-align: right !important;
    }

    #crm-index-main .clickable-row {
        cursor: pointer;
        transition: background var(--motion-base);
    }

    #crm-index-main .clickable-row:hover { background: var(--surface-2); }
    #crm-index-main .col-avatar { text-align: center !important; }
    #crm-index-main .col-name { text-align: left !important; }
    #crm-index-main .col-status { text-align: right !important; }
    #crm-index-main .col-btn { text-align: right !important; }

    #crm-index-main .btn-action-square {
        width: 36px;
        height: 36px;
        padding: 0;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: var(--radius-md);
    }

    #crm-index-main .grid-4 {
        display: grid;
        grid-template-columns: repeat(4, minmax(0, 1fr));
        gap: var(--space-4);
    }

    body #crm-index-main .product-modal-backdrop {
        position: fixed !important;
        inset: 0 !important;
        background: rgba(0,0,0,0.70) !important;
        backdrop-filter: blur(5px) !important;
        z-index: 9999 !important;
        display: none;
        align-items: center !important;
        justify-content: center !important;
        opacity: 0;
        padding: 24px !important;
        overflow: hidden !important;
        transition: opacity 0.2s ease;
    }

    body #crm-index-main .product-modal-backdrop.show {
        display: flex !important;
        opacity: 1 !important;
    }

    body #crm-index-main .product-modal-box {
        background: var(--surface-1) !important;
        width: min(1080px, calc(100vw - 48px)) !important;
        max-width: calc(100vw - 48px) !important;
        max-height: calc(100vh - 100px) !important;
        max-height: calc(100dvh - 100px) !important;
        min-height: 0 !important;
        border: 1px solid var(--border-default) !important;
        border-radius: var(--radius-xl) !important;
        box-shadow: var(--shadow-lg) !important;
        display: flex !important;
        flex-direction: column !important;
        overflow: hidden !important;
        transform: translateY(20px);
        transition: transform 0.2s ease;
    }

    body #crm-index-main #customerSummaryModal .product-modal-box {
        width: min(480px, calc(100vw - 48px)) !important;
    }

    body #crm-index-main .product-modal-backdrop.show .product-modal-box {
        transform: translateY(0);
    }

    body #crm-index-main .product-modal-header {
        flex: 0 0 auto !important;
        padding: var(--space-5) !important;
        border-bottom: 1px solid var(--border-subtle) !important;
        display: flex !important;
        justify-content: space-between !important;
        align-items: flex-start !important;
        gap: var(--space-4) !important;
    }

    body #crm-index-main .product-modal-body {
        flex: 1 1 auto !important;
        min-height: 0 !important;
        padding: var(--space-5) !important;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        -webkit-overflow-scrolling: touch !important;
    }

    body #crm-index-main .product-modal-footer {
        flex: 0 0 auto !important;
        padding: var(--space-4) var(--space-4) !important;
        border-top: 1px solid var(--border-subtle) !important;
        display: flex !important;
        flex-direction: row !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 12px !important;
        background: var(--surface-0) !important;
        border-radius: 0 0 var(--radius-xl) var(--radius-xl) !important;
    }


    /* Resumen cliente: etiquetas a la izquierda, valores a la derecha */
    body #crm-index-main #customerSummaryModal .metric-row {
        display: flex !important;
        align-items: center !important;
        justify-content: space-between !important;
        gap: 16px !important;
        width: 100% !important;
    }

    body #crm-index-main #customerSummaryModal .metric-row > span {
        flex: 0 0 42% !important;
        min-width: 0 !important;
        text-align: left !important;
        white-space: nowrap !important;
    }

    body #crm-index-main #customerSummaryModal .metric-row > .metric-value,
    body #crm-index-main #customerSummaryModal .summary-contact-value {
        flex: 1 1 auto !important;
        min-width: 0 !important;
        margin-left: auto !important;
        text-align: right !important;
    }

    body #crm-index-main #customerSummaryModal .summary-contact-value {
        display: flex !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 8px !important;
    }

    body #crm-index-main #customerSummaryModal .summary-contact-value .metric-value {
        flex: 1 1 auto !important;
        min-width: 0 !important;
        text-align: right !important;
    }

    body #crm-index-main #summaryFullLink {
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        text-align: center !important;
        gap: 4px !important;
    }

    body #crm-index-main #summaryFullLink .summary-full-link-text {
        flex: 0 1 auto !important;
        text-align: center !important;
    }

    @media (max-width: 760px) {
        body #crm-index-main.app-main.no-scroll-main {
            height: 100dvh !important;
            min-height: 0 !important;
            overflow-y: auto !important;
            overflow-x: hidden !important;
            display: flex !important;
            flex-direction: column !important;
            -webkit-overflow-scrolling: touch !important;
            overscroll-behavior-y: contain !important;
        }

        body #crm-index-main.app-main.no-scroll-main > .content.flex-content {
            flex: 0 0 auto !important;
            min-height: 0 !important;
            height: auto !important;
            overflow: visible !important;
            display: flex !important;
            flex-direction: column !important;
            gap: 12px !important;
            width: 100% !important;
            max-width: 100% !important;
            padding: 16px 12px calc(24px + env(safe-area-inset-bottom)) !important;
        }

        #crm-index-main .page-header {
            display: grid !important;
            grid-template-columns: minmax(0, 1fr) auto !important;
            justify-content: stretch !important;
            align-items: start !important;
            gap: 10px !important;
            margin: 0 !important;
        }

        #crm-index-main .page-header-content {
            min-width: 0 !important;
            padding-right: 0 !important;
        }

        #crm-index-main .page-header-content h1 {
            font-size: clamp(1.28rem, 6vw, 1.55rem) !important;
            line-height: 1.08 !important;
            margin: 0 0 3px !important;
            word-break: normal !important;
        }

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

        #crm-index-main .actions-cluster {
            margin-left: 0 !important;
            flex: 0 0 auto !important;
            display: flex !important;
            flex-wrap: nowrap !important;
            gap: 8px !important;
            align-items: center !important;
            justify-content: flex-end !important;
        }

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

        #crm-index-main .icon-btn-mobile {
            width: 42px !important;
            min-width: 42px !important;
            max-width: 42px !important;
            height: 42px !important;
            padding: 0 !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        #crm-index-main .grid-4 {
            grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
            gap: 10px !important;
            flex: 0 0 auto !important;
        }

        #crm-index-main .grid-4 .kpi-card {
            min-height: 92px !important;
            padding: 12px !important;
            border-radius: 16px !important;
        }

        #crm-index-main .grid-4 .kpi-label {
            font-size: 0.68rem !important;
            line-height: 1.15 !important;
        }

        #crm-index-main .grid-4 .kpi-value {
            font-size: clamp(1rem, 4.8vw, 1.18rem) !important;
            line-height: 1.12 !important;
            word-break: break-word !important;
        }

        #crm-index-main .grid-4 .kpi-context {
            font-size: 0.72rem !important;
            line-height: 1.15 !important;
        }

        #crm-index-main .scrollable-grid {
            display: flex !important;
            flex-direction: column !important;
            height: auto !important;
            min-height: 0 !important;
            overflow: visible !important;
            gap: 12px !important;
        }

        #crm-index-main .flex-card {
            flex: none !important;
            height: auto !important;
            min-height: 0 !important;
            max-height: none !important;
            overflow: hidden !important;
            border-radius: var(--radius-xl, 16px) !important;
        }

        #crm-index-main .flex-card .card-header {
            position: relative !important;
            z-index: 2 !important;
            background: var(--surface-1) !important;
            border-bottom: 1px solid var(--border-subtle) !important;
        }

        #crm-index-main .card-scroll-area {
            height: auto !important;
            min-height: 0 !important;
            overflow: visible !important;
            padding: 0 !important;
            display: block !important;
        }

        #crm-index-main .card-scroll-area .table-wrap {
            max-height: min(42dvh, 340px) !important;
            min-height: 156px !important;
            height: auto !important;
            overflow-y: auto !important;
            overflow-x: hidden !important;
            border: 0 !important;
            border-radius: 0 !important;
            margin: 0 !important;
        }

        #crm-index-main .table-urgent-restocks td,
        #crm-index-main .table-hot-opps td {
            padding: 10px 8px !important;
        }

        #crm-index-main .table-urgent-restocks td:last-child,
        #crm-index-main .table-hot-opps td:last-child {
            padding-right: 10px !important;
        }

        #crm-index-main .crm-col-avatar { width: 48px !important; }
        #crm-index-main .crm-col-restock-status { width: 88px !important; }
        #crm-index-main .crm-col-action { width: 48px !important; }
        #crm-index-main .crm-col-hot-value { width: 112px !important; }

        #crm-index-main .btn-action-square {
            width: 34px !important;
            height: 34px !important;
        }

        #crm-index-main .col-status span {
            max-width: 84px !important;
            white-space: normal !important;
            text-align: right !important;
        }

        body #crm-index-main .product-modal-backdrop {
            padding: 12px !important;
            align-items: center !important;
            justify-content: center !important;
        }

        body #crm-index-main .product-modal-box,
        body #crm-index-main #customerSummaryModal .product-modal-box {
            width: calc(100vw - 24px) !important;
            max-width: calc(100vw - 24px) !important;
            max-height: calc(100dvh - 140px) !important;
            border-radius: 18px !important;
            transform: translateY(10px);
        }

        body #crm-index-main .product-modal-header {
            padding: 16px !important;
        }

        body #crm-index-main .product-modal-body {
            padding: 16px !important;
            max-height: none !important;
        }

        body #crm-index-main .product-modal-footer {
            display: flex !important;
            flex-direction: row !important;
            align-items: center !important;
            justify-content: flex-end !important;
            gap: 8px !important;
            padding: 12px 12px calc(12px + env(safe-area-inset-bottom)) !important;
        }

        body #crm-index-main .product-modal-footer .btn {
            height: 42px !important;
            min-width: 42px !important;
            max-width: calc((100vw - 56px) / 2) !important;
            padding: 0 12px !important;
            white-space: nowrap !important;
            overflow: hidden !important;
            text-overflow: ellipsis !important;
        }

        /* Resumen cliente: en móvil debe conservar el layout de escritorio. */
        body #crm-index-main #customerSummaryModal .metric-row {
            display: flex !important;
            flex-direction: row !important;
            align-items: center !important;
            justify-content: space-between !important;
            gap: 16px !important;
            width: 100% !important;
            text-align: initial !important;
        }

        body #crm-index-main #customerSummaryModal .metric-row > span {
            flex: 0 0 42% !important;
            min-width: 0 !important;
            text-align: left !important;
            white-space: nowrap !important;
        }

        body #crm-index-main #customerSummaryModal .metric-row > .metric-value,
        body #crm-index-main #customerSummaryModal .summary-contact-value {
            flex: 1 1 auto !important;
            min-width: 0 !important;
            margin-left: auto !important;
            text-align: right !important;
        }

        body #crm-index-main #customerSummaryModal .summary-contact-value {
            display: flex !important;
            align-items: center !important;
            justify-content: flex-end !important;
            gap: 8px !important;
        }

        body #crm-index-main #customerSummaryModal .summary-contact-value .metric-value {
            flex: 1 1 auto !important;
            min-width: 0 !important;
            text-align: right !important;
        }

        body #crm-index-main #customerSummaryModal .product-modal-footer {
            flex-wrap: nowrap !important;
            justify-content: flex-end !important;
        }

        body #crm-index-main #customerSummaryModal .product-modal-footer .btn {
            max-width: none !important;
            overflow: visible !important;
            text-overflow: clip !important;
        }

        body #crm-index-main #customerSummaryModal .product-modal-footer button.btn {
            flex: 0 0 112px !important;
            min-width: 112px !important;
        }

        body #crm-index-main #customerSummaryModal #summaryFullLink {
            flex: 0 1 auto !important;
            min-width: 178px !important;
            max-width: none !important;
        }

        body #crm-index-main #customerSummaryModal #summaryFullLink .summary-full-link-text {
            min-width: 0 !important;
            overflow: visible !important;
            text-align: center !important;
            text-overflow: clip !important;
            white-space: nowrap !important;
        }

        #crm-index-main #form-create-opportunity .form-grid,
        #crm-index-main #form-create-opportunity .form-grid-4,
        #crm-index-main #form-create-opportunity .form-grid-client {
            grid-template-columns: minmax(0, 1fr) !important;
            gap: 12px !important;
        }

        #crm-index-main #modalNewCustomerBlock {
            padding: 14px !important;
            margin-bottom: 14px !important;
        }

        #crm-index-main #modalCustomerResults {
            max-height: min(36dvh, 260px) !important;
        }
    }


    /* =========================================================
       P18 - Nueva oportunidad CRM: alto y footer homologados
       Mantiene el mismo patrón visual en desktop y móvil.
       ========================================================= */
    body #crm-index-main #opportunityModal.product-modal-backdrop {
        padding: 24px !important;
        align-items: center !important;
        justify-content: center !important;
        overflow: hidden !important;
    }

    body #crm-index-main #opportunityModal .product-modal-box {
        width: min(1080px, calc(100vw - 48px)) !important;
        max-width: calc(100vw - 48px) !important;
        height: min(700px, calc(100dvh - 100px)) !important;
        min-height: min(560px, calc(100dvh - 100px)) !important;
        max-height: calc(100dvh - 48px) !important;
        display: flex !important;
        flex-direction: column !important;
        overflow: hidden !important;
    }

    body #crm-index-main #opportunityModal .product-modal-header,
    body #crm-index-main #opportunityModal .product-modal-footer {
        flex: 0 0 auto !important;
    }

    body #crm-index-main #opportunityModal .product-modal-body {
        flex: 1 1 auto !important;
        min-height: 0 !important;
        max-height: none !important;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        -webkit-overflow-scrolling: touch !important;
    }

    body #crm-index-main #opportunityModal .product-modal-footer {
        min-height: 76px !important;
        height: auto !important;
        max-height: none !important;
        display: flex !important;
        flex-direction: row !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 12px !important;
        flex-wrap: nowrap !important;
        padding: 14px 20px !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;
    }

    body #crm-index-main #opportunityModal .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;
    }

    body #crm-index-main #opportunityModal #saveOpportunityBtn {
        min-width: 178px !important;
    }

    body #crm-index-main #opportunityModal .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) {
        body #crm-index-main #opportunityModal.product-modal-backdrop {
            padding: 12px !important;
        }

        body #crm-index-main #opportunityModal .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 - 24px) !important;
            border-radius: 18px !important;
        }

        body #crm-index-main #opportunityModal .product-modal-header {
            padding: 16px !important;
        }

        body #crm-index-main #opportunityModal .product-modal-body {
            padding: 16px !important;
            max-height: none !important;
        }

        body #crm-index-main #opportunityModal .product-modal-footer {
            min-height: 68px !important;
            padding: 10px 12px calc(10px + env(safe-area-inset-bottom)) !important;
            gap: 10px !important;
        }

        body #crm-index-main #opportunityModal .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;
        }

        body #crm-index-main #opportunityModal #saveOpportunityBtn {
            min-width: 124px !important;
        }

        body #crm-index-main #opportunityModal #saveOpportunityBtn .mobile-hidden {
            display: none !important;
        }
    }

    </style>

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

    <section class="content flex-content">
        <div class="page-header">
            <div class="page-header-content">
                <span class="label">Comercial</span>
                <h1>CRM</h1>
                <p class="text-secondary">Centro operativo comercial y seguimiento de cuentas.</p>
            </div>
            <div class="cluster actions-cluster">
                <a href="/modules/customers/" class="btn btn-outline icon-btn-mobile" title="Ir a Clientes"><i data-lucide="users"></i><span class="mobile-hidden">Clientes</span></a>
                <a href="/modules/crm/embudo.php" class="btn btn-outline icon-btn-mobile" title="Ver Embudo"><i data-lucide="kanban-square"></i><span class="mobile-hidden">Embudo</span></a>
                <button type="button" class="btn btn-primary icon-btn-mobile" onclick="openOpportunityModal()" title="Nueva Oportunidad"><i data-lucide="plus"></i><span class="mobile-hidden">Nueva oportunidad</span></button>
            </div>
        </div>
        
        <?php if (!empty($formErrors)): ?>
            <div class="alert alert-error mt-2 mb-4" style="flex-shrink: 0;">
                <strong>No fue posible guardar la oportunidad.</strong>
                <span>Revisa los campos e inténtalo nuevamente.</span>
            </div>
        <?php endif; ?>

        <section class="grid grid-4" style="flex-shrink: 0;">
            <article class="kpi-card"><div class="kpi-label">Oportunidades abiertas</div><div class="kpi-main"><div class="kpi-value"><?php echo (int) $kpis['open_opportunities']; ?></div></div><p class="kpi-context">Embudo activo</p></article>
            <article class="kpi-card"><div class="kpi-label">Valor embudo</div><div class="kpi-main"><div class="kpi-value"><?php echo clp($kpis['embudo_value']); ?></div></div><p class="kpi-context">Valor estimado</p></article>
            <article class="kpi-card"><div class="kpi-label">Embudo ponderado</div><div class="kpi-main"><div class="kpi-value"><?php echo clp($kpis['weighted_embudo']); ?></div></div><p class="kpi-context">Ajustado por probabilidad</p></article>
            <article class="kpi-card"><div class="kpi-label">Ganadas / Perdidas</div><div class="kpi-main"><div class="kpi-value"><?php echo (int) $kpis['won_count']; ?> / <?php echo (int) $kpis['lost_count']; ?></div></div><p class="kpi-context">Resultado acumulado</p></article>
        </section>

        <div class="mt-4" style="flex-shrink: 0;"></div>

        <section class="grid grid-2 scrollable-grid">

            <article class="card flex-card">
                <div class="card-header" style="flex-shrink: 0;">
                    <div><span class="label">Prioridad de Contacto</span><h3>Reposiciones Urgentes</h3></div>
                </div>
                <div class="card-body card-scroll-area">
                    <div class="table-wrap">
                        <table class="table table-urgent-restocks">
                            <colgroup><col class="crm-col-avatar" style="width: 56px;"><col style="width: auto;"><col class="crm-col-restock-status" style="width: 110px;"><col class="crm-col-action" style="width: 66px;"></colgroup>
                            <tbody>
                                <?php foreach ($urgentRestocks as $rc): ?>
                                    <?php
                                        $name = !empty($rc['commercial_name']) ? $rc['commercial_name'] : $rc['customer_name'];
                                        $initial = mb_substr($name, 0, 1, 'UTF-8');
                                        $dl = $rc['days_left'];
                                        if ($dl < 0) { $color = 'var(--color-error)'; $txt = 'Atrasado (' . abs($dl) . 'd)'; $bg = 'rgba(255, 77, 79, 0.15)'; }
                                        elseif ($dl === 0) { $color = 'var(--color-warning)'; $txt = '¡Hoy!'; $bg = 'rgba(244, 180, 0, 0.15)'; }
                                        else { $color = 'var(--color-warning)'; $txt = 'En ' . $dl . ' días'; $bg = 'rgba(244, 180, 0, 0.15)'; }
                                        
                                        $cleanPhone = preg_replace('/[^0-9]/', '', $rc['phone'] ?? '');
                                        $fmtSales = isset($rc['total_net_sales']) ? '$' . number_format($rc['total_net_sales'], 0, ',', '.') : '$0';
                                        $fmtDate = !empty($rc['last_purchase_date']) ? date('d-m-Y', strtotime($rc['last_purchase_date'])) : 'Sin registro';

                                        $customerData = htmlspecialchars(json_encode(['id' => $rc['id'], 'name' => $name, 'rut' => $rc['customer_tax_id'] ?: 'Sin registrar', 'contact' => $rc['contact_name'] ?: 'Sin registrar', 'email' => $rc['email'] ?: '', 'phone' => $rc['phone'] ?: '', 'cleanPhone' => $cleanPhone, 'statusText' => $txt, 'statusColor' => $color, 'initial' => strtoupper($initial), 'bg' => $bg, 'lastPurchase' => $fmtDate, 'totalSales' => $fmtSales]), ENT_QUOTES, 'UTF-8');
                                    ?>
                                    <tr class="clickable-row" onclick="openCustomerSummaryModal(this)" data-customer="<?= $customerData ?>">
                                        <td class="col-avatar no-ellipsis text-center"><span class="customer-avatar-mini" style="background-color: <?= $bg ?>; color: <?= $color ?>; border: 1px solid <?= $color ?>; margin: 0 auto;"><?= safe_text(strtoupper($initial)) ?></span></td>
                                        <td class="col-name"><div class="text-truncate" style="max-width: 100%;"><strong style="font-size: 0.92rem;"><?= safe_text($name) ?></strong></div></td>
                                        <td class="col-status no-ellipsis text-right"><span style="color: <?= $color ?>; font-weight: 600; font-size: 0.8rem; line-height: 1.1; display: inline-block; white-space: nowrap;"><?= $txt ?></span></td>
                                        <td class="col-btn no-ellipsis text-right"><button type="button" onclick="event.stopPropagation(); window.openOpportunityModalWithClient(<?= $rc['id'] ?>, '<?= safe_text($name) ?>');" class="btn btn-primary btn-action-square" title="Nueva Oportunidad"><i data-lucide="plus"></i></button></td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (empty($urgentRestocks)): ?><tr><td colspan="4" class="text-center text-secondary py-6"><p>Todos los clientes están al día con sus reposiciones.</p></td></tr><?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </article>

            <article class="card flex-card">
                <div class="card-header" style="flex-shrink: 0;">
                    <div><span class="label">Embudo Activo</span><h3>Oportunidades Calientes</h3></div>
                </div>
                <div class="card-body card-scroll-area">
                    <?php if(empty($hotOpps)): ?>
                         <div class="text-center text-secondary" style="padding: 40px 20px; margin: auto;"><i data-lucide="inbox" style="width: 48px; height: 48px; color: var(--border-strong); margin-bottom: 12px;"></i><p>No hay oportunidades en etapa de negociación o cotizando actualmente.</p></div>
                    <?php else: ?>
                        <div class="table-wrap">
                            <table class="table table-hot-opps">
                                <colgroup><col style="width: auto;"><col class="crm-col-hot-value" style="width: 145px;"></colgroup>
                                <tbody>
                                    <?php foreach ($hotOpps as $opp): ?>
                                        <tr class="clickable-row" onclick="window.openOppViewModal(event, <?= $opp['id'] ?>)">
                                            <td>
                                                <div class="text-truncate" style="font-weight: 650; color: var(--text-primary); font-size: 0.95rem; margin-bottom: 4px; width: 100%;"><?= safe_text($opp['title']) ?></div>
                                                <div style="display: flex; align-items: center; gap: 6px; font-size: 0.75rem;">
                                                    <span class="badge" style="padding: 2px 6px; font-size: 0.7rem; font-weight: 700; flex-shrink: 0;"><?= safe_text(ucfirst($opp['stage'])) ?></span>
                                                    <span class="text-muted text-truncate"><?= safe_text($opp['customer_name']) ?></span>
                                                </div>
                                            </td>
                                            <td class="no-ellipsis text-right" style="vertical-align: middle;"><strong style="color: var(--color-success); font-size: 1.05rem;"><?= clp($opp['expected_value']) ?></strong></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </article>

        </section>
    </section>

    <div id="customerSummaryModal" class="product-modal-backdrop">
        <div class="product-modal-box" style="max-width: 480px;"> 
            <div class="product-modal-header">
                <div><h2 class="h3">Resumen de Cliente</h2><span class="text-secondary text-sm">Reposición Comercial</span></div>
                <button type="button" class="icon-btn" onclick="closeCustomerSummaryModal()"><i data-lucide="x"></i></button>
            </div>
            <div class="product-modal-body">
                <div style="display: flex; align-items: center; gap: 16px; margin-bottom: 24px;">
                    <span id="summaryAvatar" class="customer-avatar-mini" style="width: 56px; height: 56px; font-size: 1.5rem; display: flex; align-items: center; justify-content: center;"></span>
                    <div style="overflow: hidden;"><h3 id="summaryName" class="text-truncate" style="max-width: 300px; margin-bottom: 4px; line-height: 1.2;"></h3><div><span id="summaryStatus" style="font-weight: 600; font-size: 0.85rem; padding: 4px 8px; border-radius: 6px; display: inline-block;"></span></div></div>
                </div>
                
                <div class="metric-row"><span>RUT</span><strong class="metric-value text-truncate" id="summaryRut"></strong></div>
                
                <div class="metric-row">
                    <span>Email</span>
                    <div class="summary-contact-value">
                        <strong class="metric-value text-truncate" id="summaryEmail"></strong>
                        <a href="#" id="summaryEmailBtn" class="btn btn-sm btn-outline" style="padding: 0; width: 28px; height: 28px; display: none; align-items: center; justify-content: center; flex-shrink: 0;" target="_blank"><i data-lucide="mail" style="width:14px;height:14px;"></i></a>
                    </div>
                </div>
                
                <div class="metric-row">
                    <span>Teléfono</span>
                    <div class="summary-contact-value">
                        <strong class="metric-value text-truncate" id="summaryPhone"></strong>
                        <a href="#" id="summaryWaBtn" class="btn btn-sm btn-outline" style="padding: 0; width: 28px; height: 28px; display: none; align-items: center; justify-content: center; color: #25D366; border-color: #25D366; flex-shrink: 0;" target="_blank" title="Enviar WhatsApp">
                            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"></path></svg>
                        </a>
                    </div>
                </div>
                
                <div class="metric-row"><span>Última Compra</span><strong class="metric-value" id="summaryLastPurchase"></strong></div>
                <div class="metric-row"><span>Total Facturado</span><strong class="metric-value" id="summaryTotalSales"></strong></div>
            </div>
            <div class="product-modal-footer">
                <button type="button" class="btn btn-outline" onclick="closeCustomerSummaryModal()">Cerrar</button>
                <a href="#" id="summaryFullLink" class="btn btn-primary"><span class="summary-full-link-text">Ver ficha completa</span></i></a>
            </div>
        </div>
    </div>

    <div id="opportunityModal" class="product-modal-backdrop <?php echo !empty($formErrors) ? 'show' : ''; ?>" style="<?php echo !empty($formErrors) ? 'display: flex;' : ''; ?>">
        <div class="product-modal-box">
            <div class="product-modal-header">
                <div><h2 class="h3">Crear Nueva Oportunidad</h2><span class="text-secondary text-sm">Ingresa los datos para sumar al embudo</span></div>
                <button type="button" class="icon-btn" onclick="window.closeOpportunityModal()"><i data-lucide="x"></i></button>
            </div>
            <div class="product-modal-body">
                <form id="form-create-opportunity" action="/modules/crm/opportunity_store.php" method="POST" data-no-spa="true" style="margin: 0;">
                    
                    <div class="form-grid form-grid-client mb-4">
                        <div class="form-field is-required customer-autocomplete">
                            <label class="label">Cliente</label>
                            <div class="form-inline-control" style="display: flex; gap: 8px; align-items: stretch; width: 100%;">
                                <div style="position: relative; flex: 1; min-width: 0;">
                                    <input class="input" type="text" id="modalCustomerSearch" style="width: 100%;" placeholder="Buscar cliente por nombre o RUT" autocomplete="off" value="<?php echo safe_text($formOld['customer_name_search'] ?? ''); ?>">
                                    <div id="modalCustomerResults"></div>
                                </div>
                                <button class="btn btn-outline" type="button" id="modalNewCustomerBtn" style="flex-shrink: 0; width: 42px !important; min-width: 42px !important; height: 42px; padding: 0; display: flex; justify-content: center; align-items: center;" title="Crear Cliente Nuevo">
                                    <i data-lucide="user-plus"></i>
                                </button>
                            </div>
                            <input type="hidden" name="customer_id" id="modalCustomerId" value="<?php echo safe_text($formOld['customer_id'] ?? ''); ?>" required>
                        </div>
                        <div class="form-field is-required">
                            <label class="label">Título de la oportunidad</label>
                            <input class="input" type="text" name="title" required placeholder="Ej: Venta de Insumos Q3" value="<?php echo safe_text($formOld['title'] ?? ''); ?>">
                        </div>
                    </div>

                    <div id="modalNewCustomerBlock" style="display: none; padding: 16px; background: var(--surface-2); border-radius: var(--radius-lg); margin-bottom: 16px; border: 1px solid var(--border-default);">
                        <h4 class="h4 mb-4">Datos mínimos del cliente</h4>
                        <?php icylab_render_customer_quick_fields(array(
                            'name_field' => 'new_customer_name',
                            'tax_field' => 'new_customer_tax_id',
                            'tax_id' => 'modalCustomerTaxId',
                            'phone_prefix_id' => 'modal_opp_phone_prefix',
                            'phone_number_id' => 'modal_opp_phone_number',
                            'phone_hidden_id' => 'modal_opp_real_phone_input',
                            'values' => $formOld,
                            'errors' => $formErrors,
                            'required' => array('new_customer_name', 'country', 'address', 'district', 'city', 'region'),
                        'html_required' => false
                        )); ?>
                    </div>

                    <div class="form-grid form-grid-4">
                        <div class="form-field is-required"><label class="label">Etapa inicial</label><select class="select" name="stage" required><?php foreach ($stages as $value => $label): ?><option value="<?php echo safe_text($value); ?>"><?php echo safe_text($label); ?></option><?php endforeach; ?></select></div>
                        <div class="form-field"><label class="label">Estado de cobranza</label><select class="select" name="payment_status"><?php foreach ($paymentStatusOptions as $value => $label): ?><option value="<?php echo safe_text($value); ?>"><?php echo safe_text($label); ?></option><?php endforeach; ?></select></div>
                        <div class="form-field"><label class="label">Fecha vencimiento pago</label><input class="input" type="date" name="payment_due_date"></div>
                        <div class="form-field"><label class="label">Fecha de pago</label><input class="input" type="date" name="payment_paid_date"></div>
                        <div class="form-field">
                            <label class="label">Responsable comercial</label>
                            <select class="select" name="owner_user_id" onchange="this.nextElementSibling.value = this.options[this.selectedIndex].getAttribute('data-name') || '';">
                                <option value="">Sin responsable</option>
                                <?php foreach ($assignableUsers as $user): ?>
                                    <option value="<?php echo (int)$user['id']; ?>" data-name="<?php echo safe_text($user['name']); ?>" <?php echo $user['name'] === $ownerValue ? 'selected' : ''; ?>>
                                        <?php echo safe_text($user['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input type="hidden" name="owner_name" value="<?php echo safe_text($ownerValue ?? ''); ?>">
                        </div>
                        <div class="form-field is-required"><label class="label">Origen</label><select class="select" name="source" required><option value="" disabled selected>Seleccionar origen</option><?php foreach ($sourceOptions as $value => $label): ?><option value="<?php echo safe_text($value); ?>"><?php echo safe_text($label); ?></option><?php endforeach; ?></select></div>
                        <div class="form-field"><label class="label">Competidor / Alternativa</label><select class="select" name="competitor"><?php foreach ($competitorOptions as $value => $label): ?><option value="<?php echo safe_text($value); ?>"><?php echo safe_text($label); ?></option><?php endforeach; ?></select></div>
                        <div class="form-field"><label class="label">Valor esperado ($)</label><input class="input" type="number" name="expected_value" min="0" step="1" placeholder="Ej: 500000"></div>
                        <div class="form-field"><label class="label">Probabilidad (%)</label><input class="input" type="number" name="probability" min="0" max="100" value="20"></div>
                        <div class="form-field is-required"><label class="label">Fecha est. de cierre</label><input class="input" type="date" name="expected_close_date" required></div>
                        <div class="form-field is-required"><label class="label">Próxima acción</label><select class="select" name="next_action" required><?php foreach ($nextActionOptions as $value => $label): ?><option value="<?php echo safe_text($value); ?>"><?php echo safe_text($label); ?></option><?php endforeach; ?></select></div>
                        <div class="form-field is-required"><label class="label">Fecha próxima acción</label><input class="input" type="date" name="next_action_date" required></div>
                        <div class="form-field form-field-full"><label class="label">Notas/ Comentarios</label><textarea class="textarea" name="notes" placeholder="Escribe aquí..."></textarea></div>
                    </div>
                </form>
            </div>
            <div class="product-modal-footer">
                <button type="button" class="btn btn-outline" onclick="window.closeOpportunityModal()">Cancelar</button>
                <button type="submit" form="form-create-opportunity" class="btn btn-primary" id="saveOpportunityBtn">
                    <i data-lucide="save"></i><span>Crear <span class="mobile-hidden">Oportunidad</span></span>
                </button>
            </div>
        </div>
    </div>

<script src="/assets/js/customer-location.js?v=p4_5_1"></script>
<script>
// =========================================================================
// LÓGICA DE APLICACIÓN PROTEGIDA (SPA SAFE)
// =========================================================================
(function() {

    // --- MANEJO DE ENVÍO MANUAL (CREAR OPORTUNIDAD) ---
    const createOppForm = document.getElementById('form-create-opportunity');
    if (createOppForm && !createOppForm.dataset.customSubmitAttached) {
        createOppForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const btn = document.getElementById('saveOpportunityBtn');
            const originalHtml = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<i data-lucide="loader" class="spin-icon"></i><span class="mobile-hidden">Guardando...</span>';
            if (window.lucide) window.lucide.createIcons();

            fetch(this.action, {
                method: 'POST',
                body: new FormData(this),
                redirect: 'follow'
            })
            .then(res => {
                const url = new URL(res.url);
                const oppId = url.searchParams.get('id');
                // Si encontramos el ID en la URL de destino, recargamos limpiamente con el parámetro para abrir el modal
                if (oppId) {
                    (window.ICY_SPA_GO ? window.ICY_SPA_GO(window.location.pathname + '?open_modal=' + oppId, { replace: true, force: true }) : (window.location.href = window.location.pathname + '?open_modal=' + oppId));
                } else {
                    (window.ICY_SPA_RELOAD ? window.ICY_SPA_RELOAD({ force: true }) : window.location.reload());
                }
            })
            .catch(err => {
                console.error('Error al guardar:', err);
                btn.disabled = false;
                btn.innerHTML = originalHtml;
                if (window.lucide) window.lucide.createIcons();
            });
        });
        createOppForm.dataset.customSubmitAttached = 'true';
    }

    // --- AUTO-ABRIR MODAL SI VENIMOS DE CREAR ---
    <?php if ($openModalId > 0): ?>
        // Limpiamos la URL visualmente para que no se quede pegado el ?open_modal si recarga
        window.history.replaceState({}, document.title, window.location.pathname);
        setTimeout(() => {
            if(typeof window.openOppViewModal === 'function') {
                window.openOppViewModal(null, <?php echo $openModalId; ?>);
            }
        }, 400);
    <?php endif; ?>

    window.openOppViewModal = function(e, oppId) {
        if (e && (e.target.closest('.stage-menu-trigger') || e.target.closest('.stage-dropdown-menu'))) return;
        var existing = document.getElementById('oppViewModalBackdrop');
        if (existing) existing.remove();

        var loader = document.createElement('div');
        loader.id = 'oppViewModalBackdrop';
        loader.className = 'product-modal-backdrop show';
        loader.style.display = 'flex';
        loader.style.zIndex = '1040';
        loader.innerHTML = '<div style="color:var(--text-primary); display:flex; flex-direction:column; align-items:center; gap:12px;"><i data-lucide="loader" class="spin-icon" style="width:32px;height:32px;"></i><span>Cargando oportunidad...</span></div>';
        document.body.appendChild(loader);
        if (window.lucide) window.lucide.createIcons();

        fetch('/modules/crm/opportunity.php?id=' + oppId + '&modal=1')
        .then(res => res.text())
        .then(html => {
            loader.outerHTML = html;
            var newModal = document.getElementById('oppViewModalBackdrop');
            if (newModal) {
                var scripts = newModal.querySelectorAll('script');
                scripts.forEach(s => {
                    var newS = document.createElement('script');
                    newS.innerHTML = s.innerHTML;
                    document.body.appendChild(newS);
                });
                if (window.lucide) window.lucide.createIcons();
            }
        })
        .catch(err => { alert('Error al cargar la oportunidad'); if (loader) loader.remove(); });
    };

    window.openCustomerSummaryModal = function(rowElement) {
        var modal = document.getElementById('customerSummaryModal');
        if (!modal) return;
        var data = JSON.parse(rowElement.getAttribute('data-customer'));
        
        document.getElementById('summaryName').textContent = data.name;
        document.getElementById('summaryRut').textContent = data.rut;
        
        document.getElementById('summaryEmail').textContent = data.email ? data.email : 'Sin registro';
        var emailBtn = document.getElementById('summaryEmailBtn');
        if (data.email) { emailBtn.style.display = 'inline-flex'; emailBtn.href = 'mailto:' + data.email; } else { emailBtn.style.display = 'none'; }
        
        document.getElementById('summaryPhone').textContent = data.phone ? data.phone : 'Sin registro';
        var waBtn = document.getElementById('summaryWaBtn');
        if (data.cleanPhone) { waBtn.style.display = 'inline-flex'; waBtn.href = 'https://wa.me/' + (data.cleanPhone.startsWith('56') ? data.cleanPhone : '56' + data.cleanPhone); } else { waBtn.style.display = 'none'; }
        
        var statusEl = document.getElementById('summaryStatus');
        statusEl.textContent = data.statusText; statusEl.style.color = data.statusColor; statusEl.style.backgroundColor = data.bg;
        var avatarEl = document.getElementById('summaryAvatar');
        avatarEl.textContent = data.initial; avatarEl.style.color = data.statusColor; avatarEl.style.backgroundColor = data.bg; avatarEl.style.border = `1px solid ${data.statusColor}`;
        document.getElementById('summaryFullLink').href = `/modules/customers/view.php?id=${data.id}`;
        document.getElementById('summaryLastPurchase').textContent = data.lastPurchase;
        document.getElementById('summaryTotalSales').textContent = data.totalSales;

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

    window.closeCustomerSummaryModal = function() {
        var modal = document.getElementById('customerSummaryModal');
        if (!modal) return;
        modal.classList.remove('show');
        setTimeout(() => modal.style.display = 'none', 200);
    };

    window.openOpportunityModal = function() {
        var modal = document.getElementById('opportunityModal');
        if(modal) {
            document.getElementById('form-create-opportunity').reset();
            document.getElementById('modalCustomerId').value = '';
            document.getElementById('modalCustomerSearch').value = '';
            document.getElementById('modalNewCustomerBlock').style.display = 'none';
            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);
        }
    };
    
    window.openOpportunityModalWithClient = function(clientId, clientName) {
        window.openOpportunityModal();
        setTimeout(() => {
            document.getElementById('modalCustomerId').value = clientId;
            document.getElementById('modalCustomerSearch').value = clientName;
            document.getElementById('modalCustomerSearch').dispatchEvent(new Event('input', {bubbles: true}));
        }, 50);
    };

    window.closeOpportunityModal = function() {
        var modal = document.getElementById('opportunityModal');
        if(modal) { modal.classList.remove('show'); setTimeout(() => modal.style.display = 'none', 200); }
    };

    if (!window.__crmIndexGlobalClicksAttached) {
        document.addEventListener('click', (e) => { 
            var cModal = document.getElementById('customerSummaryModal');
            if (cModal && e.target === cModal) window.closeCustomerSummaryModal(); 
            var oModal = document.getElementById('opportunityModal');
            if (oModal && e.target === oModal) window.closeOpportunityModal(); 
        });
        window.__crmIndexGlobalClicksAttached = true;
    }

    // =========================================================================
    // AUTOCOMPLETE CLIENTES (CORREGIDO SPA SAFE)
    // =========================================================================
    var dbCustomers = <?php echo json_encode(array_map(function($c) { return [
        'id' => (int)$c['id'],
        'name' => !empty($c['commercial_name']) ? $c['commercial_name'] : $c['customer_name'],
        'commercial_name' => $c['commercial_name'] ?? '',
        'customer_name' => $c['customer_name'] ?? '',
        'legal_name' => $c['legal_name'] ?? '',
        'rut' => $c['customer_tax_id'] ?? '',
        'city' => $c['city'] ?? ''
    ]; }, $customers)); ?>;
    var modalSearch = document.getElementById('modalCustomerSearch');
    var modalHidden = document.getElementById('modalCustomerId');
    var modalResults = document.getElementById('modalCustomerResults');
    var newCustomerBlock = document.getElementById('modalNewCustomerBlock');
    var newCustomerBtn = document.getElementById('modalNewCustomerBtn');

    function normalizeSearch(text) { 
        if (window.ICY_NORMALIZE_SEARCH) return window.ICY_NORMALIZE_SEARCH(text);
        return (text || '').toString().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").trim(); 
    }
    function normalizeRutSearch(text) {
        if (window.ICY_NORMALIZE_RUT_SEARCH) return window.ICY_NORMALIZE_RUT_SEARCH(text);
        return normalizeSearch(text).replace(/[^0-9k]/g, '');
    }

    function showNewCustomerBlock(show) {
        if (!newCustomerBlock) return;
        newCustomerBlock.style.display = show ? 'block' : 'none';
        newCustomerBlock.querySelectorAll('.is-required input:not([type="hidden"]), .is-required select, .is-required textarea').forEach(function(field) {
            field.required = !!show;
        });
        if (show && window.ICY_CUSTOMER_LOCATION) {
            window.ICY_CUSTOMER_LOCATION.init(newCustomerBlock);
        }
    }
    
    function selectCustomer(c) {
        modalSearch.value = c.name; 
        modalHidden.value = c.id; 
        
        if (modalResults) {
            modalResults.style.display = 'none'; 
            modalResults.innerHTML = '';
        }
        showNewCustomerBlock(false);
        
        if(modalSearch) modalSearch.dispatchEvent(new Event('change', { bubbles: true }));
    }

    if(modalSearch) {
        if(modalResults) {
            modalResults.style.position = 'absolute';
            modalResults.style.width = '100%';
            modalResults.style.zIndex = '1060';
            modalResults.style.boxShadow = 'var(--shadow-lg)';
            modalResults.style.border = '1px solid var(--border-default)';
            modalResults.style.background = 'var(--surface-1)';
            modalResults.style.maxHeight = '220px';
            modalResults.style.overflowY = 'auto';
            modalResults.style.borderRadius = 'var(--radius-lg)';
            modalResults.style.top = '100%';
            modalResults.style.left = '0';
            modalResults.style.display = 'none';
        }

        modalSearch.addEventListener('input', function () {
            modalHidden.value = '';
            var rawQuery = modalSearch.value.trim();
            var query = normalizeSearch(rawQuery);
            var rutQuery = normalizeRutSearch(rawQuery);
            if(modalResults) modalResults.innerHTML = '';
            
            if (query.length < 2) {
                if(modalResults) modalResults.style.display = 'none';
                return;
            }
            
            var matches = dbCustomers.filter(function (c) {
                var rawHaystack = [c.name, c.commercial_name, c.customer_name, c.legal_name, c.rut, c.city].filter(Boolean).join(' ');
                var haystack = normalizeSearch(rawHaystack);
                var rutHaystack = normalizeRutSearch(rawHaystack);
                return haystack.indexOf(query) !== -1 || (rutQuery.length >= 2 && rutHaystack.indexOf(rutQuery) !== -1);
            }).slice(0, 8);

            if (!matches.length) {
                if(modalResults) {
                    modalResults.innerHTML = '<div style="padding: 12px; color: var(--text-muted); font-size: 0.85rem; text-align: center;">Sin coincidencias. Puedes crear un cliente nuevo.</div>';
                    modalResults.style.display = 'block';
                }
                return;
            }

            matches.forEach(function (c) {
                var button = document.createElement('button');
                button.type = 'button'; 
                button.style.cssText = 'width: 100%; text-align: left; padding: 10px 12px; background: var(--surface-1); border: none; border-bottom: 1px solid var(--border-subtle); cursor: pointer; display: flex; flex-direction: column; transition: background 0.2s;';
                button.innerHTML = '<strong style="color: var(--text-primary); font-size: 0.9rem;">' + (c.name || c.commercial_name || c.legal_name || c.customer_name) + '</strong><span style="color: var(--text-muted); font-size: 0.75rem; margin-top: 2px;">' + [c.legal_name, c.rut, c.city].filter(Boolean).join(' · ') + '</span>';
                
                button.addEventListener('mouseenter', function() { this.style.background = 'var(--surface-2)'; });
                button.addEventListener('mouseleave', function() { this.style.background = 'var(--surface-1)'; });

                button.addEventListener('click', function () { selectCustomer(c); });
                if(modalResults) modalResults.appendChild(button);
            });
            
            if(modalResults) modalResults.style.display = 'block';
        });

        document.addEventListener('click', function(e) {
            if (modalResults && modalSearch && !modalSearch.contains(e.target) && !modalResults.contains(e.target)) {
                modalResults.style.display = 'none';
            }
        });
    }

    if(newCustomerBtn) {
        newCustomerBtn.addEventListener('click', function () {
            var isVis = newCustomerBlock.style.display === 'block';
            if (isVis) { showNewCustomerBlock(false); } else {
                modalHidden.value = ''; modalSearch.value = ''; 
                if(modalResults) { modalResults.innerHTML = ''; modalResults.style.display = 'none'; }
                showNewCustomerBlock(true);
            }
        });
    }

    var rutInput = document.querySelector('input[name="new_customer_tax_id"]');
    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;
        });
    }

    var oPrefixSelect = document.getElementById('modal_opp_phone_prefix');
    var oNumberInput = document.getElementById('modal_opp_phone_number');
    var oRealPhone = document.getElementById('modal_opp_real_phone_input');
    if (oPrefixSelect && oNumberInput && oRealPhone) {
        function updateOppPhone() {
            var num = oNumberInput.value.replace(/[^0-9\s-]/g, ''); 
            oNumberInput.value = num;
            if (num.length > 0) oRealPhone.value = oPrefixSelect.value + ' ' + num;
            else oRealPhone.value = '';
        }
        oPrefixSelect.addEventListener('change', updateOppPhone);
        oNumberInput.addEventListener('input', updateOppPhone);
    }

})();
</script>

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