<?php
/** Exit if accessed directly. */
if ( ! defined( 'ABSPATH' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit;
}

class FSRS_COMMON {

	private $fsrs;

	private static $instance;

	public function __construct() {
	}

	/**
	 * Convert English Number To Persian Number
	 *
	 * @param $english_num
	 *
	 * @return string|string[]
	 */
	public static function convert_english_to_persian_number( $english_num ) {
		if ( get_locale() === "fa_IR" ) {
			return str_replace( [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ],
				[
					__( '۰', 'full-schema' ),
					__( '۱', 'full-schema' ),
					__( '۲', 'full-schema' ),
					__( '۳', 'full-schema' ),
					__( '۴', 'full-schema' ),
					__( '۵', 'full-schema' ),
					__( '۶', 'full-schema' ),
					__( '۷', 'full-schema' ),
					__( '۸', 'full-schema' ),
					__( '۹', 'full-schema' ),
				], $english_num );
		}

		return $english_num;
	}

	/**
	 * Get Post Rating Data
	 *
	 * @param $p_id
	 *
	 * @return int[]
	 */
	public static function get_post_rating( $p_id ): array {
		global $wpdb;
		$post_id    = $p_id;
		$seen_count = '0';
		$rating     = '0';

		$sql = "SELECT avg(meta_value) AS rating, count(meta_value) 'count'
                    FROM {$wpdb->prefix}postmeta WHERE  meta_key = '_fsrs_rating' 
                    AND post_id = '$post_id'";

		$result = $wpdb->get_results( $sql, 'ARRAY_A' );

		foreach ( $result as $row ) {
			$rating     = ceil( $row['rating'] );
			$seen_count = $row['count'];
		}
		if ( $rating == '0' ) {
			$rating     = '5';
			$seen_count = '1';
		}

		return array( 'rating' => (float) $rating, 'seen_count' => (int) $seen_count );
	}


	/**
	 * @param $purchase_code
	 *
	 * @return bool
	 */
	public function install_license( $purchase_code ) {
		/** Prepare URL. */
		$url = $this->prepare_url( $purchase_code );

		/** Download JSON file with purchase code validation status true/false. */
		$response = wp_remote_get( $url, [
			'timeout' => 15,
			'headers' => [
				'Accept' => 'application/json'
			]
		] );
		/** We’ll check whether the answer is correct. */
		if ( is_wp_error( $response ) ) {
			return false;
		}
		/** Have answer with wrong code. */
		if ( wp_remote_retrieve_response_code( $response ) !== 200 ) {
			return false;
		}

		$res = json_decode( preg_replace( '/[\x00-\x1F\x80-\xFF]/', '', $response['body'] ), true );

		return filter_var( $res, FILTER_VALIDATE_BOOLEAN );
	}

	public function check_license( $purchase_code ) {
		/** Prepare URL. */
		$url = 'https://safine.net/wp-json/pr_validate/v1/validity?purchase_code=' . $purchase_code;
		$url .= '&domain=' . $this->get_host();

		/** Download JSON file with purchase code validation status true/false. */
		$json = wp_remote_get( $url, [
			'timeout' => 15,
			'headers' => [
				'Accept' => 'application/json'
			]
		] );

		if ( is_wp_error( $json ) ) {
			return false;
		}
		/** Have answer with wrong code. */
		if ( wp_remote_retrieve_response_code( $json ) !== 200 ) {
			return false;
		}

		$res = json_decode( preg_replace( '/[\x00-\x1F\x80-\xFF]/', '', $json['body'] ), true );

		return filter_var( $res, FILTER_VALIDATE_BOOLEAN );
	}


	/**
	 * @param $purchase_code
	 *
	 * @return string
	 */
	private function prepare_url( $purchase_code ): string {
		$url = 'https://safine.net/wp-json/pr_validate/v1/fsrs_submit_code';
		$url .= '?purchase_code=' . $purchase_code;
		$url .= '&domain=' . $this->get_host();

		return $url;
	}

	/**
	 * get domain
	 *
	 * @return string
	 */
	public function get_host(): string {
		$possibleHostSources   = array( 'HTTP_X_FORWARDED_HOST', 'HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR' );
		$sourceTransformations = array(
			"HTTP_X_FORWARDED_HOST" => function ( $value ) {
				$elements = explode( ',', $value );

				return trim( end( $elements ) );
			}
		);
		$host                  = '';
		foreach ( $possibleHostSources as $source ) {
			if ( ! empty( $host ) ) {
				break;
			}
			if ( empty( $_SERVER[ $source ] ) ) {
				continue;
			}
			$host = $_SERVER[ $source ];
			if ( array_key_exists( $source, $sourceTransformations ) ) {
				$host = $sourceTransformations[ $source ]( $host );
			}
		}

		// Remove port number from host
		$host = preg_replace( '/:\d+$/', '', $host );
		// remove www from host
		$host = str_ireplace( 'www.', '', $host );

		return trim( $host );
	}

	/**
	 * this function return all ajax actions and callbacks
	 *
	 * @return string[][]
	 */
	public function get_ajax_requests(): array {
		return array(
			array(
				'action'   => 'savePostData',
				'callback' => 'fsrs_submit_callback'
			),
			array(
				'action'   => 'getPostData',
				'callback' => 'fsrs_get_star_options'
			),
			array(
				'action'   => 'fsrs_activate',
				'callback' => 'fsrs_activation_callback'
			),
			array(
				'action'   => 'fsrs_reset',
				'callback' => 'fsrs_reset_callback'
			),
			array(
				'action'   => 'fsrs_check_validity',
				'callback' => 'fsrs_check_validity_callback'
			),
			array(
				'action'   => 'fsrs_get_rating_settings',
				'callback' => 'fsrs_get_rating_settings'
			),
			array(
				'action'   => 'fsrs_save_rating_settings',
				'callback' => 'fsrs_save_rating_settings'
			),
			array(
				'action'   => 'fsrs_save_star_texts',
				'callback' => 'fsrs_save_star_texts'
			),
			array(
				'action'   => 'fsrs_set_notif_read',
				'callback' => 'fsrs_set_notif_read'
			),
			array(
				'action'   => 'fsrs_import_from_other_plugin_settings',
				'callback' => 'fsrs_import_from_other_plugin_settings'
			),
			array(
				'action'   => 'fsrs_save_marketing_settings',
				'callback' => 'fsrs_save_marketing_settings_callback'
			),
			array(
				'action'   => 'fsrs_get_dialog_info_setting',
				'callback' => 'fsrs_get_dialog_info_setting_callback'
			),
			array(
				'action'   => 'fsrs_add_user_email',
				'callback' => 'fsrs_add_user_email_callback'
			),
		);
	}

	/**
	 * @return FSRS_COMMON
	 */
	public static function get_instance(): FSRS_COMMON {

		if ( ! isset( self::$instance ) && ! ( self::$instance instanceof self ) ) {

			self::$instance = new self;

		}

		return self::$instance;

	}

}