<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/format.php';
require_once '../../core/database.php';
require_once '../../core/permissions.php';

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

$quoteId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$pdo = db();

$hasQuoteDeletedAt = false;
try {
    $stmtCol = $pdo->prepare("SHOW COLUMNS FROM `crm_quotes` LIKE ?");
    $stmtCol->execute(array('deleted_at'));
    $hasQuoteDeletedAt = (bool)$stmtCol->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $hasQuoteDeletedAt = false;
}

$stmt = $pdo->prepare("SELECT * FROM crm_quotes WHERE id = ? " . ($hasQuoteDeletedAt ? "AND deleted_at IS NULL " : "") . "LIMIT 1");
$stmt->execute(array($quoteId));
$quote = $stmt->fetch();

if (!$quote) {
    die('Cotización no encontrada o eliminada. Restáurala antes de editar.');
}

$previewData = $_SESSION['quote_preview_old'] ?? array();

if (isset($previewData['quote_id']) && (int)$previewData['quote_id'] === $quoteId) {
    $notesValue    = $previewData['notes'] ?? '';
    $statusValue   = $previewData['status'] ?? 'Borrador';
    $discountValue = $previewData['discount_percent'] ?? 0;
    
    $itemsJson = array();
    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']
        );
    }
} else {
    $notesValue    = $quote['notes'];
    $statusValue   = $quote['status'] ?? 'Borrador';
    $discountValue = $quote['discount_percent'];

    $stmtItems = $pdo->prepare("SELECT * FROM crm_quote_items WHERE quote_id = ?");
    $stmtItems->execute(array($quoteId));
    $savedItems = $stmtItems->fetchAll();

    $itemsJson = array();
    foreach ($savedItems as $sItem) {
        $skuMatch = '';
        if (preg_match('/ \(SKU: (.*)\)$/', $sItem['name'], $matches)) {
            $skuMatch = $matches[1];
        }

        $cleanName = preg_replace('/ \(SKU: .*\)$/', '', $sItem['name']);
        
        $itemsJson[] = array(
            'product_id' => $sItem['product_id'],
            'name'       => $cleanName,
            'sku'        => $skuMatch,
            'quantity'   => parse_quantity($sItem['quantity'] ?? 0),
            'unit'       => $sItem['unit'] ?? 'unidad',
            'price_unit' => (float)$sItem['price_unit']
        );
    }
}

unset($_SESSION['quote_preview_old']);

$page_title = 'Editar Cotización ' . $quote['quote_number'];

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

