/* Purchase Voucher Logic (Katchi Parchi) — Multi-Item Support */

async function initPurchase(params = {}) {
    console.log("Initializing Purchase Module (Multi-Item)...");
    const editId = params.id;
    let itemsData = []; // Will hold the inventory items for the dropdown
    const accountBalances = {};
    let originalPaymentMethodId = null;
    let originalAmountPaid = 0;

    const $form = $('#purchaseForm');
    const $submitBtn = $form.find('button[type="submit"]');

    // --- Mode Configuration ---
    if (editId) {
        $('.card-title:first').text('ترمیم کچی پرچی (Edit Purchase)');
        $submitBtn.html('<i class="fas fa-save"></i> تبدیلی محفوظ کریں').addClass('btn-accent');
    }

    // 1. Initial UI State
    $('#purchaseVoucherId').text(editId ? '...' : 'لوڈنگ...');
    $('#purchaseDate').val(Utils.getISODate());

    async function fetchPaymentBalance(accountId) {
        if (!accountId || accountId === 'khata') {
            $('#bal_purchasePaymentAccount').text('');
            delete accountBalances.purchasePaymentAccount;
            return;
        }

        try {
            $('#bal_purchasePaymentAccount').html('<i class="fas fa-spinner fa-spin"></i> لوڈنگ...');
            const res = await API.get(`/ledger/${accountId}/balance`);
            const balance = parseFloat(res.data.balance);
            accountBalances.purchasePaymentAccount = balance;

            const colorClass = balance >= 0 ? 'text-success' : 'text-danger';
            const typeStr = balance >= 0 ? ' (Dr)' : ' (Cr)';
            $('#bal_purchasePaymentAccount').html(`موجودہ بیلنس: <span class="${colorClass}">${Utils.formatNumber(Math.abs(balance))} روپے${typeStr}</span>`);
        } catch (err) {
            $('#bal_purchasePaymentAccount').text('بیلنس لوڈ نہیں ہو سکا۔');
        }
    }

    // 2. Load Data from API
    try {
        const [partiesRes, itemsRes, accountsRes, nextVoucherRes] = await Promise.all([
            API.get('/accounts', { type: 'party', sub_type: 'zamidar' }),
            API.get('/items'),
            API.get('/accounts', { type: 'bank_cash', exclude_capital: 1 }),
            editId ? Promise.resolve(null) : API.get('/purchases/next-voucher')
        ]);

        itemsData = itemsRes.data;

        if (nextVoucherRes && nextVoucherRes.success) {
            $('#purchaseVoucherId').text(nextVoucherRes.data.voucher_no);
            window._nextLotNumber = nextVoucherRes.data.lot_number;
        }

        // 2.1 Populate Party Select
        Utils.populateSelect('purchaseParty', partiesRes.data, 'زمیندار منتخب کریں...');
        
        // 2.2 Populate Payment Methods
        const $pm = $('#paymentMethod');
        $pm.empty().append(new Option('کھاتے میں (Udhar)', 'khata'));
        accountsRes.data.forEach(acc => {
            $pm.append(new Option(`${acc.name} (${acc.sub_type})`, acc.id));
        });
        $pm.select2({ dir: "rtl", width: '100%' });
        $pm.on('change', function() {
            fetchPaymentBalance($(this).val());
        });

        // 2.3 Row Addition Handler
        $('#addItemRow').on('click', () => addItemRow());

        $('#addKharchaRow').on('click', function() {
            const html = `
                <tr>
                    <td><input type="text" class="table-form-control" placeholder="خرچے کی تفصیل..."></td>
                    <td><input type="number" class="table-form-control kharcha-val" value="" step="any"></td>
                    <td class="text-center">
                        <i class="fas fa-trash text-danger cursor-pointer btn-delete-row" onclick="$(this).closest('tr').remove(); calculatePurchase();"></i>
                    </td>
                </tr>
            `;
            $('#kharchaBody').append(html);
            $('#kharchaBody').find('.kharcha-val').last().on('change input', calculatePurchase);
        });

        $('#kharchaGlobalType').on('change', function() {
            $(this).attr('data-type', $(this).val());
            calculatePurchase();
        });

        // 2.4 If Editing, load the specific record
        if (editId) {
            await loadEditData(editId);
        } else {
            // Add first empty row by default
            addItemRow();
        }

    } catch (err) {
        console.error(err);
        Toast.danger("ڈیٹا لوڈ کرنے میں غلطی آئی۔ براہ کرم پیج ریفریش کریں۔");
    }

    // --- Dynamic Row Addition ---
    function addItemRow(data = null) {
        const rowId = Date.now() + Math.floor(Math.random() * 1000);
        const itemOptions = itemsData.map(i => `<option value="${i.id}">${i.name}</option>`).join('');
        
        let displayLot = '---';
        if (data) {

        } else if (window._nextLotNumber) {
            displayLot = window._nextLotNumber;
            // Predicted next for the *next* row addition
            let parts = window._nextLotNumber.split('-');
            if (parts.length === 2) {
                window._nextLotNumber = `${parts[0]}-${parseInt(parts[1]) + 1}`;
            }
        }

        const html = `
            <tr class="item-row" id="row-${rowId}">
                <td class="text-center fw-bold text-info-dark">${displayLot}</td>
                <td>
                    <select class="table-form-control item-id select2-row" required>
                        <option value="">جنس...</option>
                        ${itemOptions}
                    </select>
                </td>

                <td>
                    <select class="table-form-control item-packing">
                        <option value="بوری">بوری</option>
                        <option value="کھلا">کھلا</option>
                    </select>
                </td>
                <td><input type="number" class="table-form-control table-form-control-num item-bori" value="${data ? data.bori_qty : ''}" step="any"></td>
                <td><input type="number" class="table-form-control table-form-control-num item-gross" value="${data ? data.gross_weight : ''}" step="any"></td>
                <td><input type="number" class="table-form-control table-form-control-num item-kat" value="${data ? (parseFloat(data.kat) + parseFloat(data.tara || 0)) : ''}" step="any"></td>
                <td><input type="text" class="table-form-control table-form-control-num item-net" value="${data ? data.net_weight : 0}" readonly></td>
                <td>
                    <select class="table-form-control item-basis">
                        <option value="40" ${data && data.rate_basis == 40 ? 'selected' : ''}>40KG</option>
                        <option value="100" ${data && data.rate_basis == 100 ? 'selected' : ''}>100KG</option>
                        <option value="1" ${data && data.rate_basis == 1 ? 'selected' : ''}>1KG</option>
                    </select>
                </td>
                <td><input type="number" class="table-form-control table-form-control-num item-rate" value="${data ? data.rate : ''}" step="any"></td>
                <td><input type="text" class="table-form-control table-form-control-num item-amount" value="${data ? data.gross_amount : 0}" readonly></td>
                <td class="text-center">
                    <i class="fas fa-trash text-danger cursor-pointer" onclick="$(this).closest('tr').remove(); calculatePurchase();"></i>
                </td>
                <input type="hidden" class="item-tara" value="0">
            </tr>
        `;
        
        $('#itemsBody').append(html);
        const $row = $(`#row-${rowId}`);

        
        // Initialize Select2 for the new row
        $row.find('.select2-row').select2({ dir: "rtl", width: '100%' });
        
        // Handling Packing selection (Only toggle Bori Qty visibility)
        const updatePackingState = () => {
            const packing = $row.find('.item-packing').val();
            const $boriInput = $row.find('.item-bori');

            if (packing === 'کھلا') {
                $boriInput.css('visibility', 'hidden').val(0);
            } else {
                $boriInput.css('visibility', 'visible');
            }
        };

        // Set values if editing
        if (data) {
            $row.find('.item-id').val(data.item_id).trigger('change');
            $row.find('.item-packing').val(data.packing);
        }
        
        updatePackingState(); // Initial run

        // Attach calculation triggers & UI state
        $row.find('input, select').on('input change', calculatePurchase);
        $row.find('.item-packing').on('change', () => {
            updatePackingState();
            calculatePurchase();
        });
    }

    async function loadEditData(id) {
        try {
            const res = await API.get(`/purchases/${id}`);
            const data = res.data;

            $('#purchaseVoucherId').text(data.voucher_no);
            $('#purchaseDate').val(data.voucher_date);
            $('#purchaseParty').val(data.zamidar_id).trigger('change');
            $('#vehicleNo').val(data.vehicle_no);
            
            // Restore Items (Lots)
            $('#itemsBody').empty();
            data.lots.forEach(lot => addItemRow(lot));

            // Restore Deductions (Kharchay)
            $('#kharchaBody').empty();
            if (data.deductions && data.deductions.length > 0) {
                // Determine global type from the first deduction
                const firstDeductionAmt = parseFloat(data.deductions[0].amount);
                const globalType = firstDeductionAmt < 0 ? '-' : '+';
                $('#kharchaGlobalType').val(globalType).attr('data-type', globalType);

                data.deductions.forEach(d => {
                    const absAmt = Math.abs(parseFloat(d.amount));
                    const html = `
                        <tr>
                            <td><input type="text" class="table-form-control" value="${d.description}"></td>
                            <td><input type="number" class="table-form-control kharcha-val" value="${absAmt}" step="any"></td>
                            <td class="text-center">
                                <i class="fas fa-times-circle btn-delete-row" onclick="$(this).closest('tr').remove(); calculatePurchase();"></i>
                            </td>
                        </tr>
                    `;
                    $('#kharchaBody').append(html);
                });
            }

            // Settlement
            if (data.payment_method_id) {
                $('#paymentMethod').val(data.payment_method_id).trigger('change');
                $('#amountPaid').val(data.amount_paid);
                originalPaymentMethodId = parseInt(data.payment_method_id) || null;
                originalAmountPaid = Utils.parseNumber(data.amount_paid);
            } else {
                originalPaymentMethodId = null;
                originalAmountPaid = 0;
            }

            calculatePurchase();
        } catch (err) {
            Toast.danger("ریکارڈ لوڈ نہیں ہو سکا۔");
        }
    }

    // 3. Calculation Triggers
    $(document).on('input change', '.kharcha-val, #amountPaid', calculatePurchase);
    
    $('#paymentMethod').on('change', function() {
        if ($(this).val() !== 'khata') {
            const paid = Utils.parseNumber($('#amountPaid').val());
            if (paid === 0 || $('#amountPaid').val() === '') {
                const netPayable = Utils.parseNumber($('#netPayable').text());
                $('#amountPaid').val(netPayable.toFixed(2));
            }
        } else {
            $('#amountPaid').val('');
        }
        calculatePurchase();
    });

    // 4. Form Submission
    $form.on('submit', async function(e) {
        e.preventDefault();

        const zamidarId = $('#purchaseParty').val();
        if (!zamidarId) {
            Toast.warning("براہ کرم زمیندار منتخب کریں۔");
            return;
        }

        const items = [];
        $('#itemsBody .item-row').each(function() {
            const $row = $(this);
            const itemId = $row.find('.item-id').val();
            const netWeight = Utils.parseNumber($row.find('.item-net').val());
            const rate = Utils.parseNumber($row.find('.item-rate').val());

            if (itemId && netWeight > 0 && rate > 0) {
                items.push({
                    item_id: parseInt(itemId),
                    packing: $row.find('.item-packing').val(),
                    bori_qty: parseInt($row.find('.item-bori').val()) || 0,
                    tara: Utils.parseNumber($row.find('.item-tara').val()),
                    gross_weight: Utils.parseNumber($row.find('.item-gross').val()),
                    kat: Utils.parseNumber($row.find('.item-kat').val()),
                    net_weight: netWeight,
                    rate_basis: parseInt($row.find('.item-basis').val()),
                    rate: rate,
                    gross_amount: Utils.parseNumber($row.find('.item-amount').val())
                });
            }
        });

        if (items.length === 0) {
            Toast.warning("براہ کرم کم از کم ایک جنس درست معلومات کے ساتھ شامل کریں۔");
            return;
        }

        const deductionsCount = $('#kharchaBody tr').length;
        const globalType = $('#kharchaGlobalType').val() || '+';
        const deductions = [];
        $('#kharchaBody tr').each(function() {
            const desc   = $(this).find('input').first().val();
            const absAmt = Utils.parseNumber($(this).find('.kharcha-val').val());
            // Store as signed based on global toggle
            const signedAmt = globalType === '-' ? -absAmt : absAmt;
            if (desc && absAmt > 0) {
                deductions.push({ description: desc, amount: signedAmt });
            }
        });

        const payload = {
            voucher_date: $('#purchaseDate').val(),
            zamidar_id: parseInt(zamidarId),
            vehicle_no: $('#vehicleNo').val(),
            items: items,
            deductions: deductions,
            net_payable: Utils.parseNumber($('#netPayable').text()),
            payment_method_id: $('#paymentMethod').val() === 'khata' ? null : parseInt($('#paymentMethod').val()),
            amount_paid: Utils.parseNumber($('#amountPaid').val())
        };

        if (payload.payment_method_id && payload.amount_paid > 0) {
            let availableBalance = accountBalances.purchasePaymentAccount;
            if (typeof availableBalance !== 'number') {
                try {
                    const balRes = await API.get(`/ledger/${payload.payment_method_id}/balance`);
                    availableBalance = parseFloat(balRes.data.balance);
                    accountBalances.purchasePaymentAccount = availableBalance;
                } catch (err) {
                    Toast.warning("اکاؤنٹ بیلنس چیک نہیں ہو سکا، دوبارہ کوشش کریں۔");
                    return;
                }
            }

            if (editId && originalPaymentMethodId === payload.payment_method_id) {
                availableBalance += originalAmountPaid;
            }

            if (payload.amount_paid > availableBalance) {
                Toast.danger(`⚠️ Insufficient Balance! دستیاب رقم ${Utils.formatNumber(availableBalance)} روپے ہے۔`);
                return;
            }
        }

        $submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> پروسیسنگ...');

        try {
            let res;
            if (editId) {
                res = await API.put(`/purchases/${editId}`, payload);
            } else {
                res = await API.post('/purchases', payload);
            }

            if (res.success) {
                const newId = res.data.id;
                Toast.success(editId ? "✅ تبدیلی محفوظ ہو گئی۔" : "✅ پرچی محفوظ ہو گئی!");
                
                if (!editId) {
                    // Show receipt immediately for new purchases
                    Utils.showPurchaseVoucher(newId);
                }
                
                window.location.hash = '#purchase-list';
            }

        } catch (err) {
            // Managed by API.js
        } finally {
            $submitBtn.prop('disabled', false).html(editId ? '<i class="fas fa-save"></i> تبدیلی محفوظ کریں' : '<i class="fas fa-save"></i> محفوظ کریں');
        }
    });

    Utils.setupEnterNavigation('#purchaseForm');
}

