<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/format.php';
require_once '../../services/crm/CrmService.php';
require_once '../../core/permissions.php';

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

$opportunityId = isset($_GET['opportunity_id']) ? (int) $_GET['opportunity_id'] : 0;
$crm = new CrmService();

$opportunity = null;
$customerLocked = false;
$customerName = '';
$customerId = 0;

if ($opportunityId > 0) {
    $opportunity = $crm->getOpportunity($opportunityId);
    if ($opportunity) {
        $customerLocked = true;
        $customerName = $opportunity['customer_name'];
        $customerId = (int)$opportunity['customer_id'];
    }
}

$previewData = $_SESSION['quote_preview_old'] ?? array();
$itemsJson = array();
$notesValue = '';
$statusValue = 'Borrador'; 
$discountValue = 0;

$isReturningFromPreview = isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'quote_preview.php') !== false;
if ($isReturningFromPreview && isset($previewData['opportunity_id'])) {
    $notesValue    = $previewData['notes'] ?? '';
    $statusValue   = $previewData['status'] ?? 'Borrador';
    $discountValue = $previewData['discount_percent'] ?? 0;
    
    foreach (($previewData['items'] ?? array()) as $pItem) {
        $itemsJson[] = array(
            'product_id' => $pItem['product_id'],
            'name'       => $pItem['name'],
            'sku'        => $pItem['sku'] ?? '',
            'quantity'   => parse_quantity($pItem['quantity'] ?? 0),
            'unit'       => $pItem['unit'] ?? 'unidad',
            'price_unit' => (float)$pItem['price_unit']
        );
    }
}
unset($_SESSION['quote_preview_old']);

$page_title = 'Nueva Cotización';
require_once '../../layouts/header.php';
require_once '../../layouts/sidebar.php';
?>

