// Copyright (c) 2024, Ebkar Technology And Management Solutions. and contributors
// For license information, please see license.txt
// timesheet_tool.js
let settings = {};

const EMPLOYEE_QUERY = "time_sheet_tool.time_sheet_tool.utils.timesheet_tool.get_active_employees_with_salary"; // Constant for employee query
const COLOR_HOUR = "#dff0d8";
const COLOR_DEDUCTION = "#c96555";

frappe.ui.form.on("Timesheet Tool", {
    refresh(frm) {
        applyBlueColorHour(COLOR_HOUR); // Use constant
        applyBlueColorToOverTime(COLOR_HOUR); // Use constant
        applyBlueColorDeduction(COLOR_DEDUCTION); // Use constant
        attachHideEventHandlers(frm);
        hideGridButtons(frm);
        preventCtrlDownKey(frm);

        // Amendment of the filter for the staff field to bring only active staff with Salary Structure Assignment
        setEmployeeQuery(frm, 'timesheet_tool_details');
        setEmployeeQuery(frm, 'timesheet_tool_details_over_time');
        setEmployeeQuery(frm, 'timesheet_tool_details_deduction');

        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
            };
        });
         addEditActivityButton(frm);

    },

    // "Get Employmentee" button to get employees based on the project
    get_employee(frm) {
        getEmployeeData(frm, "timesheet_tool_details");
    },
    get_employee_over_time(frm) {
        getEmployeeData(frm, "timesheet_tool_details_over_time");
    },
    get_employee_deduction(frm) {
        getEmployeeData(frm, "timesheet_tool_details_deduction");
    },
    project(frm) {
        frappe.call({
            method: "clear_timesheet_tool_details_table",
            doc: frm.doc,
            callback: function(response) {
                if (response.exc) {
                    frappe.msgprint(__("Error clearing details table: {0}", [response.exc]));
                    return;
                }
                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);
            }
        });
    },
});

function setEmployeeQuery(frm, grid_field) {
    frm.fields_dict[grid_field].grid.get_field('employee').get_query = function(doc, cdt, cdn) {
        return {
            query: EMPLOYEE_QUERY
        };
    };
}

function getEmployeeData(frm, child_table) {
    if (settings.is_project_mandatory && !frm.doc.project) {
        frappe.msgprint(__('Please select a Project before fetching employees.'));
        return;
    }

    frappe.confirm(
        __('Are you sure you want to fetch employees?'),
        function() {
            frappe.call({
                method: "get_all_employees",
                doc: frm.doc,
                args: {
                    child_table: child_table,
                    project: frm.doc.project || null
                },
                callback: function(response) {
                    if (response.exc) {
                        frappe.msgprint(__("Error fetching employees: {0}", [response.exc]));
                        return;
                    }

                    frm.refresh_field(child_table);
                    switch (child_table) {
                        case "timesheet_tool_details":
                            applyBlueColorHour(COLOR_HOUR); // Use constant
                            attachHideEventHandlers(frm);
                            hideGridButtons(frm);
                            break;
                        case "timesheet_tool_details_over_time":
                            applyBlueColorToOverTime(COLOR_HOUR); // Use constant
                            break;
                        case "timesheet_tool_details_deduction":
                            applyBlueColorDeduction(COLOR_DEDUCTION); // Use constant
                            break;
                    }
                },
                error: function(err) {
                    frappe.msgprint(__("An unexpected error occurred. Please check the console."));
                    console.error(err);
                }
            });
        },
        function() {
            frappe.msgprint(__('Employee fetching has been canceled.'));
        }
    );
}

