<?php

namespace Bookingor\Frontend\Controller\Booking;

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


class BookingControlFront
{

	private static $bookingorDb;
	public static $dp_prefix = "bookingor_";

	/**
	 * Confirms a booking and sends notifications to the customer and the business.
	 *
	 * This function creates a new booking record in the database and sends email notifications to the customer and the business. It also handles the payment processing for the booking.
	 *
	 * @return void
	 */

	public static function bp_confirm_booking()
	{
		global $wpdb;
		self::$bookingorDb = $wpdb;
		$default_booking_status = get_option('bookingor_settings_default_booking_status');
		$email_check = 'customer_email_' . $default_booking_status;
		$staff_email_check = 'employee_email_' . $default_booking_status;
		$get_whatsapp_action_customer = 'customer_whatsapp_' . $default_booking_status;
		$get_whatsapp_action_staff = 'employee_whatsapp_' . $default_booking_status;
		$sms_check_customer = 'customer_sms_' . $default_booking_status;
		$sms_check_staff = 'employee_sms_' . $default_booking_status;
		$booked_customer = $wpdb->prefix . self::$dp_prefix . 'booked_appointment';
		$book_appointment = $wpdb->prefix . self::$dp_prefix . 'confirm_booking_details';
		$customer_details = $wpdb->prefix . self::$dp_prefix . 'customer_add';
		$customer_payment_data = $wpdb->prefix . self::$dp_prefix . 'customers_payment';
		$notifications = $wpdb->prefix . self::$dp_prefix . 'notifications';
		$extra_booked = $wpdb->prefix . self::$dp_prefix . 'extra_booked';
		$customer_first_name = sanitize_text_field(wp_unslash($_POST['customer_first_name'] ?? ""));
		$customer_last_name = sanitize_text_field(wp_unslash($_POST['customer_last_name'] ?? ""));
		$customer_email_address = sanitize_text_field(wp_unslash($_POST['customer_email_address'] ?? ""));
		$customer_phone = sanitize_text_field(wp_unslash($_POST['customer_phone'] ?? ""));
		$customer_payment_design = sanitize_text_field(wp_unslash($_POST['customer_pay'] ?? ""));
		$f_currency_symbol = get_option("bookingor_settings_country_currency");


		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);
				}
			}

			$customer_password = wp_generate_password(12, true);
			$js = map_deep(wp_unslash($_POST['design_final_booking'] ?? ""), 'sanitize_text_field');
			$timeZoneName = $js['timeZoneName'] ?? "";
			if (get_option('bookingor_settings_woocommerce_payment_active') === 'on' && !empty($js['wc_product_id'])) {
				$order_id = get_query_var('order-received');
				$order = wc_get_order($order_id);
			}

			// user logged in
			if (is_user_logged_in() && in_array('administrator', wp_get_current_user()->roles)) {
				$current_user = wp_get_current_user();
				$user_email = $current_user->user_email;
				$escaped_user_email = $wpdb->prepare('%s', $user_email);
				$get_customer_id = null;
				$get_customer_id = self::$bookingorDb->get_var(
					$wpdb->prepare(
						"SELECT customer_id FROM {$wpdb->prefix}bookingor_customer_add WHERE customer_email = '$user_email'",

					)
				);
				if (empty($get_customer_id)) {
					self::$bookingorDb->insert(
						$customer_details,
						array(
							'customer_first_name' => $customer_first_name,
							'customer_last_name' => $customer_last_name,
							'customer_email' => $customer_email_address,
							'customer_phone' => $customer_phone,
						),
					);
				}
				$customer_id = $wpdb->insert_id;

				self::$bookingorDb->insert(
					$booked_customer,
					array(
						'customer_get_id' => !empty($get_customer_id) ? $get_customer_id : $customer_id,
						'service_get_id' => $js['get_service_id'],
						'staff_get_id' => isset($js['get_staff_id']) ? $js['get_staff_id'] : null,
						'category_get_id' => isset($js['category_id']) ? $js['category_id'] : null,
						'location_get_id' => isset($js['location_get_id']) ? $js['location_get_id'] : null,
						'people_count' => $js['selected_max_capacity'] ?? "",
						'start_time' => HelperControl::convert12To24($js['get_start_time'] ?? ""),
						'end_time' => HelperControl::convert12To24($js['get_end_time'] ?? ""),
						'duration_service' => $js['service_duration'] ?? "",
						'picked_date' => $js['get_full_date'] ?? "",
						'picked_date_end' => !empty($js['get_end_date']) ? $js['get_end_date'] : date('Y-m-d', strtotime(($js['get_full_date'] ?? '') . ' ' . HelperControl::convert12To24($js['get_start_time'] ?? '') . ' + ' . ($js['service_duration'] ?? '') . ' minutes')),
						'discount_get_price' => '',
						'extra_get_price' => isset($js['extra_total_price']) ? $js['extra_total_price'] : 0,
						'service_get_price' => $js['service_price'] ?? "",
						'tax_get_price' => $js['service_tax'] ?? "",
						'token_code' => sanitize_text_field(wp_unslash($_POST['nonce'])),
						'payment_method' => $customer_payment_design,
						'appoint_status' => $default_booking_status
					),
				);
				$booked_id = $wpdb->insert_id;
				self::$bookingorDb->update(
					$customer_details,
					array(
						'book_get_id' => $booked_id,
					),
					array('customer_id' => !empty($get_customer_id) ? $get_customer_id : $customer_id)
				);

				$get_book_id = $booked_id;
				if ($customer_payment_design === 'on-visit') {
					self::$bookingorDb->insert(
						$customer_payment_data,
						array(
							'customer_get_id' => !empty($get_customer_id) ? $get_customer_id : $customer_id,
							'book_get_id' => $booked_id,
							'payment_method' => $customer_payment_design,
							'payment_status' => 'pending',
							'paid_amount' => '',
						),
					);
				}


				$customer_full_name = $customer_first_name . ' ' . $customer_last_name;
				$f_currency_symbol = get_option("bookingor_settings_country_currency");

				$customer_id = $wpdb->insert_id;
				$email_content_customer = self::$bookingorDb->get_row(
					self::$bookingorDb->prepare("SELECT 
						id, name_action, name, subject, text, send_to, 	type, paid_amount, tax_charges, coupon_id, book_date, 
						book_time, status FROM 
						%1\$s WHERE 
						name_action = '%2\$s' and type = 'email'", $notifications, $email_check)
				);


				$content_staff_only = self::$bookingorDb->get_row(
					self::$bookingorDb->prepare("SELECT 
					id, name_action, name, subject, text, send_to, 	type, paid_amount, tax_charges, coupon_id, book_date, 
					book_time, status FROM 
					%1\$s WHERE 
					name_action = '%2\$s' and type = 'email'", $notifications, $staff_email_check)
				);


				$categoryString = [];
				$serviceString = [];
				$staffString = [];
				$locationString = [];
				$customerString = [];
				$businessString = [];
				$bookedString = [];
				$bookingData = HelperControl::get_last_booking_data($booked_id);
				$get_currency = get_option('bookingor_settings_currency_symbol');
				$categoryString = $bookingData['categoryString'];
				$serviceString = $bookingData['serviceString'];
				$staffString = isset($bookingData['staffString']) ? $bookingData['staffString'] : '';
				$customerString = $bookingData['customerString'];
				$bookedString = $bookingData['bookedString'];
				$locationString = isset($bookingData['locationString']) ? $bookingData['locationString'] : "";
				$businessString = isset($bookingData['businessString']) ? $bookingData['businessString'] : "";
				if (!empty(get_option("bookingor_settings_email_type"))) {
					$subject_customer = EmailNotification::string_Placeholder_variable($categoryString, $serviceString, $staffString, $customerString, $bookedString, $locationString, $businessString, $email_content_customer->subject);
					$subject_staff = EmailNotification::string_Placeholder_variable($categoryString, $serviceString, $staffString, $customerString, $bookedString, $locationString, $businessString, $content_staff_only->subject);
					$body_customer = EmailNotification::string_Placeholder_variable(
						$categoryString,
						$serviceString,
						$staffString,
						$customerString,
						$bookedString,
						$locationString,
						$businessString,
						$email_content_customer->text
					);

					$body_staff = EmailNotification::string_Placeholder_variable(
						$categoryString,
						$serviceString,
						$staffString,
						$customerString,
						$bookedString,
						$locationString,
						$businessString,
						$content_staff_only->text
					);
					if (!empty(get_option("bookingor_settings_email_type"))) {
						EmailNotification::sendEmail($customer_email_address, $subject_customer, $body_customer);
						EmailNotification::sendEmail($js['get_staff_email'] ?? "", $subject_staff, $body_staff);
					}
				}


				$bookingData = HelperControl::get_last_booking_data($get_book_id);
			} else {
				self::$bookingorDb->insert(
					$booked_customer,
					array(
						'service_get_id' => $js['get_service_id'],
						'staff_get_id' => isset($js['get_staff_id']) ? $js['get_staff_id'] : null,
						'category_get_id' => isset($js['category_id']) ? $js['category_id'] : null,
						'location_get_id' => isset($js['location_get_id']) ? $js['location_get_id'] : null,
						'people_count' => $js['selected_max_capacity'] ?? "",
						'start_time' => HelperControl::convert12To24($js['get_start_time'] ?? ""),
						'end_time' => HelperControl::convert12To24($js['get_end_time'] ?? ""),
						'duration_service' => $js['service_duration'] ?? "",
						'picked_date' => $js['get_full_date'] ?? "",
						'picked_date_end' => !empty($js['get_end_date']) ? $js['get_end_date'] : date('Y-m-d', strtotime(($js['get_full_date'] ?? '') . ' ' . HelperControl::convert12To24($js['get_start_time'] ?? '') . ' + ' . ($js['service_duration'] ?? '') . ' minutes')),
						'extra_get_price' => isset($js['extra_total_price']) ? $js['extra_total_price'] : 0,
						'service_get_price' => $js['service_price'] ?? "",
						'tax_get_price' => $js['service_tax'] ?? "",
						'token_code' => sanitize_text_field(wp_unslash($_POST['nonce'])),
						'payment_method' => $customer_payment_design,
						'appoint_status' => $default_booking_status
					),
				);
				$booked_id = $wpdb->insert_id;
				self::$bookingorDb->insert(
					$customer_details,
					array(
						'book_get_id' => $booked_id,
						'customer_first_name' => $customer_first_name,
						'customer_last_name' => $customer_last_name,
						'customer_email' => $customer_email_address,
						'customer_phone' => $customer_phone,
					),
				);
				$customer_id = $wpdb->insert_id;
				self::$bookingorDb->update(
					$booked_customer,
					array(
						'customer_get_id' => $customer_id,
					),
					array('book_id' => $booked_id),
				);

				if ($customer_payment_design === 'on-visit') {
					self::$bookingorDb->insert(
						$customer_payment_data,
						array(
							'customer_get_id' => $customer_id,
							'book_get_id' => $booked_id,
							'payment_method' => $customer_payment_design,
							'payment_status' => 'pending',
							'paid_amount' => '',
						),
					);
				}

				$customer_full_name = $customer_first_name . ' ' . $customer_last_name;

				$id = $wpdb->insert_id;
				$email_content_customer = self::$bookingorDb->get_row(
					self::$bookingorDb->prepare("SELECT 
						id, name_action, name, subject, text, send_to, 	type, paid_amount, tax_charges, coupon_id, book_date, 
						book_time, status FROM 
						%1\$s WHERE 
						name_action = '%2\$s' and type = 'email'", $notifications, $email_check)
				);

				$email_content_staff = self::$bookingorDb->get_row(
					self::$bookingorDb->prepare("SELECT 
					id, name_action, name, subject, text, send_to, 	type, paid_amount, tax_charges, coupon_id, book_date, 
					book_time, status FROM 
					%1\$s WHERE 
					name_action = '%2\$s' and type = 'email'", $notifications, $staff_email_check)
				);





				$categoryString = [];
				$serviceString = [];
				$staffString = [];
				$locationString = [];
				$customerString = [];
				$businessString = [];
				$bookingString = [];
				$bookingData = HelperControl::get_last_booking_data($booked_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"))) {
					$subject_customer = EmailNotification::string_Placeholder_variable($categoryString, $serviceString, $staffString, $customerString, $bookedString, $locationString, $businessString, $email_content_customer->subject);
					$body_customer = EmailNotification::string_Placeholder_variable($categoryString, $serviceString, $staffString, $customerString, $bookedString, $locationString, $businessString, $email_content_customer->text);
					$subject_staff = EmailNotification::string_Placeholder_variable($categoryString, $serviceString, $staffString, $customerString, $bookedString, $locationString, $businessString, $email_content_staff->subject);
					$body_staff = EmailNotification::string_Placeholder_variable($categoryString, $serviceString, $staffString, $customerString, $bookedString, $locationString, $businessString, $email_content_staff->text);
					EmailNotification::sendEmail($customer_email_address, $subject_customer, $body_customer);
					EmailNotification::sendEmail($js['get_staff_email'] ?? "", $subject_staff, $body_staff);
				}
			}
		}
	}
}
