<?php

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

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

$page_title = 'Nueva oportunidad';

$crm = new CrmService();
$customers = $crm->getCustomers();
$assignableUsers = $crm->getAssignableUsers();
$currentUser = current_user();

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

unset($_SESSION['form_errors']);
unset($_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'] ?? '';

$selectedCustomerId = isset($_GET['customer_id']) ? (int) $_GET['customer_id'] : 0;
if ($selectedCustomerId === 0 && isset($formOld['customer_id'])) {
    $selectedCustomerId = (int) $formOld['customer_id'];
}

$showNewCustomerScenario = !empty($formOld['new_customer_name']) ? 'true' : 'false';

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

$sourceValue = $formOld['source'] ?? '';
$sourceOptions = array(
    'Instagram' => 'Instagram',
    'Web' => 'Web',
    'OpenLab' => 'OpenLab',
    'Recomendación' => 'Recomendación',
    'Email' => 'Email',
    'Llamada' => 'Llamada',
    'Distribuidor' => 'Distribuidor',
    'Reposicion predictiva' => 'Reposición predictiva',
    'Otro' => 'Otro'
);

$stageValue = $formOld['stage'] ?? '';
$stageOptions = array(
    'nuevo' => 'Nuevo',
    'contactado' => 'Contactado',
    'cotizando' => 'Cotizando',
    'negociacion' => 'Negociación'
);

$competitorValue = $formOld['competitor'] ?? '';
$competitorOptions = array(
    '' => 'No identificado',
    'Abstrax' => 'Abstrax',
    'HopBurst' => 'HopBurst',
    'Pellets' => 'Pellets',
    'Proveedor tradicional' => 'Proveedor tradicional',
    'Otro' => 'Otro'
);

$nextActionValue = $formOld['next_action'] ?? '';
$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'
);

$paymentStatusValue = $formOld['payment_status'] ?? 'no_facturado';
$paymentStatusOptions = array(
    'no_facturado' => 'No facturado',
    'por_cobrar' => 'Por cobrar',
    'pagado' => 'Pagado',
    'atrasado' => 'Atrasado',
    'incobrable' => 'Incobrable'
);

?>

