// 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"
            };
        };

        // إخفاء الـ div باستخدام jQuery
        frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.btn-open-row').on('click', function() {
            const targetDiv = $('span.row-actions');
            if (targetDiv.length) {
                targetDiv.hide();
            } 
        });
        frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.row-index').on('click', function() {
            const targetDiv = $('span.row-actions');
            if (targetDiv.length) {
                targetDiv.hide();
            } 
        });
        frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.btn-open-row').on('click', function() {
            const targetDiv = $('div.grid-footer-toolbar');
            if (targetDiv.length) {
                targetDiv.hide();
            } 
        });
        frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.row-index').on('click', function() {
            const targetDiv = $('div.grid-footer-toolbar');
            if (targetDiv.length) {
                targetDiv.hide();
            } 
        });

        // Hide the addition button .
        frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-add-row').hide();

        // hide the deletion button .
        frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-remove-rows').hide();      

        // hide the selection box in each row  .
        frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check').closest('.row-check').hide();        
        
        // Management of the "Create Attendance" button .
        if (frm.doc.docstatus === 1 && hasRole("Create Timesheet")) {
        let can_show_create_timesheet = handle_button(
            frm,
            "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
            "create_attendance",
            "Create Timesheet",
            "Timesheet records have been created successfully.",
            "All records have already been created."
        );

        // Hide "Approval Attendance" button if "Create Timesheet" button is visible
        if (can_show_create_timesheet) {
            frm.remove_custom_button("Submit Timesheet");
        }
    }

    // Management "Approval Attendance"
    if (frm.doc.docstatus === 1 && hasRole("Submit Timesheet")) {
        handle_button(
            frm,
            "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
            "approval_attendance",
            "Submit Timesheet",
            "Timesheet records have been approved successfully.",
            "All records have already been approved."
        );
    }
    frm.set_query('project', () => {
        let filters = {
            company : frm.doc.company,
            };
        return {filters: filters};
    })
    },

    // "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(__('All active personnel with Salary Structure Assignment were brought in.'));
                }
            }
        });
    },

    project(frm) {
        frappe.call({
            method: "clear_timesheet_tool_details_table",
            doc: frm.doc,
            callback: function(response) {
                frm.refresh_field("timesheet_tool_details"); 
            }
        });
    },

    // 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, def, btn_label, success_msg, fail_msg) {
    let button_visible = false;
    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: def,
                        doc: frm.doc,
                        callback: function() {
                            frm.reload_doc();
                            frappe.msgprint(__(success_msg));
                        }
                    });
                });
                button_visible = true;  // Mark button as visible
            } else {
                // frm.remove_custom_button("Approval Timesheet");
                // frm.add_custom_button(__(btn_label), function() {
                //     frappe.throw(__(fail_msg));
                // }).prop("disabled", true);
            }
        }
    });
    return button_visible;  // Return whether the button is visible
}

// Function to check if the user has a specific role
function hasRole(roleName) {
    return frappe.user.has_role(roleName);
}