// Invoice Creation Functions
const products = window.PRODUCTS || [];
const cloneItems = window.CLONE_ITEMS || [];
const productMap = {};
products.forEach(p => { productMap[p.id] = p; });

function fmt(n) { return '₹' + parseFloat(n).toFixed(2).replace(/\d(?=(\d{3})+\.)/g,'$&,'); }

function addRow(data = null) {
    const tbody = document.getElementById('itemsBody');
    if (!tbody) return;
    
    const idx   = tbody.querySelectorAll('tr').length;
    const d     = data || {};

    const tr = document.createElement('tr');
    tr.className = 'border-b border-slate-50 item-row';
    tr.innerHTML = `
        <td class="py-2 pr-2">
            <input type="hidden" name="items[${idx}][product_id]" class="inp-pid" value="${d.product_id || ''}">
            <select class="form-input text-xs inp-product">
                <option value="">Custom / Type below</option>
                ${products.map(p => `<option value="${p.id}" ${d.product_id == p.id ? 'selected':''} data-price="${p.price}" data-gst="${p.gst_percent}">${escHtml(p.name)}</option>`).join('')}
            </select>
            <input type="text" name="items[${idx}][product_name]" class="form-input text-xs mt-1 inp-name" placeholder="Product / service name" value="${escHtml(d.product_name || '')}" required>
        </td>
        <td class="py-2 px-1">
            <input type="number" name="items[${idx}][quantity]" min="1" value="${d.quantity || 1}" class="form-input text-xs text-center inp-qty">
        </td>
        <td class="py-2 px-1">
            <input type="number" step="0.01" name="items[${idx}][unit_price]" value="${d.unit_price || 0}" class="form-input text-xs text-right inp-price">
        </td>
        <td class="py-2 px-1">
            <input type="number" step="0.01" name="items[${idx}][margin_percent]" value="${d.margin_percent || 0}" class="form-input text-xs text-right inp-margin">
        </td>
        <td class="py-2 px-1">
            <input type="number" step="0.01" name="items[${idx}][gst_percent]" value="${d.gst_percent || 18}" class="form-input text-xs text-right inp-gst">
        </td>
        <td class="py-2 pl-1 text-right">
            <span class="font-bold text-slate-800 text-xs row-total">₹0.00</span>
        </td>
        <td class="py-2 pl-2">
            <button type="button" class="removeRowBtn text-red-400 hover:text-red-600 w-6 h-6 flex items-center justify-center rounded-lg hover:bg-red-50">
                <i class="fas fa-times text-xs"></i>
            </button>
        </td>
    `;
    tbody.appendChild(tr);
    
    // Add event listeners for the new row
    const productSelect = tr.querySelector('.inp-product');
    const qtyInput = tr.querySelector('.inp-qty');
    const priceInput = tr.querySelector('.inp-price');
    const marginInput = tr.querySelector('.inp-margin');
    const gstInput = tr.querySelector('.inp-gst');
    const removeBtn = tr.querySelector('.removeRowBtn');
    
    productSelect.addEventListener('change', () => onProductSelect(productSelect, idx));
    qtyInput.addEventListener('input', () => recalcRow(qtyInput));
    priceInput.addEventListener('input', () => recalcRow(priceInput));
    marginInput.addEventListener('input', () => recalcRow(marginInput));
    gstInput.addEventListener('input', () => recalcRow(gstInput));
    removeBtn.addEventListener('click', (e) => {
        e.preventDefault();
        removeRow(removeBtn);
    });
    
    recalcRow(qtyInput);
}

function escHtml(s) { return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

function onProductSelect(sel, idx) {
    const pid = sel.value;
    const tr  = sel.closest('tr');
    tr.querySelector('.inp-pid').value = pid;
    if (pid && productMap[pid]) {
        const p = productMap[pid];
        tr.querySelector('.inp-name').value  = p.name;
        tr.querySelector('.inp-price').value = p.price;
        tr.querySelector('.inp-gst').value   = p.gst_percent;
    }
    recalcRow(tr.querySelector('.inp-qty'));
}

function recalcRow(el) {
    const tr     = el.closest('tr');
    const qty    = parseFloat(tr.querySelector('.inp-qty').value) || 0;
    const price  = parseFloat(tr.querySelector('.inp-price').value) || 0;
    const margin = parseFloat(tr.querySelector('.inp-margin').value) || 0;
    const gst    = parseFloat(tr.querySelector('.inp-gst').value) || 0;
    const base   = price * (1 + margin / 100) * qty;
    const gstAmt = base * gst / 100;
    tr.querySelector('.row-total').textContent = fmt(base + gstAmt);
    recalcTotal();
}

function recalcTotal() {
    let subtotal = 0, gstTotal = 0;
    document.querySelectorAll('#itemsBody .item-row').forEach(tr => {
        const qty    = parseFloat(tr.querySelector('.inp-qty').value) || 0;
        const price  = parseFloat(tr.querySelector('.inp-price').value) || 0;
        const margin = parseFloat(tr.querySelector('.inp-margin').value) || 0;
        const gst    = parseFloat(tr.querySelector('.inp-gst').value) || 0;
        const base   = price * (1 + margin / 100) * qty;
        subtotal += base;
        gstTotal += base * gst / 100;
    });
    const discPct = parseFloat(document.getElementById('discPct').value) || 0;
    const discAmt = subtotal * discPct / 100;
    const total   = subtotal - discAmt + gstTotal;

    document.getElementById('sumSubtotal').textContent = fmt(subtotal);
    document.getElementById('sumDiscount').textContent = '- ' + fmt(discAmt);
    document.getElementById('sumGst').textContent      = fmt(gstTotal);
    document.getElementById('sumTotal').textContent    = fmt(total);
}

function removeRow(btn) {
    btn.closest('tr').remove();
    recalcTotal();
}

function updateCustomerInfo() {
    const sel = document.getElementById('customerSelect');
    if (!sel) return;
    
    const opt = sel.options[sel.selectedIndex];
    const box = document.getElementById('customerInfoBox');
    if (!sel.value) { box.classList.add('hidden'); return; }
    const info = JSON.parse(opt.dataset.info || '{}');
    box.innerHTML = `<strong>${escHtml(info.name)}</strong><br>${escHtml(info.address || '')} ${escHtml(info.city || '')} ${escHtml(info.state || '')}${info.gstin ? '<br>GSTIN: ' + escHtml(info.gstin) : ''}`;
    box.classList.remove('hidden');
}

function previewInvoice() {
    window.open('invoice_view.php?preview=1', '_blank', 'width=900,height=700');
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    // Add event listeners to static buttons and selects
    const addRowBtn = document.getElementById('addRowBtn');
    if (addRowBtn) {
        addRowBtn.addEventListener('click', (e) => {
            e.preventDefault();
            addRow();
        });
    }
    
    const previewBtn = document.getElementById('previewBtn');
    if (previewBtn) {
        previewBtn.addEventListener('click', (e) => {
            e.preventDefault();
            previewInvoice();
        });
    }
    
    const customerSelect = document.getElementById('customerSelect');
    if (customerSelect) {
        customerSelect.addEventListener('change', updateCustomerInfo);
    }
    
    const discPct = document.getElementById('discPct');
    if (discPct) {
        discPct.addEventListener('input', recalcTotal);
    }
    
    // Initialize rows
    if (cloneItems.length > 0) {
        cloneItems.forEach(item => addRow(item));
    } else {
        addRow();
    }
    updateCustomerInfo();
});
