<?php

namespace Bookingor\Backend\Controller\Service;

use stdClass;
use Bookingor\Backend\Controller\ServiceDeposit\ServiceDepositControl;
use Bookingor\Backend\Controller\ServiceSubcategory\ServiceSubcategory;
use Bookingor\Backend\Controller\ServiceTimeSheet\ServiceTimeSheetControl;

class ServiceControl
{
    private static $bookingorDb;
    /**
     * ID of the service being retrieved.
     *
     * @var int
     */
    public $service_gets_id;
    /**
     * Flag to indicate whether the service view is enabled or disabled.
     *
     * @var bool
     */
    public static $service_view;
    /**
     * Stores data related to the retrieved service.
     *
     * @var array|null
     */
    public static $get_service_data;
    /**
     * Stores data related to the retrieved subcategory.
     *
     * @var array|null
     */
    public static $get_subcategory_data;
    /**
     * Stores data related to the service time sheet.
     *
     * @var array|null
     */
    public static $get_service_time_sheet_data;
    /**
     * Stores data related to the service subcategory.
     *
     * @var array|null
     */
    public static $service_subcategory_data;
    /**
     * Stores data related to staff assignments.
     *
     * @var array|null
     */
    public static $get_staff_assign_data;
    /**
     * Stores data related to extra service details.
     *
     * @var array|null
     */
    public static $get_service_extra_data;
    /**
     * Flag to indicate whether the staff view is enabled or disabled.
     *
     * @var bool
     */
    public static $staff_view;
    /**
     * Stores data related to staff members.
     *
     * @var array|null
     */
    public static $staff_data;
    /**
     * Stores data related to staff assignments.
     *
     * @var array|null
     */
    public static $staff_assign_data;
    /**
     * Flag to indicate whether the staff assignment view is enabled or disabled.
     *
     * @var bool
     */
    public static $staff_assign_view;
    /**
     * Retrieves category data.
     *
     * @var array|null
     */
    public static $gets_category;
    /**
     * Retrieves subcategory data for a specific service.
     *
     * @var array|null
     */
    public static $gets_subcategory_serv;
    /**
     * Retrieves staff members assigned to a service.
     *
     * @var array|null
     */
    public static $get_staff_in_service;
    /**
     * Retrieves services available at a specific location.
     *
     * @var array|null
     */
    public static $get_location_service;
    /**
     * Default image for staff members.
     *
     * @var string
     */
    public static $b_default_staff_img;
    /**
     * Default image used in the system.
     *
     * @var string
     */
    public static $default_img;
    /**
     * Icon used for viewing purposes.
     *
     * @var string
     */
    public static $view_icon;
    /**
     * Database table prefix for booking-related tables.
     *
     * @var string
     */
    public static $dp_prefix = 'bookingor_';

