<?php

namespace Bookingor\Backend\Controller\Bookings;

use Bookingor\Helper\HelperControl;
use Bookingor\Integrations\Email\EmailNotification;

/**
 * Class representing a booking controller for managing booking-related operations.
 *
 * @var string $dp_prefix Database table prefix for booking-related tables.
 * @var array|null $staff_order_booked Stores the booked orders for staff members.
 * @var array|null $customer_order_booked Stores the booked orders for customers.
 */
class BookingsControl
{
    private static $bookingorDb;
    /**
     * Database table prefix for booking-related tables.
     *
     * @var string
     */
    public static $dp_prefix = "bookingor_";
    /**
     * Stores the booked orders for staff members.
     *
     * @var array|null
     */
    public static $staff_order_booked;
    /**
     * Stores the booked orders for customers.
     *
     * @var array|null
     */
    public static $customer_order_booked;
    /**
     * This function fetches all booking orders from the database and returns them
     *
     * @return array|null
     */
    public static function bp_booking_order()
    {
        global $wpdb;
        self::$bookingorDb = $wpdb;
        $customer_booked = $wpdb->prefix . self::$dp_prefix . 'booked_appointment';
        $customer_detail = $wpdb->prefix . self::$dp_prefix . 'customer_add';
        $staff_detail = $wpdb->prefix . self::$dp_prefix . 'staff_add';
        $service_detail = $wpdb->prefix . self::$dp_prefix . 'services';
        if (isset($_REQUEST['action'])) {
            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 (!empty($customer_booked) && !empty($customer_detail) && !empty($staff_detail) && !empty($service_detail)) {
            self::$staff_order_booked = self::$bookingorDb->get_results($wpdb->prepare(
                "SELECT 
                    c.book_id, 
                    COUNT(c.start_time) AS start_time_count,
                    c.service_get_id, 
                    c.customer_get_id, 
                    c.staff_get_id, 
                    c.appoint_status, 
                    c.service_get_price,  
                    c.picked_date, 
                    c.picked_date_end, 
                    c.start_time, 
                    c.end_time, 
                    c.people_count, 
                    c.payment_method, 
                    srv.service_name, 
                    srv.service_duration, 
                    srv.service_icon, 
                    srv.service_capacity_min, 
                    srv.service_capacity_max, 
                    srv.service_cost, 
                    cd.customer_id, 
                    cd.customer_first_name, 
                    cd.customer_last_name, 
                    cd.customer_email, 
                    cd.customer_phone, 
                    st.staff_first_name, 
                    st.staff_last_name, 
                    st.staff_icon, 
                    st.staff_email, 
                    st.staff_phone
                        FROM 
                            %1\$s AS c
                        LEFT JOIN 
                            %2\$s AS srv ON c.service_get_id = srv.service_id
                        LEFT JOIN 
                            %3\$s AS cd ON c.customer_get_id = cd.customer_id
                        LEFT JOIN 
                            %4\$s AS st ON c.staff_get_id = st.staff_id
                        GROUP BY 
                            c.book_id",
                $customer_booked,
                $service_detail,
                $customer_detail,
                $staff_detail
            ));
            return self::$staff_order_booked;
        }
    }
    /**
     * Updates the status of a booking based on the provided booking ID and status.
     *
     * This function retrieves the booking details from the database, updates the status,
     * and sends a notification email to the customer if the update is successful.
     *
     * @param none
     * @throws none
     * @return JSON response with success status and message
     */
    public function change_booking_status()
    {

        if (isset($_REQUEST['action'])) {
            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();
        }
        // $response  = new \stdclass();
        // $response->success = false;
        global $wpdb;
        self::$bookingorDb = $wpdb;
        $payment = $wpdb->prefix . self::$dp_prefix . 'booked_appointment';
        if (isset($_REQUEST['action'])) {


            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.')
                    ];
                    // echo wp_json_encode($response);
                }
            }

            $get_book_id = sanitize_text_field(wp_unslash($_REQUEST['booking_stats_id'] ?? ""));
            $get_book_status = sanitize_text_field(wp_unslash($_POST['book_status'] ?? ""));

