frappe.ui.form.on('Frequency Plan', {
    // حدث عند تغيير السنة المالية
    fiscal_year: function(frm) {
        if (frm.doc.fiscal_year) {
            // استدعاء دالة السيرفر للحصول على خطة التغطية
            frappe.call({
                method: "frappe.client.get_list",
                args: {
                    doctype: "Coverage Strategy",
                    filters: { fiscal_year: frm.doc.fiscal_year },
                    fields: ["name"]
                },
                callback: function(r) {
                    if (r.message && r.message.length > 0) {
                        frm.set_value("coverage_strategy", r.message[0].name);
                    } else {
                        frm.set_value("coverage_strategy", null);
                    }
                }
            });
        } else {
            frm.set_value("coverage_strategy", null);
        }
    },

    // حدث عند الضغط على زر "Get Customer"
    get_customer: function(frm) {
        // التحقق من الحقول المطلوبة
        if (!frm.doc.employee || !frm.doc.coverage_strategy || !frm.doc.holiday_list || !frm.doc.fiscal_year) {
            frappe.msgprint(__('Please fill in all required fields: Employee, Coverage Strategy, Holiday List, and Fiscal Year.'));
            return;  // عدم فتح الـ Dialog إذا كانت الحقول غير مكتملة
        }

        // إنشاء مربع الحوار
        let dialog = new frappe.ui.Dialog({
            title: __('Get Customer Details'),
            size: 'extra-large',
            fields: [

                {
                    fieldname: 'employee',
                    fieldtype: 'Link',
                    label: __('Employee'),
                    options: 'Employee',
                    reqd: 0,
                    default: frm.doc.employee,
                    read_only: 1
                },
                {
                    fieldtype: 'Link',
                    label: __('Territory'),
                    fieldname: 'territory',
                    options: 'Territory',
                    reqd: 1
                },
                {
                    fieldname: "business_type",
                    label: __("Business Type"),
                    fieldtype: "Select",
                    options: "Business Type",
                    options: ['', 'Pharmacies', 'Clinics'],
                    reqd: 0
                },
                {
                    fieldtype: 'Column Break',
                    fieldname: 'col0'
                },
                {
                    fieldname: 'full_name',
                    fieldtype: 'Data',
                    label: __('Full Name'),
                    reqd: 0,
                    default: frm.doc.full_name,
                    read_only: 1
                },
                {
                    fieldtype: 'Link',
                    label: __('Class'),
                    fieldname: '_class',
                    options: 'Class',
                    reqd: 1
                },
                {
                    fieldtype: 'Select',
                    label: __('Days of Week'),
                    fieldname: 'days_of_week',
                    options: [
                        { "value": "Sunday", "label": "Sunday" },
                        { "value": "Monday", "label": "Monday" },
                        { "value": "Tuesday", "label": "Tuesday" },
                        { "value": "Wednesday", "label": "Wednesday" },
                        { "value": "Thursday", "label": "Thursday" },
                        { "value": "Friday", "label": "Friday" },
                        { "value": "Saturday", "label": "Saturday" }
                    ],
                    reqd: 1
                },
                {
                    "fieldname": "section_break_l3nnz",
                    "fieldtype": "Section Break"
                },
                {
                    fieldtype: 'Table',
                    label: __('Customers'),
                    fieldname: 'customers_table',
                    fields: [
                        {
                            fieldtype: 'Check',
                            label: __('Select'),
                            fieldname: 'select',
                            in_list_view: 1
                        },
                        {
                            fieldtype: 'Link',
                            label: __('Customer'),
                            fieldname: 'customer',
                            options: 'Customer',
                            in_list_view: 1
                        },
                        {
                            fieldtype: 'Link',
                            label: __('Territory'),
                            fieldname: 'territory',
                            options: 'Territory',
                            in_list_view: 1
                        },
                        {
                            fieldtype: 'Link',
                            label: __('Class'),
                            fieldname: '_class',
                            options: 'Class',
                            in_list_view: 1
                        },
                        {
                            fieldname: "business_type",
                            label: __("Business Type"),
                            fieldtype: "Select",
                            options: "Business Type",
                            options: ['', 'Pharmacies', 'Clinics'],
                            in_list_view: 1
                        }
                    ]
                },
            ]
        });

        // إضافة الأزرار بتصميم جميل
        dialog.$body.append(`
            <div class="dialog-button-container">
                <button class="btn btn-primary fetch-customers-btn">Fetch Customers</button>
                <button class="btn btn-secondary add-frequency-plan-btn">Add Customers to Frequency Plan</button>
            </div>
        `);

        // تخصيص على CSS
        dialog.$body.find(".dialog-button-container").css({
            "display": "flex",
            "justify-content": "flex-end",
            "gap": "15px",
            "margin-top": "20px",
            "margin-bottom": "20px"
        });

        // تخصيص الأزرار
        dialog.$body.find(".fetch-customers-btn").css({
            "background-color": "#007bff",
            "color": "#ffffff",
            "border": "none",
            "border-radius": "5px",
            "padding": "10px 20px",
            "cursor": "pointer",
            "transition": "background-color 0.3s"
        }).hover(function() {
            $(this).css("background-color", "#0056b3");
        }, function() {
            $(this).css("background-color", "#007bff");
        });

        dialog.$body.find(".add-frequency-plan-btn").css({
            "background-color": "#6c757d",
            "color": "#ffffff",
            "border": "none",
            "border-radius": "5px",
            "padding": "10px 20px",
            "cursor": "pointer",
            "transition": "background-color 0.3s"
        }).hover(function() {
            $(this).css("background-color", "#5a6268");
        }, function() {
            $(this).css("background-color", "#6c757d");
        });

        // التحكم في تحديد كل العملاء
        dialog.$body.on('change', 'input[name="select_all"]', function() {
            let isChecked = $(this).is(':checked');
            dialog.fields_dict.customers_table.df.data.forEach(row => {
                row.select = isChecked ? 1 : 0; // تعيين القيمة للتحديد أو الإلغاء
            });
            dialog.fields_dict.customers_table.grid.refresh(); // تحديث الجدول
        });

        // إضافة المنطق لجلب العملاء
        dialog.$body.on('click', '.fetch-customers-btn', function() {
            let values = dialog.get_values();
            if (values.territory && values._class) {
                frappe.call({
                    method: "get_customer_details", 
                    doc: frm.doc,
                    args: {
                        territory: values.territory,
                        _class: values._class,
                        business_type: values.business_type
                    },
                    callback: function(r) {
                        if (r.message && r.message.length > 0) {
                            dialog.fields_dict.customers_table.df.data = [];
                            r.message.forEach(customer => {
                                dialog.fields_dict.customers_table.df.data.push({
                                    select: 0,
                                    customer: customer.name,
                                    territory: customer.territory,
                                    _class: customer._class,
                                    business_type : customer.business_type

                                });
                            });
                            dialog.fields_dict.customers_table.grid.refresh();
                        } else {
                            frappe.msgprint(__("No customers found for the selected territory and class."));
                        }
                    }
                });
            } else {
                frappe.msgprint(__("Please select Territory and Class."));
            }
        });

        // إضافة المنطق لإضافة العملاء إلى خطة التردد
        dialog.$body.on('click', '.add-frequency-plan-btn', function() {
            let values = dialog.get_values();
            if (values.territory && values._class && values.days_of_week) {
                frappe.call({
                    method: "add_customers_to_frequency_plan",  
                    doc: frm.doc,
                    args: {
                        fiscal_year: frm.doc.fiscal_year,
                        selected_days: values.days_of_week,
                        selected_customers: dialog.fields_dict.customers_table.df.data
                            .filter(row => row.select) 
                            .map(row => row.customer) 
                    },
                    callback: function(r) {
                        if (r.message && r.message.status === "success") {
                            frappe.msgprint(r.message.message);
                            frm.refresh_field('frequency_plan_table'); // تحديث الجدول
                            dialog.hide();
                        } else {
                            frappe.msgprint(__('Error occurred while adding customers.'));
                        }
                    }
                });
            } else {
                frappe.msgprint(__('Please select Territory, Class and Days of Week.'));
            }
        });

        // إظهار مربع الحوار
        dialog.show();
    }       
});frappe.ui.form.on('Frequency Plan', {
    // حدث عند تغيير السنة المالية
    fiscal_year: function(frm) {
        if (frm.doc.fiscal_year) {
            // استدعاء دالة السيرفر للحصول على خطة التغطية
            frappe.call({
                method: "frappe.client.get_list",
                args: {
                    doctype: "Coverage Strategy",
                    filters: { fiscal_year: frm.doc.fiscal_year },
                    fields: ["name"]
                },
                callback: function(r) {
                    if (r.message && r.message.length > 0) {
                        frm.set_value("coverage_strategy", r.message[0].name);
                    } else {
                        frm.set_value("coverage_strategy", null);
                    }
                }
            });
        } else {
            frm.set_value("coverage_strategy", null);
        }
    },

    // حدث عند الضغط على زر "Get Customer"
    get_customer: function(frm) {
        // التحقق من الحقول المطلوبة
        if (!frm.doc.employee || !frm.doc.coverage_strategy || !frm.doc.holiday_list || !frm.doc.fiscal_year) {
            frappe.msgprint(__('Please fill in all required fields: Employee, Coverage Strategy, Holiday List, and Fiscal Year.'));
            return;  // عدم فتح الـ Dialog إذا كانت الحقول غير مكتملة
        }

        // إنشاء مربع الحوار
        let dialog = new frappe.ui.Dialog({
            title: __('Get Customer Details'),
            size: 'extra-large',
            fields: [

                {
                    fieldname: 'employee',
                    fieldtype: 'Link',
                    label: __('Employee'),
                    options: 'Employee',
                    reqd: 0,
                    default: frm.doc.employee,
                    read_only: 1
                },
                {
                    fieldtype: 'Link',
                    label: __('Territory'),
                    fieldname: 'territory',
                    options: 'Territory',
                    reqd: 1
                },
                {
                    fieldname: "business_type",
                    label: __("Business Type"),
                    fieldtype: "Select",
                    options: "Business Type",
                    options: ['', 'Pharmacies', 'Clinics'],
                    reqd: 0
                },
                {
                    fieldtype: 'Column Break',
                    fieldname: 'col0'
                },
                {
                    fieldname: 'full_name',
                    fieldtype: 'Data',
                    label: __('Full Name'),
                    reqd: 0,
                    default: frm.doc.full_name,
                    read_only: 1
                },
                {
                    fieldtype: 'Link',
                    label: __('Class'),
                    fieldname: '_class',
                    options: 'Class',
                    reqd: 1
                },
                {
                    fieldtype: 'Select',
                    label: __('Days of Week'),
                    fieldname: 'days_of_week',
                    options: [
                        { "value": "Sunday", "label": "Sunday" },
                        { "value": "Monday", "label": "Monday" },
                        { "value": "Tuesday", "label": "Tuesday" },
                        { "value": "Wednesday", "label": "Wednesday" },
                        { "value": "Thursday", "label": "Thursday" },
                        { "value": "Friday", "label": "Friday" },
                        { "value": "Saturday", "label": "Saturday" }
                    ],
                    reqd: 1
                },
                {
                    "fieldname": "section_break_l3nnz",
                    "fieldtype": "Section Break"
                },
                {
                    fieldtype: 'Table',
                    label: __('Customers'),
                    fieldname: 'customers_table',
                    fields: [
                        {
                            fieldtype: 'Check',
                            label: __('Select'),
                            fieldname: 'select',
                            in_list_view: 1
                        },
                        {
                            fieldtype: 'Link',
                            label: __('Customer'),
                            fieldname: 'customer',
                            options: 'Customer',
                            in_list_view: 1
                        },
                        {
                            fieldtype: 'Link',
                            label: __('Territory'),
                            fieldname: 'territory',
                            options: 'Territory',
                            in_list_view: 1
                        },
                        {
                            fieldtype: 'Link',
                            label: __('Class'),
                            fieldname: '_class',
                            options: 'Class',
                            in_list_view: 1
                        },
                        {
                            fieldname: "business_type",
                            label: __("Business Type"),
                            fieldtype: "Select",
                            options: "Business Type",
                            options: ['', 'Pharmacies', 'Clinics'],
                            in_list_view: 1
                        }
                    ]
                },
            ]
        });

        // إضافة الأزرار بتصميم جميل
        dialog.$body.append(`
            <div class="dialog-button-container">
                <button class="btn btn-primary fetch-customers-btn">Fetch Customers</button>
                <button class="btn btn-secondary add-frequency-plan-btn">Add Customers to Frequency Plan</button>
            </div>
        `);

        // تخصيص على CSS
        dialog.$body.find(".dialog-button-container").css({
            "display": "flex",
            "justify-content": "flex-end",
            "gap": "15px",
            "margin-top": "20px",
            "margin-bottom": "20px"
        });

        // تخصيص الأزرار
        dialog.$body.find(".fetch-customers-btn").css({
            "background-color": "#007bff",
            "color": "#ffffff",
            "border": "none",
            "border-radius": "5px",
            "padding": "10px 20px",
            "cursor": "pointer",
            "transition": "background-color 0.3s"
        }).hover(function() {
            $(this).css("background-color", "#0056b3");
        }, function() {
            $(this).css("background-color", "#007bff");
        });

        dialog.$body.find(".add-frequency-plan-btn").css({
            "background-color": "#6c757d",
            "color": "#ffffff",
            "border": "none",
            "border-radius": "5px",
            "padding": "10px 20px",
            "cursor": "pointer",
            "transition": "background-color 0.3s"
        }).hover(function() {
            $(this).css("background-color", "#5a6268");
        }, function() {
            $(this).css("background-color", "#6c757d");
        });

        // التحكم في تحديد كل العملاء
        dialog.$body.on('change', 'input[name="select_all"]', function() {
            let isChecked = $(this).is(':checked');
            dialog.fields_dict.customers_table.df.data.forEach(row => {
                row.select = isChecked ? 1 : 0; // تعيين القيمة للتحديد أو الإلغاء
            });
            dialog.fields_dict.customers_table.grid.refresh(); // تحديث الجدول
        });

        // إضافة المنطق لجلب العملاء
        dialog.$body.on('click', '.fetch-customers-btn', function() {
            let values = dialog.get_values();
            if (values.territory && values._class) {
                frappe.call({
                    method: "get_customer_details", 
                    doc: frm.doc,
                    args: {
                        territory: values.territory,
                        _class: values._class,
                        business_type: values.business_type
                    },
                    callback: function(r) {
                        if (r.message && r.message.length > 0) {
                            dialog.fields_dict.customers_table.df.data = [];
                            r.message.forEach(customer => {
                                dialog.fields_dict.customers_table.df.data.push({
                                    select: 0,
                                    customer: customer.name,
                                    territory: customer.territory,
                                    _class: customer._class,
                                    business_type : customer.business_type

                                });
                            });
                            dialog.fields_dict.customers_table.grid.refresh();
                        } else {
                            frappe.msgprint(__("No customers found for the selected territory and class."));
                        }
                    }
                });
            } else {
                frappe.msgprint(__("Please select Territory and Class."));
            }
        });

        // إضافة المنطق لإضافة العملاء إلى خطة التردد
        dialog.$body.on('click', '.add-frequency-plan-btn', function() {
            let values = dialog.get_values();
            if (values.territory && values._class && values.days_of_week) {
                frappe.call({
                    method: "add_customers_to_frequency_plan",  
                    doc: frm.doc,
                    args: {
                        fiscal_year: frm.doc.fiscal_year,
                        selected_days: values.days_of_week,
                        selected_customers: dialog.fields_dict.customers_table.df.data
                            .filter(row => row.select) 
                            .map(row => row.customer) 
                    },
                    callback: function(r) {
                        if (r.message && r.message.status === "success") {
                            frappe.msgprint(r.message.message);
                            frm.refresh_field('frequency_plan_table'); // تحديث الجدول
                            dialog.hide();
                        } else {
                            frappe.msgprint(__('Error occurred while adding customers.'));
                        }
                    }
                });
            } else {
                frappe.msgprint(__('Please select Territory, Class and Days of Week.'));
            }
        });

        // إظهار مربع الحوار
        dialog.show();
    },

    // حدث عند تغيير خطة التغطية
   coverage_strategy: function(frm) {
        if (frm.doc.coverage_strategy) {
            frappe.call({
                method: "get_totals",
                doc: frm.doc,
                args: {
                    coverage_strategy: frm.doc.coverage_strategy
                },
                callback: function(r) {
                    if (r.message) {
                        const totals = r.message;
                        const totalsTableHTML = `
                            <table style="width:100%; border-collapse:collapse;">
                                <thead>
                                    <tr style="background-color:#8B4513; color:#FFF;">
                                        <th style="text-align:left; padding:8px;">Business Type</th>
                                        <th style="text-align:left; padding:8px;">Class</th>
                                        <th style="text-align:right; padding:8px;">Total Visits Month</th>
                                        <th style="text-align:right; padding:8px;">Total Contribution Day</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${totals.map(total => `
                                        <tr style="background-color:#F9FFF0;">
                                            <td style="text-align:left; padding:8px;">${total.business_type}</td>
                                            <td style="text-align:left; padding:8px;">${total.class}</td>
                                            <td style="text-align:right; padding:8px;">${total.total_visits_month}</td>
                                            <td style="text-align:right; padding:8px;">${total.total_contribution_day}</td>
                                        </tr>
                                    `).join('')}
                                </tbody>
                            </table>
                        `;
                        frm.set_value('totals_table', totalsTableHTML);
                        frm.refresh_field('totals_table');
                    } else {
                        frm.set_value('totals_table', "No data found.");
                    }
                }
            });
        } else {
            frm.set_value('totals_table', "");
            frm.refresh_field('totals_table');
        }
    }

});