    /**
     * Updates a service in the system based on the provided data.
     * Retrieves service details from the form fields and updates them in the database.
     * Handles features like updating subcategories, assigning staff, adding extras, and updating locations.
     * Supports plugins for deposit payments and service scheduling.
     *
     * @return void
     */
    public function bp_service_update()
    {
        global $wpdb;
        self::$bookingorDb = $wpdb;
        $services = $wpdb->prefix . self::$dp_prefix . 'services';
        $service_subcategory = $wpdb->prefix . self::$dp_prefix . 'service_subcategory';
        $service_assign = $wpdb->prefix . self::$dp_prefix . 'staff_assign_service';
        $location_assign = $wpdb->prefix . self::$dp_prefix . 'location_assign_service';
        self::$bookingorDb = $wpdb;
        $service_get_id = isset($_REQUEST['get_service_id']) ? intval($_REQUEST['get_service_id']) : 0;
        if (isset($_REQUEST['action'])) {
            //update per id


            if (isset($_POST['nonce'])) {
                if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                    $response = [
                        'status' => htmlspecialchars('error'),
                        'message' => htmlspecialchars('Nonce verification failed.')
                    ];
                }
            }


            if (!current_user_can('manage_options')) {
                $response = [
                    'status' => htmlspecialchars('error'),
                    'message' => htmlspecialchars('You do not have permission.')
                ];
                echo wp_json_encode($response);
                die();
            }
            $service_name = sanitize_text_field(wp_unslash($_POST['service_name'] ?? ''));
            $service_description = sanitize_textarea_field(wp_unslash($_POST['service_description'] ?? ''));
            $service_icon = sanitize_text_field(wp_unslash($_POST['service_icon_id'] ?? ''));
            $service_cost = sanitize_text_field(wp_unslash($_POST['service_cost'] ?? ''));
            $service_tax = sanitize_text_field(wp_unslash($_POST['service_tax'] ?? ''));
            $min_capacity = sanitize_text_field(wp_unslash($_POST['service_min_capacity'] ?? ''));
            $max_capacity = sanitize_text_field(wp_unslash($_POST['service_max_capacity'] ?? ''));
            $service_status = sanitize_text_field(wp_unslash($_POST['status'] ?? ''));
            $get_category_id = sanitize_text_field(wp_unslash($_POST['service_get_category_id'] ?? ''));
            $service_duration = sanitize_text_field(wp_unslash($_POST['service_duration_js'] ?? ''));
            $service_min_seat = sanitize_text_field(wp_unslash($_POST['service_min_capacity'] ?? ''));
            $service_max_seat = sanitize_text_field(wp_unslash($_POST['service_max_capacity'] ?? ''));
            $service_padding_before = sanitize_text_field(wp_unslash($_POST['service_padding_before'] ?? ''));
            $service_padding_after = sanitize_text_field(wp_unslash($_POST['service_padding_after'] ?? ''));
            $service_duration_type = sanitize_text_field(wp_unslash($_POST['duration_type'] ?? ''));
            $service_duration_count = sanitize_text_field(wp_unslash($_POST['service_duration_count'] ?? ''));
            $service_setting_cancel = sanitize_text_field(wp_unslash($_POST['service_advance']['cancel_booking'] ?? ''));
            $service_settings_zoom_allow = sanitize_text_field(wp_unslash($_POST['service_advance']['zoom_meeting'] ?? ''));
            $service_setting_before_book = sanitize_text_field(wp_unslash($_POST['service_advance']['min_book_time'] ?? ''));
            $woocommerce_product_id = sanitize_text_field(isset($_POST['bookingor_woocommerce_product']) ? sanitize_text_field(wp_unslash($_POST['bookingor_woocommerce_product'])) : '');
            $service_slot_toggle = sanitize_text_field(isset($_POST['service_slot_available']) ? sanitize_text_field(wp_unslash($_POST['service_slot_available'])) : '');
            $service_slot_toggle ? $service_slot_toggle : $service_slot_toggle = '0';
            if (!empty($service_slot_toggle) && isset($_POST['service_time_slot'])) {
                $service_time_slot = sanitize_text_field(wp_unslash($_POST['service_time_slot'] ?? ''));
            }

            if (is_plugin_active('bookingor-recurring-appointment/bookingor-recurring-appointment.php')) {
                if (isset($_POST['service_advance']['recurrence'])) {
                    $service_setting_repeat_on = sanitize_text_field(wp_unslash($_POST['service_advance']['recurrence'] ?? ''));
                    $service_setting_repeat_type = sanitize_text_field(wp_unslash($_POST['service_advance']['recurring_type'] ?? ''));
                    $service_setting_repeat_payment_type = sanitize_text_field(wp_unslash($_POST['service_advance']['recurring_payment'] ?? ''));
                }

                self::$bookingorDb->update(
                    $services,
                    [
                        'recurring_status' => $service_setting_repeat_on,
                        'recurring_type' => $service_setting_repeat_type,
                        'recurring_payment' => $service_setting_repeat_payment_type,
                    ],
                    ['service_id' => $service_get_id]
                );
            }
            self::$bookingorDb->update(
                $services,
                [
                    'service_name' => $service_name,
                    'service_description' => $service_description,
                    'service_icon' => $service_icon,
                    'status' => $service_status,
                    'service_cost' => $service_cost,
                    'service_tax' => $service_tax,
                    'service_capacity_min' => $min_capacity,
                    'service_capacity_max' => $max_capacity,
                    'service_duration' => $service_duration,
                    'timeslot_length' => $service_time_slot ?? '',
                    'service_capacity_min' => $service_min_seat,
                    'service_capacity_max' => $service_max_seat,
                    'padding_before' => $service_padding_before,
                    'padding_after' => $service_padding_after,
                    'category_get_id' => $get_category_id,
                    'service_duration_type' => $service_duration_type,
                    'service_duration_count' => $service_duration_count,
                    'service_slot_increment' => $service_slot_toggle,
                    'service_allow_booking_time' => $service_setting_before_book,
                    'service_allow_zoom_meeting' => $service_settings_zoom_allow,
                    'service_cancel_booking_time' => $service_setting_cancel,
                    'wc_id' => $woocommerce_product_id,
                ],
                ['service_id' => $service_get_id],
            );

            /* ============================================================
            Update assign staff on header
            ============================================ */
            $assign_staff_service = map_deep(wp_unslash($_POST['assign_staff_in_service'] ?? ''), 'sanitize_text_field');
            if (!empty($assign_staff_service)) {
                self::$bookingorDb->delete($service_assign, [
                    'service_get_id' => $service_get_id,
                ]);
                foreach ($assign_staff_service as $key => $value) {
                    if (isset($_POST['service_staff_get_id'])) {
                        self::$bookingorDb->update(
                            $service_assign,
                            [
                                'service_get_id' => $service_get_id,
                                'staff_get_id' => $value['service_staff_get_id'],
                            ],
                            ['service_get_id', $service_get_id]
                        );
                    }
                    if (empty($assign_staff_service)) {
                        self::$bookingorDb->delete($service_assign, [
                            'service_get_id' => $service_get_id,
                        ]);
                    } else {
                        self::$bookingorDb->insert(
                            $service_assign,
                            [
                                'service_get_id' => $service_get_id,
                                'staff_get_id' => $value['service_staff_get_id'],
                            ]
                        );
                    }
                }
            } else {
                self::$bookingorDb->delete($service_assign, [
                    'service_get_id' => $service_get_id,
                ]);
                $_POST['assign_staff_in_service'] = null;
            }
            // ========================= update staff assign end ==============================
            /* ============================================================
            location update
            ============================================ */

            $service_location = map_deep(wp_unslash($_POST['service_assign_location_updated'] ?? ''), 'sanitize_text_field');
            if (!empty($service_location)) {
                self::$bookingorDb->delete($location_assign, [
                    'service_get_id' => $service_get_id,
                ]);
                foreach ($service_location as $key => $value) {
                    if (isset($_POST['service_location_get_id'])) {
                        self::$bookingorDb->update(
                            $location_assign,
                            [
                                'service_get_id' => $service_get_id,
                                'location_get_id' => $value['service_location_get_id'],
                            ],
                            ['service_get_id', $service_get_id]
                        );
                    }
                    if (empty($_POST['service_assign_location_updated'])) {
                        self::$bookingorDb->delete($location_assign, [
                            'service_get_id' => $service_get_id,
                        ]);
                    } else {
                        self::$bookingorDb->insert(
                            $location_assign,
                            [
                                'service_get_id' => $service_get_id,
                                'location_get_id' => $value['service_location_get_id'],
                            ],
                        );
                    }
                }
            } else {
                self::$bookingorDb->delete($location_assign, [
                    'service_get_id' => $service_get_id,
                ]);
                $_POST['service_location_get_id'] = null;
            }
            // ========================= location update end ==============================


            if (class_exists('Bookingor\Backend\Controller\ServiceDeposit\ServiceDepositControl')) {
                ServiceDepositControl::service_deposit_update($service_get_id);
                // $subcategoryHandler->service_deposit_update($service_get_id);
            }

            /* ===================================================
                subcategory update
                =====================================*/
            if (class_exists('Bookingor\Backend\Controller\ServiceSubcategory\ServiceSubcategory')) {
                ServiceSubcategory::service_subcategory_update($service_get_id);
            }
        }
        $response = [
            'status' => htmlspecialchars('success'),
            'message' => htmlspecialchars('Service Updated Successfully'),
        ];
        echo wp_json_encode($response);
        exit;
    }

    /**
     * Adds a new service to the system based on the provided data.
     *
     * Retrieves service details from the form fields and inserts them into the database.
     * Handles additional features like assigning staff, adding extras, and updating locations.
     * Supports plugins for deposit payments and service scheduling.
     *
     * @return void
     */
    public function bp_add_service()
    {
        global $wpdb;
        self::$bookingorDb = $wpdb;
        $services_add = $wpdb->prefix . self::$dp_prefix . 'services';
        $service_assign_data = $wpdb->prefix . self::$dp_prefix . 'staff_assign_service';
        $location_assign = $wpdb->prefix . self::$dp_prefix . 'location_assign_service';

        if (isset($_REQUEST['action'])) {
            //tab basic


            if (isset($_POST['nonce'])) {
                if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                    $response = [
                        'status' => htmlspecialchars('error'),
                        'message' => htmlspecialchars('Nonce verification failed.')
                    ];
                }
            }
            if (!current_user_can('manage_options')) {
                $response = [
                    'status' => htmlspecialchars('error'),
                    'message' => htmlspecialchars('You do not have permission.')
                ];
                echo wp_json_encode($response);
                die();
            }

            // Check service limit for free version
            $services = self::bp_view_service();
            $service_count = is_array($services) ? count($services) : (is_object($services) ? count((array)$services) : 0);
            $is_pro = class_exists('Bookingor\Backend\Controller\LocationTimeSheet\LocationTimeSheetControl');
            
            if ($service_count >= 4 && !$is_pro) {
                $response = [
                    'status' => 'error',
                    'message' => __('The free version allows only 4 services. Upgrade to our Pro plan to add unlimited services.', 'bookingor')
                ];
                echo wp_json_encode($response);
                exit;
            }

            $service_name = sanitize_text_field(wp_unslash($_POST['service_name'] ?? ''));
            $service_description = sanitize_textarea_field(wp_unslash($_POST['service_description'] ?? ''));
            $service_icon = sanitize_text_field(wp_unslash($_POST['service_icon_id'] ?? ''));
            $service_cost = sanitize_text_field(wp_unslash($_POST['service_cost'] ?? ''));
            $service_tax = sanitize_text_field(wp_unslash($_POST['service_tax'] ?? ''));
            $min_capacity = sanitize_text_field(wp_unslash($_POST['service_min_capacity'] ?? ''));
            $max_capacity = sanitize_text_field(wp_unslash($_POST['service_max_capacity'] ?? ''));
            $service_status = sanitize_text_field(wp_unslash($_POST['status'] ?? ''));
            $get_category_id = sanitize_text_field(wp_unslash($_POST['service_get_category_id'] ?? ''));
            $service_min_seat = sanitize_text_field(wp_unslash($_POST['service_min_capacity'] ?? ''));
            $service_max_seat = sanitize_text_field(wp_unslash($_POST['service_max_capacity'] ?? ''));
            $service_padding_before = sanitize_text_field(wp_unslash($_POST['service_padding_before'] ?? ''));
            $service_duration = sanitize_text_field(wp_unslash($_POST['service_duration_js'] ?? ''));

            $service_padding_after = sanitize_text_field(wp_unslash($_POST['service_padding_after'] ?? ''));
            $service_duration_type = sanitize_text_field(wp_unslash($_POST['duration_type'] ?? ''));
            $service_duration_count = sanitize_text_field(wp_unslash($_POST['service_duration_count'] ?? ''));
            $service_setting_cancel = sanitize_text_field(wp_unslash($_POST['service_advance']['cancel_booking'] ?? ''));
            $service_setting_before_book = sanitize_text_field(wp_unslash($_POST['service_advance']['min_book_time'] ?? ''));
            $service_assign = sanitize_text_field(isset($_POST['service_assign']) ? sanitize_text_field(wp_unslash($_POST['service_assign'])) : '');
            $woocommerce_product_id = sanitize_text_field(isset($_POST['bookingor_woocommerce_product']) ? sanitize_text_field(wp_unslash($_POST['bookingor_woocommerce_product'])) : '');
            $service_slot_toggle = sanitize_text_field(isset($_POST['service_slot_available']) ? sanitize_text_field(wp_unslash($_POST['service_slot_available'])) : '');
            $service_slot_toggle ? $service_slot_toggle : $service_slot_toggle = '0';
            if (!empty($service_slot_toggle) && isset($_POST['service_slot_available'])) {
                $service_times_slot = sanitize_text_field(isset($_POST['service_time_slot']) ? sanitize_text_field(wp_unslash($_POST['service_time_slot'])) : '0');
            } else {
                $service_times_slot = '0';
            }

            self::$bookingorDb->insert(
                $services_add,
                [
                    'service_name' => $service_name,
                    'service_description' => $service_description,
                    'service_icon' => $service_icon,
                    'status' => $service_status,
                    'service_cost' => $service_cost,
                    'service_tax' => $service_tax,
                    'service_capacity_min' => $min_capacity,
                    'service_capacity_max' => $max_capacity,
                    'wc_id' => $woocommerce_product_id,
                    'service_duration' => $service_duration,
                    'timeslot_length' => $service_times_slot,
                    'service_capacity_min' => $service_min_seat,
                    'service_capacity_max' => $service_max_seat,
                    'padding_before' => $service_padding_before,
                    'padding_after' => $service_padding_after,
                    'category_get_id' => $get_category_id,
                    'service_duration_type' => $service_duration_type,
                    'service_duration_count' => $service_duration_count,
                    'service_slot_increment' => $service_slot_toggle,
                    'service_allow_booking_time' => $service_setting_before_book,
                    'service_cancel_booking_time' => $service_setting_cancel,
                ],
            );

            $this->service_gets_id = $wpdb->insert_id;

            if (is_plugin_active('bookingor-recurring-appointment/bookingor-recurring-appointment.php')) {
                if (isset($_POST['service_advance']['recurrence'])) {
                    $service_setting_repeat_on = sanitize_text_field(wp_unslash($_POST['service_advance']['recurrence'] ?? ''));
                    $service_setting_repeat_type = sanitize_text_field(wp_unslash($_POST['service_advance']['recurring_type'] ?? ''));
                    $service_setting_repeat_payment_type = sanitize_text_field(wp_unslash($_POST['service_advance']['recurring_payment'] ?? ''));
                }
            }




            /* ============================================================
            assign staff on header
            ============================================ */

            $assign_staff_service = map_deep(wp_unslash($_POST['assign_staff_in_service'] ?? ''), 'sanitize_text_field');
            if (!empty($assign_staff_service)) {
                foreach ($assign_staff_service as $key => $value) {
                    self::$bookingorDb->insert(
                        $service_assign_data,
                        [
                            'service_get_id' => $this->service_gets_id,
                            'staff_get_id' => $value['service_staff_get_id'],
                        ],
                        [
                            '%s',
                            '%s',
                            '%s',
                            '%s',
                        ]
                    );
                }
            } else {
                $_POST['assign_staff_in_service'] = null;
            }

            // assign service end
            // ===================================


            /* ============================================================
            location add
            ============================================ */

            $service_location = map_deep(wp_unslash($_POST['service_assign_location'] ?? ''), 'sanitize_text_field');
            if (!empty($service_location)) {
                foreach ($service_location as $key => $value) {
                    self::$bookingorDb->insert(
                        $location_assign,
                        [
                            'service_get_id' => $this->service_gets_id,
                            'location_get_id' => $value['service_location_get_id'],
                        ],
                    );
                }
            } else {
                $_POST['service_location_get_id'] = null;
            }
            // ========================= location end ==============================



            /* ============================================================
            subcategory add
            ============================================ */
            if (class_exists('Bookingor\Backend\Controller\ServiceSubcategory\ServiceSubcategory')) {
                ServiceSubcategory::service_subcategory_add($this->service_gets_id);
            }
            if (class_exists('Bookingor\Backend\Controller\ServiceDeposit\ServiceDepositControl')) {
                $subcategoryHandler = ServiceDepositControl::service_deposit_add($this->service_gets_id);
                $subcategoryHandler->service_deposit_add($this->service_gets_id);
            }
            $response = [
                'status' => htmlspecialchars('success'),
                'message' => htmlspecialchars('Service Created successfully'),
            ];
            echo wp_json_encode($response);
            exit;
        }
    }

    /**
     * Retrieves and returns a list of services with detailed information.
     * Populates the 'service_view' property with the fetched data.
     *
     * @return array|null Fetched service data including ID, icon, name, cost, duration, category ID, status, and category name.
     */
    public static function bp_view_service()
    {
        self::$view_icon = plugin_dir_url(dirname(dirname(__FILE__))) . 'assets/images/cate-serv.jpg';
        self::$default_img = plugin_dir_url(dirname(dirname(__FILE__))) . 'assets/images/cate-serv.jpg';
        global $wpdb;
        self::$bookingorDb = $wpdb;
        $category = $wpdb->prefix . self::$dp_prefix . 'categories';
        $services = $wpdb->prefix . self::$dp_prefix . 'services';

        return self::$service_view = self::$bookingorDb->get_results(
            $wpdb->prepare(
                'SELECT t1.service_id, t1.service_icon, t1.service_name, t1.service_cost, t1.service_duration, t1.service_duration_type, t1.service_duration_count, t1.category_get_id, t1.status, t2.category_name 
                FROM %1$s AS t1 
                INNER JOIN %2$s AS t2 ON t1.category_get_id = t2.category_id',
                $services,
                $category
            )
        );
    }

    /**
     * Deletes a service and its related data from the database.
     * Deletes the service entry, associated time sheet, service subcategory, staff assignments, and extra service details.
     *
     * @return void
     */
    public function bp_delete_service()
    {
        global $wpdb;
        self::$bookingorDb = $wpdb;
        $delete_service = $wpdb->prefix . self::$dp_prefix . 'services';
        $delete_time_sheet = $wpdb->prefix . self::$dp_prefix . 'timesheet';
        $delete_service_subcategory = $wpdb->prefix . self::$dp_prefix . 'service_subcategory';
        $delete_staff_assign_service = $wpdb->prefix . self::$dp_prefix . 'staff_assign_service';
        self::$bookingorDb = $wpdb;
        self::$bookingorDb->delete($delete_service, [
            'service_id' => sanitize_text_field(wp_unslash($_REQUEST['id'] ?? '')),

        ]);

        self::$bookingorDb->delete($delete_time_sheet, [
            'service_get_id' => sanitize_text_field(wp_unslash($_REQUEST['id'] ?? '')),
        ]);

        if (isset($_POST['nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                $response = [
                    'status' => htmlspecialchars('error'),
                    'message' => htmlspecialchars('Nonce verification failed.')
                ];
            }
        }

        if (class_exists('Bookingor\Frontend\Controller\ServiceSubcategory\ServiceSubcategoryControl')) {
            require_once ABSPATH . 'wp-content/plugins/bookingor-subcategory-addon/admin/include/subcategory/subcategory-control.php';
            self::$bookingorDb->delete($delete_service_subcategory, [
                'service_get_id' => sanitize_text_field(wp_unslash($_REQUEST['id'] ?? '')),
            ]);
        }
        self::$bookingorDb->delete($delete_staff_assign_service, [
            'service_get_id' => sanitize_text_field(wp_unslash($_REQUEST['id'] ?? '')),
        ]);
        if (isset($_POST['nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                $response = [
                    'status' => htmlspecialchars('error'),
                    'message' => htmlspecialchars('Nonce verification failed.')
                ];
            }
        }
        $response = [
            'status' => htmlspecialchars('success'),
            'message' => htmlspecialchars('Service Deleted Successfully'),
        ];
        echo wp_json_encode($response);
        exit;
    }

    /**
     * Updates a service in the system based on the provided data.
     * Retrieves service details from the form fields and updates them in the database.
     * Handles features like updating subcategories, assigning staff, adding extras, and updating locations.
     * Supports plugins for deposit payments and service scheduling.
     *
     * @return stdClass Contains detailed information about the updated service including staff assignments, extra service details, and time sheet data.
     */
    public static function bp_update_service()
    {
        $serviceUpdate = new stdClass();
        global $wpdb;
        self::$bookingorDb = $wpdb;
        $get_subcategory = $wpdb->prefix . self::$dp_prefix . 'subcategory';
        self::$b_default_staff_img = plugin_dir_url(__FILE__) . 'images/staff-icon.jpg';
        $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
        if (isset($_POST['nonce'])) {
            if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
                $response = [
                    'status' => htmlspecialchars('error'),
                    'message' => htmlspecialchars('Nonce verification failed.')
                ];
            }
        }

        self::$get_service_data = self::$bookingorDb->get_results($wpdb->prepare(
            "SELECT service_id, service_icon, service_name, service_description, category_get_id, service_cost, service_deposit, service_deposit_type, service_tax, service_duration, service_duration_type, service_duration_count, timeslot_length, service_slot_increment, padding_before, padding_after, service_capacity_min, service_capacity_max, recurring_status, recurring_type, recurring_payment, service_cancel_booking_time, service_allow_booking_time, single_booking_only_slot, service_time_sheet, wc_id, status FROM {$wpdb->prefix}bookingor_services WHERE service_id = %d",
            $id,
        ));

        self::$get_staff_in_service = self::$bookingorDb->get_results($wpdb->prepare("SELECT assign_id, staff_get_id, service_get_id, staff_price FROM {$wpdb->prefix}bookingor_staff_assign_service WHERE service_get_id = %d", $id));
        self::$get_location_service = self::$bookingorDb->get_results($wpdb->prepare("SELECT location_assign_id, location_get_id, service_get_id FROM {$wpdb->prefix}bookingor_location_assign_service WHERE service_get_id = %d", $id));
        self::$get_service_time_sheet_data = self::$bookingorDb->get_results($wpdb->prepare("SELECT time_id, service_get_id, team_id, time_sheet_weekly FROM {$wpdb->prefix}bookingor_timesheet WHERE service_get_id = %d", $id));

        $serviceUpdate->servicesDetails = self::$get_service_data;
        $serviceUpdate->staffDetails = self::$get_staff_in_service;
        $serviceUpdate->locationDetails = self::$get_location_service;
        wp_json_encode(self::$service_subcategory_data);

        if (class_exists('Bookingor\Backend\Controller\ServiceTimeSheet\ServiceTimeSheetControl')) {
            if (isset(self::$get_service_data[0]->service_time_sheet) && !empty(self::$get_service_data[0]->service_time_sheet)) {
                $serviceUpdate->serviceTimeSheetDetails = self::$get_service_data[0]->service_time_sheet;
                // self::$get_service_data[0]->service_time_sheet = self::$get_service_time_sheet_data;
            }
        }
        return $serviceUpdate;
    }

    /**
     * Retrieves a list of categories from the database that are active and have associated services.
     * This function is used to populate the category dropdown in the service creation and editing forms.
     * The function returns an array of categories with their details, including the category ID, icon, category name, and status.
     *
     * @return array An array of category details
     */
    public static function bp_get_category_for_services()
    {
        global $wpdb;
        self::$bookingorDb = $wpdb;

        return self::$gets_category = self::$bookingorDb->get_results($wpdb->prepare("SELECT category_id, icon, category_name, status FROM {$wpdb->prefix}bookingor_categories WHERE status = %d", 1));
    }
}
