<?php

// =========================================================================
// MOTOR AJAX: ACTUALIZACION RAPIDA DE ESTADO (DRAG & DROP / MENU)
// =========================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_update_stage'])) {
    require_once '../../core/config.php';
    require_once '../../core/session.php';
    require_once '../../core/database.php';
    require_once '../../core/permissions.php';
    require_once '../../services/crm/PaymentStatusService.php';

    header('Content-Type: application/json; charset=utf-8');

    require_login();

    if (!user_can('module.crm')) {
        http_response_code(403);
        echo json_encode(array('success' => false, 'error' => 'No autorizado para actualizar oportunidades.'));
        exit;
    }

    $allowedStages = array('nuevo', 'contactado', 'cotizando', 'negociacion', 'ganada', 'perdida', 'facturada');

    $pdo = db();
    $sessionUser = current_user();
    $currentUser = !empty($sessionUser['name']) ? $sessionUser['name'] : (!empty($sessionUser['email']) ? $sessionUser['email'] : 'Sistema');

    $oppId = isset($_POST['id']) ? (int) $_POST['id'] : 0;
    $newStage = isset($_POST['stage']) ? trim($_POST['stage']) : '';

    if ($oppId <= 0 || $newStage === '' || !in_array($newStage, $allowedStages, true)) {
        http_response_code(422);
        echo json_encode(array('success' => false, 'error' => 'Datos invalidos para actualizar etapa.'));
        exit;
    }

    $stmt = $pdo->prepare("
        SELECT o.*, c.payment_terms, c.facto_payment_term
        FROM crm_opportunities o
        LEFT JOIN crm_customers c ON c.id = o.customer_id
        WHERE o.id = ? AND o.deleted_at IS NULL
        LIMIT 1
    ");
    $stmt->execute(array($oppId));
    $old = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$old) {
        http_response_code(404);
        echo json_encode(array('success' => false, 'error' => 'Oportunidad no encontrada.'));
        exit;
    }

    if ($old['stage'] === $newStage) {
        echo json_encode(array('success' => true, 'stage' => $newStage, 'unchanged' => true));
        exit;
    }

    try {
        $pdo->beginTransaction();

        $paymentStatus = $old['payment_status'] ?? 'no_facturado';
        $paymentDueDate = $old['payment_due_date'] ?? null;
        $paymentPaidDate = $old['payment_paid_date'] ?? null;
        $billingChanges = array();

        if ($newStage === 'facturada') {
            $billingAdjustment = PaymentStatusService::applyFacturadaRules(array(
                'stage' => $newStage,
                'old_stage' => $old['stage'] ?? '',
                'payment_status' => $paymentStatus,
                'payment_due_date' => $paymentDueDate,
                'payment_paid_date' => $paymentPaidDate,
                'payment_terms' => $old['payment_terms'] ?? ($old['facto_payment_term'] ?? 'contado'),
                'base_date' => date('Y-m-d'),
            ));
            $paymentStatus = $billingAdjustment['payment_status'];
            $paymentDueDate = $billingAdjustment['payment_due_date'];
            $paymentPaidDate = $billingAdjustment['payment_paid_date'];
            $billingChanges = $billingAdjustment['changes'];
        }

        $stmt = $pdo->prepare("
            UPDATE crm_opportunities
            SET stage = ?, payment_status = ?, payment_due_date = ?, payment_paid_date = ?, updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute(array($newStage, $paymentStatus, $paymentDueDate, $paymentPaidDate, $oppId));

        $desc = 'Etapa: ' . $old['stage'] . ' -> ' . $newStage;
        if (!empty($billingChanges)) {
            $desc .= "
" . implode("
", $billingChanges);
        }
        $stmt = $pdo->prepare("
            INSERT INTO crm_activities
            (opportunity_id, customer_id, customer_name, activity_type, title, description, owner_name, activity_date)
            VALUES (?, ?, ?, 'sistema', 'Oportunidad actualizada', ?, ?, NOW())
        ");
        $stmt->execute(array(
            $oppId,
            (int) $old['customer_id'],
            $old['customer_name'],
            $desc,
            $currentUser
        ));

        $pdo->commit();

        echo json_encode(array(
            'success' => true,
            'id' => $oppId,
            'old_stage' => $old['stage'],
            'stage' => $newStage,
            'payment_status' => $paymentStatus,
            'payment_due_date' => $paymentDueDate,
            'payment_paid_date' => $paymentPaidDate
        ));
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        http_response_code(500);
        echo json_encode(array('success' => false, 'error' => 'Error al actualizar etapa.'));
    }

    exit;
}

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 = 'Embudo Comercial';
PaymentStatusService::processOverdueOpportunities(db());
$crm = new CrmService();
$embudo = $crm->getEmbudo();
$customers = $crm->getCustomers();
$assignableUsers = $crm->getAssignableUsers();
$currentUser = current_user();

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

function field_error($field, $formErrors) { return isset($formErrors[$field]) ? $formErrors[$field] : ''; }
function field_class($field, $formErrors, $required = false) {
    $classes = array('form-field');
    if ($required) $classes[] = 'is-required';
    if (isset($formErrors[$field])) $classes[] = 'has-error';
    return implode(' ', $classes);
}

$ownerValue = $formOld['owner_name'] ?? $currentUser['name'] ?? '';

$stages = array('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 = array('' => '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');

$openModalId = isset($_GET['open_modal']) ? (int) $_GET['open_modal'] : 0;

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

<main class="app-main no-scroll-main" id="embudo-main">
    
    <style>
    /* =========================================================
       Embudo CRM - mobile/desktop UX contained in this module
       Desktop: page locked, internal kanban/card scroll.
       Mobile: horizontal kanban swipe + internal column scroll.
       ========================================================= */
    body #embudo-main {
        min-width: 0 !important;
        height: 100vh !important;
        height: 100dvh !important;
        min-height: 0 !important;
        overflow: hidden !important;
        display: flex !important;
        flex-direction: column !important;
    }

    body #embudo-main > .content.flex-content,
    body #embudo-main > .flex-content {
        flex: 1 1 0% !important;
        min-height: 0 !important;
        height: auto !important;
        overflow: hidden !important;
        display: flex !important;
        flex-direction: column !important;
        padding-bottom: 24px !important;
    }

    #embudo-main .header-responsive,
    #embudo-main .filter-bar-container,
    #embudo-main .alert {
        flex: 0 0 auto !important;
    }

    #embudo-main .header-responsive {
        display: flex !important;
        align-items: flex-start !important;
        justify-content: space-between !important;
        gap: 16px !important;
        margin-bottom: 16px !important;
    }

    #embudo-main .page-header-content {
        min-width: 0 !important;
    }

    #embudo-main .page-header-content h2 {
        line-height: 1.1 !important;
        margin-bottom: 4px !important;
    }

    #embudo-main .top-actions-cluster {
        flex: 0 0 auto !important;
        display: flex !important;
        align-items: center !important;
        justify-content: flex-end !important;
        gap: 10px !important;
        flex-wrap: nowrap !important;
    }

    #embudo-main .filter-bar-container {
        position: relative !important;
        z-index: 50 !important;
        display: flex !important;
        gap: 12px !important;
        flex-wrap: nowrap !important;
        padding: 12px 16px !important;
        background: var(--surface-1) !important;
        border: 1px solid var(--border-default) !important;
        border-radius: var(--radius-xl) !important;
        margin-bottom: 16px !important;
        align-items: center !important;
    }

    #embudo-main .filter-bar-container .form-field {
        margin: 0 !important;
        min-width: 0 !important;
    }

    #embudo-main .input-with-icon {
        position: relative !important;
        display: flex !important;
        align-items: center !important;
        width: 100% !important;
    }

    #embudo-main .input-with-icon svg {
        position: absolute !important;
        left: 14px !important;
        top: 50% !important;
        transform: translateY(-50%) !important;
        width: 18px !important;
        height: 18px !important;
        color: var(--text-muted) !important;
        pointer-events: none !important;
    }

    #embudo-main .input-with-icon input {
        padding-left: 42px !important;
        width: 100% !important;
        min-width: 0 !important;
    }

    #embudo-main .crm-kanban-wrapper {
        flex: 1 1 0% !important;
        min-height: 0 !important;
        width: 100% !important;
        max-width: 100% !important;
        overflow-x: auto !important;
        overflow-y: hidden !important;
        scroll-behavior: smooth !important;
        overscroll-behavior-x: contain !important;
        -webkit-overflow-scrolling: touch !important;
        scrollbar-width: thin !important;
        scrollbar-color: var(--border-strong) transparent !important;
    }

    #embudo-main .crm-kanban-wrapper::-webkit-scrollbar { height: 8px !important; }
    #embudo-main .crm-kanban-wrapper::-webkit-scrollbar-track { background: transparent !important; }
    #embudo-main .crm-kanban-wrapper::-webkit-scrollbar-thumb { background: var(--border-strong) !important; border-radius: 4px !important; }
    #embudo-main .crm-kanban-wrapper::-webkit-scrollbar-thumb:hover { background: var(--text-muted) !important; }

    #embudo-main .crm-kanban-track {
        display: flex !important;
        align-items: stretch !important;
        gap: 16px !important;
        height: 100% !important;
        min-height: 0 !important;
        width: max-content !important;
        min-width: max-content !important;
        padding-bottom: 8px !important;
    }

    #embudo-main .crm-column {
        flex: 0 0 320px !important;
        width: 320px !important;
        max-width: 320px !important;
        min-width: 320px !important;
        height: 100% !important;
        min-height: 0 !important;
        display: flex !important;
        flex-direction: column !important;
        background: var(--surface-1) !important;
        border: 1px solid var(--border-default) !important;
        border-radius: var(--radius-xl) !important;
        overflow: hidden !important;
    }

    #embudo-main .crm-column-header {
        flex: 0 0 54px !important;
        min-height: 54px !important;
        padding: 0 var(--space-4) !important;
        display: flex !important;
        align-items: center !important;
        justify-content: space-between !important;
        border-bottom: 1px solid var(--border-subtle) !important;
        background: var(--surface-2) !important;
        z-index: 4 !important;
    }

    #embudo-main .crm-column-body {
        flex: 1 1 0% !important;
        min-height: 0 !important;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        padding: 12px !important;
        display: flex !important;
        flex-direction: column !important;
        gap: 12px !important;
        transition: background 0.2s !important;
        -webkit-overflow-scrolling: touch !important;
        overscroll-behavior: contain !important;
        scrollbar-width: thin !important;
        scrollbar-color: var(--border-default) transparent !important;
    }

    #embudo-main .crm-column-body.drag-over {
        background: color-mix(in srgb, var(--color-primary) 5%, var(--surface-1)) !important;
    }

    #embudo-main .crm-column-body::-webkit-scrollbar { width: 5px !important; }
    #embudo-main .crm-column-body::-webkit-scrollbar-track { background: transparent !important; }
    #embudo-main .crm-column-body::-webkit-scrollbar-thumb { background: var(--border-default) !important; border-radius: 4px !important; }

    #embudo-main .crm-opportunity-card {
        position: relative !important;
        flex: 0 0 auto !important;
        padding: 14px !important;
        background: var(--surface-2) !important;
        border: 1px solid var(--border-default) !important;
        border-radius: var(--radius-lg) !important;
        cursor: grab !important;
        transition: transform 0.1s, box-shadow 0.1s, border-color 0.1s, background 0.1s !important;
        user-select: none !important;
        overflow: visible !important;
    }

    #embudo-main .crm-opportunity-card:active { cursor: grabbing !important; }
    #embudo-main .crm-opportunity-card:hover { border-color: var(--border-strong) !important; background: var(--surface-3) !important; }
    #embudo-main .crm-opportunity-card.is-dragging { opacity: 0.5 !important; transform: scale(0.96) !important; box-shadow: var(--shadow-md) !important; z-index: 100 !important; }
    #embudo-main .crm-opportunity-card.is-hidden { display: none !important; }

    #embudo-main .crm-opportunity-header {
        display: flex !important;
        align-items: flex-start !important;
        justify-content: space-between !important;
        margin-bottom: 4px !important;
        gap: 8px !important;
    }

    #embudo-main .block-truncate {
        display: block !important;
        width: 100% !important;
        min-width: 0 !important;
    }

    #embudo-main .crm-empty {
        flex: 0 0 auto !important;
        text-align: center !important;
        padding: 24px 12px !important;
        color: var(--text-muted) !important;
        font-size: 0.85rem !important;
        border: 1px dashed var(--border-default) !important;
        border-radius: var(--radius-md) !important;
        margin-top: 8px !important;
    }

    #embudo-main .btn-invisible {
        position: absolute !important;
        top: 10px !important;
        right: 10px !important;
        background: transparent !important;
        border: none !important;
        padding: 4px !important;
        border-radius: 6px !important;
        color: var(--text-muted) !important;
        cursor: pointer !important;
        z-index: 10 !important;
    }

    #embudo-main .btn-invisible:hover {
        background: var(--border-subtle) !important;
        color: var(--text-primary) !important;
    }

    #embudo-main .btn-invisible i { width: 18px !important; height: 18px !important; }

    #embudo-main .btn-sort-col {
        background: transparent !important;
        border: 1px solid var(--border-default) !important;
        padding: 4px 6px !important;
        border-radius: 6px !important;
        color: var(--text-muted) !important;
        cursor: pointer !important;
        display: inline-flex !important;
        align-items: center !important;
        justify-content: center !important;
        transition: all 0.2s !important;
    }

    #embudo-main .btn-sort-col:hover {
        background: var(--surface-3) !important;
        color: var(--text-primary) !important;
        border-color: var(--border-strong) !important;
    }

    #embudo-main .stage-dropdown-menu {
        position: absolute !important;
        top: 36px !important;
        right: 10px !important;
        width: 160px !important;
        background: var(--surface-1) !important;
        border: 1px solid var(--border-default) !important;
        border-radius: 12px !important;
        box-shadow: var(--shadow-lg) !important;
        z-index: 80 !important;
        display: none !important;
        flex-direction: column !important;
        padding: 6px !important;
    }

    #embudo-main .stage-dropdown-menu.is-open { display: flex !important; }

    #embudo-main .stage-dropdown-btn {
        background: transparent !important;
        border: none !important;
        padding: 9px 12px !important;
        text-align: left !important;
        font-size: 0.85rem !important;
        color: var(--text-primary) !important;
        border-radius: 8px !important;
        cursor: pointer !important;
    }

    #embudo-main .stage-dropdown-btn:hover {
        background: var(--surface-2) !important;
        color: var(--color-primary) !important;
    }

    /* Create opportunity modal: same height and footer pattern as CRM Index. */
    body #embudo-main #opportunityModal.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 !important;
    }

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

    body #embudo-main #opportunityModal .product-modal-box {
        background: var(--surface-1) !important;
        width: min(1080px, calc(100vw - 48px)) !important;
        max-width: calc(100vw - 48px) !important;
        height: min(700px, calc(100dvh - 48px)) !important;
        min-height: min(560px, calc(100dvh - 100px)) !important;
        max-height: calc(100dvh - 100px) !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) !important;
        transition: transform 0.2s ease !important;
    }

    body #embudo-main #opportunityModal.product-modal-backdrop.show .product-modal-box {
        transform: translateY(0) !important;
    }

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

    body #embudo-main #opportunityModal .product-modal-header {
        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 #embudo-main #opportunityModal .product-modal-body {
        flex: 1 1 auto !important;
        min-height: 0 !important;
        max-height: none !important;
        padding: var(--space-5) !important;
        margin-left: 0 !important;
        overflow-y: auto !important;
        overflow-x: hidden !important;
        -webkit-overflow-scrolling: touch !important;
    }

    body #embudo-main #opportunityModal .product-modal-footer {
        min-height: 76px !important;
        height: auto !important;
        max-height: none !important;
        padding: 14px 20px !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;
        flex-wrap: nowrap !important;
        background: var(--surface-0) !important;
        border-radius: 0 0 var(--radius-xl) var(--radius-xl) !important;
        overflow: visible !important;
    }

    body #embudo-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 #embudo-main #opportunityModal #saveOpportunityBtn {
        min-width: 178px !important;
    }

    body #embudo-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;
    }

    #embudo-main #modalNewCustomerBlock {
        padding: 16px !important;
        background: var(--surface-2) !important;
        border-radius: var(--radius-lg) !important;
        margin-bottom: 16px !important;
        border: 1px solid var(--border-default) !important;
    }

    @media (max-width: 760px) {
        body #embudo-main > .content.flex-content,
        body #embudo-main > .flex-content {
            padding: 16px 12px calc(16px + env(safe-area-inset-bottom)) !important;
            gap: 12px !important;
        }

        #embudo-main .header-responsive {
            display: grid !important;
            grid-template-columns: minmax(0, 1fr) auto !important;
            align-items: start !important;
            gap: 10px !important;
            margin-bottom: 0 !important;
        }

        #embudo-main .page-header-content {
            padding-right: 0 !important;
        }

        #embudo-main .page-header-content .label {
            font-size: 0.66rem !important;
        }

        #embudo-main .page-header-content h2 {
            font-size: clamp(1.28rem, 6vw, 1.55rem) !important;
            line-height: 1.08 !important;
            margin: 0 !important;
        }

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

        #embudo-main .top-actions-cluster {
            gap: 8px !important;
            margin-left: 0 !important;
        }

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

        #embudo-main .btn-icon-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;
        }

        #embudo-main .filter-bar-container {
            flex-direction: row !important;
            padding: 10px !important;
            gap: 8px !important;
            margin-bottom: 0 !important;
            border-radius: 16px !important;
        }

        #embudo-main .filter-bar-container .form-field:nth-child(1) {
            flex: 1 1 auto !important;
            min-width: 0 !important;
        }

        #embudo-main .filter-bar-container .form-field:nth-child(2) {
            flex: 0 0 118px !important;
            width: 118px !important;
            min-width: 118px !important;
        }

        #embudo-main .filter-bar-container select.select {
            padding-left: 10px !important;
            padding-right: 28px !important;
            font-size: 0.85rem !important;
            text-overflow: ellipsis !important;
            white-space: nowrap !important;
            overflow: hidden !important;
        }

        #embudo-main .input-with-icon svg {
            left: 12px !important;
            width: 17px !important;
            height: 17px !important;
        }

        #embudo-main .input-with-icon input {
            padding-left: 38px !important;
            font-size: 0.9rem !important;
        }

        #embudo-main .crm-kanban-wrapper {
            scroll-snap-type: x mandatory !important;
            padding: 0 !important;
        }

        #embudo-main .crm-kanban-track {
            gap: 12px !important;
            height: 100% !important;
            padding: 0 2px 12px 0 !important;
        }

        #embudo-main .crm-column {
            scroll-snap-align: start !important;
            flex: 0 0 calc(100vw - 34px) !important;
            width: calc(100vw - 34px) !important;
            min-width: calc(100vw - 34px) !important;
            max-width: calc(100vw - 34px) !important;
            border-radius: 18px !important;
        }

        #embudo-main .crm-column-header {
            min-height: 50px !important;
            flex-basis: 50px !important;
            padding: 0 12px !important;
        }

        #embudo-main .crm-column-header strong {
            font-size: 0.92rem !important;
        }

        #embudo-main .crm-column-body {
            padding: 10px !important;
            gap: 10px !important;
        }

        #embudo-main .crm-opportunity-card {
            padding: 12px !important;
            cursor: pointer !important;
        }

        #embudo-main .stage-dropdown-menu {
            width: min(172px, calc(100vw - 84px)) !important;
            right: 8px !important;
        }

        body #embudo-main #opportunityModal.product-modal-backdrop {
            padding: 12px !important;
        }

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

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

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

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

        body #embudo-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 #embudo-main #opportunityModal #saveOpportunityBtn {
            min-width: 124px !important;
        }

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

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

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

        #embudo-main #modalCustomerResults {
            max-height: min(36dvh, 260px) !important;
        }
    }
    </style>

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

    <section class="content flex-content">

        <div class="page-header header-responsive" style="flex-shrink: 0; margin-bottom: 16px;">
            <div class="page-header-content">
                <span class="label">CRM</span>
                <h2>Embudo Comercial</h2>
                <p class="text-secondary text-truncate" style="max-width: 100%;">Vista interactiva de oportunidades en curso.</p>
            </div>

            <div class="cluster top-actions-cluster">
                <a class="btn btn-outline btn-icon-mobile" href="/modules/crm/" title="Volver al Dashboard">
                    <i data-lucide="arrow-left"></i>
                    <span class="mobile-hidden">Volver al CRM</span>
                </a>

                <button type="button" class="btn btn-primary btn-icon-mobile" onclick="window.openOpportunityModal()" title="Nueva oportunidad">
                    <i data-lucide="plus"></i>
                    <span class="mobile-hidden">Nueva oportunidad</span>
                </button>
            </div>
        </div>

        <div class="filter-bar-container" style="flex-shrink: 0;">
            <div class="form-field" style="flex: 1; min-width: 0; margin: 0;">
                <div class="input-with-icon">
                    <i data-lucide="search"></i>
                    <input type="text" id="filterSearch" class="input" placeholder="Buscar oportunidad, cliente, RUT, ciudad..." autocomplete="off">
                </div>
            </div>
            <div class="form-field" style="flex: 0 0 180px; margin: 0;">
                <select id="filterOwner" class="select" style="width: 100%;">
                    <option value="">Todos</option>
                    <?php foreach ($assignableUsers as $user): ?>
                        <?php if (in_array($user['role'], ['comercial', 'administracion'])): ?>
                            <option value="<?php echo safe_text($user['name']); ?>"><?php echo safe_text($user['name']); ?></option>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        
        <?php if (!empty($formErrors)): ?>
            <div class="alert alert-error 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="crm-kanban-wrapper">
            <div class="crm-kanban-track" id="kanban-track">

                <?php foreach ($stages as $stageKey => $stageLabel): ?>
                    <div class="crm-column" data-stage="<?php echo $stageKey; ?>">

                        <div class="crm-column-header">
                            <strong style="font-size: 0.95rem;"><?php echo safe_text($stageLabel); ?></strong>
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <button type="button" class="btn-sort-col" onclick="window.sortColumn('<?php echo $stageKey; ?>', this)" title="Ordenar: Más recientes / Más antiguas">
                                    <i data-lucide="arrow-down" style="width: 14px; height: 14px;"></i>
                                </button>
                                <span class="badge badge-counter" style="font-size: 0.8rem; padding: 2px 8px;"><?php echo count($embudo[$stageKey] ?? []); ?></span>
                            </div>
                        </div>

                        <div class="crm-column-body dropzone" data-stage="<?php echo $stageKey; ?>" data-sort-dir="desc">
                            <?php if (!empty($embudo[$stageKey])): ?>
                                <?php foreach ($embudo[$stageKey] as $opportunity): 
                                    $oppId = (int) $opportunity['id'];
                                    $sortTimestamp = strtotime($opportunity['updated_at'] ?? $opportunity['created_at'] ?? 'now');
                                ?>
                                    
                                    <div class="crm-opportunity-card" 
                                         draggable="true" 
                                         data-id="<?php echo $oppId; ?>" 
                                         data-stage="<?php echo $stageKey; ?>" 
                                         data-date="<?php echo $sortTimestamp; ?>" 
                                         data-title="<?php echo htmlspecialchars(mb_strtolower($opportunity['title'], 'UTF-8'), ENT_QUOTES, 'UTF-8'); ?>"
                                         data-customer="<?php echo htmlspecialchars(mb_strtolower($opportunity['customer_name'], 'UTF-8'), ENT_QUOTES, 'UTF-8'); ?>"
                                         data-search="<?php echo htmlspecialchars(mb_strtolower(implode(' ', array_filter(array($opportunity['title'] ?? '', $opportunity['customer_name'] ?? '', $opportunity['customer_tax_id'] ?? '', $opportunity['customer_legal_name'] ?? '', $opportunity['customer_email'] ?? '', $opportunity['customer_phone'] ?? '', $opportunity['customer_city'] ?? '', $opportunity['customer_district'] ?? '', $opportunity['customer_region'] ?? '', $opportunity['customer_country'] ?? ''))), 'UTF-8'), ENT_QUOTES, 'UTF-8'); ?>"
                                         data-owner="<?php echo safe_text($opportunity['owner_name'] ?: 'Sistema'); ?>"
                                         onclick="window.openOppViewModal(event, <?php echo $oppId; ?>)">
                                        
                                        <div class="crm-opportunity-header">
                                            <strong style="font-size: 0.9rem; color: var(--text-primary); padding-right: 28px; display: block; line-height: 1.3; word-break: break-word;">
                                                <?php echo safe_text($opportunity['title']); ?>
                                            </strong>
                                            
                                            <button type="button" class="btn-invisible stage-menu-trigger" onclick="window.toggleStageMenu(event, <?php echo $oppId; ?>)" title="Cambiar etapa">
                                                <i data-lucide="chevron-down"></i>
                                            </button>
                                            
                                            <div class="stage-dropdown-menu" id="stage-menu-<?php echo $oppId; ?>">
                                                <div style="padding: 8px 12px; font-size: 0.7rem; font-weight: 700; color: var(--text-muted); text-transform: uppercase;">Mover a...</div>
                                                <?php foreach ($stages as $sk => $sl): ?>
                                                    <?php if ($sk !== $stageKey): ?>
                                                        <button type="button" class="stage-dropdown-btn" onclick="window.changeStage(event, <?php echo $oppId; ?>, '<?php echo $sk; ?>', this)">
                                                            <?php echo safe_text($sl); ?>
                                                        </button>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>

                                        <span class="text-truncate block-truncate" style="color: var(--text-secondary); font-size: 0.8rem; margin-top: 4px;">
                                            <?php echo safe_text($opportunity['customer_name']); ?>
                                        </span>

                                        <div class="crm-opportunity-meta">
                                            <span style="color: var(--color-success); font-weight: 650;"><?php echo clp($opportunity['expected_value']); ?></span>
                                            <span class="badge" style="font-size: 0.7rem;"><?php echo (int) $opportunity['probability']; ?>%</span>
                                        </div>

                                        <div class="crm-opportunity-meta" style="margin-top: 8px; border-top: 1px dashed var(--border-subtle); padding-top: 8px;">
                                            <span class="text-truncate" style="max-width: 60%;">
                                                <?php echo !empty($opportunity['next_action']) ? safe_text($opportunity['next_action']) : 'Sin acción'; ?>
                                            </span>
                                            <span style="font-size: 0.75rem;">
                                                <?php echo !empty($opportunity['next_action_date']) ? safe_text(date('d-m', strtotime($opportunity['next_action_date']))) : '—'; ?>
                                            </span>
                                        </div>
                                    </div>

                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="crm-empty drop-placeholder">
                                    <i data-lucide="inbox" style="margin: 0 auto 8px; color: var(--border-strong);"></i>
                                    Soltar aquí
                                </div>
                            <?php endif; ?>
                        </div>

                    </div>
                <?php endforeach; ?>

            </div>
        </section>

    </section>
    
    <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 opportunity-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() {
    
    // --- MAGIA SPA: INTERCEPTOR GLOBAL PARA ELIMINAR OPORTUNIDADES ---
    // Atrapamos cualquier intento de eliminar una oportunidad desde los modales y lo hacemos silenciosamente.
    if (!window.__embudoGlobalDeleteAttached) {
        document.addEventListener('submit', function(e) {
            const deleteForm = e.target.closest('form[action*="opportunity_delete.php"]');
            if (deleteForm) {
                // Si el evento ya fue prevenido (ej. el usuario canceló el confirm nativo), no hacemos nada
                if (e.defaultPrevented) return;
                
                e.preventDefault();
                
                const btn = deleteForm.querySelector('button[type="submit"]');
                const originalHtml = btn ? btn.innerHTML : '';
                if (btn) {
                    btn.disabled = true;
                    btn.innerHTML = '<i data-lucide="loader" class="spin-icon"></i>';
                    if (window.lucide) window.lucide.createIcons();
                }

                // Agregamos la bandera mágica para que opportunity_delete.php nos responda con JSON
                const formData = new FormData(deleteForm);
                formData.append('ajax', '1');
                const oppId = formData.get('id');

                fetch(deleteForm.action, {
                    method: 'POST',
                    body: formData
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        // 1. Desaparecemos el modal flotante instantáneamente
                        const backdrop = document.getElementById('oppViewModalBackdrop');
                        if (backdrop) backdrop.remove();
                        
                        // 2. Buscamos la tarjeta en el tablero y la eliminamos sin recargar la página
                        const card = document.querySelector(`.crm-opportunity-card[data-id="${oppId}"]`);
                        if (card) {
                            card.remove();
                            // 3. Recalculamos los contadores de la columna
                            window.updateColumnCounts();
                        } else {
                            // Backup: si por algún motivo no encontramos la tarjeta, recargamos
                            (window.ICY_SPA_RELOAD ? window.ICY_SPA_RELOAD({ force: true }) : window.location.reload());
                        }
                    } else {
                        alert(data.error || 'Error al eliminar la oportunidad.');
                        if (btn) { btn.disabled = false; btn.innerHTML = originalHtml; if (window.lucide) window.lucide.createIcons(); }
                    }
                })
                .catch(err => {
                    alert('Error de conexión al eliminar.');
                    if (btn) { btn.disabled = false; btn.innerHTML = originalHtml; if (window.lucide) window.lucide.createIcons(); }
                });
            }
        });
        window.__embudoGlobalDeleteAttached = true;
    }


    window.removeAccents = function(str) {
        return (str || '').toString().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
    };

    window.applyKanbanFilters = function() {
        const searchInput = document.getElementById('filterSearch');
        const ownerSelect = document.getElementById('filterOwner');
        if (!searchInput || !ownerSelect) return;

        const searchQuery = window.removeAccents(searchInput.value.toLowerCase().trim());
        const ownerFilter = ownerSelect.value.trim();
        const cards = document.querySelectorAll('.crm-opportunity-card');

        cards.forEach(card => {
            const title = window.removeAccents(card.dataset.title);
            const customer = window.removeAccents(card.dataset.customer);
            const searchBlob = window.removeAccents(card.dataset.search || '');
            const owner = (card.dataset.owner || '').trim();

            const matchesSearch = searchQuery === '' || title.includes(searchQuery) || customer.includes(searchQuery) || searchBlob.includes(searchQuery);
            const matchesOwner = ownerFilter === '' || owner === ownerFilter;

            if (matchesSearch && matchesOwner) {
                card.classList.remove('is-hidden');
            } else {
                card.classList.add('is-hidden');
            }
        });
        window.updateColumnCounts();
    };

    window.sortColumn = function(stage, btn) {
        const colBody = document.querySelector(`.crm-column-body[data-stage="${stage}"]`);
        if (!colBody) return;

        const cards = Array.from(colBody.querySelectorAll('.crm-opportunity-card'));
        if (cards.length < 2) return; 

        let currentDir = colBody.dataset.sortDir || 'desc';
        let newDir = currentDir === 'desc' ? 'asc' : 'desc';
        colBody.dataset.sortDir = newDir;

        cards.sort((a, b) => {
            let dateA = parseInt(a.dataset.date) || 0;
            let dateB = parseInt(b.dataset.date) || 0;
            return newDir === 'desc' ? (dateB - dateA) : (dateA - dateB);
        });

        cards.forEach(card => colBody.appendChild(card));

        if (newDir === 'desc') {
            btn.innerHTML = '<i data-lucide="arrow-down" style="width: 14px; height: 14px;"></i>';
            btn.setAttribute('title', 'Ordenar: Más recientes / Más antiguas');
        } else {
            btn.innerHTML = '<i data-lucide="arrow-up" style="width: 14px; height: 14px;"></i>';
            btn.setAttribute('title', 'Ordenar: Más antiguas / Más recientes');
        }

        if (window.lucide) lucide.createIcons();
    };

    window.toggleStageMenu = function(e, oppId) {
        e.preventDefault(); e.stopPropagation();
        document.querySelectorAll('.stage-dropdown-menu').forEach(menu => {
            if (menu.id !== 'stage-menu-' + oppId) menu.classList.remove('is-open');
        });
        var menu = document.getElementById('stage-menu-' + oppId);
        if (menu) menu.classList.toggle('is-open');
    };

    window.changeStage = function(e, oppId, newStage, btnElement) {
        e.preventDefault(); e.stopPropagation();
        btnElement.innerHTML = 'Moviendo...'; btnElement.disabled = true;
        const card = document.querySelector(`.crm-opportunity-card[data-id="${oppId}"]`);
        const targetCol = document.querySelector(`.crm-column-body[data-stage="${newStage}"]`);
        if (card && targetCol) {
            const emptyMsg = targetCol.querySelector('.crm-empty');
            if (emptyMsg) emptyMsg.style.display = 'none';
            
            const currentDir = targetCol.dataset.sortDir || 'desc';
            if (currentDir === 'desc' && targetCol.firstChild) {
                targetCol.insertBefore(card, targetCol.firstChild);
            } else {
                targetCol.appendChild(card); 
            }
            card.dataset.stage = newStage;
        }
        window.executeStageUpdate(oppId, newStage);
    };

    window.executeStageUpdate = function(oppId, newStage) {
        var formData = new FormData(); formData.append('ajax_update_stage', 'true'); formData.append('id', oppId); formData.append('stage', newStage);
        fetch('/modules/crm/embudo.php', { method: 'POST', body: formData }).then(response => response.json()).then(data => { if(data.success) { window.updateColumnCounts(); } else { alert('Error al mover la oportunidad: ' + (data.error || 'Desconocido')); (window.ICY_SPA_RELOAD ? window.ICY_SPA_RELOAD({ force: true }) : window.location.reload()); } }).catch(err => { alert('Error de conexión.'); (window.ICY_SPA_RELOAD ? window.ICY_SPA_RELOAD({ force: true }) : window.location.reload()); });
    };

    window.updateColumnCounts = function() {
        document.querySelectorAll('.crm-column').forEach(col => {
            const visibleCards = col.querySelectorAll('.crm-opportunity-card:not(.is-hidden)');
            const count = visibleCards.length; 
            const badge = col.querySelector('.badge-counter'); 
            if(badge) badge.textContent = count;
            
            const body = col.querySelector('.crm-column-body'); 
            let emptyMsg = col.querySelector('.crm-empty');
            
            if(count === 0) { 
                if(!emptyMsg) { 
                    const div = document.createElement('div'); 
                    div.className = 'crm-empty drop-placeholder'; 
                    div.innerHTML = '<i data-lucide="inbox" style="margin: 0 auto 8px; color: var(--border-strong);"></i>Sin resultados'; 
                    body.appendChild(div); 
                    if (typeof lucide !== 'undefined') lucide.createIcons(); 
                } else { 
                    emptyMsg.style.display = 'block'; 
                } 
            } else if(emptyMsg) { 
                emptyMsg.style.display = 'none'; 
            }
        });
    };

    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.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');
                var search = document.getElementById('modalCustomerSearch');
                if (search && window.matchMedia && !window.matchMedia('(pointer: coarse)').matches) search.focus();
            }, 10);
        }
    };

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

    // --- ENLAZAR EVENTOS DE FORMA SEGURA ---
    const filterSearch = document.getElementById('filterSearch');
    const filterOwner = document.getElementById('filterOwner');

    if (filterSearch) {
        filterSearch.addEventListener('input', window.applyKanbanFilters);
        filterSearch.addEventListener('keyup', window.applyKanbanFilters);
    }
    
    if (filterOwner) {
        filterOwner.addEventListener('change', window.applyKanbanFilters);
    }

    if (!window.__embudoGlobalClicksAttached) {
        document.addEventListener('click', function(e) {
            document.querySelectorAll('.stage-dropdown-menu').forEach(menu => { menu.classList.remove('is-open'); });
            var oModal = document.getElementById('opportunityModal');
            if (oModal && e.target === oModal) window.closeOpportunityModal(); 
        });
        window.__embudoGlobalClicksAttached = true;
    }

    // --- 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');
                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): ?>
        window.history.replaceState({}, document.title, window.location.pathname);
        setTimeout(() => {
            window.openOppViewModal(null, <?php echo $openModalId; ?>);
        }, 400);
    <?php endif; ?>

    // --- DRAG AND DROP ---
    const cards = document.querySelectorAll('.crm-opportunity-card');
    const dropzones = document.querySelectorAll('.dropzone');
    const isCoarsePointer = window.matchMedia && window.matchMedia('(pointer: coarse)').matches;
    
    cards.forEach(card => {
        if (isCoarsePointer) {
            card.setAttribute('draggable', 'false');
            return;
        }
        card.addEventListener('dragstart', function(e) { 
            window.draggedCard = this; 
            setTimeout(() => this.classList.add('is-dragging'), 0); 
            e.dataTransfer.effectAllowed = 'move'; 
            e.dataTransfer.setData('text/plain', this.dataset.id); 
        });
        card.addEventListener('dragend', function() { 
            this.classList.remove('is-dragging'); 
            window.draggedCard = null; 
            dropzones.forEach(dz => dz.classList.remove('drag-over')); 
            window.updateColumnCounts(); 
        });
    });
    
    dropzones.forEach(dz => {
        dz.addEventListener('dragover', function(e) { 
            e.preventDefault(); 
            e.dataTransfer.dropEffect = 'move'; 
            if (!window.draggedCard) return; 
            
            const getDragAfterElement = function(container, y) {
                const draggableElements = [...container.querySelectorAll('.crm-opportunity-card:not(.is-dragging):not(.is-hidden)')];
                return draggableElements.reduce((closest, child) => { 
                    const box = child.getBoundingClientRect(); 
                    const offset = y - box.top - box.height / 2; 
                    if (offset < 0 && offset > closest.offset) { return { offset: offset, element: child }; } else { return closest; } 
                }, { offset: Number.NEGATIVE_INFINITY }).element;
            };

            const afterElement = getDragAfterElement(this, e.clientY); 
            if (afterElement == null) { this.appendChild(window.draggedCard); } else { this.insertBefore(window.draggedCard, afterElement); } 
        });
        dz.addEventListener('dragenter', function(e) { e.preventDefault(); this.classList.add('drag-over'); });
        dz.addEventListener('dragleave', function() { this.classList.remove('drag-over'); });
        dz.addEventListener('drop', function(e) { 
            e.preventDefault(); 
            this.classList.remove('drag-over'); 
            if (!window.draggedCard) return; 
            
            const newStage = this.dataset.stage; 
            const currentStage = window.draggedCard.dataset.stage; 
            const emptyMsg = this.querySelector('.crm-empty'); 
            if (emptyMsg) emptyMsg.style.display = 'none'; 
            
            if (newStage !== currentStage) { 
                window.draggedCard.dataset.stage = newStage; 
                const oppId = window.draggedCard.dataset.id; 
                window.executeStageUpdate(oppId, newStage); 
            } 
        });
    });

    // --- AUTOCOMPLETE MODAL CLIENTES ---
    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 normalize(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 normalize(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 = normalize(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 = normalize(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'; ?>