// 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", {
    // onload: function(frm) {
    //         // إضافة حدث على جدول التفاصيل لإظهار Popup عند التحويم فوق الخلايا
    // frm.fields_dict['timesheet_tool_details_over_time'].grid.wrapper.on('mouseenter', '.grid-static-col', function(event) {
    //     let cell_content = $(this).text().trim(); // محتوى الخلية
    //     if (cell_content) {
    //         showPreviewPopup(event, cell_content);
    //     }
    // });

    // // إزالة الـ Popup عند مغادرة الخلية
    // frm.fields_dict['timesheet_tool_details_over_time'].grid.wrapper.on('mouseleave', '.grid-static-col', function() {
    //     $('.preview-popup').remove();
    // });
    // },
    refresh(frm) {

        // تأكد من أن الحدث يُطبق فقط بعد تحميل النموذج
        frm.fields_dict['timesheet_tool_details'].grid.wrapper.on('click', '.grid-static-col[data-fieldname="attendance"]', function(event) {
            let row = frm.fields_dict['timesheet_tool_details'].grid.get_row(this);
            openActivityTypeDialog(frm, row);
        });

        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;
        }
        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");
                    attachHideEventHandlers(frm);
                    hideGridButtons(frm);
                }
            }
        });
    },
    get_employee_over_time(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: {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");
                }
            }
        });
    },
    get_employee_deduction(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: {child_table:"timesheet_tool_details_deduction", project: frm.doc.project || null },
            callback: function(response) {
                if (!response.exc) {
                    frm.refresh_field("timesheet_tool_details_deduction");
                }
            }
        });
    },
    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) {
    // استهداف كل زر "Absent" داخل الجدول الفرعي
    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> Absent');
            }
        });
}
frappe.ui.form.on('Timesheet Tool Details', {   
    refresh: function(frm, cdt, cdn) {
        setTimeout(function() {
            update_absent_buttons(frm);
        }, 300);
    },
    absent: function(frm, cdt, cdn) {
        // عند الضغط على زر Absent، تعيين قيمة attendance إلى "Absent"
        frappe.model.set_value(cdt, cdn, 'attendance', 'Absent');
        frappe.msgprint(__('Attendance marked as Absent.'));
        // تأخير إعادة التطبيق للتنسيق بعد التغيير
        setTimeout(function() {
            update_absent_buttons(frm);
        }, 300);
    },
    // attendance: function(frm, cdt, cdn) {
    //     let row = frappe.get_doc(cdt, cdn);
    //     openActivityTypeDialog(frm, row);
    // }
});
// دالة لإظهار Popup عند التحويم
// function showPreviewPopup(event, content) {
//     // إزالة أي نوافذ منبثقة سابقة
//     $('.preview-popup').remove();
  
//     // إنشاء النافذة المنبثقة الجديدة
//     var $popup = $('<div class="preview-popup">' + content + '</div>').appendTo('body');
  
//     // تطبيق التنسيقات على النافذة المنبثقة
//     $popup.css({
//         position: 'absolute',
//         top: event.pageY + 10,
//         left: event.pageX + 10,
//         border: '1px solid #8ccf54',
//         background: '#f9fff6',
//         padding: '10px 15px',
//         'border-radius': '8px',
//         'box-shadow': '0 4px 8px rgba(0, 0, 0, 0.1)',
//         'font-family': 'Arial, sans-serif',
//         'font-size': '14px',
//         color: '#333',
//         'max-width': '300px',
//         'z-index': 1000,
//         'word-wrap': 'break-word'
//     });
  
//     // إظهار النافذة المنبثقة بتأثير تلاشي
//     $popup.hide().fadeIn(200);
  
//     // إزالة النافذة عند مغادرة الخلية
//     $(event.currentTarget).on('mouseleave', function() {
//         $popup.fadeOut(200, function() {
//             $(this).remove();
//         });
//     });
//   }
  function openActivityTypeDialog(frm, row) {
    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: [
                        {
                            fieldname: "activity_container",
                            fieldtype: "HTML"
                        }
                    ],
                    size: "large"
                });

                let $container = $(dialog.fields_dict.activity_container.wrapper);
                $container.css({
                    "display": "grid",
                    "grid-template-columns": "repeat(auto-fit, minmax(120px, 1fr))",
                    "gap": "10px",
                    "margin-top": "10px"
                });

                activity_types.forEach(type => {
                    let $btn = $(`<button class="btn btn-primary">${type}</button>`);
                    $btn.css({
                        "padding": "10px",
                        "font-size": "14px",
                        "text-align": "center",
                        "border-radius": "8px"
                    });
                    
                    $btn.on("click", function() {
                        // اريد ان يتم هنا تعبئة القل attendance المتواجد في الجدول الفرعي Timesheet Tool Details بقيمة type ومن ثم اغلاق الدايلوق

                    });

                    $container.append($btn);
                });

                dialog.show();
            }
        }
    });
}

// function openActivityTypeDialog(frm, row) {
//     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: [{
//                         fieldname: "activity_type",
//                         fieldtype: "Select",
//                         label: __("Activity Type"),
//                         options: activity_types.join("\n"),
//                         default: row.attendance // تعيين القيمة الحالية إن وجدت
//                     }],
//                     size: 'small',
//                     primary_action: function() {
//                         let selected_value = dialog.get_value('activity_type');
//                         if (selected_value) {
//                             frappe.model.set_value(cdt, row.name, 'attendance', selected_value);
//                             dialog.hide();
//                         }
//                     },
//                     primary_action_label: __("Select")
//                 });
                
//                 dialog.show();
//             }
//         }
//     });
// }