<?php
/**
 * REST endpoints for maca Hub (maca-hub/v1 namespace, site key auth).
 *
 * @package Maca_Menu_List
 */

defined( 'ABSPATH' ) || exit;

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/hub-dishes.php';

/**
 * Hub REST controller for maca Restu Pro.
 */
class Maca_Restu_Hub_Rest {

	/**
	 * @return void
	 */
	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	/**
	 * @return void
	 */
	public function register_routes() {
		$key_args = array(
			'maca_key' => array(
				'required'          => false,
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			),
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu',
			array(
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'get_restu' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => array_merge(
						$key_args,
						array(
							'resource' => array(
								'required'          => false,
								'type'              => 'string',
								'sanitize_callback' => 'sanitize_key',
							),
							'category_id' => array(
								'required'          => false,
								'type'              => 'integer',
								'sanitize_callback' => 'absint',
							),
							'datetime' => array(
								'required'          => false,
								'type'              => 'string',
								'sanitize_callback' => 'sanitize_text_field',
							),
						)
					),
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/license',
			array(
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'get_license' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'post_license' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/categories',
			array(
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'list_categories' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/menus',
			array(
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'list_menus' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => array_merge(
						$key_args,
						array(
							'category_id' => array(
								'required'          => false,
								'type'              => 'integer',
								'sanitize_callback' => 'absint',
							),
						)
					),
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/qr',
			array(
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'get_qr' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/preview',
			array(
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'get_preview' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => array_merge(
						$key_args,
						array(
							'datetime' => array(
								'required'          => false,
								'type'              => 'string',
								'sanitize_callback' => 'sanitize_text_field',
							),
						)
					),
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/category-save',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'save_category' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/category-delete',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'delete_category' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/menu-save',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'save_menu' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/menu-delete',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'delete_menu' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/qr-update',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'update_qr' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/upload',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'upload_menu_file' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/dish-category-save',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'save_dish_category' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/dish-category-delete',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'delete_dish_category' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/dish-save',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'save_dish' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);

		register_rest_route(
			'maca-hub/v1',
			'/restu/dish-delete',
			array(
				array(
					'methods'             => 'POST',
					'callback'            => array( $this, 'delete_dish' ),
					'permission_callback' => array( $this, 'check_site_key' ),
					'args'                => $key_args,
				),
			)
		);
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return true|WP_Error
	 */
	public function check_site_key( $request ) {
		if ( class_exists( 'Maca_Hub_Connector' ) && Maca_Hub_Connector::request_has_valid_bearer( $request ) ) {
			return true;
		}

		$stored = maca_restu_hub_get_site_key();
		if ( '' === $stored ) {
			return new WP_Error(
				'maca_no_site_key',
				__( 'Ingen sajtnyckel sparad i WordPress (maca Sec).', 'maca-restu-pro' ),
				array( 'status' => 401 )
			);
		}

		$key = $this->extract_request_site_key( $request );
		if ( '' === $key ) {
			return new WP_Error(
				'maca_missing_key',
				__( 'Sajtnyckel saknas.', 'maca-restu-pro' ),
				array( 'status' => 401 )
			);
		}

		if ( ! hash_equals( $stored, $key ) ) {
			return new WP_Error(
				'maca_invalid_key',
				__( 'Fel sajtnyckel.', 'maca-restu-pro' ),
				array( 'status' => 401 )
			);
		}

		return true;
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return string
	 */
	private function extract_request_site_key( $request ) {
		$key = $request->get_header( 'X-Maca-Site-Key' );
		if ( is_string( $key ) && '' !== trim( $key ) ) {
			return trim( $key );
		}

		$key = $request->get_param( 'maca_key' );
		if ( is_string( $key ) && '' !== trim( $key ) ) {
			return trim( $key );
		}

		return '';
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function get_restu( $request ) {
		$resource = sanitize_key( (string) $request->get_param( 'resource' ) );

		if ( 'categories' === $resource ) {
			return $this->list_categories();
		}
		if ( 'menus' === $resource ) {
			return $this->list_menus( $request );
		}
		if ( 'qr' === $resource ) {
			return $this->get_qr();
		}
		if ( 'preview' === $resource ) {
			return $this->get_preview( $request );
		}
		if ( 'qr-print' === $resource ) {
			return $this->get_qr_print();
		}
		if ( 'dish-categories' === $resource ) {
			return $this->list_dish_categories();
		}
		if ( 'dishes' === $resource ) {
			return $this->list_dishes( $request );
		}
		if ( 'allergens' === $resource ) {
			return $this->list_allergens();
		}

		return rest_ensure_response( maca_restu_hub_get_status() );
	}

	/**
	 * @return WP_REST_Response
	 */
	public function get_status() {
		return rest_ensure_response( maca_restu_hub_get_status() );
	}

	/**
	 * @return WP_REST_Response
	 */
	public function get_license() {
		return rest_ensure_response( maca_restu_hub_get_license_status() );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function post_license( $request ) {
		$params = $request->get_json_params();
		if ( ! is_array( $params ) || empty( $params ) ) {
			$params = $request->get_params();
		}

		$action = isset( $params['action'] ) ? sanitize_key( (string) $params['action'] ) : 'activate';
		if ( 'deactivate' === $action ) {
			$result = maca_restu_hub_deactivate_license();
		} else {
			$key    = isset( $params['license_key'] ) ? sanitize_text_field( (string) $params['license_key'] ) : '';
			$result = maca_restu_hub_activate_license( $key );
		}

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return array<string, mixed>
	 */
	private function get_request_params( $request ) {
		$params = $request->get_json_params();
		if ( ! is_array( $params ) || empty( $params ) ) {
			$params = $request->get_params();
		}

		return is_array( $params ) ? $params : array();
	}

	/**
	 * @return WP_REST_Response
	 */
	public function list_categories() {
		return rest_ensure_response(
			array(
				'categories' => maca_restu_hub_list_categories(),
			)
		);
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response
	 */
	public function list_menus( $request ) {
		$category_id = absint( $request->get_param( 'category_id' ) );

		return rest_ensure_response(
			array(
				'menus' => maca_restu_hub_list_menus( $category_id ),
			)
		);
	}

	/**
	 * @return WP_REST_Response
	 */
	public function get_qr() {
		return rest_ensure_response(
			array(
				'qr' => maca_restu_hub_get_qr_settings(),
			)
		);
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function get_preview( $request ) {
		$datetime = (string) $request->get_param( 'datetime' );
		$result   = maca_restu_hub_get_preview( $datetime );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function save_category( $request ) {
		$result = maca_restu_hub_save_category( $this->get_request_params( $request ) );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function delete_category( $request ) {
		$result = maca_restu_hub_delete_category( $this->get_request_params( $request ) );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function save_menu( $request ) {
		$result = maca_restu_hub_save_menu( $this->get_request_params( $request ) );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function delete_menu( $request ) {
		$result = maca_restu_hub_delete_menu( $this->get_request_params( $request ) );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_qr( $request ) {
		$result = maca_restu_hub_update_qr_settings( $this->get_request_params( $request ) );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @return WP_REST_Response
	 */
	public function get_qr_print() {
		return rest_ensure_response(
			array(
				'print' => maca_restu_hub_get_qr_print_info(),
			)
		);
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function upload_menu_file( $request ) {
		$result = maca_restu_hub_upload_menu_file_from_base64( $this->get_request_params( $request ) );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @return WP_REST_Response|WP_Error
	 */
	public function list_dish_categories() {
		$denied = maca_restu_hub_require_dishes_mode();
		if ( is_wp_error( $denied ) ) {
			return $denied;
		}

		return rest_ensure_response(
			array(
				'dish_categories' => maca_restu_hub_list_dish_categories(),
			)
		);
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function list_dishes( $request ) {
		$denied = maca_restu_hub_require_dishes_mode();
		if ( is_wp_error( $denied ) ) {
			return $denied;
		}

		$category_id = absint( $request->get_param( 'category_id' ) );

		return rest_ensure_response(
			array(
				'dishes' => maca_restu_hub_list_dishes( $category_id ),
			)
		);
	}

	/**
	 * @return WP_REST_Response|WP_Error
	 */
	public function list_allergens() {
		$denied = maca_restu_hub_require_dishes_mode();
		if ( is_wp_error( $denied ) ) {
			return $denied;
		}

		return rest_ensure_response(
			array(
				'allergens' => maca_restu_hub_list_allergens(),
			)
		);
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function save_dish_category( $request ) {
		$result = maca_restu_hub_save_dish_category( $this->get_request_params( $request ) );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function delete_dish_category( $request ) {
		$result = maca_restu_hub_delete_dish_category( $this->get_request_params( $request ) );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function save_dish( $request ) {
		$result = maca_restu_hub_save_dish( $this->get_request_params( $request ) );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	/**
	 * @param WP_REST_Request $request Request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function delete_dish( $request ) {
		$result = maca_restu_hub_delete_dish( $this->get_request_params( $request ) );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}
}
