<?php
/**
 * FE Admin Event Scan Keys controller.
 *
 * @since 1.0
 * @since 1.4 Event authorization restriction
 */

declare( strict_types=1 );
namespace FeData\FastEvents\RestAPI\Public;

defined( 'ABSPATH' ) || exit;

use FeData\FastEvents\Helpers\AuthHelper;
use FeData\FastEvents\Utilities\JsonUtil;
use FeData\FastEvents\Utilities\UniqIds;
use FeData\FastEvents\Utilities\WebhookUtil;
use stdClass;
use WP_Error;
use WP_REST_Controller;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

/**
 * FE Admin Scan Keys class.
 */
class ScanKeysController extends WP_REST_Controller {

	/**
	 * Are webhooks needed?
	 *
	 * @since 1.0
	 *
	 * @var bool
	 */
	private bool $webhooks_needed;

	/**
	 * Available tickets.
	 *
	 * @since 1.0
	 *
	 * @var array
	 */
	private array $tickets = array();

	/**
	 * Event id.
	 *
	 * @since 1.0
	 *
	 * @var int
	 */
	private int $event_id;

	/**
	 * Admin Scan Keys constructor.
	 *
	 * @param AuthHelper $auth The auth helper instance.
	 *
	 * @since 1.0
	 */
	public function __construct( private readonly AuthHelper $auth ) {
		$this->namespace = 'fast-events/v1';
		$this->rest_base = 'admin/events';
	}


