/**
 * Sale List (History) — Pakki Parchi Logic
 */

function initSaleList() {
    console.log("Initializing Sale List Module...");

    const state = {
        page: 1,
        limit: 20,
        date: '',
        party: '',
        item_id: ''
    };

    // --- Selectors ---
    const $tbody = $('#saleListBody');
    const $filterDate = $('#filterDate');
    const $filterParty = $('#filterParty');
    const $filterItem = $('#filterItem');
    const $btnSearch = $('#btnSearch');

    // --- Load Items for Dropdown ---
    async function loadItemsDropdown() {
        try {
            const res = await API.get('/items');
            if (res.success && res.data) {
                res.data.forEach(item => {
                    $filterItem.append(new Option(item.name, item.id));
                });
                $filterItem.select2({ placeholder: 'تمام اجناس...', allowClear: true, dir: 'rtl', width: '100%' });
            }
        } catch (e) {
            console.error("Failed to load items for filter:", e);
        }
    }
    loadItemsDropdown();

    // --- Load Data ---
    async function loadSales() {
        $tbody.html('<tr><td colspan="8" class="text-center p-4"><i class="fas fa-spinner fa-spin"></i> لوڈنگ...</td></tr>');

        try {
            const params = {
                page: state.page,
                limit: state.limit,
                date: state.date,
                party: state.party,
                item_id: state.item_id
            };

            const response = await API.get('/sales', params);
            
            // Update stats boxes
            const totalGross = parseFloat(response.data.total_gross_amount || 0);
            $('#cbDashboardTotalSaleAmount').text(Utils.formatNumber(totalGross) + ' روپے');

            if (response.success && response.data.data.length > 0) {
                renderTable(response.data.data);
                renderPagination(response.data.pagination);
            } else {
                $tbody.html('<tr><td colspan="8" class="text-center p-4 text-muted">کوئی ریکارڈ نہیں ملا۔</td></tr>');
            }
        } catch (error) {
            console.error("Failed to load sales:", error);
            $tbody.html('<tr><td colspan="8" class="text-center p-4 text-danger">ڈیٹا لوڈ کرنے میں غلطی ہوئی۔</td></tr>');
        }
    }

    function renderTable(data) {
        let html = '';
        data.forEach(item => {
            html += `
                <tr data-id="${item.id}">
                    <td class="fw-bold">${item.voucher_no}</td>
                    <td>${Utils.formatDate(item.voucher_date)}</td>
                    <td>${item.khareedar_name}</td>
                    <td class="text-muted"><small>${item.item_count > 1 ? 'متعدد' : item.lot_number}</small></td>
                    <td>${item.item_count > 1 ? item.item_name + ' و دیگر...' : item.item_name}</td>
                    <td>${parseFloat(item.sale_weight).toLocaleString()}</td>
                    <td class="text-danger">${parseFloat(item.total_deduction || 0).toLocaleString()}</td>
                    <td class="fw-bold text-accent">${parseFloat(item.net_receivable).toLocaleString()}</td>
                    <td class="text-center">
                        <div class="action-btns">
                            <button class="btn btn-outline btn-icon btn-sm btn-view" title="بل دیکھیں" onclick="viewSaleVoucher(${item.id})">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-outline btn-icon btn-sm btn-edit" title="ایڈٹ کریں" onclick="editSaleVoucher(${item.id})">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-outline btn-icon btn-sm btn-delete" title="ریورس کریں" onclick="reverseSaleVoucher(${item.id})">
                                <i class="fas fa-trash-alt text-danger"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        });
        $tbody.html(html);
    }

    function renderPagination(meta) {
        const totalPages = Math.ceil(meta.total / meta.limit);
        $('#paginationInfo').text(`Showing ${meta.total} records (Page ${meta.page} of ${totalPages})`);

        let paginationHtml = '';
        if (meta.page > 1) {
            paginationHtml += `<button class="btn btn-outline btn-sm" onclick="changeSalePage(${meta.page - 1})">Previous</button>`;
        }
        if (meta.page < totalPages) {
            paginationHtml += `<button class="btn btn-outline btn-sm" onclick="changeSalePage(${meta.page + 1})">Next</button>`;
        }
        $('#paginationControls').html(paginationHtml);
    }

    // --- Search Handlers ---
    $btnSearch.on('click', function() {
        state.date = $filterDate.val();
        state.party = $filterParty.val();
        state.item_id = $filterItem.val() || '';
        state.page = 1;
        loadSales();
    });

    // --- Actions ---
    window.changeSalePage = function(p) {
        state.page = p;
        loadSales();
    };

    window.viewSaleVoucher = function(id) {
        Utils.showSaleVoucher(id);
    };

    window.editSaleVoucher = function(id) {
        window.location.hash = `#sale?id=${id}`;
    };

    window.reverseSaleVoucher = function(id) {
        if (confirm("کیا آپ واقعی اس فروخت پرچی کو ریورس کرنا چاہتے ہیں؟ اس سے اکاؤنٹس اور انوینٹری بحال ہو جائے گی۔")) {
            API.post(`/sales/${id}/reverse`)
                .then(r => {
                    Toast.success("پرچی ریورس ہو گئی۔");
                    loadSales();
                })
                .catch(e => {
                    console.error("Reverse failed:", e);
                });
        }
    };

    // Initial load
    loadSales();
}
