/**
 * Purchase List (History) — Katchi Parchi Logic
 */

function initPurchaseList() {
    console.log("Initializing Purchase List Module...");

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

    // --- Selectors ---
    const $tbody = $('#purchaseListBody');
    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 loadPurchases() {
        $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('/purchases', params);
            
            // Update stats box
            const totalPurchaseAmount = parseFloat(response.data.total_purchase_amount || 0);
            $('#cbDashboardTotalPurchaseAmount').text(Utils.formatNumber(totalPurchaseAmount) + ' روپے');

            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 purchases:", 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 class="text-info-dark fw-bold">${item.lot_numbers || '---'}</td>
                    <td>${Utils.formatDate(item.voucher_date)}</td>
                    <td>${item.zamidar_name}</td>
                    <td>${item.item_name}</td>
                    <td>${parseFloat(item.total_net_weight || item.net_weight).toLocaleString()}</td>
                    <td class="fw-bold">${parseFloat(item.total_gross_amount || item.gross_amount).toLocaleString()}</td>
                    <td class="text-center">
                        <div class="action-btns">

                            <button class="btn btn-outline btn-icon btn-sm btn-view" title="بل دیکھیں" onclick="viewVoucher(${item.id})">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="btn btn-outline btn-icon btn-sm btn-edit" title="ایڈٹ کریں" onclick="editVoucher(${item.id})">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn btn-outline btn-icon btn-sm btn-delete" title="ریورس کریں" onclick="reverseVoucher(${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="changePage(${meta.page - 1})">Priveous</button>`;
        }
        if (meta.page < totalPages) {
            paginationHtml += `<button class="btn btn-outline btn-sm" onclick="changePage(${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;
        loadPurchases();
    });

    // --- Actions ---
    window.changePage = function(p) {
        state.page = p;
        loadPurchases();
    };

    window.viewVoucher = function(id) {
        Utils.showPurchaseVoucher(id);
    };

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

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

    // Initial load
    loadPurchases();
}