function addEditActivityButton(frm) {
    const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
    const btnSelector = '.grid-buttons .grid-edit-activity';  // Define the selector

    // Check if the button already exists in the right context
    if (gridWrapper.find(btnSelector).length > 0) {
        return;
    }

    let edit_button = `<button type="button" class="btn btn-xs btn-success grid-edit-activity" style="display: none;"><svg class="icon icon-sm" style="margin-right: 5px; color : white;"><use href="#icon-edit"></use></svg>Edit Activity Type</button>`;
    gridWrapper.find('.grid-buttons').append(edit_button);

    function toggle_edit_button_visibility() {
        let selected_rows = frm.fields_dict['timesheet_tool_details'].grid.get_selected();
        if (selected_rows.length > 0) {
            gridWrapper.find(btnSelector).show();
        } else {
            gridWrapper.find(btnSelector).hide();
        }
    }

    toggle_edit_button_visibility();

    gridWrapper.on('click', '.grid-row-check', function() {
        toggle_edit_button_visibility();
    });

    gridWrapper.on('click', btnSelector, function() {
        editActivityTypeForSelected(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.exc) {
                frappe.msgprint(__("Error during {0}: {1}", [btn_label, response.exc]));
                return;
            }

            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(response) {
                                     if (response.exc) {
                                        frappe.msgprint(__("Error during {0}: {1}", [btn_label, response.exc]));
                                        return;
                                    }
                                    frm.reload_doc();
                                    frappe.msgprint(__(success_msg));
                                }
                            });
                        },
                        () => {
                            frappe.msgprint(__("Action cancelled."));
                        }
                    );
                });
            }
        },
        error: function(err) {
            frappe.msgprint(__("An unexpected error occurred. Please check the console."));
            console.error(err);
        }
    });
}

// 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
    const gridWrapper = frm.fields_dict['timesheet_tool_details'].grid.wrapper;
    gridWrapper.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
        }
    });
}

// A function to modify the activity type of the selected rows
function editActivityTypeForSelected(frm) {
    let selectedRows = [];
    // استخدام خانة الاختيار الموجودة (row-check) لتحديد الصفوف
    frm.fields_dict['timesheet_tool_details'].grid.wrapper.find('.grid-row-check:checked').each(function() {
        let row = $(this).closest('.grid-row'); // الحصول على الصف الأب
        let rowName = row.data('name'); // استخراج اسم الصف من البيانات
        selectedRows.push(rowName);
    });

    if (selectedRows.length === 0) {
        frappe.msgprint(__('Please select at least one row.'));
        return;
    }

    // تجميع أسماء الموظفين
    let employeeNames = selectedRows.map(rowName => {
        let child = frappe.get_doc('Timesheet Tool Details', rowName);
        return child ? child.employee_name : null;
    }).filter(name => name !== null);

    // استدعاء دالة editActivityType مع قائمة الصفوف وأسماء الموظفين
    editActivityType(selectedRows, employeeNames, () => {
        frm.refresh_field('timesheet_tool_details');
        attachHideEventHandlers(frm);
        hideGridButtons(frm);
    });
}

