/* Fieldly — Core JS */

// CSRF helper for AJAX POSTs
function csrfHeaders() {
    const token = document.querySelector('meta[name="csrf-token"]');
    return { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': token ? token.content : '' };
}

// Confirm delete helper
document.addEventListener('DOMContentLoaded', function() {

    // Confirm before delete forms
    document.querySelectorAll('form[data-confirm]').forEach(function(form) {
        form.addEventListener('submit', function(e) {
            if (!confirm(form.dataset.confirm || 'Are you sure?')) e.preventDefault();
        });
    });

    // Auto-dismiss alerts after 5 seconds
    document.querySelectorAll('.alert:not(.alert-permanent)').forEach(function(alert) {
        setTimeout(function() {
            const bsAlert = bootstrap.Alert.getOrCreateInstance(alert);
            if (bsAlert) bsAlert.close();
        }, 5000);
    });

    // Line items functionality
    initLineItems();

    // Phone fields
    initPhoneFields();

    // Customer search
    initCustomerSearch();

    // Totals calculation
    calcLineTotals();
});

/* ── Line Items ─────────────────────────────────────────────── */
function initLineItems() {
    const container = document.getElementById('line-items-container');
    const addBtn    = document.getElementById('add-line-item');
    if (!container || !addBtn) return;

    addBtn.addEventListener('click', function() {
        const rows = container.querySelectorAll('.line-item-row');
        const idx  = rows.length;
        const row  = document.createElement('tr');
        row.className = 'line-item-row';
        row.innerHTML = lineItemRow(idx, {description:'',qty:1,unit_price:'',discount:0,tax_rate:20,line_total:0});
        container.appendChild(row);
        row.querySelector('.item-desc').focus();
    });

    container.addEventListener('input', function(e) {
        if (e.target.matches('.item-qty,.item-price,.item-discount,.item-tax')) {
            calcRowTotal(e.target.closest('tr'));
            calcLineTotals();
        }
    });

    container.addEventListener('click', function(e) {
        if (e.target.closest('.remove-line-item')) {
            e.target.closest('tr').remove();
            reindexRows();
            calcLineTotals();
        }
    });
}

function lineItemRow(idx, item) {
    const taxRates = window.fieldlyTaxRates || [{rate:0,name:'0%'},{rate:5,name:'5%'},{rate:20,name:'20%'}];
    const taxOpts  = taxRates.map(t => `<option value="${t.rate}" ${parseFloat(t.rate)===parseFloat(item.tax_rate)?'selected':''}>${t.name} (${t.rate}%)</option>`).join('');
    return `
    <td><input type="text"   class="form-control form-control-sm item-desc"     name="items[${idx}][description]" value="${esc(item.description||'')}" placeholder="Description" required/></td>
    <td style="width:70px"><input type="number" class="form-control form-control-sm item-qty" name="items[${idx}][qty]"   value="${item.qty||1}" min="0" step="0.5"/></td>
    <td style="width:110px"><div class="input-group input-group-sm"><span class="input-group-text">${window.currencySymbol||'£'}</span><input type="number" class="form-control item-price" name="items[${idx}][unit_price]" value="${item.unit_price||''}" min="0" step="0.01" placeholder="0.00"/></div></td>
    <td style="width:80px"><div class="input-group input-group-sm"><input type="number" class="form-control item-discount" name="items[${idx}][discount]" value="${item.discount||0}" min="0" max="100"/><span class="input-group-text">%</span></div></td>
    <td style="width:130px"><select class="form-select form-select-sm item-tax" name="items[${idx}][tax_rate]">${taxOpts}</select></td>
    <td style="width:100px" class="text-end fw-bold item-total">${window.currencySymbol||'£'}${parseFloat(item.line_total||0).toFixed(2)}</td>
    <td style="width:40px"><button type="button" class="btn btn-sm btn-outline-danger remove-line-item"><i class="bi bi-trash3"></i></button></td>`;
}

function calcRowTotal(row) {
    const qty      = parseFloat(row.querySelector('.item-qty')?.value||0);
    const price    = parseFloat(row.querySelector('.item-price')?.value||0);
    const discount = parseFloat(row.querySelector('.item-discount')?.value||0);
    const total    = Math.round(qty * price * (1 - discount/100) * 100) / 100;
    const totalEl  = row.querySelector('.item-total');
    if (totalEl) totalEl.textContent = (window.currencySymbol||'£') + total.toFixed(2);
    const hidden = row.querySelector('.item-line-total');
    if (hidden) hidden.value = total;
}

function calcLineTotals() {
    let sub = 0, tax = 0;
    document.querySelectorAll('#line-items-container tr.line-item-row').forEach(function(row) {
        const qty      = parseFloat(row.querySelector('.item-qty')?.value||0);
        const price    = parseFloat(row.querySelector('.item-price')?.value||0);
        const discount = parseFloat(row.querySelector('.item-discount')?.value||0);
        const taxRate  = parseFloat(row.querySelector('.item-tax')?.value||0);
        const lt       = Math.round(qty * price * (1 - discount/100) * 100) / 100;
        sub += lt;
        tax += Math.round(lt * taxRate / 100 * 100) / 100;
    });
    const total = Math.round((sub + tax) * 100) / 100;
    const sym   = window.currencySymbol || '£';
    setText('subtotal-display',    sym + sub.toFixed(2));
    setText('tax-display',         sym + tax.toFixed(2));
    setText('total-display',       sym + total.toFixed(2));
    setVal('subtotal-hidden',  sub.toFixed(2));
    setVal('tax-hidden',       tax.toFixed(2));
    setVal('total-hidden',     total.toFixed(2));
}

function reindexRows() {
    document.querySelectorAll('#line-items-container tr.line-item-row').forEach(function(row, i) {
        row.querySelectorAll('[name]').forEach(function(el) {
            el.name = el.name.replace(/items\[\d+\]/, `items[${i}]`);
        });
    });
}

function setText(id, val) { const el = document.getElementById(id); if (el) el.textContent = val; }
function setVal(id, val)  { const el = document.getElementById(id); if (el) el.value = val; }
function esc(str) { return String(str).replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }

/* ── Phone Fields ───────────────────────────────────────────── */
function initPhoneFields() {
    const container = document.getElementById('phones-container');
    const addBtn    = document.getElementById('add-phone');
    if (!container || !addBtn) return;

    addBtn.addEventListener('click', function() {
        const idx = container.querySelectorAll('.phone-row').length;
        const row = document.createElement('div');
        row.className = 'phone-row d-flex gap-2 mb-2';
        row.innerHTML = `
            <select class="form-select form-select-sm" name="phones[${idx}][type]" style="width:110px;flex-shrink:0">
                <option>Mobile</option><option>Work</option><option>Home</option><option>Fax</option><option>Other</option>
            </select>
            <input type="tel" class="form-control form-control-sm" name="phones[${idx}][number]" placeholder="Phone number" style="font-size:16px"/>
            <button type="button" class="btn btn-sm btn-outline-danger remove-phone"><i class="bi bi-trash3"></i></button>`;
        container.appendChild(row);
    });

    container.addEventListener('click', function(e) {
        if (e.target.closest('.remove-phone')) {
            e.target.closest('.phone-row').remove();
        }
    });
}

/* ── Customer Search (typeahead) ────────────────────────────── */
function initCustomerSearch() {
    const input   = document.getElementById('customer-search');
    const hiddenId= document.getElementById('customer_id');
    const results = document.getElementById('customer-results');
    if (!input || !results) return;

    let timeout;
    input.addEventListener('input', function() {
        clearTimeout(timeout);
        const q = this.value.trim();
        if (q.length < 2) { results.style.display = 'none'; return; }
        timeout = setTimeout(function() {
            fetch('/ajax/customers/search?q=' + encodeURIComponent(q))
                .then(r => r.json())
                .then(data => {
                    results.innerHTML = data.map(c =>
                        `<div class="customer-result p-2 cursor-pointer" data-id="${c.id}" data-name="${esc((c.company_name||c.first_name+' '+c.last_name).trim())}">
                            <div class="fw-semibold">${esc(c.company_name || c.first_name+' '+c.last_name)}</div>
                            <div class="text-muted small">${esc(c.ref)} ${c.phone ? '· '+esc(c.phone) : ''}</div>
                        </div>`
                    ).join('') || '<div class="p-2 text-muted small">No customers found</div>';
                    results.style.display = 'block';
                });
        }, 300);
    });

    results.addEventListener('click', function(e) {
        const item = e.target.closest('.customer-result');
        if (!item) return;
        if (hiddenId) hiddenId.value = item.dataset.id;
        input.value = item.dataset.name;
        results.style.display = 'none';
    });

    document.addEventListener('click', function(e) {
        if (!input.contains(e.target) && !results.contains(e.target)) results.style.display = 'none';
    });
}
