<?php

namespace BookWellAB;

defined('ABSPATH') || exit;

if (!class_exists('BookWellAB_Shortcode_Generator')) {

    class BookWellAB_Shortcode_Generator
    {
        private static $instance = null;
        private $bookwell_page = 'shortcode-generator';

        public static function get_instance()
        {
            if (self::$instance === null) {
                self::$instance = new self();
            }
            return self::$instance;
        }

        public function __construct()
        {
            global $BOOKWELLAB;
            $current_page = (isset($BOOKWELLAB) && $BOOKWELLAB instanceof BOOKWELL)
                ? $BOOKWELLAB->get_bookwell_admin_page()
                : '';

            if (is_admin() && $current_page == $this->bookwell_page) {
                add_filter('bookwellab_admin_script_vriable_data', [$this, 'bookwellab_admin_script_vriable_data_func'], 10, 2);
                add_action('bookwellab_shortcode-generator_admin_html', [$this, 'bookwellab_shortcode_generator_admin_html_func'], 10);
                add_filter('bookwellab_page_method_data', [$this, 'bookwellab_page_method_data_func'], 10, 2);
                add_filter('bookwellab_page_mounted_data', [$this, 'bookwellab_page_mounted_data_func'], 10, 2);
                add_filter('bookwellab_define_script_vriable_data', [$this, 'bookwellab_define_script_vriable_data_func'], 10, 2);
                add_action('bookwellab_add_extra_admin_assets', [$this, 'bookwellab_add_shortcode_generator_assets']);
            }
        }

        public function bookwellab_add_shortcode_generator_assets()
        {
            wp_register_style(
                'bookwellab-shortcode-generator-admin',
                plugin_dir_url(BOOKWELLAB_FILE) . 'assets/css/shortcode-generator-admin.css',
                ['bookwellab-admin-style'],
                BOOKWELLAB_VERSION
            );
            wp_enqueue_style('bookwellab-shortcode-generator-admin');
        }

        public function bookwellab_define_script_vriable_data_func($bookwellab_define_script_vriable_data, $bookwellpage)
        {
            if ($this->bookwell_page != $bookwellpage) {
                return $bookwellab_define_script_vriable_data;
            }

            // No extra ref definitions needed as they are initialized in bookwellab_admin_script_vriable_data_func
            return $bookwellab_define_script_vriable_data;
        }

        public function bookwellab_admin_script_vriable_data_func($bookwellab_admin_script_vriable_data, $bookwellpage)
        {
            if ($this->bookwell_page != $bookwellpage) {
                return $bookwellab_admin_script_vriable_data;
            }

            $bookwellab_admin_script_vriable_data['sc_staff_list'] = [];
            $bookwellab_admin_script_vriable_data['sc_service_list'] = [];
            $bookwellab_admin_script_vriable_data['selected_staff_id'] = "";
            $bookwellab_admin_script_vriable_data['selected_service_id'] = "";
            $bookwellab_admin_script_vriable_data['popup_btn_staff_id'] = "";
            $bookwellab_admin_script_vriable_data['popup_btn_service_id'] = "";
            $bookwellab_admin_script_vriable_data['popup_btn_label'] = __('Book Appointment', 'bookwellnow-appointment-booking');
            $bookwellab_admin_script_vriable_data['popup_btn_class'] = "";
            $bookwellab_admin_script_vriable_data['customer_panel_shortcode'] = '[bookwellnow_customer_panel]';
            $bookwellab_admin_script_vriable_data['customer_panel_shortcode_hint'] = __(
                'Customers must log in to view appointments. Enable "Create WordPress user upon appointment booking" in Settings → Customer Panel to auto-create accounts after booking.',
                'bookwellnow-appointment-booking'
            );

            $settings = BookWellAB_Settings::get_settings();
            $appearance = (isset($settings['appearance']) && is_array($settings['appearance']))
                ? $settings['appearance']
                : [];
            $form_type = isset($appearance['form_type']) ? sanitize_key((string) $appearance['form_type']) : 'wizard';
            if (!in_array($form_type, ['wizard', 'full_page_list'], true)) {
                $form_type = 'wizard';
            }
            $bookwellab_admin_script_vriable_data['sc_form_type'] = $form_type;
            $bookwellab_admin_script_vriable_data['sc_save_form_type_loader'] = false;
            $bookwellab_admin_script_vriable_data['sc_appearance_preview'] = [
                'primary_color' => isset($appearance['primary_color']) ? (string) $appearance['primary_color'] : '#044343',
                'panel_bg_color' => isset($appearance['panel_bg_color']) ? (string) $appearance['panel_bg_color'] : '#F8F4F8',
                'content_text_color' => isset($appearance['content_text_color']) ? (string) $appearance['content_text_color'] : '#64748b',
            ];

            return $bookwellab_admin_script_vriable_data;
        }

        public function bookwellab_page_mounted_data_func($bookwellab_page_mounted_data, $bookwellpage)
        {
            if ($this->bookwell_page != $bookwellpage) {
                return $bookwellab_page_mounted_data;
            }

            $bookwellab_page_mounted_data .= '
                const vuedata = this;
                vuedata.bwab_sc_fetchStaff();
                vuedata.bwab_sc_fetchServices();
            ';

            return $bookwellab_page_mounted_data;
        }

        public function bookwellab_page_method_data_func($bookwellab_page_method_data, $bookwellpage)
        {
            if ($this->bookwell_page != $bookwellpage) {
                return $bookwellab_page_method_data;
            }

            $sc_preview_title = esc_js(__('Shortcode preview', 'bookwellnow-appointment-booking'));
            $sc_preview_msg = esc_js(__('Your selections are reflected in the generated shortcode below.', 'bookwellnow-appointment-booking'));
            $sc_form_type_saved = esc_js(__('Form type saved.', 'bookwellnow-appointment-booking'));
            $sc_form_type_error = esc_js(__('Could not save form type. Please try again.', 'bookwellnow-appointment-booking'));

            $bookwellab_page_method_data .= '
                bwab_sc_fetchStaff() {
                    const vuedata = this;
                    var ajax_url = bookwellab_ajax_obj.ajax_url;
                    var pass_data = {
                        action: "bookwellab_get_staff",
                        _wpnonce: bookwellab_ajax_obj.bookwellab_nonce
                    };
                    axios.post(ajax_url, Qs.stringify(pass_data))
                    .then(function(response) {
                        if(response.data.type == "success") {
                            vuedata.sc_staff_list = response.data.list_data || [];
                        }
                    });
                },

                bwab_sc_fetchServices() {
                    const vuedata = this;
                    var ajax_url = bookwellab_ajax_obj.ajax_url;
                    var pass_data = {
                        action: "bookwellab_get_services",
                        _wpnonce: bookwellab_ajax_obj.bookwellab_nonce
                    };
                    axios.post(ajax_url, Qs.stringify(pass_data))
                    .then(function(response) {
                        if(response.data.type == "success") {
                            vuedata.sc_service_list = response.data.list_data || [];
                        }
                    });
                },

                bwab_sc_setFormType(formType) {
                    const vuedata = this;
                    if (!formType || formType === vuedata.sc_form_type || vuedata.sc_save_form_type_loader) {
                        return;
                    }
                    const previous = vuedata.sc_form_type;
                    vuedata.sc_form_type = formType;
                    if (formType === "full_page_list") {
                        vuedata.selected_service_id = "";
                    }
                    vuedata.sc_save_form_type_loader = true;
                    axios.post(bookwellab_ajax_obj.ajax_url, Qs.stringify({
                        action: "bookwellab_save_appearance_form_type",
                        form_type: formType,
                        _wpnonce: bookwellab_ajax_obj.bookwellab_nonce
                    })).then(function(response) {
                        if (response.data && response.data.success) {
                            vuedata.sc_form_type = (response.data.data && response.data.data.form_type)
                                ? response.data.data.form_type
                                : formType;
                            vuedata.$notify({
                                title: "Success",
                                message: (response.data.data && response.data.data.msg) ? response.data.data.msg : "' . $sc_form_type_saved . '",
                                type: "success",
                                duration: 2200,
                                offset: vuedata.bwab_sc_getNotificationOffset(),
                                customClass: "bwab-admin-notification",
                            });
                        } else {
                            vuedata.sc_form_type = previous;
                            vuedata.$notify({
                                title: "Error",
                                message: (response.data && response.data.data && response.data.data.msg)
                                    ? response.data.data.msg
                                    : "' . $sc_form_type_error . '",
                                type: "error",
                                duration: 3000,
                                offset: vuedata.bwab_sc_getNotificationOffset(),
                                customClass: "bwab-admin-notification",
                            });
                        }
                    }).catch(function() {
                        vuedata.sc_form_type = previous;
                        vuedata.$notify({
                            title: "Error",
                            message: "' . $sc_form_type_error . '",
                            type: "error",
                            duration: 3000,
                            offset: vuedata.bwab_sc_getNotificationOffset(),
                            customClass: "bwab-admin-notification",
                        });
                    }).finally(function() {
                        vuedata.sc_save_form_type_loader = false;
                    });
                },

                bwab_sc_getNotificationOffset() {
                    const adminBar = document.getElementById("wpadminbar");
                    if (!adminBar) {
                        return 16;
                    }
                    return adminBar.offsetHeight + 12;
                },

                bwab_sc_copyShortcode() {
                    const vuedata = this;
                    vuedata.bwab_sc_copyText(vuedata.bwab_sc_generatedShortcode());
                },

                bwab_sc_copyPopupButtonShortcode() {
                    const vuedata = this;
                    vuedata.bwab_sc_copyText(vuedata.bwab_sc_generatedPopupButtonShortcode());
                },

                bwab_sc_copyCustomerPanelShortcode() {
                    const vuedata = this;
                    vuedata.bwab_sc_copyText(vuedata.customer_panel_shortcode || "[bookwellnow_customer_panel]");
                },

                bwab_sc_copyText(shortcode) {
                    const vuedata = this;
                    const onCopySuccess = () => {
                        vuedata.$notify({
                            title: "Success",
                            message: "Shortcode copied to clipboard",
                            type: "success",
                            duration: 2000,
                            offset: vuedata.bwab_sc_getNotificationOffset(),
                            customClass: "bwab-admin-notification",
                        });
                    };

                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        navigator.clipboard.writeText(shortcode).then(onCopySuccess).catch(() => {
                            const textarea = document.createElement("textarea");
                            textarea.value = shortcode;
                            textarea.setAttribute("readonly", "");
                            textarea.style.position = "absolute";
                            textarea.style.left = "-9999px";
                            document.body.appendChild(textarea);
                            textarea.select();
                            document.execCommand("copy");
                            document.body.removeChild(textarea);
                            onCopySuccess();
                        });
                        return;
                    }

                    const textarea = document.createElement("textarea");
                    textarea.value = shortcode;
                    textarea.setAttribute("readonly", "");
                    textarea.style.position = "absolute";
                    textarea.style.left = "-9999px";
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand("copy");
                    document.body.removeChild(textarea);
                    onCopySuccess();
                },

                bwab_sc_onStaffChange() {
                    this.selected_service_id = "";
                },
                bwab_sc_onPopupBtnStaffChange() {
                    this.popup_btn_service_id = "";
                },
                bwab_sc_filteredServices() {
                    const vuedata = this;
                    if (!vuedata.selected_staff_id) {
                        return vuedata.sc_service_list;
                    }
                    const staff = vuedata.sc_staff_list.find(s => s.bw_staff_id == vuedata.selected_staff_id);
                    if (!staff || !staff.bw_staff_services) {
                        return [];
                    }
                    const staffServiceIds = staff.bw_staff_services.map(s => s.bw_service_id);
                    return vuedata.sc_service_list.filter(service => staffServiceIds.includes(service.bw_service_id));
                },
                bwab_sc_filteredPopupBtnServices() {
                    const vuedata = this;
                    if (!vuedata.popup_btn_staff_id) {
                        return vuedata.sc_service_list;
                    }
                    const staff = vuedata.sc_staff_list.find(s => s.bw_staff_id == vuedata.popup_btn_staff_id);
                    if (!staff || !staff.bw_staff_services) {
                        return [];
                    }
                    const staffServiceIds = staff.bw_staff_services.map(s => s.bw_service_id);
                    return vuedata.sc_service_list.filter(service => staffServiceIds.includes(service.bw_service_id));
                },
                bwab_sc_generatedShortcode() {
                    const vuedata = this;
                    let sc = "[bookwell_booking";
                    if (vuedata.selected_staff_id) {
                        sc += " staff_id=\"" + vuedata.selected_staff_id + "\"";
                    }
                    if (vuedata.sc_form_type !== "full_page_list" && vuedata.selected_service_id) {
                        sc += " service_id=\"" + vuedata.selected_service_id + "\"";
                    }
                    sc += "]";
                    return sc;
                },
                bwab_sc_generatedPopupButtonShortcode() {
                    const vuedata = this;
                    let sc = "[bookwell_booking_button";
                    if (vuedata.popup_btn_staff_id) {
                        sc += " staff_id=\"" + vuedata.popup_btn_staff_id + "\"";
                    }
                    if (vuedata.popup_btn_service_id) {
                        sc += " service_id=\"" + vuedata.popup_btn_service_id + "\"";
                    }
                    const label = (vuedata.popup_btn_label || "").trim();
                    if (label && label !== "Book Appointment") {
                        sc += " label=\"" + label.replace(/"/g, "&quot;") + "\"";
                    }
                    const btnClass = (vuedata.popup_btn_class || "").trim();
                    if (btnClass) {
                        sc += " class=\"" + btnClass.replace(/"/g, "&quot;") + "\"";
                    }
                    sc += "]";
                    return sc;
                },
                bwab_sc_behaviorMessage() {
                    const vuedata = this;
                    if (vuedata.sc_form_type === "full_page_list") {
                        if (vuedata.selected_staff_id) {
                            return "Service list with popup: customers pick a service from the grid. Staff will be pre-selected when booking opens.";
                        }
                        return "Service list with popup: customers pick a service from the grid, then continue in the booking popup.";
                    }
                    if (vuedata.selected_staff_id && vuedata.selected_service_id) {
                        return "Both staff & service step will be hidden. Customers will skip straight to Date & Time selection.";
                    } else if (vuedata.selected_staff_id) {
                        return "Staff step will be hidden (auto-selected). Customers will go directly to Service selection.";
                    } else if (vuedata.selected_service_id) {
                        return "Service step will be hidden (auto-selected). Customers will go directly to Staff selection.";
                    }
                    return "By default, customers will see the full booking process starting from Service selection.";
                },
                bwab_sc_popupButtonBehaviorMessage() {
                    const vuedata = this;
                    if (vuedata.popup_btn_staff_id && vuedata.popup_btn_service_id) {
                        return "Button opens the booking popup with service & staff pre-selected. Customers go straight to Date & Time.";
                    } else if (vuedata.popup_btn_service_id) {
                        return "Button opens the booking popup with the service pre-selected. Customers continue from Staff selection.";
                    } else if (vuedata.popup_btn_staff_id) {
                        return "Button opens the booking popup showing only that staff member\'s active services. Staff is applied after a service is chosen.";
                    }
                    return "Button opens the same booking popup at Service selection with all active services. Place it on any page (e.g. a service detail page).";
                },

                bwab_sc_notifyPreviewUpdated() {
                    const vuedata = this;
                    vuedata.$notify({
                        title: "' . $sc_preview_title . '",
                        message: "' . $sc_preview_msg . '",
                        type: "success",
                        duration: 2200,
                        offset: vuedata.bwab_sc_getNotificationOffset(),
                        customClass: "bwab-admin-notification",
                    });
                }
            ';

            return $bookwellab_page_method_data;
        }

        public function bookwellab_shortcode_generator_admin_html_func()
        {
            require_once BOOKWELLAB_HTML_PATH . "shortcode_generator_view_v2.php";
        }
    }
}
