function calcTotalPurchase() {
    const price = parseFloat(document.getElementById('purchasing_price')?.value) || 0;
    const qty = parseFloat(document.getElementById('purchased_qty')?.value) || 0;
    const totalEl = document.getElementById('total_purchasing_price');
    if (totalEl) {
        totalEl.value = (price * qty).toFixed(2);
    }
}

function validateProductForm() {
    const ids = ['product_name', 'purchasing_price', 'selling_price', 'purchased_qty', 'unit'];
    for (let id of ids) {
        const el = document.getElementById(id);
        if (el && !String(el.value).trim()) {
            alert('Please fill all fields.');
            return false;
        }
    }
    return true;
}

function filterTable() {
    const inputEl = document.getElementById('search_product');
    const rows = document.querySelectorAll('#productTable tr');
    if (!inputEl) return;

    const input = inputEl.value.toLowerCase();
    rows.forEach((row, index) => {
        if (index === 0) return;
        const text = row.innerText.toLowerCase();
        row.style.display = text.includes(input) ? '' : 'none';
    });
}

function extractKgValueFromProductName(productName) {
    const name = String(productName || '');
    const match = name.match(/(\d+(?:\.\d+)?)\s*kg/i);
    if (match) {
        return parseFloat(match[1]) || 0;
    }
    return 0;
}

function getDualPackQty() {
    const productName = document.getElementById('search_product')?.value || '';
    const mode1QtyInput = parseFloat(document.getElementById('edit_dual_mode_qty_1')?.value) || 0;

    const qtyFromName = extractKgValueFromProductName(productName);
    if (qtyFromName > 0) {
        return qtyFromName;
    }

    return mode1QtyInput > 0 ? mode1QtyInput : 0;
}

function updateDualQtyPreview() {
    const isDual = parseInt(document.getElementById('is_dual_mode')?.value || '0', 10) === 1;
    const qtyLabel = document.getElementById('edit_purchased_qty_label');
    const preview = document.getElementById('dual_qty_preview');
    const enteredQty = parseFloat(document.getElementById('edit_purchased_qty')?.value) || 0;
    const unit = document.getElementById('edit_unit')?.value || '';
    const packQty = getDualPackQty();

    if (!qtyLabel || !preview) return;

    if (isDual) {
        qtyLabel.textContent = 'Purchased Qty (Bags)';
        const actualQty = enteredQty * packQty;

        if (packQty > 0 && enteredQty > 0) {
            preview.textContent = 'Actual Total Qty: ' + formatNumber(actualQty) + ' ' + (unit || 'Kg');
        } else if (packQty > 0) {
            preview.textContent = 'Actual Total Qty will be calculated using ' + formatNumber(packQty) + ' Kg per bag';
        } else {
            preview.textContent = 'Enter product name with Kg value or set Mode 1 Qty Reduction';
        }
    } else {
        qtyLabel.textContent = 'Purchased Qty';
        preview.textContent = '';
    }
}