            // print_r($get_book_id);
            // exit;
            $bookings = self::$bookingorDb->get_row(
                $wpdb->prepare(
                    "SELECT book_id, customer_get_id, duration_service, start_time, end_time, picked_date_end, picked_date, people_count, service_get_price,  discount_get_price,  paid_amount, payment_method, customer_time_zone, token_code, appoint_status, category_get_id, service_get_id, staff_get_id, location_get_id FROM {$wpdb->prefix}bookingor_booked_appointment WHERE book_id = %d",
                    $get_book_id
                )
            );
            $customer_details = self::$bookingorDb->get_row(
                $wpdb->prepare(
                    "SELECT customer_id, book_get_id, customer_first_name, customer_last_name, customer_email, customer_phone, customer_gender, customer_location, customer_description, customer_image, status FROM {$wpdb->prefix}bookingor_customer_add WHERE customer_id = %d",
                    $bookings->customer_get_id
                )
            );
            $staff_details = self::$bookingorDb->get_row(
                $wpdb->prepare(
                    "SELECT staff_id, staff_first_name, staff_last_name, staff_email, staff_phone, staff_location FROM {$wpdb->prefix}bookingor_staff_add WHERE staff_id = %d",
                    $bookings->staff_get_id
                )
            );
            if ($get_book_status) {
                self::$bookingorDb->update(
                    $payment,
                    array(
                        'appoint_status' => $get_book_status
                    ),
                    array('book_id' => $get_book_id)
                );

                $customer_where = strtolower("customer_email_{$get_book_status}");
                $customer_email_content = self::$bookingorDb->get_row($wpdb->prepare(
                    "SELECT 
                        id, 
                        name_action, 
                        name, 
                        subject, 
                        text, 
                        send_to, 
                        type, 
                        paid_amount, 
                        tax_charges, 
                        coupon_id, 
                        book_date, 
                        book_time, 
                        status 
                    FROM 
                       {$wpdb->prefix}bookingor_notifications
                    WHERE
                        name_action = %s",
                    $customer_where
                ));

                $staff_where = strtolower("employee_email_{$get_book_status}");
                $staff_email_content = self::$bookingorDb->get_row($wpdb->prepare(
                    "SELECT 
                        id, 
                        name_action, 
                        name, 
                        subject, 
                        text, 
                        send_to, 
                        type, 
                        paid_amount, 
                        tax_charges, 
                        coupon_id, 
                        book_date, 
                        book_time, 
                        status 
                    FROM 
                       {$wpdb->prefix}bookingor_notifications
                    WHERE
                        name_action = %s",
                    $staff_where
                ));


                $categoryString = [];
                $serviceString = [];
                $staffString = [];
                $locationString = [];
                $customerString = [];
                $businessString = [];
                $bookingString = [];
                $bookingData = HelperControl::get_last_booking_data($get_book_id);
                $categoryString = $bookingData['categoryString'];
                $serviceString = $bookingData['serviceString'];
                $staffString = $bookingData['staffString'];
                $customerString = $bookingData['customerString'];
                $bookedString = $bookingData['bookedString'];
                $locationString = $bookingData['locationString'];
                $businessString = $bookingData['businessString'];
                if (!empty(get_option("bookingor_settings_email_type"))) {

                    // send customer email
                    $subject = EmailNotification::string_Placeholder_variable($categoryString, $serviceString, $staffString, $customerString, $bookedString, $locationString, $businessString, $customer_email_content->subject);
                    $body = EmailNotification::string_Placeholder_variable($categoryString, $serviceString, $staffString, $customerString, $bookedString, $locationString, $businessString, $customer_email_content->text);

                    // staff email send
                    $subject = EmailNotification::string_Placeholder_variable($categoryString, $serviceString, $staffString, $customerString, $bookedString, $locationString, $businessString, $staff_email_content->subject);
                    $body = EmailNotification::string_Placeholder_variable($categoryString, $serviceString, $staffString, $customerString, $bookedString, $locationString, $businessString, $staff_email_content->text);

                    EmailNotification::sendEmail($customer_details->customer_email, $subject, $body);
                    EmailNotification::sendEmail($staff_details->staff_email, $subject, $body);
                }
                $response = [
                    'status' => 'success',
                    'message' =>  __("Booking Status ", "bookingor") . $get_book_status . __(" Updated", "bookingor"),
                ];
                echo wp_json_encode($response);
                exit;
            } else {
                $response = [
                    'status' => 'error',
                    'message' =>  __("Error occurred while updating Status", "bookingor"),
                ];
                echo wp_json_encode($response);
                exit;
            }
        }
        // echo wp_json_encode($response);
        // die;
    }
}
