<?php
/**
 * Fast Events Ordering controller.
 *
 * @since 1.3
 */

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

defined( 'ABSPATH' ) || exit;

use FeData\FastEvents\Storage\PluginSettings;
use WP_Error;
use WP_REST_Controller;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

/**
 * Fast Events Ordering class.
 */
class OrderingController extends WP_REST_Controller {

	/**
	 * Fast Events Ordering constructor.
	 *
	 * @param PluginSettings $settings Settings of this plugin.
	 *
	 * @since 1.3
	 */
	public function __construct( private readonly PluginSettings $settings ) {}


	/**
	 * Register the routes for the objects of the controller.
	 *
	 * @since 1.3
	 */
	public function register_routes(): void {

		if ( ! $this->settings->misc_ordering_api() ) {
			return;
		}

		// Get ordering form.
		register_rest_route(
			'fast-events',
			'/v1/ordering/form/(?P<id>[\w-]{1,32})',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'fast_events_ordering_get_form' ),
				'permission_callback' => '__return_true',
			)
		);

		// Get ordering status.
		register_rest_route(
			'fast-events',
			'/v1/ordering/status/(?P<id>[\w-]{1,32})/(?P<uid>[\w]{40})',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'fast_events_ordering_status' ),
				'permission_callback' => '__return_true',
			)
		);
	}


	/**
	 * Retrieve the orderform.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
	 *
	 * @since 1.3
	 */
	public function fast_events_ordering_get_form( WP_REST_Request $request ): WP_Error|WP_REST_Response {
		$ctime = $this->settings->misc_cache_time_order_form();
		if ( 0 !== $ctime ) {
			header( "Cache-Control: public, max-age=$ctime, s-max-age=$ctime" );
		}

		return rest_ensure_response( array( 'form' => do_shortcode( $this->get_shortcode( $request['id'] ) ) ) );
	}


	/**
	 * Retrieve the ordering status.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
	 *
	 * @since 1.3
	 * @since 3.0 Removed payment_app and simplified the query.
	 */
	public function fast_events_ordering_status( WP_REST_Request $request ): WP_Error|WP_REST_Response {
		global $wpdb;

		// Look up the uid in the orders table.
		$payment_status = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT payment_status FROM {$wpdb->prefix}fe_event_orders WHERE uid = %s",
				$request['uid']
			)
		);

		// Does the key exist?
		$order_success = true;
		$form          = '';
		if ( 'paid' !== $payment_status && ! str_starts_with( $payment_status, 'dashboard' ) && ! str_starts_with( $payment_status, 'booked' ) ) {
			$order_success = false;
		} else {
			$sc = $this->get_shortcode( $request['id'] );
			if ( empty( $sc ) ) {
				$form = do_shortcode( '[fe_download showimage="no" downloadtext="' . esc_html__( 'Download tickets', 'fast-events' ) . '" uid="' . $request['uid'] . '"]' );
			} else {
				$form = do_shortcode( substr( $sc, 0, - 1 ) . ' uid="' . $request['uid'] . '"]' );
			}
		}

		// Return response.
		return rest_ensure_response(
			array(
				'success' => $order_success,
				'form'    => $form,
			)
		);
	}

	/**
	 * Retrieve the shortcode from the option table.
	 *
	 * @param string $token Search token.
	 * @return string The shortcode.
	 *
	 * @since 1.3
	 * @since 3.0 Shortcodes are stored in the options table.
	 */
	private function get_shortcode( string $token ): string {
		global $wpdb;

		// Look up the shortcode.
		$key       = 'fast_events_ordering_' . $token;
		$shortcode = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM $wpdb->options WHERE option_name = %s ", $key ) );
		if ( is_wp_error( $shortcode ) || empty( $shortcode ) ) {
			return '';
		}

		return $shortcode;
	}
}
