<?php

namespace Bookify\Controllers\REST;

use WP_Error;
use WP_REST_Response;
use Bookify\Models\Bookify_Notification_Models;

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

if ( ! class_exists( 'Bookify_Notification_Rest_API' ) ) {

	class Bookify_Notification_Rest_API {

		public function __construct() {

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

		public function rest_api_notification() {

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

			register_rest_route('bookify/v1', '/add-notification', array(
				'methods'               => 'POST',
				'callback'              => array( $this, 'rest_add_notification_callback' ),
				'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
			)); 

			register_rest_route('bookify/v1', '/update-notification', array(
				'methods'               => 'POST',
				'callback'              => array( $this, 'rest_update_notification_callback' ),
				'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
			));

			register_rest_route('bookify/v1', '/update-notification-state', array(
				'methods'               => 'POST',
				'callback'              => array( $this, 'rest_update_notification_state_callback' ),
				'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
			));

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

		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_notification_data_callback( $request ) {
			$page = $request->get_param('page');
			$pageSize = $request->get_param('pageSize');
			$search = $request->get_param('search');

			$notification_data = Bookify_Notification_Models::bookify_get_all_notifications();

			foreach ( $notification_data as $key => $value ) {
				$notification_data[ $key ]['email_sends_to'] = json_decode( $value['email_sends_to'] );
				$notification_data[ $key ]['notification_toggle'] = $value['notification_toggle'] == 1 ? true : false;
			}

			if ( ! empty( $search ) ) {
				$notification_data = array_filter( $notification_data, function ( $notification ) use ( $search ) {
					$search_lower = strtolower( $search );
					return (
						strpos( strtolower( $notification['notification_name'] ), $search_lower ) !== false ||
						strpos( strtolower( $notification['notification_event'] ), $search_lower ) !== false
					);
				});
			}

			$startIndex = ( $page - 1 ) * $pageSize;

			$paginatedData = array_slice($notification_data, $startIndex, $pageSize);

			return new WP_REST_Response(array(
				'notificationData' => $paginatedData,
				'total' => count($notification_data),
			), 200);
		}

		public function rest_add_notification_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();

			$notificationName = isset( $params['notificationName'] ) && ! empty( $params['notificationName'] ) ? sanitize_text_field( $params['notificationName'] ) : '';
			$notificationToggle = isset( $params['notificationToggle'] ) && ! empty( $params['notificationToggle'] ) ? sanitize_text_field( $params['notificationToggle'] ) : true;
			$notificationEvent = isset( $params['notificationEvent'] ) && ! empty( $params['notificationEvent'] ) ? sanitize_text_field( $params['notificationEvent'] ) : 'Appointment Requested';
			$emailSubject = isset( $params['emailSubject'] ) && ! empty( $params['emailSubject'] ) ? sanitize_text_field( $params['emailSubject'] ) : '';
			$emailBody = isset( $params['emailBody'] ) && ! empty( $params['emailBody'] ) ? wp_kses_post( $params['emailBody'] ) : '';
			$emailToAdmin = isset( $params['emailToAdmin'] ) && ! empty( $params['emailToAdmin'] ) ? rest_sanitize_boolean( $params['emailToAdmin'] ) : true;
			$emailToStaff = isset( $params['emailToStaff'] ) && ! empty( $params['emailToStaff'] ) ? rest_sanitize_boolean( $params['emailToStaff'] ) : false;
			$emailToCustomer = isset( $params['emailToCustomer'] ) && ! empty( $params['emailToCustomer'] ) ? rest_sanitize_boolean( $params['emailToCustomer'] ) : false;

			$email_sends_to = json_encode( array(
				'admin' => $emailToAdmin ? "true" : "false",
				'staff' => $emailToStaff ? "true" : "false",
				'customer' => $emailToCustomer ? "true" : "false"
			), true );

			if ( ! $notificationName || ! $emailSubject || ! $emailBody ) {
				return new WP_REST_Response(array(
					'success' => false,
					'message' => 'Please Fill the required fields!'
				), 200);
			}

			$notification_data = array(
				'notification_name' => $notificationName,
				'notification_event' => $notificationEvent,
				'notification_toggle' => $notificationToggle ? 1 : 0,
				'notification_email_subject' => $emailSubject,
				'notification_email_body' => $emailBody,
				'email_sends_to' =>  $email_sends_to
			);

			$notification_id = Bookify_Notification_Models::bookify_add_notification( $notification_data );
			
			if ( $notification_id ) {
				return new WP_REST_Response(array(
					'success' => true,
					'message' => 'Notification has been saved successfully!'
				), 200);
			} else {
				return new WP_REST_Response(array(
					'success' => false,
					'message' => 'Error while adding notification!'
				), 200);
			}
		}

		public function rest_update_notification_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();

			$notification_id = isset( $params['notification_id'] ) && ! empty( $params['notification_id'] ) ? sanitize_text_field( $params['notification_id'] ) : '';
			$notificationName = isset( $params['notificationName'] ) && ! empty( $params['notificationName'] ) ? sanitize_text_field( $params['notificationName'] ) : '';
			$notificationEvent = isset( $params['notificationEvent'] ) && ! empty( $params['notificationEvent'] ) ? sanitize_text_field( $params['notificationEvent'] ) : 'Appointment Requested';
			$emailSubject = isset( $params['emailSubject'] ) && ! empty( $params['emailSubject'] ) ? sanitize_text_field( $params['emailSubject'] ) : '';
			$emailBody = isset( $params['emailBody'] ) && ! empty( $params['emailBody'] ) ? wp_kses_post( $params['emailBody'] ) : '';
			$emailToAdmin = isset( $params['emailToAdmin'] ) && ! empty( $params['emailToAdmin'] ) ? rest_sanitize_boolean( $params['emailToAdmin'] ) : true;
			$emailToStaff = isset( $params['emailToStaff'] ) && ! empty( $params['emailToStaff'] ) ? rest_sanitize_boolean( $params['emailToStaff'] ) : false;
			$emailToCustomer = isset( $params['emailToCustomer'] ) && ! empty( $params['emailToCustomer'] ) ? rest_sanitize_boolean( $params['emailToCustomer'] ) : false;

			$email_sends_to = json_encode( array(
				'admin' => $emailToAdmin ? "true" : "false",
				'staff' => $emailToStaff ? "true" : "false",
				'customer' => $emailToCustomer ? "true" : "false"
			), true );

			if ( ! $notification_id || ! $notificationName || ! $emailSubject || ! $emailBody ) {
				return new WP_REST_Response(array(
					'success' => false,
					'message' => 'Please Fill the required fields!'
				), 200);
			}

			$notification_data = array( 
				'notification_name' => $notificationName,
				'notification_event' => $notificationEvent,
				'notification_email_subject' => $emailSubject,
				'notification_email_body' => $emailBody,
				'email_sends_to'    =>  $email_sends_to
			);

			$result = Bookify_Notification_Models::bookify_update_notification( $notification_id, $notification_data );
			
			if ( $result ) {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'Notification has been updated successfully!'
				), 200);
			} else {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'Error while updating notification!'
				), 200);
			}
		}

		public function rest_update_notification_state_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();

			$notification_id = isset( $params['notification_id'] ) && ! empty( $params['notification_id'] ) ? sanitize_text_field( $params['notification_id'] ) : '';
			$notificationState = isset( $params['notificationState'] ) ? sanitize_text_field( $params['notificationState'] ) : true;

			$notification_data = array( 
				'notification_toggle' => $notificationState ? 1 : 0,
			);

			$result = Bookify_Notification_Models::bookify_update_notification_state( $notification_id, $notification_data );
			
			if ( $result ) {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'Notification has been updated successfully!'
				), 200);
			} else {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'Error while updating notification!'
				), 200);
			}
		}

		public function rest_delete_notification_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();

			$notification_id = isset( $params['notification_id'] ) && ! empty( $params['notification_id'] ) ? sanitize_text_field( $params['notification_id'] ) : '';

			if ( ! $notification_id ) {
				return new WP_REST_Response(array(
					'success' => false,
					'message' => 'No notification id is selected for deleting!',
				), 200);
			}

			$result = Bookify_Notification_Models::bookify_delete_notification( $notification_id );

			if ( $result ) {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'Notification has been deleted successfully!'
				), 200);
			} else {
				return new WP_REST_Response(array(
					'success' => $result,
					'message' => 'Error while deleitng notification!'
				), 200);
			}
		}
	}

	new Bookify_Notification_Rest_API();

}