function fillEditForm(
    id,
    name,
    purchase,
    sell,
    qty,
    unit,
    total,
    invoice = '',
    expiry = '',
    supplier = '',
    isDualMode = 0,
    mode1Name = '',
    mode1Qty = 0,
    mode1Price = 0,
    mode2Name = '',
    mode2Qty = 0,
    mode2Price = 0,
    purchasePercentage = 0,
    baseUnitCost = 0
) {
    const el = (id) => document.getElementById(id);

    let displayQty = qty;
    const dualMode = parseInt(isDualMode || 0, 10) === 1;
    const parsedMode1Qty = parseFloat(mode1Qty) || 0;

    if (dualMode && parsedMode1Qty > 0) {
        displayQty = (parseFloat(qty) || 0) / parsedMode1Qty;
    }

    if (el('edit_id')) el('edit_id').value = id;
    if (el('search_product')) el('search_product').value = name;
    if (el('edit_purchasing_price')) el('edit_purchasing_price').value = purchase;
    if (el('edit_selling_price')) el('edit_selling_price').value = sell;
    if (el('edit_purchased_qty')) el('edit_purchased_qty').value = displayQty;
    if (el('edit_unit')) el('edit_unit').value = unit;
    if (el('edit_total_purchasing_price')) el('edit_total_purchasing_price').value = total;
    if (el('edit_invoice_number')) el('edit_invoice_number').value = invoice;
    if (el('edit_expiry_date')) el('edit_expiry_date').value = expiry;
    if (el('edit_supplier')) el('edit_supplier').value = supplier;
    if (el('is_dual_mode')) el('is_dual_mode').value = isDualMode;
    if (el('edit_dual_mode_name_1')) el('edit_dual_mode_name_1').value = mode1Name;
    if (el('edit_dual_mode_qty_1')) el('edit_dual_mode_qty_1').value = mode1Qty;
    if (el('edit_dual_mode_price_1')) el('edit_dual_mode_price_1').value = mode1Price;
    if (el('edit_dual_mode_name_2')) el('edit_dual_mode_name_2').value = mode2Name;
    if (el('edit_dual_mode_qty_2')) el('edit_dual_mode_qty_2').value = mode2Qty;
    if (el('edit_dual_mode_price_2')) el('edit_dual_mode_price_2').value = mode2Price;
    if (el('edit_purchase_percentage')) el('edit_purchase_percentage').value = purchasePercentage;
    if (el('edit_base_unit_cost')) el('edit_base_unit_cost').value = baseUnitCost;

    toggleDualModeFields();
    syncPrimarySellingPrice();
    calcDailyPurchaseTotal();
}

function toggleDualModeFields() {
    const dualWrap = document.getElementById('dual_mode_wrap');
    const isDual = parseInt(document.getElementById('is_dual_mode')?.value || '0', 10) === 1;

    if (dualWrap) {
        dualWrap.style.display = isDual ? 'grid' : 'none';
    }

    if (isDual) {
        if (document.getElementById('edit_dual_mode_name_1') && !document.getElementById('edit_dual_mode_name_1').value) {
            document.getElementById('edit_dual_mode_name_1').value = '50Kg Bag';
        }

        const derivedQty = extractKgValueFromProductName(document.getElementById('search_product')?.value || '');
        if (document.getElementById('edit_dual_mode_qty_1')) {
            if (derivedQty > 0) {
                document.getElementById('edit_dual_mode_qty_1').value = derivedQty;
            } else if (!document.getElementById('edit_dual_mode_qty_1').value) {
                document.getElementById('edit_dual_mode_qty_1').value = '50';
            }
        }

        if (document.getElementById('edit_dual_mode_name_2') && !document.getElementById('edit_dual_mode_name_2').value) {
            document.getElementById('edit_dual_mode_name_2').value = 'Loose Kg';
        }
        if (document.getElementById('edit_dual_mode_qty_2') && !document.getElementById('edit_dual_mode_qty_2').value) {
            document.getElementById('edit_dual_mode_qty_2').value = '1';
        }
    }

    updateDualQtyPreview();
}

function syncPrimarySellingPrice() {
    const isDual = parseInt(document.getElementById('is_dual_mode')?.value || '0', 10) === 1;
    const mainSellingPrice = document.getElementById('edit_selling_price');
    const mode1Price = document.getElementById('edit_dual_mode_price_1');

    if (isDual && mainSellingPrice && mode1Price) {
        const mode1Value = parseFloat(mode1Price.value || 0);
        if (mode1Value > 0) {
            mainSellingPrice.value = mode1Price.value;
        }
    }
}