<main class="app-main">
    <style>
    .mb-4 { margin-bottom: 1rem; }
    .mobile-label { display: none; }
    .table td .input, .item-search { width:100% !important; box-sizing:border-box !important; }
    .table-overflow-visible, .table-overflow-visible table, .table-overflow-visible td { overflow: visible !important; }
    .metric-row { display: flex !important; justify-content: space-between !important; align-items: center !important; }
    .metric-row strong { text-align: right !important; margin-left: auto !important; }
    
    .search-results-box, .customer-results-box {
        position: absolute; width: 100%; z-index: 99; box-shadow: var(--shadow-lg);
        border: 1px solid var(--border-default); background: var(--surface-1);
        max-height: 220px; overflow-y: auto; border-radius: var(--radius-lg); top: 100%; left: 0;
    }
    .search-result-item {
        width: 100%; background: transparent; border: none; padding: 10px 12px;
        text-align: left; cursor: pointer; color: var(--text-secondary);
        border-bottom: 1px solid var(--border-subtle); display: flex; flex-direction: column;
    }
    .search-result-item:hover { background: var(--surface-2); }
    .search-result-item strong { color: var(--text-primary); font-size: 0.9rem; }
    .search-result-item span { color: var(--text-muted); font-size: 0.75rem; }
    
    @media (max-width: 1024px) {
        .table-wrap { border: none !important; overflow: visible !important; }
        .table, .table tbody, .table tr, .table td, #itemsContainer { display: block !important; width: 100% !important; }
        .table thead { display: none !important; }
        #itemsContainer .quote-row { display: grid !important; grid-template-columns: 1fr 1fr !important; gap: 14px !important; padding: 16px !important; border: 1px solid var(--border-default) !important; border-radius: var(--radius-xl) !important; background: var(--surface-2) !important; margin-bottom: 16px !important; }
        #itemsContainer .quote-row td { display: grid !important; gap: 6px !important; padding: 0 !important; border: 0 !important; }
        #itemsContainer .quote-row td:nth-child(1) { grid-column: 1 / -1 !important; }
        #itemsContainer .quote-row td:nth-child(2) { display: none !important; }
        .mobile-label { display: block !important; color: var(--text-muted) !important; font-size: 0.7rem !important; font-weight: 800 !important; text-transform: uppercase !important; }
        .responsive-grid { grid-template-columns: 1fr !important; }
        .responsive-actions { flex-direction: column !important; }
        .responsive-actions .btn { width:100% !important; justify-content:center; }
    }
    </style>

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

    <section class="content">
        <div class="page-header page-header-compact">
            <div class="page-header-content">
                <span class="label"><?php echo $customerLocked ? 'Venta Consultiva (Embudo)' : 'Venta Rápida (Directa)'; ?></span>
                <h1>Nueva Cotización</h1>
            </div>
        </div>

        <form id="quoteForm" action="/modules/crm/quote_preview.php" method="POST">
            <input type="hidden" name="opportunity_id" value="<?php echo $opportunityId; ?>">
            
            <section class="card mb-6">
                <div class="card-header"><h3>Información del Cliente</h3></div>
                <div class="card-body">
                    <div class="form-grid form-grid-2">
                        <div class="form-field is-required" style="position:relative;">
                            <label class="label">Cliente</label>
                            <?php if ($customerLocked): ?>
                                <input type="text" class="input" value="<?php echo safe_text($customerName); ?>" disabled style="background:var(--surface-2);">
                                <input type="hidden" name="customer_id" value="<?php echo $customerId; ?>">
                            <?php else: ?>
                                <input type="text" id="customer_search" class="input" placeholder="Escribe para buscar cliente corporativo..." autocomplete="off" required>
                                <input type="hidden" name="customer_id" id="customer_id" value="0">
                                <div id="customer_results" class="customer-results-box" style="display:none;"></div>
                            <?php endif; ?>
                        </div>
                        <div class="form-field">
                            <label class="label">Vendedor / Responsable</label>
                            <input type="text" class="input" value="<?php echo safe_text(current_user()['name'] ?? 'Sistema'); ?>" disabled style="background:var(--surface-2);">
                        </div>
                    </div>
                </div>
            </section>

            <section class="card form-card">
                <div class="card-header"><h3>Detalle de Productos</h3></div>
                <div class="card-body">
                    <div class="table-wrap table-overflow-visible">
                        <table class="table" style="table-layout: fixed; width: 100%;">
                            <thead>
                                <tr>
                                    <th style="width: 40%;">Buscar Producto</th>
                                    <th style="width: 15%;">SKU</th>
                                    <th style="width: 12%;">Cantidad</th>
                                    <th style="width: 18%;">Precio Unitario Neto</th>
                                    <th style="width: 12%;">Total Fila</th>
                                    <th style="width: 3%;"></th>
                                </tr>
                            </thead>
                            <tbody id="itemsContainer"></tbody>
                        </table>
                    </div>
                    <div class="mt-4">
                        <button type="button" class="btn btn-outline btn-sm" id="addRowBtn" style="width: auto;">
                            <i data-lucide="plus"></i> <span>Añadir fila</span>
                        </button>
                    </div>
                </div>
            </section>

            <section class="grid grid-2 mt-6 responsive-grid">
                <article class="card">
                    <div class="card-body">
                        <div class="form-field mb-4">
                            <label class="label">Estado Inicial</label>
                            <select class="input" name="status" style="width: 100%; max-width: 300px;">
                                <option value="Borrador">Borrador</option>
                                <option value="Enviada">Enviada</option>
                            </select>
                        </div>
                        <div class="form-field">
                            <label class="label">Condiciones comerciales o notas internas</label>
                            <textarea class="textarea" name="notes" rows="6" placeholder="Condiciones de pago, validez de la oferta..."><?php echo safe_text($notesValue); ?></textarea>
                        </div>
                    </div>
                </article>
                <article class="card">
                    <div class="card-body">
                        <div class="metric-row"><span>Subtotal Neto</span><strong id="summarySubtotal">$ 0</strong></div>
                        <div class="metric-row align-items-center my-2" style="margin: 10px 0;">
                            <span>Descuento (%)</span>
                            <input type="number" name="discount_percent" id="discountPercent" class="input" value="<?php echo (float)$discountValue; ?>" min="0" max="100" step="0.1" style="width: 80px; text-align: right; padding: 4px 8px;">
                        </div>
                        <div class="metric-row text-muted" id="discountAmountRow" style="display: none; font-size: 0.9rem;"><span>Monto Descuento</span><strong id="summaryDiscount">$ 0</strong></div>
                        <div class="metric-row"><span>IVA (19%)</span><strong id="summaryIva">$ 0</strong></div>
                        <hr class="my-4" style="border: 0; border-top: 1px solid var(--border-default);">
                        <div class="metric-row" style="font-size: 1.25rem;"><span>Total General</span><strong id="summaryTotal" style="color: var(--color-success);">$ 0</strong></div>
                    </div>
                </article>
            </section>

            <section class="card form-card form-actions-card mt-6">
                <div class="card-body">
                    <div class="cluster responsive-actions" style="justify-content:flex-end; width:100%;">
                        <button class="btn btn-primary" type="submit" id="submitBtn" disabled>
                            <i data-lucide="file-check"></i> <span>Ir a Vista Previa →</span>
                        </button>
                        <a class="btn btn-outline" href="/modules/crm/quotes.php">Cancelar</a>
                    </div>
                </div>
            </section>
        </form>
    </section>

    <script>
    (function () {
        var container = document.getElementById('itemsContainer');
        var addBtn = document.getElementById('addRowBtn');
        var discountInput = document.getElementById('discountPercent');
        var savedItems = <?php echo json_encode($itemsJson); ?>;
        var rowIndex = 0;

        function formatCLP(value) { return '$ ' + Math.round(value).toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."); }

        function calculateTotals() {
            var subtotal = 0;
            container.querySelectorAll('.quote-row').forEach(function(row) {
                var qty = parseFloat(row.querySelector('.item-qty').value) || 0;
                var price = parseFloat(row.querySelector('.item-price').value) || 0;
                var totalRow = qty * price;
                row.querySelector('.item-total-text').innerText = formatCLP(totalRow);
                subtotal += totalRow;
            });
            var discountPercent = parseFloat(discountInput.value) || 0;
            var discountAmount = subtotal * (discountPercent / 100);
            var netWithDiscount = subtotal - discountAmount;

            document.getElementById('discountAmountRow').style.display = discountAmount > 0 ? 'flex' : 'none';
            document.getElementById('summaryDiscount').innerText = '- ' + formatCLP(discountAmount);
            document.getElementById('summarySubtotal').innerText = formatCLP(subtotal);
            document.getElementById('summaryIva').innerText = formatCLP(netWithDiscount * 0.19);
            document.getElementById('summaryTotal').innerText = formatCLP(netWithDiscount * 1.19);
            
            // Bloqueo de seguridad si no hay productos o no se ha seleccionado cliente directo
            var cId = document.getElementById('customer_id') ? parseInt(document.getElementById('customer_id').value) : 1;
            document.getElementById('submitBtn').disabled = (subtotal <= 0 || cId <= 0);
        }

        // --- LÓGICA AUTOCOMPLETE DE CLIENTES DIRECTOS ---
        var cSearch = document.getElementById('customer_search');
        var cResults = document.getElementById('customer_results');
        if (cSearch) {
            var cTimeout = null;
            cSearch.addEventListener('input', function() {
                clearTimeout(cTimeout);
                var val = cSearch.value.trim();
                if(val.length < 2) { cResults.style.display = 'none'; return; }
                cTimeout = setTimeout(function() {
                    fetch('/modules/crm/api_customers.php?q=' + encodeURIComponent(val)) // Asegúrate de tener o crear esta pequeña API que busque en crm_customers
                        .then(r => r.json())
                        .then(d => {
                            cResults.innerHTML = '';
                            if(!d.length) { cResults.innerHTML = '<div class="search-result-item-empty" style="padding:10px;color:var(--text-muted);">Sin resultados</div>'; cResults.style.display='block'; return; }
                            d.forEach(cust => {
                                var b = document.createElement('button'); b.type = 'button'; b.className = 'search-result-item';
                                b.innerHTML = '<strong>'+cust.customer_name+'</strong><span>RUT: '+cust.customer_tax_id+'</span>';
                                b.addEventListener('click', function() {
                                    cSearch.value = cust.customer_name;
                                    document.getElementById('customer_id').value = cust.id;
                                    cResults.style.display = 'none';
                                    calculateTotals();
                                });
                                cResults.appendChild(b);
                            });
                            cResults.style.display = 'block';
                        });
                }, 250);
            });
        }

        var quoteUnitOptions = ['unidad', 'mL', 'L', 'g', 'kg', 'pack', 'caja', 'servicio'];
        function cleanQuoteUnit(value) { return quoteUnitOptions.indexOf(String(value || '').trim()) !== -1 ? String(value).trim() : 'unidad'; }
        function unitSelectHtml(index, value) {
            var current = cleanQuoteUnit(value);
            return '<select name="items[' + index + '][unit]" class="input item-unit">' + quoteUnitOptions.map(function(unit) {
                return '<option value="' + unit + '"' + (unit === current ? ' selected' : '') + '>' + unit + '</option>';
            }).join('') + '</select>';
        }

        function addRow(data) {
            var tr = document.createElement('tr'); tr.className = 'quote-row'; tr.dataset.index = rowIndex;
            var inputStyle = 'style="width: 100% !important;"';

            tr.innerHTML = 
                '<td><span class="mobile-label">Buscar Producto</span><div class="search-field-wrapper" style="position:relative; width: 100%; display: block;"><input type="text" class="input item-search" ' + inputStyle + ' placeholder="Buscar en Facto..." autocomplete="off" value="'+(data ? data.name : '')+'"><input type="hidden" name="items['+rowIndex+'][product_id]" class="item-product-id" value="'+(data ? data.product_id : '')+'"><input type="hidden" name="items['+rowIndex+'][name]" class="item-name" value="'+(data ? data.name : '')+'"><div class="search-results-box" style="display:none;"></div></div></td>' +
                '<td><span class="mobile-label">SKU</span><input type="text" name="items['+rowIndex+'][sku]" class="input item-sku" readonly style="background: rgba(255,255,255,0.03); color: var(--text-muted);" value="'+(data ? data.sku : '')+'"></td>' +
                '<td><span class="mobile-label">Cantidad</span><input type="number" name="items['+rowIndex+'][quantity]" class="input item-qty" ' + inputStyle + ' value="'+(data ? data.quantity : 1)+'" min="0.001" step="0.001" inputmode="decimal"></td>' +
                '<td><span class="mobile-label">Unidad</span>' + unitSelectHtml(rowIndex, data ? data.unit : 'unidad') + '</td>' +
                '<td><span class="mobile-label">Precio Unitario</span><input type="number" name="items['+rowIndex+'][price_unit]" class="input item-price" ' + inputStyle + ' min="0" step="0.01" value="'+(data ? data.price_unit : '')+'"></td>' +
                '<td><span class="mobile-label">Total Fila</span><strong class="item-total-text">$ 0</strong></td>' +
                '<td class="remove-action-cell"><span class="mobile-label">Eliminar</span><button type="button" class="btn btn-danger remove-row-btn"><i data-lucide="trash-2"></i></button></td>';

            container.appendChild(tr);
            if (window.lucide) lucide.createIcons();

            var sInput = tr.querySelector('.item-search'); var rBox = tr.querySelector('.search-results-box');
            var qInp = tr.querySelector('.item-qty'); var pInp = tr.querySelector('.item-price');

            qInp.addEventListener('input', calculateTotals); pInp.addEventListener('input', calculateTotals);
            tr.querySelector('.remove-row-btn').addEventListener('click', function() { tr.remove(); calculateTotals(); });

            var timeout = null;
            sInput.addEventListener('input', function() {
                clearTimeout(timeout); var query = sInput.value.trim();
                if (query.length < 2) { rBox.style.display = 'none'; return; }
                timeout = setTimeout(function() {
                    fetch('/modules/crm/api_products.php?q=' + encodeURIComponent(query))
                        .then(r => r.json()).then(data => {
                            rBox.innerHTML = '';
                            if (!data.length) { rBox.innerHTML = '<div class="search-result-item-empty">Sin resultados</div>'; rBox.style.display = 'block'; return; }
                            data.forEach(prod => {
                                var btn = document.createElement('button'); btn.type = 'button'; btn.className = 'search-result-item';
                                btn.innerHTML = '<strong>' + prod.name + '</strong><span>SKU: ' + prod.sku + ' · ' + formatCLP(prod.price) + '</span>';
                                btn.addEventListener('click', function() {
                                    sInput.value = prod.name;
                                    tr.querySelector('.item-product-id').value = prod.id;
                                    tr.querySelector('.item-name').value = prod.name;
                                    tr.querySelector('.item-sku').value = prod.sku;
                                    pInp.value = prod.price;
                                    rBox.style.display = 'none';
                                    calculateTotals();
                                });
                                rBox.appendChild(btn);
                            });
                            rBox.style.display = 'block';
                        });
                }, 300);
            });
            rowIndex++;
        }

        discountInput.addEventListener('input', calculateTotals);
        addBtn.addEventListener('click', function() { addRow(null); });
        if (savedItems.length > 0) { savedItems.forEach(addRow); } else { addRow(null); }
        calculateTotals();
    })();
    </script>
</main>
<?php require_once '../../layouts/footer.php'; ?>