// Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
// For license information, please see license.txt
// timesheet_tool.js
let settings = {};
frappe.ui.form.on("Timesheet Tool", {
    refresh(frm) {
        // Amendment of the filter for the staff field to bring only active staff with Salary Structure Assignment
        frm.fields_dict['timesheet_tool_details'].grid.get_field('employee').get_query = function(doc, cdt, cdn) {
            return {
                query: "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.get_active_employees_with_salary"
            };
        };

        // Fetch settings and dynamically update mandatory fields
        frappe.call({
            method: "fetch_settings_and_update_mandatory",
            doc: frm.doc,
            callback: function(response) {
                if (response.message) {
                    settings = response.message;
                    frm.toggle_reqd("project", settings.is_project_mandatory);
                    frm.toggle_reqd("company", settings.is_company_mandatory);
                }
            }
        });

        // Management of the "Create Attendance" button
        if (frm.doc.docstatus === 1) {
            handle_button(
                frm,
                "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
                "Create Timesheet",
                "Timesheet records have been created successfully.",
                "All records have already been created."
            );

        }

        // Management "Approval Attendance"
        if (frm.doc.docstatus === 1) {
            handle_button(
                frm,
                "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
                "Approval Timesheet",
                "Timesheet records have been approved successfully.",
                "All records have already been approved."
            );
        }

    },

    // "Get Employmentee" button to get employees based on the project
    get_employee(frm) {
        if (settings.is_project_mandatory && !frm.doc.project) {
            frappe.msgprint(__('Please select a Project before fetching employees.'));
            return;
        }

        frappe.call({
            method: "get_all_employees",
            doc: frm.doc,
            args: { project: frm.doc.project || null },
            callback: function(response) {
                if (!response.exc) {
                    frm.refresh_field("timesheet_tool_details");
                    frappe.msgprint(__('Employees have been fetched successfully.'));
                }
            }
        });
    },

    // Update the fields when adjusting the Table "Timesheet Tool Details"
    timesheet_tool_details: {
        hour(frm, cdt, cdn) {
            let row = frappe.get_doc(cdt, cdn);
            row.total_working_hours = row.hour * row.ratio_attendance;
            frm.refresh_field("timesheet_tool_details");
        },

        over_time_h(frm, cdt, cdn) {
            frappe.call({
                method: "process_all", 
                doc: frm.doc,
                callback: function() {
                    frm.refresh_field("timesheet_tool_details");
                }
            });
        },

        over_time_n(frm, cdt, cdn) {
            frappe.call({
                method: "process_all", 
                doc: frm.doc,
                callback: function() {
                    frm.refresh_field("timesheet_tool_details");
                }
            });
        },

        deduction(frm, cdt, cdn) {
            frappe.call({
                method: "process_all", 
                doc: frm.doc,
                callback: function() {
                    frm.refresh_field("timesheet_tool_details");
                }
            });
        }
    }  
      
});

function handle_button(frm, method, btn_label, success_msg, fail_msg) {
    frappe.call({
        method: method,
        args: { timesheet_tool_name: frm.doc.name },
        callback: function(response) {
            if (response.message && response.message === "missing") {
                frm.add_custom_button(__(btn_label), function() {
                    if (frm.is_dirty()) {
                        frappe.throw(__("You have unsaved changes in this form. Please save before you continue."));
                    }
                    frappe.call({
                        method: btn_label.toLowerCase().replace(" ", "_"),
                        doc: frm.doc,
                        callback: function() {
                            frm.reload_doc();
                            frappe.msgprint(__(success_msg));
                        }
                    });
                });
            } else {
                frm.add_custom_button(__(btn_label), function() {
                    frappe.throw(__(fail_msg));
                }).prop("disabled", true);
            }
        }
    });
}