function calculatePurchase() {
    let overallGrossAmount = 0;
    let overallBori = 0;
    let overallWeight = 0;

    $('#itemsBody .item-row').each(function() {
        const $row = $(this);
        const gross = Utils.parseNumber($row.find('.item-gross').val());
        const bori = Utils.parseNumber($row.find('.item-bori').val());
        const packing = $row.find('.item-packing').val();
        const kat = Utils.parseNumber($row.find('.item-kat').val());
        const taraPerBori = Utils.parseNumber($row.find('.item-tara').val());
        const rate = Utils.parseNumber($row.find('.item-rate').val());
        const basis = Utils.parseNumber($row.find('.item-basis').val()) || 40;

        const totalTara = bori * taraPerBori;
        const netWeight = gross - totalTara - kat;

        
        $row.find('.item-net').val(netWeight > 0 ? netWeight.toFixed(2) : "0.00");
        
        let rowGrossAmount = 0;
        if (netWeight > 0 && rate > 0) {
            rowGrossAmount = (netWeight / basis) * rate;
        }
        $row.find('.item-amount').val(rowGrossAmount.toFixed(2));

        overallGrossAmount += rowGrossAmount;
        overallBori += bori;
        overallWeight += netWeight;
    });

    $('#overallGrossAmount').text(Utils.formatNumber(overallGrossAmount));
    $('#summaryGrossAmount').text(Utils.formatNumber(overallGrossAmount));
    $('#summaryTotalWeight').text(overallWeight.toFixed(2));
    $('#summaryTotalBori').text(overallBori);

    let totalKharchay = 0;
    const globalType = $('#kharchaGlobalType').val() || '+';
    // Update header toggle attribute just in case for color-coding
    $('#kharchaGlobalType').attr('data-type', globalType);

    $('#kharchaBody tr').each(function() {
        const absAmt = Utils.parseNumber($(this).find('.kharcha-val').val());
        // Apply sign based on global toggle
        totalKharchay += globalType === '-' ? -absAmt : absAmt;
    });
    $('#totalKharchay').text(Utils.formatNumber(totalKharchay));

    const netPayable = overallGrossAmount + totalKharchay;
    $('#netPayable').text(Utils.formatNumber(netPayable));

    // Removed forced auto-fill block. Auto-fill should be handled by the payment method dropdown change event instead.
    
    const paid = Utils.parseNumber($('#amountPaid').val());
    const balance = netPayable - paid;
    $('#remainingBalance').val(Utils.formatNumber(balance));
}