<main class="app-main">

    <style>
    /* Base de Estilos Requeridos */
    .mb-4 { margin-bottom: 1rem; }
    .mobile-label { display: none; }
    .mobile-remove-text { display: none; }

    .table td .input,
    .item-search {
        width: 100% !important;
        min-width: 0 !important;
        max-width: none !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;
        flex-direction: row !important;
        justify-content: space-between !important;
        align-items: center !important;
        width: 100% !important;
    }

    .metric-row strong,
    .metric-value {
        text-align: right !important;
        margin-left: auto !important;
    }

    .search-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; margin-top: 2px; }
    .search-result-item-empty { padding: 12px; color: var(--text-muted); font-size: 0.85rem; text-align: center; }

    .remove-action-cell { text-align: center; vertical-align: middle; }
    .remove-action-cell .remove-row-btn { padding: 6px; display: inline-flex; align-items: center; justify-content: center; }
    .remove-action-cell .remove-row-btn i { width: 16px; height: 16px; }

    @media (max-width: 1024px) {
        .table-wrap {
            border: none !important;
            overflow: visible !important;
            width: 100% !important;
        }

        .table, .table tbody, .table tr, .table td, #itemsContainer {
            display: block !important;
            width: 100% !important;
            box-sizing: border-box !important;
            table-layout: auto !important;
        }

        .table { min-width: 0 !important; }
        .table thead { display: none !important; }

        #itemsContainer .quote-row {
            display: grid !important;
            grid-template-columns: minmax(0, 1fr) minmax(0, 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;
            width: auto !important; 
            max-width: none !important;
            padding: 0 !important;
            border: 0 !important;
            text-align: left !important;
            overflow: visible !important;
        }

        #itemsContainer .quote-row td:nth-child(1) { grid-column: 1 / -1 !important; }
        #itemsContainer .quote-row td:nth-child(2) { display: none !important; }
        #itemsContainer .quote-row td:nth-child(3) { grid-column: 1 / 2 !important; }
        #itemsContainer .quote-row td:nth-child(4) { grid-column: 2 / 3 !important; }
        #itemsContainer .quote-row td:nth-child(5) { grid-column: 1 / 2 !important; align-self: center !important; }
        #itemsContainer .quote-row td:nth-child(6) { grid-column: 2 / 3 !important; align-self: end !important; justify-self: end !important; }

        .mobile-label {
            display: block !important;
            color: var(--text-muted) !important;
            font-size: 0.7rem !important;
            font-weight: 800 !important;
            letter-spacing: 0.08em !important;
            text-transform: uppercase !important;
        }

        .item-total-text {
            min-height: 42px !important;
            display: inline-flex !important;
            align-items: center !important;
            padding: 0 14px !important;
            border: 1px solid var(--border-default) !important;
            border-radius: var(--radius-md) !important;
            color: var(--text-primary) !important;
            background: var(--surface-0) !important;
            font-size: 0.95rem !important;
            font-weight: 700 !important;
            width: 100% !important;
        }

        .remove-action-cell { text-align: right !important; }
        .remove-action-cell .mobile-label { text-align: right !important; margin-bottom: 4px !important; }
        
        .remove-action-cell .remove-row-btn {
            width: 100% !important;
            max-width: 120px !important;
            height: 42px !important;
            display: inline-flex !important;
            align-items: center !important;
            justify-content: center !important;
            border-radius: var(--radius-md) !important;
            background-color: var(--color-error) !important;
            color: var(--text-inverse) !important;
            border: none !important;
        }

        .remove-action-cell .remove-row-btn i,
        .remove-action-cell .remove-row-btn svg { width: 18px !important; height: 18px !important; }
        .search-results-box { position: absolute !important; z-index: 200 !important; width: 100% !important; }
        .responsive-grid { grid-template-columns: 1fr !important; gap: 16px !important; }
        .responsive-actions { flex-direction: column !important; gap: 12px !important; width: 100% !important; }
        .responsive-actions .btn { width: 100% !important; justify-content: center !important; padding: 12px !important; }
    }

    @media (max-width: 576px) {
        #itemsContainer .quote-row {
            grid-template-columns: minmax(0, 1fr) !important;
            gap: 12px !important;
        }
        #itemsContainer .quote-row td:nth-child(1),
        #itemsContainer .quote-row td:nth-child(3),
        #itemsContainer .quote-row td:nth-child(4),
        #itemsContainer .quote-row td:nth-child(5),
        #itemsContainer .quote-row td:nth-child(6) {
            grid-column: 1 / -1 !important;
        }
        .remove-action-cell { text-align: left !important; }
        .remove-action-cell .mobile-label { text-align: left !important; }
        .remove-action-cell .remove-row-btn { max-width: 100% !important; }
    }
    </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">CRM · Edición</span>
                <h1>Modificar Cotización <?php echo safe_text($quote['quote_number']); ?></h1>
            </div>
        </div>

        <form id="quoteForm" action="/modules/crm/quote_preview.php" method="POST">
            <input type="hidden" name="opportunity_id" value="<?php echo $quote['opportunity_id']; ?>">
            <input type="hidden" name="customer_id" value="<?php echo $quote['customer_id']; ?>">
            <input type="hidden" name="quote_id" value="<?php echo $quoteId; ?>">

            <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 de la Cotización</label>
                            <select class="input" name="status" style="width: 100%; max-width: 300px;">
                                <option value="Borrador" <?php echo $statusValue === 'Borrador' ? 'selected' : ''; ?>>Borrador</option>
                                <option value="Enviada" <?php echo $statusValue === 'Enviada' ? 'selected' : ''; ?>>Enviada</option>
                                <option value="Aceptada" <?php echo $statusValue === 'Aceptada' ? 'selected' : ''; ?>>Aceptada</option>
                                <option value="Rechazada" <?php echo $statusValue === 'Rechazada' ? 'selected' : ''; ?>>Rechazada</option>
                            </select>
                        </div>

                        <div class="form-field">
                            <label class="label">Condiciones comerciales o notas internas</label>
                            <textarea class="textarea" name="notes" rows="6" placeholder="Ej: Precios válidos por 15 días. Entrega inmediata..."><?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" class="text-primary" 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">
                        <button class="btn btn-primary" type="submit" id="submitBtn">
                            <i data-lucide="file-check"></i>
                            <span>Ir a Vista Previa →</span>
                        </button>
                        <a class="btn btn-outline" href="/modules/crm/opportunity.php?id=<?php echo $quote['opportunity_id']; ?>">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);
            
            document.getElementById('submitBtn').disabled = (subtotal <= 0);
        }

        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; min-width: 0 !important; max-width: none !important; box-sizing: border-box !important;"';

            tr.innerHTML = 
                '<td>' +
                    '<span class="mobile-label">Buscar Producto</span>' +
                    '<div class="search-field-wrapper" style="position:relative; width: 100% !important; max-width: none !important; display: block !important;">' +
                        '<input type="text" class="input item-search" ' + inputStyle + ' placeholder="Escribe para 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); width: 100% !important; min-width: 0 !important; max-width: none !important; box-sizing: border-box !important;" 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">Precio Unitario Neto</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" aria-label="Eliminar fila">' +
                        '<i data-lucide="trash-2"></i>' +
                    '</button>' +
                '</td>';

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

            var searchInput = tr.querySelector('.item-search');
            var resultsBox = tr.querySelector('.search-results-box');
            var qtyInput = tr.querySelector('.item-qty');
            var priceInput = tr.querySelector('.item-price');
            var removeBtn = tr.querySelector('.remove-row-btn');

            qtyInput.addEventListener('input', calculateTotals);
            priceInput.addEventListener('input', calculateTotals);
            
            removeBtn.addEventListener('click', function() {
                tr.remove();
                calculateTotals();
            });

            var timeout = null;
            searchInput.addEventListener('input', function() {
                clearTimeout(timeout);
                var query = searchInput.value.trim();
                
                if (query.length < 2) {
                    resultsBox.innerHTML = '';
                    resultsBox.style.display = 'none';
                    return;
                }

                timeout = setTimeout(function() {
                    fetch('/modules/crm/api_products.php?q=' + encodeURIComponent(query))
                        .then(function(res) { return res.json(); })
                        .then(function(data) {
                            resultsBox.innerHTML = '';
                            if (!data.length) {
                                resultsBox.innerHTML = '<div class="search-result-item-empty">Sin resultados en Facto</div>';
                                resultsBox.style.display = 'block';
                                return;
                            }

                            data.forEach(function(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() {
                                    searchInput.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;
                                    priceInput.value = prod.price;
                                    resultsBox.innerHTML = '';
                                    resultsBox.style.display = 'none';
                                    calculateTotals();
                                });
                                resultsBox.appendChild(btn);
                            });
                            resultsBox.style.display = 'block';
                        });
                }, 300);
            });

            document.addEventListener('click', function(e) {
                if (!tr.contains(e.target)) {
                    resultsBox.innerHTML = '';
                    resultsBox.style.display = 'none';
                }
            });

            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'; ?>