// 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) {
        applyBlueColorHour()
        applyBlueColorToOverTime();
        applyBlueColorDeduction()

        update_absent_buttons(frm);
        let grid_wrapper = frm.fields_dict.timesheet_tool_details.grid.wrapper.get(0);
        let observer = new MutationObserver(function(mutations) {
            update_absent_buttons(frm);
        });
        observer.observe(grid_wrapper, { childList: true, subtree: true });
    
        attachHideEventHandlers(frm);
        hideGridButtons(frm);
        preventCtrlDownKey(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"
            };
        };
        frm.fields_dict['timesheet_tool_details_over_time'].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"
            };
        };
        frm.fields_dict['timesheet_tool_details_deduction'].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"
            };
        };

        if (frm.doc.docstatus === 1) {
            if (hasRole("Create Timesheet") && !frm.doc.timesheets_created) {
                handleCreateTimesheetButton(frm);
            }
            if (hasRole("Submit Timesheet") && frm.doc.timesheets_created && !frm.doc.timesheets__submited) {
                handleSubmitTimesheetButton(frm);
            }
        }

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

    // Presentation of confirmation message before data is collected
    frappe.confirm(
        __('Are you sure you want to fetch employees?'),
        function() {
            frappe.call({
                method: "get_all_employees",
                doc: frm.doc,
                args: {child_table: "timesheet_tool_details", project: frm.doc.project || null },
                callback: function(response) {
                    if (!response.exc) {
                        frm.refresh_field("timesheet_tool_details");
                        applyBlueColorHour()
                        attachHideEventHandlers(frm);
                        hideGridButtons(frm);
                    }
                }
            });
        },
        function() {
            frappe.msgprint(__('Employee fetching has been canceled.'));
        }
    );
    },
    get_employee_over_time(frm) {
        if (settings.is_project_mandatory && !frm.doc.project) {
            frappe.msgprint(__('Please select a Project before fetching employees.'));
            return;
        }

    // Presentation of confirmation message before data is collected
    frappe.confirm(
        __('Are you sure you want to fetch employees?'),
        function() {
            frappe.call({
                method: "get_all_employees",
                doc: frm.doc,
                args: {child_table:"timesheet_tool_details_over_time", project: frm.doc.project || null },
                callback: function(response) {
                    if (!response.exc) {
                        frm.refresh_field("timesheet_tool_details_over_time");
                        applyBlueColorToOverTime()
                    }
                }
            });
        },
        function() {
            frappe.msgprint(__('Employee fetching has been canceled.'));
        }
    );        
    },
    get_employee_deduction(frm) {
        if (settings.is_project_mandatory && !frm.doc.project) {
            frappe.msgprint(__('Please select a Project before fetching employees.'));
            return;
        }
    // Presentation of confirmation message before data is collected
    frappe.confirm(
        __('Are you sure you want to fetch employees?'),
        function() {
            frappe.call({
                method: "get_all_employees",
                doc: frm.doc,
                args: {child_table:"timesheet_tool_details_deduction", project: frm.doc.project || null },
                callback: function(response) {
                    if (!response.exc) {
                        frm.refresh_field("timesheet_tool_details_deduction");
                        applyBlueColorDeduction()
                    }
                }
            });
        },
        function() {
            frappe.msgprint(__('Employee fetching has been canceled.'));
        }
    );


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

// A function to handle the "Create Timesheet" button
function handleCreateTimesheetButton(frm) {
    handle_button(
        frm,
        "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records",
        "create_attendance",
        "Create Timesheets",
        "Timesheet records have been created successfully.",
        "All records have already been created."
    );
}

// A function to handle the "Submit Timesheet" button
function handleSubmitTimesheetButton(frm) {
    handle_button(
        frm,
        "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.check_missing_records_for_approval",
        "approval_attendance",
        "Submit Timesheets",
        "Timesheet records have been submitted successfully.",
        "All records have already been approved."
    );
}

// A function to handle buttons
function handle_button(frm, method, def, 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() {
                    frappe.confirm(
                        `Are you sure you want to ${btn_label.toLowerCase()}?`,
                        () => {
                            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));
                                }
                            });
                        },
                        () => {
                            frappe.msgprint(__("Action cancelled."));
                        }
                    );
                });
            }
        }
    });
}

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


// Hide specified DVD using jQuery
function hideTargetDiv(selector) {
    const targetDiv = $(selector);
    if (targetDiv.length) {
        targetDiv.hide();
    }
}

// Add processors to buttons
function attachHideEventHandlers(frm) {
    const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
    gridWrapper.find('.btn-open-row').on('click', function() {
        hideTargetDiv('span.row-actions');
        hideTargetDiv('div.grid-footer-toolbar');
    });

    gridWrapper.find('.row-index').on('click', function() {
        hideTargetDiv('span.row-actions');
        hideTargetDiv('div.grid-footer-toolbar');
    });
}

// A function to hide buttons in the table.
function hideGridButtons(frm) {
    const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
    gridWrapper.find('.grid-add-row').hide();
    gridWrapper.find('.grid-remove-rows').hide();
    gridWrapper.find('.grid-row-check').closest('.row-check').hide();
}

// A function for general treatment
function processAll(frm) {
    frappe.call({
        method: "process_all", 
        doc: frm.doc,
        callback: function() {
            frm.refresh_field("timesheet_tool_details");
            attachHideEventHandlers(frm);
            hideGridButtons(frm);
        }
    });
}

