<?php
namespace rentsyst\site;
use rentsyst\admin\components\Rentsyst_Api;
use rentsyst\admin\components\Rentsyst_Language;
use rentsyst\includes\Rentsyst_CatalogFilter;
use rentsyst\includes\Rentsyst_PluginSettings;
use rentsyst\includes\RS_Company;
use function add_action;

/**
 * The public-facing functionality of the plugin.
 *
 * @package    Rentsyst
 * @subpackage rentsyst/site
 */
class Rentsyst_Site
{
	public function init()
	{
		if(!get_option(RS_Company::COMPANY_SETTINGS_ID)) {
			return false;
		}

		Rentsyst_CatalogContent::getInstance();

		add_filter( 'wp_list_pages_excludes', array( __CLASS__, 'exclude_service_page_from_menu' ) );

		// Prevent WordPress canonical redirect loop on paginated catalog URLs (e.g. /fleet/page/2/)
		// when a catalog filter value contains spaces or special characters. redirect_canonical()
		// re-encodes such query args and ends up redirecting the URL onto itself indefinitely.
		add_filter( 'redirect_canonical', function ( $redirect_url ) {
			if ( isset( $_GET['rentsyst'] ) ) {
				return false;
			}
			return $redirect_url;
		} );

		add_action( 'pre_get_posts', function ( $context )
		{
			if ( $context->is_post_type_archive( [ 'vehicle' ] ) ) {
				new Rentsyst_CatalogFilter();
			}
		} );

		add_action('wp_footer', [$this, 'add_booking_button']);

		add_action( 'rest_api_init', function () {
			register_rest_route( 'rentsyst/v1', '/access-token', array(
				'methods' => 'GET',
				'callback' => [$this, 'wp_rest_get_token_handler'],
				'permission_callback' => '__return_true'
			) );
		} );
	}

	public static function exclude_service_page_from_menu( $exclude_array )
	{
		array_push( $exclude_array, get_option( 'rentsyst_confirmation_page_id' ), get_option( Rentsyst_PluginSettings::CATALOG_SINGLE_PAGE_ID ) );

		return $exclude_array;
	}

	public function add_booking_button()
	{
		if ( ! get_option( 'rentsyst_enable_booking_button' ) || Rentsyst_BookingWidget::$is_display ) {
			if ( $page_id = get_option( Rentsyst_PluginSettings::BOOKING_PAGE_ID ) ) {

				$page_id = Rentsyst_Language::getConnectedPagesId($page_id)[Rentsyst_Language::getLanguageCode()] ?? $page_id;
				$booking_page_url = get_permalink( $page_id );

				echo "<script>window.rsBokingPageUrl = '$booking_page_url'</script>";
			}

			return false;
		}

		Rentsyst_ResourceLoader::registerAll();

		$settings = Rentsyst_PluginSettings::getSettings();
		require_once plugin_dir_path( __FILE__ ) . 'partials/booking-button.php';
	}

	public function wp_rest_get_token_handler()
	{
		nocache_headers();

		if (!$this->isValidOrigin()) {
			return new \WP_Error(
				'forbidden',
				'Access denied',
				['status' => 403]
			);
		}

		return [
			'token' => Rentsyst_Api::getInstance()->getToken(),
			'status' => 'success'
		];
	}

	/**
	 * Check if the request originates from the same site
	 */
	private function isValidOrigin()
	{
		$site_url = parse_url(home_url(), PHP_URL_HOST);

		// Check Origin header (preferred for CORS requests)
		if (!empty($_SERVER['HTTP_ORIGIN'])) {
			$origin_host = parse_url($_SERVER['HTTP_ORIGIN'], PHP_URL_HOST);
			return $origin_host === $site_url;
		}

		// Fallback to Referer header
		if (!empty($_SERVER['HTTP_REFERER'])) {
			$referer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
			return $referer_host === $site_url;
		}

		// No origin/referer header - deny access
		return false;
	}
}
