/* Sale Voucher Logic (Pakki Parchi) — Full API Integration */

async function initSale(params = {}) {
    console.log("Initializing Sale Module (Live)...");
    const editId = params.id;

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

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

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

    // 2. Load Data from API
    try {
        let existingSaleData = null;
        if (editId) {
            const saleRes = await API.get(`/sales/${editId}`);
            existingSaleData = saleRes.data;
        }

        // Fetch all lots (in a real scenario, this would be filtered or paginated)
        // We do not pass include_lot_id specifically because a voucher can have multiple lots now.
        const [partiesRes, accountsRes, lotsRes, nextVoucherRes] = await Promise.all([
            API.get('/accounts', { type: 'party', sub_type: 'khareedar' }),
            API.get('/accounts', { type: 'bank_cash', exclude_capital: 1 }),
            API.get('/lots'), // Fetching active lots
            editId ? Promise.resolve(null) : API.get('/sales/next-voucher')
        ]);

        if (nextVoucherRes && nextVoucherRes.success) {
            $('#saleVoucherId').text(nextVoucherRes.data.voucher_no);
        }

        // 2.1 Populate Selects
        Utils.populateSelect('saleParty', partiesRes.data, 'خریدار منتخب کریں...');
        
        // 2.2 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%' });

        // Map lots for quick lookup
        window._availableLots = lotsRes.data;
        if (editId && existingSaleData && existingSaleData.items) {
             // In edit mode, some lots might already be sold, but we need them in the dropdown. 
             // We can push them if not exists.
             existingSaleData.items.forEach(item => {
                 if (!window._availableLots.find(l => l.id == item.lot_id)) {
                     window._availableLots.push({
                         id: item.lot_id,
                         lot_number: item.lot_number,
                         item_name: item.item_name,
                         zamidar_name: item.zamidar_name,
                         remaining_qty: item.remaining_qty,
                         item_id: item.item_id,
                         status: 'sold'
                     });
                 }
             });
        }

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

        // 2.4 Load Edit Data
        if (editId && existingSaleData) {
            await loadSaleEditData(editId, existingSaleData);
        } else {
            addSaleItemRow(); // Add one empty row by default
        }

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

    // --- Dynamic Row Addition ---
    function addSaleItemRow(data = null) {
        const rowId = Date.now() + Math.floor(Math.random() * 1000);
        let lotOptions = '<option value=""></option>';
        window._availableLots.forEach(lot => {
            const label = lot.status === 'sold'
                ? `${lot.lot_number} — ${lot.item_name} (${lot.zamidar_name}) [مکمل فروخت]`
                : `${lot.lot_number} — ${lot.item_name} (${lot.zamidar_name})`;
            lotOptions += `<option value="${lot.id}">${label}</option>`;
        });

        const html = `
            <tr class="sale-item-row" id="row-${rowId}">
                <td>
                    <select class="table-form-control lot-id select2-row" required>
                        ${lotOptions}
                    </select>
                </td>
                <td><input type="text" class="table-form-control table-form-control-num lot-available" readonly value="0.00"></td>
                <td><input type="number" class="table-form-control table-form-control-num item-weight" value="${data ? data.weight : ''}" step="any" required></td>
                <td><input type="number" class="table-form-control table-form-control-num item-deduction" value="${data ? data.deduction : '0'}" step="any"></td>
                <td>
                    <div style="display:flex; gap: 5px;">
                        <select class="table-form-control item-basis" style="min-width: 65px;">
                            <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>
                            <option value="other" ${data && ![40,100,1].includes(data.rate_basis) ? 'selected' : ''}>دیگر</option>
                        </select>
                        <input type="number" class="table-form-control table-form-control-num item-basis-custom" value="${data ? data.rate_basis : ''}" style="width: 50px; ${data && ![40,100,1].includes(data.rate_basis) ? '' : 'display:none;'}">
                    </div>
                </td>
                <td><input type="number" class="table-form-control table-form-control-num item-rate" value="${data ? data.rate : ''}" step="any" required></td>
                <td><input type="text" class="table-form-control table-form-control-num item-amount fw-bold" value="${data ? data.gross_amount : '0.00'}" readonly></td>
                <td class="text-center">
                    <i class="fas fa-trash text-danger cursor-pointer" onclick="$(this).closest('tr').remove(); calculateSale();"></i>
                </td>
                <input type="hidden" class="item-id-hidden" value="${data ? data.item_id : ''}">
            </tr>
        `;
        
        $('#saleItemsBody').append(html);
        const $row = $(`#row-${rowId}`);

        $row.find('.select2-row').select2({ placeholder: "ڈیری (Lot)...", allowClear: true, dir: "rtl", width: '100%' });

        // Attach calculation triggers
        $row.find('.item-weight, .item-deduction, .item-rate, .item-basis, .item-basis-custom').on('input change', calculateSale);
        
        $row.find('.item-basis').on('change', function() {
            if($(this).val() === 'other') {
                $(this).siblings('.item-basis-custom').show().focus();
            } else {
                $(this).siblings('.item-basis-custom').hide();
            }
            calculateSale();
        });

        $row.find('.lot-id').on('change', function() {
            const lotId = $(this).val();
            if (!lotId) {
                $row.find('.lot-available').val('0.00');
                $row.find('.item-id-hidden').val('');
                return;
            }
            const lot = window._availableLots.find(l => l.id == lotId);
            if (lot) {
                $row.find('.item-id-hidden').val(lot.item_id);
                // Alert info
                $('#alertZamidar').text(lot.zamidar_name);
                $('#alertItem').text(lot.item_name);
                if (lot.status === 'sold') {
                    $('#alertWeightLabel').text('دستیاب وزن');
                    $('#alertWeight').text('0.00');
                    $('#alertSoldBadge').show();
                    $row.find('.lot-available').val('0.00');
                } else {
                    $('#alertWeightLabel').text('دستیاب وزن');
                    $('#alertWeight').text(parseFloat(lot.remaining_qty).toFixed(2));
                    $('#alertSoldBadge').hide();
                    $row.find('.lot-available').val(parseFloat(lot.remaining_qty).toFixed(2));
                }
                $('#lotInfoAlert').fadeIn();

                // Auto-fill weight ONLY on new selection
                if (!$row.find('.item-weight').val() && lot.status !== 'sold') {
                    $row.find('.item-weight').val(lot.remaining_qty);
                }
            }
            calculateSale();
        });

        // Focus event to update Lot info alert
        $row.on('focusin', function() {
            const lotId = $(this).find('.lot-id').val();
            if(lotId) { $(this).find('.lot-id').trigger('change'); }
        });

        // TRIGGER LOAD DATA AFTER LISTENERS ARE ATTACHED
        if (data) {
            $row.find('.lot-id').val(data.lot_id).trigger('change');
            // Timeout to reset weight because change trigger overwrites it
            setTimeout(() => {
                $row.find('.item-weight').val(data.weight);
                $row.find('.item-rate').val(data.rate);
                calculateSale();
            }, 50);
        }
    }

    async function loadSaleEditData(id, preloadedData = null) {
        try {
            const data = preloadedData || (await API.get(`/sales/${id}`)).data;

            $('#saleVoucherId').text(data.voucher_no);
            $('#saleDate').val(data.voucher_date);
            $('#saleDueDate').val(data.due_date || '');
            $('#saleParty').val(data.khareedar_id).trigger('change');
            $('#saleHavala').val(data.havala_name || '');
            
            $('#saleItemsBody').empty();
            if(data.items && data.items.length > 0) {
               data.items.forEach(item => addSaleItemRow(item));
            }

            // Sync Additions (Commission, etc.)
            // 1. Reset static rows first, and remove dynamic rows
            $('.sale-kharcha-val').val(0);
            $('#commRs').val(0);
            $('.sale-comm-pct').val(0);
            
            // Remove rows that were added dynamically (they have a delete button)
            $('#saleKharchaBody tr').each(function() {
                if ($(this).find('.btn-delete-row').length > 0) {
                    $(this).remove();
                }
            });

            const additions = data.additions || [];
            if (additions.length > 0) {
                const globalType = additions[0].type || 'plus';
                $('#globalKharchaType').val(globalType);
                $(`#globalKharchaToggle .toggle-btn[data-value="${globalType}"]`).addClass('active').siblings().removeClass('active');
            } else {
                $('#globalKharchaType').val('plus');
                $('#globalKharchaToggle .toggle-btn[data-value="plus"]').addClass('active').siblings().removeClass('active');
            }

            additions.forEach(a => {
                const desc = a.description;
                if (desc.includes('کمیشن')) {
                    $('.sale-comm-pct').val(a.percentage || 0);
                    $('#commRs').val(a.amount);
                } else {
                    // Try to find a static row with this description
                    let found = false;
                    $('#saleKharchaBody tr').each(function() {
                        const rowDesc = $(this).find('input').first().val();
                        if (rowDesc === desc) {
                            $(this).find('.sale-kharcha-val').val(a.amount);
                            found = true;
                            return false;
                        }
                    });

                    if (!found) {
                        // Append as a new dynamic row
                        const html = `
                            <tr>
                                <td><input type="text" class="table-form-control" value="${desc}"></td>
                                <td></td>
                                <td><input type="number" class="table-form-control sale-kharcha-val" value="${a.amount}" step="any"></td>
                                <td class="text-center">
                                    <i class="fas fa-times-circle btn-delete-row" onclick="$(this).closest('tr').remove(); calculateSale();"></i>
                                </td>
                            </tr>
                        `;
                        $('#saleKharchaBody').append(html);
                    }
                }
            });

            // Settlement
            if (data.payment_method_id) {
                $('#paymentMethod').val(data.payment_method_id).trigger('change');
                $('#amountReceived').val(data.amount_received);
            } else {
                $('#paymentMethod').val('khata').trigger('change');
            }

            // Calculate after all rows are loaded
            setTimeout(() => { calculateSale(); }, 150);
            Toast.info(`فروخت پرچی #${data.voucher_no} لوڈ ہو گئی ہے۔`);
        } catch (err) {
            Toast.danger("ریکارڈ لوڈ نہیں ہو سکا۔");
        }
    }


    // 4. Payment Method Change
    $('#paymentMethod').on('change', function() {
        const val = $(this).val();
        const netVal = Utils.parseNumber($('#netReceivable').text());
        
        if (val === 'khata') {
            $('#amountReceived').val(0).prop('disabled', true);
        } else {
            const received = Utils.parseNumber($('#amountReceived').val());
            if (received === 0 || $('#amountReceived').val() === '') {
                $('#amountReceived').val(netVal.toFixed(2));
            }
            $('#amountReceived').prop('disabled', false);
        }
        calculateSale();
    });

    // 6. Calculation Triggers
    $('.sale-comm-pct, #amountReceived').on('input', calculateSale);
    $(document).on('input', '.sale-kharcha-val', calculateSale);
    
    $('#addSaleKharchaRow').on('click', function() {
        const html = `
            <tr>
                <td><input type="text" class="table-form-control" placeholder="خرچے کا نام..."></td>
                <td></td>
                <td><input type="number" class="table-form-control sale-kharcha-val" value="0" step="any"></td>
                <td class="text-center">
                    <i class="fas fa-times-circle btn-delete-row" onclick="$(this).closest('tr').remove(); calculateSale();"></i>
                </td>
            </tr>
        `;
        $('#saleKharchaBody').append(html);
    });
    
    $(document).on('change', '#globalKharchaType', calculateSale);
    
    // Global Kharcha Type Toggle Handler
    $('#globalKharchaToggle .toggle-btn').on('click', function() {
        const val = $(this).data('value');
        $('#globalKharchaType').val(val);
        $('#globalKharchaToggle .toggle-btn').removeClass('active');
        $(this).addClass('active');
        calculateSale();
    });

    // 7. Form Submission (API POST/PUT)
    $form.on('submit', async function(e) {
        e.preventDefault();

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

        const items = [];
        $('#saleItemsBody .sale-item-row').each(function() {
            const $row = $(this);
            const lotId = $row.find('.lot-id').val();
            const weight = Utils.parseNumber($row.find('.item-weight').val());
            const deduction = Utils.parseNumber($row.find('.item-deduction').val());
            const rate = Utils.parseNumber($row.find('.item-rate').val());
            const itemId = $row.find('.item-id-hidden').val();
            let basis = $row.find('.item-basis').val();
            if (basis === 'other') { basis = Utils.parseNumber($row.find('.item-basis-custom').val()); } else { basis = parseInt(basis); }

            if (lotId && weight > 0 && rate > 0) {
                items.push({
                    lot_id: parseInt(lotId),
                    item_id: parseInt(itemId),
                    weight: weight,
                    deduction: deduction,
                    rate_basis: basis,
                    rate: rate,
                    gross_amount: Utils.parseNumber($row.find('.item-amount').val())
                });
            }
        });

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

        // Prepare Additions (Extra Charges)
        const globalType = $('#globalKharchaType').val() || 'plus';
        const additions = [];
        $('#saleKharchaBody tr').each(function() {
            const desc = $(this).find('input').first().val();
            const $amtInput = $(this).find('.sale-kharcha-val');
            if ($amtInput.length === 0) return;
            const amt = Utils.parseNumber($amtInput.val());
            if (desc && amt > 0) {
                additions.push({ description: desc, amount: amt, type: globalType });
            }
        });

        // Commission calculation (if any)
        const commPct = Utils.parseNumber($('.sale-comm-pct').val());
        if (commPct > 0) {
            const commAmt = Utils.parseNumber($('#commRs').val());
            additions.push({ description: `کمیشن (${commPct}%)`, amount: commAmt, percentage: commPct, type: globalType });
        }

        const payload = {
            voucher_date: $('#saleDate').val(),
            due_date: $('#saleDueDate').val() || null,
            khareedar_id: parseInt(khareedarId),
            havala_name: $('#saleHavala').val() || null,
            items: items,
            additions: additions,
            net_receivable: Utils.parseNumber($('#netReceivable').text().replace(/,/g, '')),
            payment_method_id: $('#paymentMethod').val() === 'khata' ? null : parseInt($('#paymentMethod').val()),
            amount_received: Utils.parseNumber($('#amountReceived').val())
        };

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

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

            if (res.success) {
                const newId = res.data.id || editId;
                Toast.success(editId ? "✅ تبدیلی محفوظ ہو گئی۔" : `✅ بکری پرچی محفوظ ہو گئی!`);
                if (!editId) {
                    Utils.showSaleVoucher(newId);
                }
                window.location.hash = '#sale-list';
            }

        } catch (err) {
            // Error 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('#saleForm');
}

function calculateSale() {
    let overallGrossAmount = 0;
    
    $('#saleItemsBody .sale-item-row').each(function() {
        const $row = $(this);
        const weight = Utils.parseNumber($row.find('.item-weight').val());
        const deduction = Utils.parseNumber($row.find('.item-deduction').val());
        const rate = Utils.parseNumber($row.find('.item-rate').val());
        let basis = $row.find('.item-basis').val();
        if (basis === 'other') {
             basis = Utils.parseNumber($row.find('.item-basis-custom').val()) || 1;
        } else {
             basis = parseInt(basis);
        }
        
        let rowGrossStr = "0.00";
        const netWeight = weight - deduction;
        if (netWeight > 0 && rate > 0) {
            const rowGross = (netWeight / basis) * rate;
            rowGrossStr = rowGross.toFixed(2);
            overallGrossAmount += parseFloat(rowGrossStr);
        }
        $row.find('.item-amount').val(rowGrossStr);
    });

    $('#saleGrossAmount').val(Utils.formatNumber(overallGrossAmount));

    // Commission logic
    const commPct = Utils.parseNumber($('.sale-comm-pct').val());
    let commRs = (overallGrossAmount * commPct) / 100;
    commRs = parseFloat(commRs.toFixed(2));
    $('#commRs').val(commRs.toFixed(2));

    let totalAdditions = 0;
    $('.sale-kharcha-val').each(function() {
        totalAdditions += Utils.parseNumber($(this).val());
    });
    totalAdditions += commRs; // Add commission to total additions
    totalAdditions = parseFloat(totalAdditions.toFixed(2));
    
    $('#totalSaleKharchay').text(Utils.formatNumber(totalAdditions));

    const globalType = $('#globalKharchaType').val() || 'plus';
    let netReceivable = overallGrossAmount;
    if (globalType === 'minus') {
        netReceivable -= totalAdditions;
    } else {
        netReceivable += totalAdditions;
    }
    netReceivable = parseFloat(netReceivable.toFixed(2));

    $('#netReceivable').text(Utils.formatNumber(netReceivable));

    const received = Utils.parseNumber($('#amountReceived').val());
    let balance = netReceivable - received;
    balance = parseFloat(balance.toFixed(2));
    $('#remainingBalance').val(Utils.formatNumber(balance));
    $('#remainingBalance').css('color', balance > 0 ? 'var(--danger)' : 'var(--success)');
}
