frappe.ui.form.on("Sales Invoice", {
    onload: function(frm) {
        console.log("Sales Invoice loaded...");
        if (frm.doc.rent) {
            fetch_items(frm, frm.doc.rent);
        } else {
            console.log("No rent found:", frm.doc.rent);
        }
    }
});

let fetch_items = (frm, rent_name) => {
    if (frm.doc.__islocal && frm.doc.selling_price_list == "Daily") {
        console.log("Fetching items for rent:", rent_name);
        frm.doc.items = [];

        frappe.call({
            method: 'frappe.client.get_list',
            args: {
                'doctype': 'Rent Detail',
                'filters': { 'parent': rent_name, "returned": 0 },
                'fields': [
                    'name', "item_name", "item_code", "rate",
                    'income_account', "uom", "qty", "return_qty"
                ]
            },
            callback: (r) => {
                console.log("Rent Details fetched:", r.message);
                if (r.message) {
                    get_item_code(frm, rent_name);

                    r.message.forEach((value) => {
                        let remaining_qty = value.qty - value.return_qty;
                        if (remaining_qty > 0) {
                            console.log("Adding item:", value.item_code, "Qty:", remaining_qty);
                            let item = frm.add_child("items");
                            item.item_code = value.item_code;
                            item.item_name = value.item_name;
                            item.description = value.item_name;
                            item.income_account = 'خدمة - EA';
                            item.rate = value.rate;
                            item.uom = value.uom;
                            item.rent_detail = value.name;
                            item.rent_qty = remaining_qty;
                        }
                    });

                    frm.refresh_field('items');
                }
            },
            freeze: true,
            freeze_message: __("Filling items Table ......")
        });
    }
};

let get_item_code = (frm, rent) => {
    if (frm.doc.__islocal && frm.doc.selling_price_list == "Daily") {
        console.log("Fetching Rent date for:", rent);

        frappe.call({
            method: 'frappe.client.get_list',
            args: {
                'doctype': 'Rent',
                'filters': { 'name': rent },
                'fields': ["name", "date"]
            },
            callback: (r) => {
                console.log("Rent data:", r.message);
                if (r.message) {
                    let date_1 = new Date(frm.doc.posting_date);
                    let date_2 = new Date(r.message[0].date);

                    let days = Math.max(1, Math.ceil((date_1 - date_2) / (1000 * 3600 * 24)));
                    console.log("Days calculated:", days);

                    frm.doc.items.forEach((item, idx) => {
                        let row = cur_frm.get_field("items").grid.grid_rows[idx].doc;
                        row.days = days;
                        row.qty = days * row.rent_qty;
                    });

                    frm.refresh_field("items");
                }
            }
        });
    }
};

frappe.ui.form.on('Sales Invoice', "validate", function(frm) {
    console.log("Validating Sales Invoice...");
    frm.doc.items.forEach(d => {
        if (frm.doc.rent && frm.doc.selling_price_list == "Daily") {
            d.qty = d.rent_qty * d.days;
            console.log("Final qty for", d.item_code, ":", d.qty);
        }
    });
});