function calcDailyPurchaseTotal() {
    const isDual = parseInt(document.getElementById('is_dual_mode')?.value || '0', 10) === 1;

    const mainSellingPrice = parseFloat(document.getElementById('edit_selling_price')?.value) || 0;
    const purchasePercentage = parseFloat(document.getElementById('edit_purchase_percentage')?.value) || 0;
    const enteredQty = parseFloat(document.getElementById('edit_purchased_qty')?.value) || 0;
    const mode1Qty = getDualPackQty();

    const purchasingEl = document.getElementById('edit_purchasing_price');
    const totalEl = document.getElementById('edit_total_purchasing_price');
    const baseUnitEl = document.getElementById('edit_base_unit_cost');

    let purchasingValue = mainSellingPrice - ((mainSellingPrice * purchasePercentage) / 100);
    if (purchasingValue < 0) {
        purchasingValue = 0;
    }

    if (purchasingEl) {
        purchasingEl.value = purchasingValue.toFixed(2);
    }

    let total = 0;
    let baseUnitCost = purchasingValue;

    if (isDual) {
        // User enters bag count, so total purchasing is based on entered bag count
        total = purchasingValue * enteredQty;

        if (mode1Qty > 0) {
            baseUnitCost = purchasingValue / mode1Qty;
        } else {
            baseUnitCost = 0;
        }
    } else {
        total = purchasingValue * enteredQty;
        baseUnitCost = purchasingValue;
    }

    if (total < 0) total = 0;
    if (baseUnitCost < 0) baseUnitCost = 0;

    if (totalEl) {
        totalEl.value = total.toFixed(2);
    }

    if (baseUnitEl) {
        baseUnitEl.value = baseUnitCost.toFixed(4);
    }

    updateDualQtyPreview();
}

function formatNumber(value) {
    const num = parseFloat(value) || 0;
    return Number.isInteger(num) ? String(num) : num.toFixed(2).replace(/\.0+$/, '').replace(/(\.\d*[1-9])0+$/, '$1');
}

function showProductSuggestions() {
    const input = document.getElementById('product_name');
    const suggestionBox = document.getElementById('product_suggestions');
    const rows = document.querySelectorAll('#stockSuggestionTable .stock-data-row');

    if (!input || !suggestionBox) return;

    const keyword = input.value.toLowerCase().trim();
    suggestionBox.innerHTML = '';

    if (keyword === '') {
        suggestionBox.style.display = 'none';
        return;
    }

    let found = 0;

    rows.forEach(row => {
        const productName = (row.dataset.product_name || '').toLowerCase();

        if (productName.includes(keyword)) {
            found++;

            const item = document.createElement('div');
            item.className = 'product-suggestion-item';
            item.innerHTML = `
                <strong>${row.dataset.product_name}</strong><br>
                <small>
                    Purchase: ${row.dataset.purchasing_price} |
                    Selling: ${row.dataset.selling_price} |
                    Qty: ${row.dataset.purchased_qty} |
                    Unit: ${row.dataset.unit}
                </small>
            `;

            item.onclick = function () {
                fillProductFromSuggestion(row);
            };

            suggestionBox.appendChild(item);
        }
    });

    suggestionBox.style.display = found > 0 ? 'block' : 'none';
}

function fillProductFromSuggestion(row) {
    const productName = document.getElementById('product_name');
    const purchasingPrice = document.getElementById('purchasing_price');
    const sellingPrice = document.getElementById('selling_price');
    const unit = document.getElementById('unit');
    const purchasedQty = document.getElementById('purchased_qty');
    const totalPurchasingPrice = document.getElementById('total_purchasing_price');
    const suggestionBox = document.getElementById('product_suggestions');

    if (productName) productName.value = row.dataset.product_name || '';
    if (purchasingPrice) purchasingPrice.value = row.dataset.purchasing_price || '';
    if (sellingPrice) sellingPrice.value = row.dataset.selling_price || '';
    if (unit) unit.value = row.dataset.unit || '';
    if (purchasedQty) purchasedQty.value = '';
    if (totalPurchasingPrice) totalPurchasingPrice.value = '';

    if (suggestionBox) {
        suggestionBox.style.display = 'none';
        suggestionBox.innerHTML = '';
    }
}

document.addEventListener('click', function (e) {
    const productInput = document.getElementById('product_name');
    const suggestionBox = document.getElementById('product_suggestions');

    if (!productInput || !suggestionBox) return;

    if (!productInput.contains(e.target) && !suggestionBox.contains(e.target)) {
        suggestionBox.style.display = 'none';
    }
});

document.addEventListener('DOMContentLoaded', function () {
    updateDualQtyPreview();
});