// A function to prevent "Ctrl + Down" in the table
function preventCtrlDownKey(frm) {
    // Listening to the keydown event in the table
    frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('keydown', function(event) {
        // Check if the user presses "Ctrl + Down"
        if (event.ctrlKey && event.key === "ArrowDown") {
            return false; // Preventing further treatment of the event
        }
    });
}
function update_absent_buttons(frm) {
    // Target each "Absent" button within the sub-table
    frm.fields_dict.timesheet_tool_details.grid.wrapper
        .find('[data-fieldname="absent"] button')
        .each(function() {
            let $btn = $(this);
            if (!$btn.hasClass('styled')) {
                $btn.addClass('btn btn-danger styled');
                $btn.html('<i class="fa fa-user-times"></i> Edit Activity Type');
            }
        });
}
frappe.ui.form.on('Timesheet Tool Details', {   
    refresh: function(frm, cdt, cdn) {
        setTimeout(function() {
            update_absent_buttons(frm);
        }, 300);
        frm.fields_dict["edit_activity_type"].$wrapper.find('.grid-body .rows').find(".grid-row").each(function (i, item) {


        
        });
        
    },
    edit_activity_type: function(frm, cdt, cdn) {
        let child = frappe.get_doc(cdt, cdn);
        let employeeName = child.employee_name
        frappe.call({
            method: "frappe.client.get_list",
            args: {
                doctype: "Activity Type",
                fields: ["name"]
            },
            callback: function(response) {
                if (response.message) {
                    let activity_types = response.message.map(item => item.name);
    
                    let dialog = new frappe.ui.Dialog({
                        title: "Select Activity Type",
                        fields: [
                            {
                                "fetch_from": "employee.employee_name",
                                "fieldname": "employee_name",
                                "fieldtype": "Read Only",
                                "label": "Member Name"
                            },
                            {
                                fieldname: "activity_container",
                                fieldtype: "HTML"
                            }
                        ],
                        size: "large"
                    });
                    // Set the value of the employee_name field
                    dialog.fields_dict.employee_name.set_value(employeeName);

                    let $container = $(dialog.fields_dict.activity_container.wrapper);
                    $container.css({
                        "display": "grid",
                        "grid-template-columns": "repeat(auto-fit, minmax(120px, 1fr))",
                        "gap": "15px",
                        "margin-top": "20px",
                        "padding": "20px",
                        "border-radius": "8px",
                        "background-color": "#f7f7f7",
                        "box-shadow": "0 2px 10px rgba(0, 0, 0, 0.1)"
                    });
    
                    activity_types.forEach(type => {
                        let $btn = $(`<button class="btn btn-primary">${type}</button>`);
                        
                        // Design of the button
                        $btn.css({
                            "padding": "15px",
                            "font-size": "14px",
                            "text-align": "center",
                            "border-radius": "5px",
                            "border": "none",
                            "transition": "background-color 0.3s, transform 0.2s",
                            "background-color": "#21bdad",
                            "color": "#fff",
                            "box-shadow": "0 4px 6px rgba(0, 0, 0, 0.1)"
                        });
    
                        // The button's on the pass.
                        $btn.on("mouseenter", function() {
                            $(this).css("background-color", "#20887d");
                            $(this).css("transform", "scale(1.05)");
                        });
                        $btn.on("mouseleave", function() {
                            $(this).css("background-color", "#21bdad");
                            $(this).css("transform", "scale(1)");
                        });
    
                        // When you press the button
                        $btn.on("click", function() {
                            frappe.model.set_value(cdt, cdn, 'attendance', type);
                            frappe.model.set_value(cdt, cdn, 'hour', 0);
                            dialog.hide();
                            frm.refresh_field('timesheet_tool_details');
                        });
    
                        $container.append($btn);
                    });
    
                    dialog.show();
                }
            }
        });
    }
});


// Apply "#dff0d8" background to 'Hour' and 'Edit Activity Type' column dynamically
function applyBlueColorHour() {
    const hourColumn = document.querySelectorAll('[data-fieldname="hour"] .static-area');
    hourColumn.forEach(cell => {
        cell.style.backgroundColor = "#dff0d8";
        cell.style.color = "black";
    });
    // const editActivityTypeColumn = document.querySelectorAll('[data-fieldname="edit_activity_type"] .static-area');
    // editActivityTypeColumn.forEach(cell => {
    //     cell.style.backgroundColor = "#dff0d8";
    //     cell.style.color = "black";
    // });

}
// Apply "#dff0d8" background to 'Over Time N' and 'Over Time H' column dynamically
function applyBlueColorToOverTime() {
    const overTimeNColumn = document.querySelectorAll('[data-fieldname="over_time_n"] .static-area');
    overTimeNColumn.forEach(cell => {
        cell.style.backgroundColor = "#dff0d8";
        cell.style.color = "black";
    });
    const overTimeHColumn = document.querySelectorAll('[data-fieldname="over_time_h"] .static-area');
    overTimeHColumn.forEach(cell => {
        cell.style.backgroundColor = "#dff0d8";
        cell.style.color = "black";
    });
}
// Apply "#dff0d8" background to 'Deduction' column dynamically

function applyBlueColorDeduction() {
    const deductionColumn = document.querySelectorAll('[data-fieldname="deduction"] .static-area');
    deductionColumn.forEach(cell => {
        cell.style.backgroundColor = "#c56565";
        cell.style.color = "black";
    });
}