function fillFromCompanyDefaults(frm) {
    const company = frappe.defaults.get_user_default('Company')
        || frappe.defaults.get_default('Company');
    if (!company) return;

    frappe.call({
        method: 'taxes_az.taxes_az.doctype.single_declaration_related_to_salaried_and_non_salaried_work.single_declaration_related_to_salaried_and_non_salaried_work.get_company_defaults',
        args: { company: company },
        callback: function(r) {
            if (!r || !r.message) return;
            const v = r.message;
            if (v.mdssüzrə) frm.set_value('mdssüzrə', v.mdssüzrə);
            if (v.icbaritibbisığortaüzrə) frm.set_value('icbaritibbisığortaüzrə', v.icbaritibbisığortaüzrə);
            if (v.işsizlikdənsığortaüzrə) frm.set_value('işsizlikdənsığortaüzrə', v.işsizlikdənsığortaüzrə);
            if (v.main_activity) frm.set_value('vergiüzrə', v.main_activity);
        }
    });
}

frappe.ui.form.on('Single declaration related to salaried and non-salaried work', {
    onload: function(frm) {
        if (!frm.doc.__islocal) return;
        fillFromCompanyDefaults(frm);
    },

    il: function(frm) {
        fillFromCompanyDefaults(frm);
        reload_hisse_1_data(frm);
    },

    rüb: function(frm) {
        reload_hisse_1_data(frm);
    },

    refresh: function(frm) {
        frm.add_custom_button(__('Export XML'), function() {
            frappe.call({
                method: 'taxes_az.taxes_az.doctype.xml_mapping_tool.xml_mapping_tool.generate_xml',
                args: {
                    mapping_tool: 'Single declaration related to salaried and non-salaried work',
                    doctype: 'Single declaration related to salaried and non-salaried work',
                    docname: frm.docname
                },
                callback: function(r) {
                    if (r.message) {
                        var element = document.createElement('a');
                        element.setAttribute('href', 'data:text/xml;charset=utf-8,' + encodeURIComponent(r.message));
                        element.setAttribute('download', frm.docname + '.xml');
                        element.style.display = 'none';
                        document.body.appendChild(element);
                        element.click();
                        document.body.removeChild(element);

                        frappe.show_alert({
                            message: __('XML file generated and downloaded'),
                            indicator: 'green'
                        });
                    }
                }
            });
        }, __('Actions'));
    }
});

function reload_hisse_1_data(frm) {
    if (!frm.doc.il || !frm.doc.rüb) {
        return;
    }

    const company = frappe.defaults.get_user_default('Company')
        || frappe.defaults.get_default('Company');
    if (!company) {
        frappe.msgprint(__('Company not found in user defaults'));
        return;
    }

    frappe.dom.freeze(__('Loading payroll data...'));

    frappe.call({
        method: 'taxes_az.taxes_az.doctype.single_declaration_related_to_salaried_and_non_salaried_work.single_declaration_related_to_salaried_and_non_salaried_work.populate_declaration_tables',
        args: {
            company: company,
            year: frm.doc.il,
            quarter: frm.doc.rüb
        },
        callback: function(r) {
            frappe.dom.unfreeze();

            if (r.message && r.message.success) {
                populate_hisse_1(frm, r.message.hisse_1_data || []);
                populate_child_table(frm, 'hissə_2', r.message.hisse_2_data || []);
                populate_child_table(frm, 'hissə_3', r.message.hisse_3_data || []);
                update_existing_rows(frm, 'bolme2_hisse1', r.message.bolme2_hisse1_data || {});
                update_existing_rows(frm, 'bölmə_3', r.message.bolme_3_data || {});
                populate_child_table(frm, 'vergi_', r.message.vergi_data || []);
                populate_child_table(frm, 'mdss_', r.message.mdss_data || []);
                populate_child_table(frm, 'issizlik', r.message.issizlik_data || []);
                populate_child_table(frm, 'its', r.message.its_data || []);
                frm.dirty();
                frm.refresh_fields();

                frappe.show_alert({
                    message: __('Payroll data loaded successfully'),
                    indicator: 'green'
                });
            } else {
                frappe.msgprint({
                    title: __('Error'),
                    message: r.message ? r.message.error : __('Failed to load data'),
                    indicator: 'red'
                });
            }
        },
        error: function() {
            frappe.dom.unfreeze();
            frappe.msgprint({
                title: __('Error'),
                message: __('Server error while loading payroll data'),
                indicator: 'red'
            });
        }
    });
}

function populate_hisse_1(frm, data) {
    populate_child_table(frm, 'hissə_1', data);
}

function update_existing_rows(frm, table_name, data) {
    // Update existing rows by matching göstəricilər field
    (frm.doc[table_name] || []).forEach(function(row) {
        let key = row.göstəricilər;
        if (key && data[key]) {
            let values = data[key];
            Object.keys(values).forEach(function(field) {
                frappe.model.set_value(row.doctype, row.name, field, values[field]);
            });
        }
    });
    frm.refresh_field(table_name);
}

function populate_child_table(frm, table_name, data) {
    frm.clear_table(table_name);

    data.forEach(function(row_data) {
        let row = frm.add_child(table_name);
        Object.keys(row_data).forEach(function(field) {
            if (row_data[field] !== null && row_data[field] !== undefined) {
                row[field] = row_data[field];
            }
        });
    });

    frm.refresh_field(table_name);
}