<main class="app-main">
    <?php require_once '../../layouts/topbar.php'; ?>

    <section class="content">

        <?php if (!empty($formErrors)): ?>
            <div class="alert alert-error">
                <strong>No fue posible guardar la oportunidad.</strong>
                <span>Revisa los campos marcados en rojo.</span>
            </div>
        <?php endif; ?>

        <form id="form-create-opportunity" class="opportunity-form" action="/modules/crm/opportunity_store.php" method="POST">

            <section class="card form-card">
                <div class="card-body">
                    <div class="form-grid form-grid-client">

                        <div class="<?php echo field_class('customer_id', $formErrors, true); ?> customer-autocomplete">
                            <label class="label">Cliente</label>

                            <div class="form-inline-control">
                                <input
                                    class="input"
                                    type="text"
                                    id="customerSearch"
                                    placeholder="Buscar cliente por nombre, razón social, RUT o email"
                                    autocomplete="off"
                                >
                                
                                <button class="btn btn-outline" type="button" id="newCustomerButton" style="width: 46px !important; min-width: 46px !important; height: 46px; 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="customerId" value="<?php echo $selectedCustomerId > 0 ? (int) $selectedCustomerId : ''; ?>">
                            <div class="customer-results" id="customerResults"></div>
                            
                            <?php if ($error = field_error('customer_id', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>

                        <div class="<?php echo field_class('title', $formErrors, true); ?>">
                            <label class="label">Título de la oportunidad</label>
                            <input
                                class="input"
                                type="text"
                                name="title"
                                value="<?php echo safe_text($formOld['title'] ?? ''); ?>"
                                placeholder="Ej: Bloom Hopper para nueva línea de producción"
                            >
                            <?php if ($error = field_error('title', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>

                    </div>
                </div>
            </section>

            <section class="card form-card" id="newCustomerBlock" style="display: none;">
                <div class="card-header">
                    <div>
                        <span class="label">Cliente nuevo</span>
                        <h3>Crear nuevo cliente</h3>
                    </div>

                    <span class="badge">Sólo si no existe</span>
                </div>

                <div class="card-body">
                    <?php icylab_render_customer_quick_fields(array(
                        'name_field' => 'new_customer_name',
                        'tax_field' => 'new_customer_tax_id',
                        'tax_id' => 'oppNewCustomerTaxId',
                        'phone_prefix_id' => 'opp_phone_prefix',
                        'phone_number_id' => 'opp_phone_number',
                        'phone_hidden_id' => 'opp_real_phone_input',
                        'show_commercial_name' => true,
                        'values' => $formOld,
                        'errors' => $formErrors,
                        'required' => array('new_customer_name', 'country', 'address', 'district', 'city', 'region'),
                        'html_required' => false
                    )); ?>
                </div>
            </section>

            <section class="card form-card">
                <div class="card-header">
                    <div>
                        <span class="label">Oportunidad</span>
                        <h3>Datos comerciales</h3>
                    </div>
                </div>

                <div class="card-body">
                    <div class="form-grid form-grid-4">

                        <div class="<?php echo field_class('stage', $formErrors, true); ?>">
                            <label class="label">Etapa</label>
                            <div class="custom-select">
                                <button class="custom-select-trigger" type="button">
                                    <span class="custom-select-label">
                                        <?php echo safe_text($stageOptions[$stageValue] ?? 'Seleccionar etapa'); ?>
                                    </span>
                                    <i data-lucide="chevron-down"></i>
                                </button>
                            
                                <input type="hidden" name="stage" value="<?php echo safe_text($stageValue); ?>">
                            
                                <div class="custom-select-menu">
                                    <?php foreach ($stageOptions as $value => $label): ?>
                                        <button class="custom-select-option <?php echo $stageValue === $value ? 'is-selected' : ''; ?>" type="button" data-value="<?php echo safe_text($value); ?>">
                                            <?php echo safe_text($label); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php if ($error = field_error('stage', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>
                        
                        <div class="form-field">
                            <label class="label">Estado de cobranza</label>
                            <div class="custom-select">
                                <button class="custom-select-trigger" type="button">
                                    <span class="custom-select-label">
                                        <?php echo safe_text($paymentStatusOptions[$paymentStatusValue] ?? 'No facturado'); ?>
                                    </span>
                                    <i data-lucide="chevron-down"></i>
                                </button>
                            
                                <input type="hidden" name="payment_status" value="<?php echo safe_text($paymentStatusValue); ?>">
                            
                                <div class="custom-select-menu">
                                    <?php foreach ($paymentStatusOptions as $value => $label): ?>
                                        <button class="custom-select-option <?php echo $paymentStatusValue === $value ? 'is-selected' : ''; ?>" type="button" data-value="<?php echo safe_text($value); ?>">
                                            <?php echo safe_text($label); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-field">
                            <label class="label">Fecha vencimiento pago</label>
                            <input class="input" type="date" name="payment_due_date" value="<?php echo safe_text($formOld['payment_due_date'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-field">
                            <label class="label">Fecha de pago</label>
                            <input class="input" type="date" name="payment_paid_date" value="<?php echo safe_text($formOld['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): ?>
                                    <?php 
                                        $isSelected = false;
                                        if (!empty($opportunity['owner_user_id']) && (int)$opportunity['owner_user_id'] === (int)$user['id']) $isSelected = true;
                                        elseif (!empty($ownerValue) && $user['name'] === $ownerValue) $isSelected = true;
                                    ?>
                                    <option value="<?php echo (int)$user['id']; ?>" data-name="<?php echo safe_text($user['name']); ?>" <?php echo $isSelected ? '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="<?php echo field_class('source', $formErrors, true); ?>">
                            <label class="label">Origen</label>
                            <div class="custom-select">
                                <button class="custom-select-trigger" type="button">
                                    <span class="custom-select-label">
                                        <?php echo safe_text($sourceOptions[$sourceValue] ?? 'Seleccionar origen'); ?>
                                    </span>
                                    <i data-lucide="chevron-down"></i>
                                </button>
                            
                                <input type="hidden" name="source" value="<?php echo safe_text($sourceValue); ?>">
                            
                                <div class="custom-select-menu">
                                    <?php foreach ($sourceOptions as $value => $label): ?>
                                        <button
                                            class="custom-select-option <?php echo $sourceValue === $value ? 'is-selected' : ''; ?>"
                                            type="button"
                                            data-value="<?php echo safe_text($value); ?>"
                                        >
                                            <?php echo safe_text($label); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php if ($error = field_error('source', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>

                        <div class="form-field">
                            <label class="label">Competidor / Alternativa</label>
                            <div class="custom-select">
                                <button class="custom-select-trigger" type="button">
                                    <span class="custom-select-label">
                                        <?php echo safe_text($competitorOptions[$competitorValue] ?? 'No identificado'); ?>
                                    </span>
                                    <i data-lucide="chevron-down"></i>
                                </button>
                            
                                <input type="hidden" name="competitor" value="<?php echo safe_text($competitorValue); ?>">
                            
                                <div class="custom-select-menu">
                                    <?php foreach ($competitorOptions as $value => $label): ?>
                                        <button class="custom-select-option <?php echo $competitorValue === $value ? 'is-selected' : ''; ?>" type="button" data-value="<?php echo safe_text($value); ?>">
                                            <?php echo safe_text($label); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>

                        <div class="form-field">
                            <label class="label">Valor esperado</label>
                            <input class="input" type="number" name="expected_value" min="0" step="1" placeholder="$ 0" value="<?php echo safe_text($formOld['expected_value'] ?? ''); ?>">
                        </div>

                        <div class="form-field">
                            <label class="label">Probabilidad (%)</label>
                            <input class="input" type="number" name="probability" min="0" max="100" value="<?php echo safe_text($formOld['probability'] ?? '20'); ?>">
                        </div>

                        <div class="<?php echo field_class('expected_close_date', $formErrors, true); ?>">
                            <label class="label">Fecha estimada de cierre</label>
                            <input class="input" type="date" name="expected_close_date" value="<?php echo safe_text($formOld['expected_close_date'] ?? ''); ?>">
                            <?php if ($error = field_error('expected_close_date', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>

                        <div class="<?php echo field_class('next_action', $formErrors, true); ?>">
                            <label class="label">Próxima acción</label>
                            <div class="custom-select">
                                <button class="custom-select-trigger" type="button">
                                    <span class="custom-select-label">
                                        <?php echo safe_text($nextActionOptions[$nextActionValue] ?? 'Sin acción'); ?>
                                    </span>
                                    <i data-lucide="chevron-down"></i>
                                </button>
                            
                                <input type="hidden" name="next_action" value="<?php echo safe_text($nextActionValue); ?>">
                            
                                <div class="custom-select-menu">
                                    <?php foreach ($nextActionOptions as $value => $label): ?>
                                        <button class="custom-select-option <?php echo $nextActionValue === $value ? 'is-selected' : ''; ?>" type="button" data-value="<?php echo safe_text($value); ?>">
                                            <?php echo safe_text($label); ?>
                                        </button>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php if ($error = field_error('next_action', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>

                        <div class="<?php echo field_class('next_action_date', $formErrors, true); ?>">
                            <label class="label">Fecha próxima acción</label>
                            <input class="input" type="date" name="next_action_date" value="<?php echo safe_text($formOld['next_action_date'] ?? ''); ?>">
                            <?php if ($error = field_error('next_action_date', $formErrors)): ?>
                                <small class="field-error"><?php echo safe_text($error); ?></small>
                            <?php endif; ?>
                        </div>

                        <div class="form-field form-field-wide">
                            <label class="label">Notas iniciales</label>
                            <textarea class="textarea" name="notes" placeholder="Escribe aquí las notas iniciales de la oportunidad..."><?php echo safe_text($formOld['notes'] ?? ''); ?></textarea>
                        </div>

                    </div>
                </div>
            </section>

            <section class="card form-card form-actions-card">
                <div class="card-body">
                    <div class="cluster">
                        <button
                            id="saveOpportunityBtn"
                            class="btn btn-primary"
                            type="submit"
                            disabled
                        >
                            Guardar oportunidad
                        </button>

                        <a class="btn btn-outline" href="/modules/crm/">
                            Cancelar
                        </a>
                    </div>
                </div>
            </section>

        </form>

    </section>
</main>

<script src="/assets/js/customer-location.js?v=p4_6_0"></script>
<script>
(function () {
    var customers = <?php echo json_encode(array_map(function ($customer) {
        return array(
            'id' => (int) $customer['id'],
            'name' => !empty($customer['commercial_name']) ? $customer['commercial_name'] : $customer['customer_name'],
            'commercial_name' => $customer['commercial_name'] ?? '',
            'customer_name' => $customer['customer_name'] ?? '',
            'legal_name' => $customer['legal_name'] ?? '',
            'rut' => $customer['customer_tax_id'] ?? '',
            'city' => $customer['city'] ?? ''
        );
    }, $customers)); ?>;

    var selectedCustomerId = <?php echo (int) $selectedCustomerId; ?>;

    var search = document.getElementById('customerSearch');
    var hidden = document.getElementById('customerId');
    var results = document.getElementById('customerResults');
    var newCustomerBlock = document.getElementById('newCustomerBlock');
    var newCustomerButton = document.getElementById('newCustomerButton');

    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 normalizeRut(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;
        });
        var opportunityForm = newCustomerBlock.closest('form');
        if (opportunityForm) opportunityForm.dispatchEvent(new Event('icy:opportunity-customer-mode'));
        if (show && window.ICY_CUSTOMER_LOCATION) {
            window.ICY_CUSTOMER_LOCATION.init(newCustomerBlock);
        }
        
        // Disparamos un evento "input" fantasma para que la validación nativa 
        // chequee si el botón guardar se debe habilitar o no
        var evt = new Event('input', { bubbles: true });
        if(search) search.dispatchEvent(evt);
    }

    function selectCustomer(customer) {
        search.value = customer.name;
        hidden.value = customer.id;
        results.innerHTML = '';
        showNewCustomerBlock(false);
    }

    function renderResults(query) {
        results.innerHTML = '';

        if (!query || query.length < 2) {
            return;
        }

        var normalizedQuery = normalize(query);
        var rutQuery = normalizeRut(query);
        var matches = customers.filter(function (customer) {
            var rawHaystack = [customer.name, customer.commercial_name, customer.customer_name, customer.legal_name, customer.rut, customer.city].filter(Boolean).join(' ');
            var haystack = normalize(rawHaystack);
            var rutHaystack = normalizeRut(rawHaystack);
            return haystack.indexOf(normalizedQuery) !== -1 || (rutQuery.length >= 2 && rutHaystack.indexOf(rutQuery) !== -1);
        }).slice(0, 8);

        if (!matches.length) {
            results.innerHTML = '<div class="customer-result-empty">Sin coincidencias. Puedes crear un cliente nuevo.</div>';
            hidden.value = '';
            return;
        }

        matches.forEach(function (customer) {
            var button = document.createElement('button');
            button.type = 'button';
            button.className = 'customer-result-item';

            button.innerHTML =
                '<strong>' + customer.name + '</strong>' +
                '<span>' + [customer.legal_name, customer.rut, customer.city].filter(Boolean).join(' · ') + '</span>';

            button.addEventListener('click', function () {
                selectCustomer(customer);
            });

            results.appendChild(button);
        });
    }

    if(search) {
        search.addEventListener('input', function () {
            hidden.value = '';
            renderResults(search.value);
        });
    }

    if(newCustomerButton) {
        newCustomerButton.addEventListener('click', function () {
            var isCurrentlyVisible = newCustomerBlock.style.display === 'block';
            
            if (isCurrentlyVisible) {
                showNewCustomerBlock(false);
            } else {
                hidden.value = '';
                search.value = '';
                results.innerHTML = '';
                showNewCustomerBlock(true);
            }
        });
    }

    // Formateador de RUT Chileno interactivo
    var rutInput = document.getElementById('oppNewCustomerTaxId');
    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;
        });
        rutInput.dispatchEvent(new Event('input'));
    }

    // Selector de Teléfono
    var oPrefixSelect = document.getElementById('opp_phone_prefix');
    var oNumberInput = document.getElementById('opp_phone_number');
    var oRealPhone = document.getElementById('opp_real_phone_input');

    if (oPrefixSelect && oNumberInput && oRealPhone) {
        var savedPhone = oRealPhone.value.trim();
        if (savedPhone) {
            var foundPrefix = Array.from(oPrefixSelect.options).find(opt => savedPhone.startsWith(opt.value));
            if (foundPrefix) {
                oPrefixSelect.value = foundPrefix.value;
                oNumberInput.value = savedPhone.substring(foundPrefix.value.length).trim();
            } else {
                oNumberInput.value = savedPhone;
            }
        }

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

    var preselected = customers.find(function (customer) {
        return customer.id === selectedCustomerId;
    });

    if (window.ICY_CUSTOMER_LOCATION) {
        window.ICY_CUSTOMER_LOCATION.init(document.querySelector('.app-main') || document);
    }

    if (preselected) {
        selectCustomer(preselected);
    } else if (<?php echo $showNewCustomerScenario; ?>) {
        showNewCustomerBlock(true);
    } else {
        showNewCustomerBlock(false);
    }
})();
</script>

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