	/**
	 * Register the routes for the objects of the controller.
	 *
	 * @since 1.0
	 * @since 2.0 Refactored for a new permission system
	 */
	public function register_routes(): void {

		// Get scan keys.
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<id>[\d]+)/scan-keys',
			array(
				'args'   => array(
					'id' => array(
						'description'       => __( 'The unique id of the event', 'fast-events' ),
						'type'              => 'integer',
						'required'          => true,
						'sanitize_callback' => 'absint',
					),
				),
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_items' ),
					'permission_callback' => function () {
						return $this->fast_events_admin_permissions( $this->auth::SCAN_APP_READ );
					},
					'args'                => $this->get_collection_params(),
				),
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'create_item' ),
					'permission_callback' => function () {
						return $this->fast_events_admin_permissions( $this->auth::SCAN_APP_CHANGE );
					},
					'args'                => $this->get_endpoint_args_for_item_schema(),
				),
				'schema' => array( $this, 'get_public_item_schema' ),
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<id>[\d]+)/scan-keys/(?P<scan_key>[\w]{16})',
			array(
				'args'   => array(
					'id'       => array(
						'description'       => __( 'The unique id of the event', 'fast-events' ),
						'type'              => 'integer',
						'required'          => true,
						'sanitize_callback' => 'absint',
					),
					'scan_key' => array(
						'description'       => __( 'The unique id of the scan key', 'fast-events' ),
						'type'              => 'string',
						'required'          => true,
						'sanitize_callback' => 'sanitize_text_field',
					),
				),
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_item' ),
					'permission_callback' => function () {
						return $this->fast_events_admin_permissions( $this->auth::SCAN_APP_READ );
					},
					'args'                => array(
						'context' => $this->get_context_param( array( 'default' => 'view' ) ),
					),
				),
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_item' ),
					'permission_callback' => function () {
						return $this->fast_events_admin_permissions( $this->auth::SCAN_APP_CHANGE );
					},
					'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
				),
				array(
					'methods'             => WP_REST_Server::DELETABLE,
					'callback'            => array( $this, 'delete_item' ),
					'permission_callback' => function () {
						return $this->fast_events_admin_permissions( $this->auth::SCAN_APP_CHANGE );
					},
				),
				'schema' => array( $this, 'get_public_item_schema' ),
			)
		);
	}


	/**
	 * Get the authorization for the Events Scan Keys endpoints.
	 *
	 * @param int $action The action on the controller.
	 * @return WP_Error|bool
	 *
	 * @since 1.0
	 * @since 2.0 Refactored for a new permission system
	 */
	public function fast_events_admin_permissions( int $action ): WP_Error|bool {
		return $this->auth->authorize( $action );
	}


	/**
	 * Get all scan keys of the event.
	 *
	 * @param WP_REST_Request $request Request instance.
	 * @return WP_REST_Response|WP_Error|array
	 *
	 * @since 1.0
	 */
	public function get_items( $request ): WP_Error|WP_REST_Response|array {

		$result = $this->get_event_data( $request );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		$scan_keys = array();

		foreach ( $result as $scan_key ) {
			$data        = $this->prepare_item_for_response( $scan_key, $request );
			$scan_keys[] = $this->prepare_response_for_collection( $data );
		}

		$response = rest_ensure_response( $scan_keys );

		// Generate the totals headers.
		$response->header( 'X-WP-Total', count( $scan_keys ) );
		$response->header( 'X-WP-TotalPages', 1 );

		return $response;
	}


	/**
	 * Retrieve scan-keys.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return array|WP_Error Response object on success, or WP_Error object on failure.
	 *
	 * @since 1.0
	 * @since 1.4 Event authorization restriction
	 */
	private function get_event_data( WP_REST_Request $request ): WP_Error|array {
		global $wpdb;

		// Check the event authorization.
		$resp = $this->auth->check_event_authorization( $request['id'] );
		if ( is_wp_error( $resp ) ) {
			return $resp;
		}

		// Look up the event.
		$event = $wpdb->get_row( $wpdb->prepare( "SELECT id, input_fields, scan_keys, webhooks_needed FROM {$wpdb->prefix}fe_events WHERE id = %d", $request['id'] ) );
		if ( empty( $event ) ) {
			return new WP_Error( 'not_found', __( 'Event not found', 'fast-events' ), array( 'status' => 404 ) );
		}

		// Get the ticket types.
		$fields = json_decode( $event->input_fields );
		if ( null !== $fields && isset( $fields->tickets ) ) {
			foreach ( $fields->tickets as $ticket ) {
				$this->tickets[] = $ticket->name;
			}
		}

		// Set private vars.
		$this->event_id        = (int) $event->id;
		$this->webhooks_needed = 1 === (int) $event->webhooks_needed;

		// Add all keys to the structure.
		$scan_keys = array();
		$json      = json_decode( $event->scan_keys );
		if ( null !== $event->scan_keys ) {
			if ( null !== $json ) {
				foreach ( $json as $key => $value ) {
					$tmp['key']         = $key;
					$tmp['level']       = $value->entry;
					$tmp['tickets']     = $value->tickets;
					$tmp['date_format'] = $value->date_format;
					$tmp['location']    = $value->location;
					$scan_keys[]        = $tmp;
				}
			}
		}

		return $scan_keys;
	}


	/**
	 * Retrieve a single scan_key.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_REST_Response|WP_Error|array Response object on success, or WP_Error object on failure.
	 *
	 * @since 1.0
	 */
	public function get_item( $request ): WP_Error|WP_REST_Response|array {

		// Look up the scan keys.
		$result = $this->get_event_data( $request );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		// Does this key exist?
		$key = array_search( $request['scan_key'], array_column( $result, 'key' ), true );
		if ( false === $key ) {
			return new WP_Error( 'not_found', __( 'Scan key not found', 'fast-events' ), array( 'status' => 404 ) );
		}

		return rest_ensure_response( $this->prepare_item_for_response( $result[ $key ], $request ) );
	}


	/**
	 * Create a new scan_key.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_REST_Response|WP_Error|bool|array|string Response object on success, or WP_Error object on failure.
	 *
	 * @since 1.0
	 */
	public function create_item( $request ): WP_Error|WP_REST_Response|bool|array|string {

		// Look up the scan keys.
		$result = $this->get_event_data( $request );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		$new_scan = array();

		// Is a key provided?
		if ( isset( $request['key'] ) ) {
			$new_key = sanitize_text_field( $request['key'] );
			if ( in_array( $new_key, array_column( $result, 'key' ), true ) ) {
				return new WP_Error( 'invalid_key', __( 'Scan key already exists', 'fast-events' ), array( 'status' => 400 ) );
			}
			$new_scan['key'] = $new_key;
		} else {
			$new_scan['key'] = UniqIds::uniq_id();
		}

		// Are there tickets set?
		if ( isset( $request['tickets'] ) ) {
			$resp = $this->sanitize_tickets( $request['tickets'] );
			if ( is_wp_error( $resp ) ) {
				return $resp;
			}
			$new_scan['tickets'] = $resp;
		} else {
			$new_scan['tickets'] = '';
		}

		// Is the level set??
		if ( isset( $request['level'] ) ) {
			$new_scan['level'] = $request['level'];
		} else {
			$new_scan['level'] = 0;
		}

		// Is the location set?
		if ( isset( $request['location'] ) ) {
			$location = trim( sanitize_text_field( $request['location'] ) );
			if ( in_array( $location, array_column( $result, 'location' ), true ) ) {
				return new WP_Error( 'duplicates_found', __( 'Duplicate location is not allowed', 'fast-events' ), array( 'status' => 400 ) );
			}
			$new_scan['location'] = $location;
		} else {
			$new_scan['location'] = $new_scan['key'];
		}

		// Is the date format set?
		if ( isset( $request['date_format'] ) ) {
			$new_scan['date_format'] = trim( sanitize_text_field( $request['date_format'] ) );
		} else {
			$new_scan['date_format'] = 'l, j F H:i:s';
		}

		// Update event.
		$result[] = $new_scan;
		$resp     = $this->update_event_data( $result );
		if ( is_wp_error( $resp ) ) {
			return $resp;
		}

		$request->set_param( 'context', 'view' );

		return rest_ensure_response( $this->prepare_item_for_response( $new_scan, $request ) );
	}


	/**
	 * Update a single scan_key.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_REST_Response|WP_Error|bool|array|string Response object on success, or WP_Error object on failure.
	 *
	 * @since 1.0
	 * @since 1.6 Allow location change
	 */
	public function update_item( $request ): WP_Error|WP_REST_Response|bool|array|string {

		// Look up the scan keys.
		$result = $this->get_event_data( $request );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		// Does this key exist?
		$key = array_search( $request['scan_key'], array_column( $result, 'key' ), true );
		if ( false === $key ) {
			return new WP_Error( 'not_found', __( 'Scan key not found', 'fast-events' ), array( 'status' => 404 ) );
		}

		// Did the key change?
		if ( isset( $request['key'] ) ) {
			$new_key = sanitize_text_field( $request['key'] );
			if ( in_array( $new_key, array_column( $result, 'key' ), true ) && $new_key !== $result[ $key ]['key'] ) {
				return new WP_Error( 'invalid_key', __( 'Scan key already exists', 'fast-events' ), array( 'status' => 400 ) );
			}
			$result[ $key ]['key'] = $new_key;
		}

		// Did the tickets change?
		if ( isset( $request['tickets'] ) ) {
			$resp = $this->sanitize_tickets( $request['tickets'] );
			if ( is_wp_error( $resp ) ) {
				return $resp;
			}
			$result[ $key ]['tickets'] = $resp;
		}

		// Did the level change?
		if ( isset( $request['level'] ) ) {
			$result[ $key ]['level'] = $request['level'];
		}

		// Did the location change?
		if ( isset( $request['location'] ) ) {
			$location = trim( sanitize_text_field( $request['location'] ) );
			$l_index  = array_search( $location, array_column( $result, 'location' ), true );
			$k_index  = array_search( $request['scan_key'], array_column( $result, 'key' ), true );
			if ( false !== $l_index && $l_index !== $k_index ) {
				return new WP_Error( 'duplicates_found', __( 'Duplicate location is not allowed', 'fast-events' ), array( 'status' => 400 ) );
			}
			$result[ $key ]['location'] = $location;
		}

		// Did the date format change?
		if ( isset( $request['date_format'] ) ) {
			$result[ $key ]['date_format'] = trim( sanitize_text_field( $request['date_format'] ) );
		}

		// Update event.
		$resp = $this->update_event_data( $result );
		if ( is_wp_error( $resp ) ) {
			return $resp;
		}

		$request->set_param( 'context', 'edit' );

		return rest_ensure_response( $this->prepare_item_for_response( $result[ $key ], $request ) );
	}


	/**
	 * Sanitize new ticket string.
	 *
	 * @param string $tickets Comma separated string of tickets.
	 * @return string|WP_Error Sanitized string of tickets, or WP_Error object on failure.
	 *
	 * @since 1.0
	 */
	private function sanitize_tickets( string $tickets ): WP_Error|string {
		$str = sanitize_text_field( $tickets );
		if ( ! empty( $str ) ) {
			$tmp          = array();
			$scan_tickets = explode( ',', $str );
			foreach ( $scan_tickets as $scan_ticket ) {
				$find_ticket = trim( $scan_ticket );
				if ( ! empty( $find_ticket ) ) {
					if ( ! in_array( $find_ticket, $this->tickets, true ) ) {
						return new WP_Error( 'failed', __( 'Scaninfo: ticket does not exists: ', 'fast-events' ) . $find_ticket, array( 'status' => 400 ) );
					}
					$tmp[] = $find_ticket;
				}
			}
			$result = array_unique( $tmp );
			$str    = implode( ',', $result );
		}

		return $str;
	}


	/**
	 * Delete a single scan_key.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_REST_Response|WP_Error|bool|array Response object on success, or WP_Error object on failure.
	 *
	 * @since 1.0
	 */
	public function delete_item( $request ): WP_Error|WP_REST_Response|bool|array {

		// Look up the scan keys.
		$result = $this->get_event_data( $request );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		// Does this key exist?
		$key = array_search( $request['scan_key'], array_column( $result, 'key' ), true );
		if ( false === $key ) {
			return new WP_Error( 'not_found', __( 'Scan key not found', 'fast-events' ), array( 'status' => 404 ) );
		}
		$old_data = $result[ $key ];

		// Delete the key and update event.
		unset( $result[ $key ] );
		$resp = $this->update_event_data( $result );
		if ( is_wp_error( $resp ) ) {
			return $resp;
		}

		$request->set_param( 'context', 'edit' );

		$previous = $this->prepare_item_for_response( $old_data, $request );

		$response = new WP_REST_Response();
		$response->set_data(
			array(
				'deleted'  => true,
				'previous' => $previous->get_data(),
			)
		);

		return $response;
	}


	/**
	 * Update event data.
	 *
	 * @param array $scan_keys Array of scan keys.
	 * @return bool|WP_Error True, or WP_Error object on failure.
	 *
	 * @since 1.0
	 * @since 2.3.0 Use fast_events_json_encode.
	 */
	private function update_event_data( array $scan_keys ): WP_Error|bool {
		global $wpdb;

		// Create the scan_keys DB field.
		$db_field = new stdClass();
		foreach ( $scan_keys as $scan_key ) {
			$key                           = $scan_key['key'];
			$db_field->{$key}              = new stdClass();
			$db_field->{$key}->tickets     = $scan_key['tickets'];
			$db_field->{$key}->entry       = $scan_key['level'];
			$db_field->{$key}->location    = $scan_key['location'];
			$db_field->{$key}->date_format = $scan_key['date_format'];
		}

		// Update event.
		$event_table = $wpdb->prefix . 'fe_events';
		$result      = $wpdb->update( $event_table, array( 'scan_keys' => JsonUtil::fast_events_json_encode( $db_field ) ), array( 'id' => $this->event_id ) );

		// Analyse the update.
		if ( false === $result ) {
			return new WP_Error( 'failed', __( 'Scan keys update failed: ', 'fast-events' ) . $wpdb->last_error, array( 'status' => 400 ) );
		}
		if ( 0 === $result ) {
			return new WP_Error( 'nothing_to_update', __( 'Scan keys update: nothing to update', 'fast-events' ), array( 'status' => 400 ) );
		}

		// Fire webhooks if needed.
		if ( true === $this->webhooks_needed ) {
			WebhookUtil::create_webhook( 'event.updated', $this->event_id );
		}

		return true;
	}


	/**
	 * Retrieves the query params for the collections.
	 *
	 * @return array Query parameters for the collection.
	 *
	 * @since 2.0
	 */
	public function get_collection_params(): array {
		return array(
			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
		);
	}


	/**
	 * Prepares a single scan_key output for response.
	 *
	 * @param mixed           $item    Scan key object.
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response Response object.
	 *
	 * @since 1.0
	 */
	public function prepare_item_for_response( $item, $request ): WP_REST_Response {

		$data   = array();
		$fields = $this->get_fields_for_response( $request );

		if ( rest_is_field_included( 'key', $fields ) ) {
			$data['key'] = $item['key'];
		}

		if ( rest_is_field_included( 'level', $fields ) ) {
			$data['level'] = $item['level'];
		}

		if ( rest_is_field_included( 'tickets', $fields ) ) {
			$data['tickets'] = $item['tickets'];
		}

		if ( rest_is_field_included( 'date_format', $fields ) ) {
			$data['date_format'] = $item['date_format'];
		}

		if ( rest_is_field_included( 'location', $fields ) ) {
			$data['location'] = $item['location'];
		}

		$context = ! empty( $request['context'] ) ? $request['context'] : 'embed';

		$data = $this->add_additional_fields_to_object( $data, $request );
		$data = $this->filter_response_by_context( $data, $context );

		// Wrap the data in a response object.
		$response = rest_ensure_response( $data );

		if ( rest_is_field_included( '_links', $fields ) || rest_is_field_included( '_embedded', $fields ) ) {
			$response->add_links( $this->prepare_links( $item ) );
		}

		return $response;
	}


	/**
	 * Prepares links for the scan_keys request.
	 *
	 * @param array $scan_key Scan key object.
	 * @return array Links for the given order.
	 *
	 * @since 1.0
	 */
	protected function prepare_links( array $scan_key ): array {
		return array(
			'self'       => array(
				'href' => rest_url( sprintf( '%s/%s/%d/scan-keys/%s', $this->namespace, $this->rest_base, $this->event_id, $scan_key['key'] ) ),
			),
			'collection' => array(
				'href' => rest_url( sprintf( '%s/%s/%d/scan-keys', $this->namespace, $this->rest_base, $this->event_id ) ),
			),
		);
	}


	/**
	 * Return the scan-keys schema.
	 *
	 * @return array
	 *
	 * @since 1.0
	 * @since 2.4.0 Added level 7 (Temporarily leave) and level 8 (Re-enter).
	 * @since 2.5.0 Added level 6 (Reset).
	 */
	public function get_item_schema(): array {
		if ( $this->schema ) {
			return $this->add_additional_fields_schema( $this->schema );
		}

		$this->schema = array(
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
			'title'      => 'scan-keys',
			'type'       => 'object',
			'properties' => array(
				'key'         => array(
					'description' => __( 'The scan key.', 'fast-events' ),
					'context'     => array( 'view', 'edit', 'embed' ),
					'type'        => 'string',

				),
				'level'       => array(
					'description' => __( 'The scan level (0=Entry, 1=Staged, 6=Reset, 7=Temporarily leave, 8= Re-enter, 9=Exit).', 'fast-events' ),
					'context'     => array( 'view', 'edit', 'embed' ),
					'type'        => 'integer',
					'enum'        => array( 0, 1, 6, 7, 8, 9 ),
					'default'     => 0,
				),
				'tickets'     => array(
					'description' => __( 'Only these tickets can be scanned (Empty is all tickets).', 'fast-events' ),
					'context'     => array( 'view', 'edit', 'embed' ),
					'type'        => 'string',
					'default'     => '',
				),
				'date_format' => array(
					'description' => __( 'The date format output for the Scan App.', 'fast-events' ),
					'context'     => array( 'view', 'edit', 'embed' ),
					'type'        => 'string',
					'default'     => 'l, j F H:i:s',
					'mexLength'   => 32,
				),
				'location'    => array(
					'description' => __( 'The location of the scan.', 'fast-events' ),
					'context'     => array( 'view', 'edit', 'embed' ),
					'type'        => 'string',
					'minLength'   => 1,
				),
			),
		);

		return $this->add_additional_fields_schema( $this->schema );
	}
}