// Function to create an activity type selection dialog
// Function to create an activity type selection dialog
function editActivityType(rowNames, employeeNames, callback) {
    // Get the user's desk theme
    frappe.db.get_single_value('User', frappe.session.user, 'desk_theme')
        .then(desk_theme => {
            // Apply CSS based on desk theme
            let dialog_style = '';
            let card_background_color = ''; // Variable for the card's background color

            if (desk_theme === 'Dark') {
                dialog_style = `
                    .frappe-ui-dialog {
                        background-color: #333;
                        color: #fff;
                    }
                    .frappe-ui-dialog .btn-primary {
                        background-color: #555;
                        color: #fff;
                        border: 1px solid #777;
                    }
                    .frappe-ui-dialog .btn-primary:hover {
                        background-color: #777;
                    }
                `;
                card_background_color = '#444'; // Darker background for dark theme
            } else {
                // Light theme (default) or any other theme handling can be added here
                dialog_style = `
                  .frappe-ui-dialog {
                        background-color: #fff;
                        color: #000;
                    }
                     .frappe-ui-dialog .btn-primary {
                        background-color: #21bdad;
                        color: #fff;
                        border: 1px solid #21bdad;
                    }
                     .frappe-ui-dialog .btn-primary:hover {
                        background-color: #21bdad;
                    }
                `;
                card_background_color = '#fff'; // White background for light theme
            }

            // Create a style element for the dialog
            let style_element = document.createElement('style');
            style_element.innerHTML = dialog_style;
            document.head.appendChild(style_element);


            frappe.call({
                method: "frappe.client.get_list",
                args: {
                    doctype: "Activity Type",
                    fields: ["name"]
                },
                callback: function(response) {
                    if (response.exc) {
                        frappe.msgprint(__("Error fetching activity types: {0}", [response.exc]));
                        return;
                    }

                    if (response.message) {
                        let activity_types = response.message.map(item => item.name);

                        let dialog = new frappe.ui.Dialog({
                            title: "Select Activity Type",
                            fields: [{
                                    "fieldname": "employee_names",
                                    "fieldtype": "Small Text",
                                    "label": "Member Names",
                                    "read_only": 1,
                                    "bold": 1,
                                },
                                {
                                    fieldname: "activity_container",
                                    "fieldtype": "HTML"
                                }
                            ],
                            size: "large",
                            onhide: () => {
                                // Remove style element when dialog is closed
                                document.head.removeChild(style_element);
                            }
                        });

                        // عرض قائمة بأسماء الموظفين في الحقل Read Only
                        dialog.fields_dict.employee_names.set_value(employeeNames.join(', '));

                        let $container = $(dialog.fields_dict.activity_container.wrapper);
                         // Apply the background color dynamically to the card
                        $container.html(`<div class="card" style="padding: 20px; border-radius: 8px; background-color: ${card_background_color};"></div>`);


                        let $card = $container.find('.card');

                        $card.css({
                            "display": "grid",
                            "grid-template-columns": "repeat(auto-fit, minmax(120px, 1fr))",
                            "gap": "15px",
                            "margin-top": "20px",
                        });

                        activity_types.forEach(type => {
                            let $btn = $(`<button class="btn btn-primary">${type}</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)"
                            });

                            // حدث الزر
                            $btn.on("click", function() {
                                // تحديث Attendance لجميع الصفوف المحددة
                                rowNames.forEach(rowName => {
                                    let child = frappe.get_doc('Timesheet Tool Details', rowName);
                                    if (child) {
                                        frappe.model.set_value(child.doctype, child.name, 'attendance', type);
                                        frappe.model.set_value(child.doctype, child.name, 'hour', 0);
                                    }
                                });

                                dialog.hide();
                                // استدعاء دالة callback بعد إغلاق مربع الحوار
                                if (callback) {
                                    callback();
                                }
                            });

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

                        dialog.show();
                    }
                },
                error: function(err) {
                    frappe.msgprint(__("An unexpected error occurred. Please check the console."));
                    console.error(err);
                }
            });

        });
}

// Apply "#dff0d8" background to 'Hour' and 'Edit Activity Type' column dynamically
function applyBlueColorHour(color) {
    const hourHeader = document.querySelector('[data-fieldname="hour"] .static-area');

    if (hourHeader) {
        hourHeader.style.backgroundColor = color;
        hourHeader.style.color = "black"; // Ensure text is readable
    }
}
// Apply "#dff0d8" background to 'Over Time N' and 'Over Time H' column dynamically
function applyBlueColorToOverTime(color) {
    const overTimeNColumn = document.querySelector('[data-fieldname="over_time_n"] .static-area');
    if (overTimeNColumn) {
        overTimeNColumn.style.backgroundColor = color;
        overTimeNColumn.style.color = "black"; // Ensure text is readable
    }
    const overTimeHColumn = document.querySelector('[data-fieldname="over_time_h"] .static-area');
    if (overTimeHColumn) {
        overTimeHColumn.style.backgroundColor = color;
        overTimeHColumn.style.color = "black"; // Ensure text is readable
    }
}
// Apply "#c56565" background to 'Deduction' column dynamically

function applyBlueColorDeduction(color) {
    const deductionColumn = document.querySelector('[data-fieldname="deduction"] .static-area');
    if (deductionColumn) {
        deductionColumn.style.backgroundColor = color;
        deductionColumn.style.color = "black"; // Ensure text is readable
    }
}