<?php

namespace Bookify\Controllers\REST;

use WP_Error;
use WP_REST_Response;

// don't call the file directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'Bookify_Settings_Rest_API' ) ) {

	class Bookify_Settings_Rest_API {

		public function __construct() {

			add_action( 'rest_api_init' , array( $this, 'rest_api_general_settings' ) );
		}

		public function rest_api_general_settings() {

			register_rest_route('bookify/v1', '/settings', array(
				'methods'               => 'GET',
				'callback'              => array( $this, 'rest_settings_data_callback' ),
				'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
			)); 

			register_rest_route('bookify/frontend/v1', '/payment-settings', array(
				'methods'               => 'GET',
				'callback'              => array( $this, 'rest_frontend_payment_settings_data_callback' ),
				'permission_callback'   => array( $this, 'frontend_nonce_verification' )
			)); 

			register_rest_route('bookify/frontend/v1', '/settings', array(
				'methods'               => 'GET',
				'callback'              => array( $this, 'rest_frontend_settings_data_callback' ),
				'permission_callback'   => array( $this, 'frontend_nonce_verification' )
			)); 

			register_rest_route('bookify/v1', '/save-general-settings', array(
				'methods'               => 'POST',
				'callback'              => array( $this, 'save_general_settings_callback' ),
				'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
			));

			register_rest_route('bookify/v1', '/save-company-details', array(
				'methods'               => 'POST',
				'callback'              => array( $this, 'save_company_details_callback' ),
				'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
			));

			register_rest_route('bookify/v1', '/save-payment-settings', array(
				'methods'               => 'POST',
				'callback'              => array( $this, 'save_payment_settings_callback' ),
				'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
			));

			// register_rest_route('bookify/v1', '/save-integration-settings', array(
			// 	'methods'               => 'POST',
			// 	'callback'              => array( $this, 'save_integration_settings_callback' ),
			// 	'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
			// ));

			register_rest_route('bookify/v1', '/save-notification-settings', array(
				'methods'               => 'POST',
				'callback'              => array( $this, 'save_notification_settings_callback' ),
				'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
			));
		}

		public function frontend_nonce_verification( $request ) {
			$nonce = $request->get_header('X-WP-Nonce'); 

			$referer = $request->get_header('referer');
			if ( $referer && ( strpos( $referer, '/wp-admin/' ) !== false || strpos( $referer, admin_url() ) !== false ) ) {
				return new WP_Error(
					'rest_forbidden',
					__('Not allowed in backend', 'bookify'),
					array( 
						'status' => 403,
						'message' => 'This endpoint is not accessible from the admin area.'
					)
				);
			}

			if ( !$nonce ) {
				return new WP_Error( 
					'rest_missing_nonce', 
					__('You do not have permission to access this resource. Please contact the administrator if you believe this is an error.', 'bookify'), 
					array( 
						'status' => 403, 
						'message' => 'Nonce is missing.' 
					) 
				);
			}

			return true;
		}

		public function verify_nonce_and_permissions( $request ) {
			$nonce = $request->get_header('X-WP-Nonce');
			$current_user = wp_get_current_user();
			
			if ( ! is_user_logged_in() ) {
				return new WP_Error( 'rest_forbidden', __('You are not logged in.', 'bookify'), array( 'status' => 401 ) );
			}

			if ( in_array( 'bookify-staff', (array) $current_user->roles ) || in_array( 'administrator', (array) $current_user->roles ) ) {
				return true;
			}

			return new WP_Error( 'rest_forbidden', __('You do not have permission to access this resource.', 'bookify'), array( 'status' => 403 ) );
		}

		public function rest_frontend_settings_data_callback() {
			$settings = array();

			$general_settings = get_option( 'bookify_general_settings' );
			$integration_settings 	= get_option( 'bookify_integration_settings' );
			
			$settings['general']['DefaultWeekStartOn'] = is_array( $general_settings ) && isset( $general_settings['DefaultWeekStartOn'] ) ? sanitize_text_field( $general_settings['DefaultWeekStartOn'] ) : 'Saturday';
			$settings['general']['DefaultPriorToBooking'] = is_array( $general_settings ) && isset( $general_settings['DefaultPriorToBooking'] ) ? sanitize_text_field( $general_settings['DefaultPriorToBooking'] ) : 'Disable';
			$settings['general']['PriorTimeToBooking'] = is_array( $general_settings ) && isset( $general_settings['PriorTimeToBooking'] ) ? sanitize_text_field( absint( $general_settings['PriorTimeToBooking'] ) ) : '3';
			$settings['general']['DefaultGeneralCurrencies'] = is_array( $general_settings ) && isset( $general_settings['DefaultGeneralCurrencies'] ) ? sanitize_text_field( $general_settings['DefaultGeneralCurrencies'] ) : 'USD';
			$settings['general']['DefaultTimeFormat'] = is_array( $general_settings ) && isset( $general_settings['DefaultTimeFormat'] ) ? sanitize_text_field( $general_settings['DefaultTimeFormat'] ) : false;
			$settings['general']['slotsTimezone'] = is_array( $general_settings ) && isset( $general_settings['slotsTimezone'] ) ? sanitize_text_field( $general_settings['slotsTimezone'] ) : false;
			$settings['general']['supportLinkText'] = is_array( $general_settings ) && isset( $general_settings['supportLinkText'] ) ? sanitize_text_field( $general_settings['supportLinkText'] ) : 'Need Help?';
			$settings['general']['supportLinkUrl'] = is_array( $general_settings ) && isset( $general_settings['supportLinkUrl'] ) ? sanitize_text_field( $general_settings['supportLinkUrl'] ) : '';
			$settings['general']['showFormSupportLink'] = is_array( $general_settings ) && isset( $general_settings['showFormSupportLink'] ) ? sanitize_text_field( filter_var( $general_settings['showFormSupportLink'], FILTER_VALIDATE_BOOLEAN ) ) : false;
			$settings['integration']['gcalForCustomer'] = is_array( $integration_settings ) && isset( $integration_settings['GoogleSettings']['toggleForCustomer'] ) ? $integration_settings['GoogleSettings']['toggleForCustomer'] : false;
			$settings['integration']['ocalForCustomer'] = is_array( $integration_settings ) && isset( $integration_settings['OutlookSettings']['toggleForCustomer'] ) ? $integration_settings['OutlookSettings']['toggleForCustomer'] : false;
			$settings['integration']['ZoomToggle'] = is_array( $integration_settings ) && isset( $integration_settings['ZoomSettings']['toggleZoom'] ) ? $integration_settings['ZoomSettings']['toggleZoom'] : false;
			
			return $settings;
		}

		public function rest_frontend_payment_settings_data_callback() {
			$settings = array();

			$default_val = array(
				'onsite' => array(
					'toggled' => true,
				),
				'paypal' => array(
					'toggled' => false,
					'clientId' => '',
				),
				'stripe' => array(
					'toggled' => false,
					'publishableKey' => '',
				),
			);

			$payment_settings = get_option( 'bookify_payment_settings' );

			$settings['payment'] = isset( $payment_settings ) && ! empty( $payment_settings ) ? json_decode( sanitize_text_field(  $payment_settings ), true ) : $default_val;

			if ( isset( $settings['payment']['paypal']['secretKey'] ) ) {
				unset( $settings['payment']['paypal']['secretKey'] );
			}
			if ( isset( $settings['payment']['stripe']['secretKey'] ) ) {
				unset( $settings['payment']['stripe']['secretKey'] );
			}

			return $settings;
		}

		public function rest_settings_data_callback() {

			$settings = array();
			$settings['general'] = get_option( 'bookify_general_settings' );
			$settings['company'] = get_option( 'bookify_company_details' );
			$settings['payment'] = get_option( 'bookify_payment_settings' );
			$settings['integration'] = get_option( 'bookify_integration_settings' );
			$settings['notification'] = get_option( 'bookify_notification_settings' );

			return $settings;
		}

		public function save_general_settings_callback( $request ) {

			$nonce = $request->get_header('X-WP-Nonce');
			if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
				return new WP_Error( 'rest_forbidden', __('Invalid nonce.', 'bookify'), array( 'status' => 403 ) );
			}

			$params = $request->get_json_params();

			$prev_multi_booking = get_option( 'bookify_prev_multi_booking', false );
			$bookify_general_settings = array();

			$bookify_general_settings['DefaultGlobalSlotTimeDuration'] = isset( $params['DefaultGlobalSlotTimeDuration'] ) && ! empty( $params['DefaultGlobalSlotTimeDuration'] ) ? sanitize_text_field( $params['DefaultGlobalSlotTimeDuration'] ) : '30';
			$bookify_general_settings['DefaultGlobalSlotTimeInterval'] = isset( $params['DefaultGlobalSlotTimeInterval'] ) && ! empty( $params['DefaultGlobalSlotTimeInterval'] ) ? sanitize_text_field( $params['DefaultGlobalSlotTimeInterval'] ) : '15';
			$bookify_general_settings['DefaultWeekStartOn'] = isset( $params['DefaultWeekStartOn'] ) && ! empty( $params['DefaultWeekStartOn'] ) ? sanitize_text_field( $params['DefaultWeekStartOn'] ) : 'Saturday';
			$bookify_general_settings['DefaultAppointmentStatus'] = isset( $params['DefaultAppointmentStatus'] ) && ! empty( $params['DefaultAppointmentStatus'] ) ? sanitize_text_field( $params['DefaultAppointmentStatus'] ) : 'Pending';
			$bookify_general_settings['DefaultTimeFormat'] = isset( $params['DefaultTimeFormat'] ) && ! empty( $params['DefaultTimeFormat'] ) ? sanitize_text_field( $params['DefaultTimeFormat'] ) : '12-hour';
			$bookify_general_settings['DefaultDateFormat'] = isset( $params['DefaultDateFormat'] ) && ! empty( $params['DefaultDateFormat'] ) ? sanitize_text_field( $params['DefaultDateFormat'] ) : 'DD/MM/YY';
			$bookify_general_settings['DefaultGeneralCurrencies'] = isset( $params['DefaultGeneralCurrencies'] ) && ! empty( $params['DefaultGeneralCurrencies'] ) ? sanitize_text_field( $params['DefaultGeneralCurrencies'] ) : 'USD';
			$bookify_general_settings['DefaultPriorToBooking'] = isset( $params['DefaultPriorToBooking'] ) && ! empty( $params['DefaultPriorToBooking'] ) ? sanitize_text_field( $params['DefaultPriorToBooking'] ) : 'Disable';
			$bookify_general_settings['PriorTimeToBooking'] = isset( $params['PriorTimeToBooking'] ) && ! empty( $params['PriorTimeToBooking'] ) ? sanitize_text_field( absint( $params['PriorTimeToBooking'] ) ) : '3';
			$bookify_general_settings['MaxBookingsPerEmailPerDay'] = isset( $params['MaxBookingsPerEmailPerDay'] ) && ! empty( $params['MaxBookingsPerEmailPerDay'] ) ? sanitize_text_field( absint( $params['MaxBookingsPerEmailPerDay'] ) ) : '5';
			$bookify_general_settings['usersCanBook'] = isset( $params['usersCanBook'] ) && ! empty( $params['usersCanBook'] ) ? sanitize_text_field( $params['usersCanBook'] ) : 'registerAfterBook';
			$bookify_general_settings['supportLinkText'] = isset( $params['supportLinkText'] ) && ! empty( $params['supportLinkText'] ) ? sanitize_text_field( $params['supportLinkText'] ) : 'Need Help?';
			$bookify_general_settings['supportLinkUrl'] = isset( $params['supportLinkUrl'] ) && ! empty( $params['supportLinkUrl'] ) ? sanitize_text_field( $params['supportLinkUrl'] ) : '';
			$bookify_general_settings['showFormSupportLink'] = isset( $params['showFormSupportLink'] ) && ! empty( $params['showFormSupportLink'] ) ? sanitize_text_field( $params['showFormSupportLink'] ) : false;
			$bookify_general_settings['deleteDataWhenUnistall'] = isset( $params['deleteDataWhenUnistall'] ) && ! empty( $params['deleteDataWhenUnistall'] ) ? sanitize_text_field( $params['deleteDataWhenUnistall'] ) : false;

			if ( class_exists('\BookifyPro\Bookify_Pro_Main') && defined( 'BOOKIFY_PRO_LICENCE_ACTIVATED' ) == true ) {
				$multiple_booking_value = isset( $params['multipleBooking'] ) ? $params['multipleBooking'] : false;
				$bookify_general_settings['multipleBooking'] = ( $multiple_booking_value === 'true' || $multiple_booking_value === true ) ? 'true' : 'false';
				$bookify_general_settings['slotsTimezone'] = isset( $params['slotsTimezone'] ) && ! empty( $params['slotsTimezone'] ) ? sanitize_text_field( $params['slotsTimezone'] ) : false;

				update_option( 'bookify_prev_multi_booking', $bookify_general_settings['multipleBooking'] );
				
				if ( $prev_multi_booking != $bookify_general_settings['multipleBooking'] ) {
					
					$args = array(
						'role'    => 'bookify-staff',
						'number'  => -1
					);
					$users = get_users( $args );
					
					if ( $users ) {
						foreach ( $users as $user ) {
							update_user_meta( $user->ID, 'bookify_staff_mutiple_booking', $bookify_general_settings['multipleBooking'] );
						}
					}
				}
			}
		
			$result = update_option( 'bookify_general_settings', $bookify_general_settings );

			if ( $result ) {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'General settings has been saved successfully!'
				), 200);
			} else {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'No changes have been made to the form.'
				), 200);
			}
		}

		public function save_company_details_callback( $request ) {

			$nonce = $request->get_header('X-WP-Nonce');
			if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
				return new WP_Error( 'rest_forbidden', __('Invalid nonce.', 'bookify'), array( 'status' => 403 ) );
			}

			$params = $request->get_json_params();

			$bookify_company_details = array();

			$bookify_company_details['companyName'] = isset( $params['companyName'] ) && ! empty( $params['companyName'] ) ? sanitize_text_field( $params['companyName'] ) : '';
			$bookify_company_details['address'] = isset( $params['address'] ) && ! empty( $params['address'] ) ? sanitize_text_field( $params['address'] ) : '';
			$bookify_company_details['phoneNumber'] = isset( $params['phoneNumber'] ) && ! empty( $params['phoneNumber'] ) ? sanitize_text_field( $params['phoneNumber'] ) : '';
			$bookify_company_details['website'] = isset( $params['website'] ) && ! empty( $params['website'] ) ? sanitize_text_field( $params['website'] ) : '';
			$bookify_company_details['image'] = isset( $params['image'] ) && ! empty( $params['image'] ) ? sanitize_text_field( $params['image'] ) : '';

			$result = update_option( 'bookify_company_details', $bookify_company_details );

			if ( $result ) {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'Company details has been saved successfully!'
				), 200);
			} else {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'No changes have been made to the form.'
				), 200);
			}
		}

		public function save_payment_settings_callback( $request ) {

			$nonce = $request->get_header('X-WP-Nonce');
			if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
				return new WP_Error( 'rest_forbidden', __('Invalid nonce.', 'bookify'), array( 'status' => 403 ) );
			}

			$params = $request->get_json_params();

			$bookify_payment_settings = array();
			$bookify_payment_settings = isset( $params['payment_gateways'] ) && ! empty( $params['payment_gateways'] ) ? sanitize_text_field( stripslashes( $params['payment_gateways'] ) ) : '';
			
			
			$result = update_option( 'bookify_payment_settings', $bookify_payment_settings );

			if ( $result ) {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'Payment settings has been saved successfully!'
				), 200);
			} else {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'No changes have been made to the form.'
				), 200);
			}
		}

		public function save_integration_settings_callback( $request ) {

			$nonce = $request->get_header('X-WP-Nonce');
			if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
				return new WP_Error( 'rest_forbidden', __('Invalid nonce.', 'bookify'), array( 'status' => 403 ) );
			}

			$params = $request->get_json_params();

			$bookify_integration_settings = array();

			$bookify_integration_settings['GoogleClientID'] = isset( $params['GoogleClientID'] ) && ! empty( $params['GoogleClientID'] ) ? sanitize_text_field( $params['GoogleClientID'] ) : '';
			$bookify_integration_settings['GoogleClientSecret'] = isset( $params['GoogleClientSecret'] ) && ! empty( $params['GoogleClientSecret'] ) ? sanitize_text_field( $params['GoogleClientSecret'] ) : '';
			
			$result = update_option( 'bookify_integration_settings', $bookify_integration_settings );

			if ( $result ) {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'Integration settings has been saved successfully!'
				), 200);
			} else {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'No changes have been made to the form.'
				), 200);
			}
		}

		public function save_notification_settings_callback( $request ) {

			$nonce = $request->get_header('X-WP-Nonce');
			if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
				return new WP_Error( 'rest_forbidden', __('Invalid nonce.', 'bookify'), array( 'status' => 403 ) );
			}

			$params = $request->get_json_params();

			$bookify_notification_settings = array();

			$bookify_notification_settings['senderName'] = isset( $params['senderName'] ) && ! empty( $params['senderName'] ) ? sanitize_text_field( $params['senderName'] ) : '';
			$bookify_notification_settings['senderEmail'] = isset( $params['senderEmail'] ) && ! empty( $params['senderEmail'] ) ? sanitize_text_field( $params['senderEmail'] ) : '';
			
			$result = update_option( 'bookify_notification_settings', $bookify_notification_settings );

			if ( $result ) {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'Notification settings has been saved successfully!'
				), 200);
			} else {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'No changes have been made to the form.'
				), 200);
			}
		}
	}

	new Bookify_Settings_Rest_API();

}
