<?php
namespace Prodigy\Includes\Helpers;

use Prodigy\Includes\Prodigy;

/**
 * Class Prodigy Helper
 */
class Prodigy_Page {
	/**
	 * @param string $page
	 *
	 * @return bool|int
	 */
	public static function prodigy_get_page_id( string $page ) {
		$page = apply_filters( 'prodigy_get_' . $page . '_page_id', get_option( 'prodigy_' . $page . '_page_id' ) );

		if ( $page ) {
			return absint( $page );
		}

		return false;
	}

	/**
	 * @return bool
	 */
	public static function prodigy_is_frontend_ajax(): bool {
		$script_filename = sanitize_url( wp_unslash( $_SERVER['SCRIPT_FILENAME'] ?? '' ) );

		if ( wp_doing_ajax() ) {
			$ref = '';
			if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
				$ref = sanitize_url( wp_unslash( $_REQUEST['_wp_http_referer'] ) );
			} elseif ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
				$ref = sanitize_url( wp_unslash( $_SERVER['HTTP_REFERER'] ) );
			}

			// If referer does not contain admin URL and we are using the admin-ajax.php endpoint, this is likely a frontend AJAX request
			if ( ( ( strpos( $ref, admin_url() ) === false ) && ( basename( $script_filename ) === 'admin-ajax.php' ) ) ) {
				return true;
			}
		}

		// If no checks triggered, we end up here - not an AJAX request.
		return false;
	}

	/**
	 * @return bool
	 */
	public static function prodigy_is_frontend(): bool {
		$valid_actions = array( 'edit', 'login', 'logout', 'elementor' );
		if ( ( isset( $_GET['elementor_library'], $_GET['render_mode'] ) && $_GET['render_mode'] === 'template-preview' ) ||
			( isset( $_GET['action'] ) && in_array( $_GET['action'], $valid_actions, true ) ) ||
			( isset( $_GET['context'] ) && $_GET['context'] === 'edit' ) ||
			isset( $_GET['elementor-preview'] ) ||
			isset( $_GET['_locale'] ) ||
			isset( $_GET['reauth'] ) ||
			preg_match( '/wp-login\.php/', Prodigy_Url_Helper::prodigy_get_request_uri() ) ||
			isset( $_GET['preview'] )
		) {
			return false;
		}

		$parts        = explode( '/', Prodigy_Url_Helper::prodigy_get_request_uri() );
		$stringToFind = 'elementor';

		if ( in_array( $stringToFind, $parts ) ) {
			return false;
		}

		if ( wp_doing_ajax() ) {
			return self::prodigy_is_frontend_ajax();
		}

		return ! is_admin();
	}

	/**
	 * @return bool
	 */
	public static function prodigy_is_need_user_authorise(): bool {
		$result = true;

		if ( ( isset( $_GET['elementor_library'], $_GET['render_mode'] ) && $_GET['render_mode'] === 'template-preview' ) ||
			( isset( $_GET['action'] ) && $_GET['action'] === 'edit' ) ||
			( isset( $_GET['action'] ) && ( $_GET['action'] === 'logout' ) ) ||
			( isset( $_GET['post_type'] ) && ( $_GET['post_type'] === 'elementor_library' ) ) ||
			isset( $_GET['preview'] ) || isset( $_GET['doing_wp_cron'] ) ||
			( isset( $_GET['context'] ) && $_GET['context'] === 'edit' ) ||
			isset( $_GET['elementor-preview'] ) || isset( $_GET['_locale'] ) ||
			isset( $_GET['reauth'] ) || preg_match( '/wp-login\.php/', Prodigy_Url_Helper::prodigy_get_request_uri() ) ||
			is_admin() || is_wp_api_request()
		) {
			$result = false;
		}

		if ( $result && self::is_excluded_page_from_authorization() && ! self::has_session_token_in_request() ) {
			$result = false;
		}

		return $result;
	}

	/**
	 * @return bool
	 */
	private static function has_session_token_in_request(): bool {
		$token = Prodigy_Parameters::get_parameter( $_GET, 'session_token' );
		return is_string( $token ) && $token !== '';
	}

	/**
	 * @return bool
	 */
	private static function is_excluded_page_from_authorization(): bool {
		$excluded_page_ids = get_option( 'prodigy_excluded_page_ids', array() );
		if ( ! is_array( $excluded_page_ids ) || empty( $excluded_page_ids ) ) {
			return false;
		}

		$excluded_page_ids = array_values(
			array_filter(
				array_map( 'absint', $excluded_page_ids ),
				function ( $id ) {
					return $id > 0;
				}
			)
		);

		if ( empty( $excluded_page_ids ) ) {
			return false;
		}

		$current_page_id = get_queried_object_id();
		if ( empty( $current_page_id ) ) {
			$request_uri = Prodigy_Url_Helper::prodigy_get_request_uri();
			if ( ! empty( $request_uri ) ) {
				$path = wp_parse_url( $request_uri, PHP_URL_PATH );
				if ( is_string( $path ) && $path !== '' ) {
					$current_page_id = url_to_postid( home_url( $path ) );
				}
			}
		}

		if ( empty( $current_page_id ) && isset( $_GET['page_id'] ) ) {
			$current_page_id = absint( wp_unslash( $_GET['page_id'] ) );
		}

		return ! empty( $current_page_id ) && in_array( (int) $current_page_id, $excluded_page_ids, true );
	}

	/**
	 * @return bool
	 */
	public static function prodigy_check_shop_page(): bool {
		$url_params = Prodigy_Url_Helper::prodigy_parse_request_uri( -1 );
		$path       = explode( '/', $url_params['path'] );
		foreach ( $path as $part ) {
			if ( ! empty( $part ) &&
				(
					$part === Prodigy::get_prodigy_category_slug() ||
					$part === Prodigy::get_prodigy_tag_slug()
				)
			) {
				return true;
			}
		}

		return false;
	}

	/**
	 * @return bool
	 */
	public static function prodigy_is_blog(): bool {
		return ( is_archive() || is_author() || is_category() || is_home() || is_single() || is_tag() ) && 'post' == get_post_type();
	}


	/**
	 * @return bool
	 */
	public static function is_prodigy_shop(): bool {
		return is_page( self::prodigy_get_page_id( 'shop' ) );
	}

	/**
	 * Check the current page is Cart
	 *
	 * @return bool
	 */
	public static function is_cart(): bool {
		$url = Prodigy_Url_Helper::prodigy_get_cart_url();
		$uri = Prodigy_Url_Helper::prodigy_get_request_uri();

		if ( ! empty( $url ) && ! empty( $uri ) ) {
			return substr_count( $url, $uri );
		}

		return false;
	}

	/**
	 * @param string $slug
	 * @param int    $page_id
	 *
	 * @return bool
	 */
	public static function is_shop_page( string $slug, int $page_id ): bool {
		$post = get_post( $page_id );

		return $slug === Prodigy::get_prodigy_category_slug() ||
				$slug === Prodigy::get_prodigy_tag_slug() ||
				$slug === Prodigy::get_prodigy_brand_slug() ||
				( isset( $post ) && $slug === $post->post_name );
	}
}
