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

final class FSRS_REQUESTS {
	private static $instance;

	public function __construct() {
		$ajax_actions = FSRS_COMMON::get_instance()->get_ajax_requests();
//add actions when ajax action call
		foreach ( $ajax_actions as $action ) {
			add_action( 'wp_ajax_' . $action['action'], [ $this, $action['callback'] ] );
			add_action( 'wp_ajax_nopriv_' . $action['action'], [ $this, $action['callback'] ] );
		}
	}

	//submit star ratings
	public function fsrs_submit_callback() {
		//check nonce
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs_nonce" ) ) {
			$p_id        = $_POST['fsrsPostId'] ?? '0';
			$post_rating = (int) $_POST['pRating'];

			//get cookie
			$ratingCookie = isset( $_COOKIE['_fsrs_rating'] ) ? unserialize( base64_decode( $_COOKIE['_fsrs_rating'] ),
				[ stdClass::class ] )
				: array();

			if ( ! $ratingCookie ) {
				$ratingCookie = array();
			}

			$error_text = __( 'امتیاز شما قبلا ثبت شده است!', 'full-schema' );

			//check user Already rated or not
			if ( ! in_array( $p_id, $ratingCookie, true ) ) {
				$new_post_data = $post_rating;
				$result        = add_post_meta( $p_id, '_fsrs_rating', $new_post_data );

				global $wpdb;

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

				$rating_live_values = $wpdb->get_results( $sql, 'ARRAY_A' );
				$rating             = '0';
				$seen_count         = '0';

			foreach ( $rating_live_values as $row ) {
				$rating     = ceil( $row['rating'] );
				$seen_count = $row['count'];
			}

			$live_rating_view  = __( "میانگین امتیازات ", 'full-schema' ) . '<strong>' .
			                     FSRS_COMMON::convert_english_to_persian_number( $rating ) .
			                     '</strong>' . __( " از ۵", 'full-schema' );
			$live_rating_count = __( "از مجموع ", 'full-schema' ) . '<strong>' .
			                     FSRS_COMMON::convert_english_to_persian_number( $seen_count ) .
			                     '</strong>' . __( " رای", 'full-schema' );

				if ( $result ) {
					echo json_encode( array(
						'result'          => 'success',
						'liveRating'      => $live_rating_view,
						'liveRatingCount' => $live_rating_count,
						'postUrl'         => get_permalink( $p_id ),
						'ratingCount'     => FSRS_COMMON::convert_english_to_persian_number( $seen_count ),
						'ratingValue'     => round( $rating, 1 ),
						'faRatingDigit'   => FSRS_COMMON::convert_english_to_persian_number( $rating )
					) );
				} else {
					echo json_encode( array( 'result' => $error_text ) );
				}

				$ratingCookie[] = $p_id;
				$expire         = time() + 30 * DAY_IN_SECONDS;
				setcookie( '_fsrs_rating', base64_encode( serialize( $ratingCookie ) ), $expire, COOKIEPATH, COOKIE_DOMAIN );
				$_COOKIE['_fsrs_rating'] = base64_encode( serialize( $ratingCookie ) );

				$this->clear_cache( $p_id );
			} else {
				echo json_encode( array( 'result' => $error_text ) );
			}
		}
		wp_die();
	}

// clears cache for the most popular caching plugins
	private function clear_cache( $post_id ) {
		// WP Super Cache
		if ( function_exists( 'wp_cache_post_change' ) ) {
			wpsc_delete_post_cache( $post_id );
		}
		// WP Rocket
		if ( function_exists( 'rocket_clean_post' ) ) {
			rocket_clean_post( $post_id );
		}
		// LiteSpeed Cache
		if ( method_exists( 'LiteSpeed_Cache_API', 'purge_post' ) ) {
			LiteSpeed_Cache_API::purge_post( $post_id );
		}
		// WP Fastest Cache
		if ( function_exists( 'wpfc_clear_post_cache_by_id' ) ) {
			wpfc_clear_post_cache_by_id( $post_id );
		}
		// SG Optimizer
		if ( function_exists( 'sg_cachepress_purge_cache' ) ) {
			$url = get_permalink( $post_id );
			sg_cachepress_purge_cache( $url );
		}
		//W3TC
		if ( function_exists( 'w3tc_flush_post' ) ) {
			w3tc_flush_post( $post_id );
		}
	}

//return star options
	public function fsrs_get_star_options() {
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs_nonce" ) ) {
			$p_id = $_POST['fsrsPostId'] ?? '0';
			global $wpdb;
			$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 = '$p_id'";

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

			foreach ( $result as $row ) {
				$rating = round( $row['rating'], 1 );

				$seen_count = $row['count'];
			}
			if ( $rating === '0' ) {
				add_post_meta( $p_id, '_fsrs_rating', 5 );
				$rating     = '5';
				$seen_count = '1';
			}

			if ( ! empty( $result ) ) {
				echo json_encode( array(
					'result'       => 'success',
					'ratingValue'  => (string) $rating,
					'faDigitValue' => str_replace( [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ], [
						'۰',
						'۱',
						'۲',
						'۳',
						'۴',
						'۵',
						'۶',
						'۷',
						'۸',
						'۹'
					],
						$rating ),
					'faDigitCount' => str_replace( [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ], [
						'۰',
						'۱',
						'۲',
						'۳',
						'۴',
						'۵',
						'۶',
						'۷',
						'۸',
						'۹'
					],
						$seen_count )
				) );
			}

		}
		wp_die();
	}

	public function fsrs_activation_callback() {
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs-activation-nonce" ) ) {
			$license_key = $_POST['licenseKey'];
			if ( empty( $license_key ) ) {
				$license_key = '';
				echo json_encode( array( 'result' => '0' ) );
				wp_die();
			}

			$activation_result = FSRS_COMMON::get_instance()->install_license( $license_key );

			if ( $activation_result ) {
				update_option( 'fsrs-pr-license', (string) $license_key, true );
				update_option( 'fsrs_pr_option', array( 'license' => (string) $license_key, 'valid' => '1' ),
					true );
				echo json_encode( array( 'result' => '1' ) );
			} else {
				echo json_encode( array( 'result' => '0' ) );
			}
		} else {
			echo 'nonce is invalid!';
		}
		wp_die();
	}

	public function fsrs_check_validity_callback() {
		check_ajax_referer( 'fsrs-check-validity-nonce', 'nonce' );
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs-check-validity-nonce" ) ) {
			$pr_license = get_option( 'fsrs-pr-license' );
			if ( ! empty( $pr_license ) ) {
				$res = FSRS_COMMON::get_instance()->check_license( $pr_license );
				if ( $res ) {
					update_option( 'fsrs_pr_option', array( 'license' => $pr_license, 'valid' => '1' ) );
					echo json_encode( array( 'valid' => '1' ) );
				} else {
					update_option( 'fsrs_pr_option', array( 'license' => $pr_license, 'valid' => '0' ) );
					echo json_encode( array( 'valid' => '0' ) );
				}
			} else {
				echo json_encode( array( 'valid' => '0' ) );
			}
		} else {
			echo json_encode( array( 'valid' => 'nonce not valid' ) );
		}
		wp_die();
	}

	public function fsrs_reset_callback() {
		check_ajax_referer( 'fsrs-reset-nonce', 'nonce' );
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs-reset-nonce" ) ) {
			delete_post_meta_by_key( '_fsrs_schema' );
			delete_post_meta_by_key( '_fsrs_script' );
			delete_post_meta_by_key( '_fsrs_faq_schema' );
			delete_post_meta_by_key( '_fsrs_rating' );
			delete_option( 'fsrs_def_settings' );
			delete_option( 'fsrs_star_texts' );
			delete_option( 'fsrs_marketing_setting' );
			add_option( MARKETING_OPTION_NAME, FULL_SCHEMA_RICH_SNIPPET_SETTINGS::marketing_def_settings() );
			add_option( DESIGN_OPTION_NAME, FULL_SCHEMA_RICH_SNIPPET_SETTINGS::design_def_settings() );
			add_option( 'fsrs_star_texts', FULL_SCHEMA_RICH_SNIPPET_SETTINGS::star_texts() );
			delete_post_meta_by_key( '_fsrs_page_star_option' );
			echo json_encode( array( 'code' => '1' ) );
		} else {
			echo 'nonce is invalid';
		}
		wp_die();
	}

	public function fsrs_get_rating_settings() {
		check_ajax_referer( 'fsrs_nonce', 'nonce' );
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs_nonce" ) ) {
			$ratings_setting = get_option( 'fsrs_def_settings', FULL_SCHEMA_RICH_SNIPPET_SETTINGS::design_def_settings() );
			$star_text       = get_option( 'fsrs_star_texts', FULL_SCHEMA_RICH_SNIPPET_SETTINGS::star_texts() );
			echo json_encode( array(
				'result'                   => 'success',
				'fsrs_st_down_thanks_text' => $ratings_setting['fsrs_st_down_thanks_text'],
				'star1'                    => $star_text['star1'],
				'star2'                    => $star_text['star2'],
				'star3'                    => $star_text['star3'],
				'star4'                    => $star_text['star4'],
				'star5'                    => $star_text['star5'],
			) );
		} else {
			echo json_encode( array( 'result' => 'failed' ) );
		}
		wp_die();
	}

	public function fsrs_save_rating_settings() {
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs_admin_nonce" ) ) {
			parse_str( $_POST['f'], $output );
			$default_options = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::design_def_settings();

			$result = [];
			foreach ( $default_options as $key => $value ) {
				$result[ $key ] = $output[ $key ];
			}
			$design_option_updated = update_option( 'fsrs_def_settings', $result );
			if ( $design_option_updated ) {
				echo json_encode( array( 'code' => '110' ) );
			}
		} else {
			echo 'nonce is invalid';
		}
		wp_die();
	}

	public function fsrs_save_marketing_settings_callback() {
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs_marketing_nonce" ) ) {
			$marketing_options = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::marketing_def_settings();
			$output            = $_POST['f'];
			$result            = [];
			foreach ( $marketing_options as $key => $value ) {
				$result[ $key ] = $output[ $key ];
			}
			update_option( 'fsrs_marketing_setting', $result );
			echo json_encode( array( 'code' => '110' ) );
		} else {
			echo 'nonce is invalid';
		}
		wp_die();
	}

	public function fsrs_save_star_texts() {
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs_admin_nonce" ) ) {
			parse_str( $_POST['f'], $output );
			$star_options = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::star_texts();

			$result = [];
			foreach ( $star_options as $key => $value ) {
				$result[ $key ] = $output[ $key ];
			}

			$update_status = update_option( 'fsrs_star_texts', $result );
			if ( $update_status ) {
				echo json_encode( array( 'code' => '110', 'bool' => true ) );
			} else {
				echo json_encode( array( 'code' => '25', 'reason' => 'update options has failed!' ) );
			}
		} else {
			echo 'nonce is invalid!';
		}
		wp_die();
	}

	public function fsrs_import_from_other_plugin_settings() {
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs_import_from_other_plugin_settings" ) ) {
			$plugin_for_import = $_POST['plugin'];
			global $wpdb;
			$is_post_added = false;

			if ( $plugin_for_import === 'kkstar' ) {
				$is_post_added = $this->import_from_other_plugin_public_action( $wpdb, '_kksr_casts',
					'_kksr_avg' );
			} elseif ( $plugin_for_import === 'rmp' ) {
				$is_post_added = $this->import_from_other_plugin_public_action( $wpdb, 'rmp_vote_count',
					'rmp_avg_rating' );
			} else if ( $plugin_for_import === 'yasr' ) {
				$vote_counts = $wpdb->get_results( "select * from {$wpdb->prefix}yasr_log ",
					ARRAY_A );
				$ratings     = array();
				for ( $i = 0, $iMax = count( $vote_counts ); $i < $iMax; $i ++ ) {
					$ratings[ $i ]['rating']  = $vote_counts[ (string) $i ]['vote'];
					$ratings[ $i ]['post_id'] = $vote_counts[ (string) $i ]['post_id'];
				}
				foreach ( $ratings as $rating ) {
					$meta_id = add_post_meta( $rating['post_id'], '_fsrs_rating', $rating['rating'] );
					if ( is_int( $meta_id ) ) {
						$is_post_added = true;
					}
				}

			}

			if ( $is_post_added ) {
				echo wp_json_encode( array( 'code' => '110' ) );
			} else {
				echo wp_json_encode( array( 'code' => '25' ) );
			}
		}
		wp_die();
	}

	private function import_from_other_plugin_public_action( $wpdb, $vote_counts_meta_key, $avg_meta_key ): bool {
		$is_post_added = false;
		$vote_counts   = $wpdb->get_results( "select * from {$wpdb->prefix}postmeta 
   			 where `meta_key` = '$vote_counts_meta_key' ", ARRAY_A );
		$ratings       = array();
		foreach ( $vote_counts as $key => $value ) {
			$post_id         = $value['post_id'];
			$avg             = $wpdb->get_row( "select * from {$wpdb->prefix}postmeta 
   				 where `meta_key` =  '$avg_meta_key' AND  `post_id` = '$post_id' " );
			$count           = $wpdb->get_row( "select * from {$wpdb->prefix}postmeta 
    		where `meta_key` = '$vote_counts_meta_key' and `post_id` = '$post_id' ", ARRAY_A );
			$ratings[ $key ] = array(
				'post_id' => $post_id,
				'avg'     => $avg->meta_value,
				'count'   => $count['meta_value']
			);
		}
		for ( $i = 0, $iMax = count( $ratings ); $i < $iMax; $i ++ ) :
			$key     = (string) $i;
			$post_id = $ratings[ $key ]['post_id'];
			$count   = $ratings[ $key ]['count'];
			$rating  = $ratings[ $key ]['avg'];
			for ( $j = 0; $j < $count; $j ++ ) {
				$meta_id = add_post_meta( $post_id, '_fsrs_rating', $rating );
				if ( is_int( $meta_id ) ) {
					$is_post_added = true;
				}
			}
		endfor;

		return $is_post_added;
	}

	public function fsrs_set_notif_read() {
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs_admin_nonce" ) ) {
			$notif = $_POST['content'];
			update_option( 'fsrs_notif_option',
				array( 'notif_content' => str_replace( '\\', '', $notif ) ) );
			echo json_encode( array(
				'code' => '110'
			) );
		} else {
			echo 'nonce is invalid';
		}
		wp_die();
	}

	public function fsrs_get_dialog_info_setting_callback() {
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs_nonce" ) ) {
			$post_id        = $_POST['p_id'];
			$dialog_options = get_option( 'fsrs_marketing_setting',
				FULL_SCHEMA_RICH_SNIPPET_SETTINGS::marketing_def_settings() );
			echo json_encode( array(
				'post_url'      => get_permalink( $post_id ),
				'popup_options' => json_encode( $dialog_options )
			) );
			wp_die();
		}
	}

	public function fsrs_add_user_email_callback() {
		if ( wp_verify_nonce( $_REQUEST['nonce'], "fsrs_nonce" ) ) {
			$user_email   = $_POST['email'];
			$headers      = array( 'Content-Type: text/html; charset=UTF-8' );
			$post_title   = get_the_title( $_POST['post_id'] );
			$post_url     = get_permalink( $_POST['post_id'] );
			$is_mail_sent = wp_mail( get_option( 'admin_email' ), __( 'تبریک! ایمیل یک کاربر دریافت شد!',
				'full-schema' ),
				FSRS_MAIL_TEMP::get_instance()->get_email_body( $user_email, $post_title, $post_url ), $headers );
			if ( is_bool( $is_mail_sent ) ) {
				echo json_encode( array( 'result' => 'success' ) );
			} else {
				echo json_encode( array( 'result' => 'error' ) );
			}
			wp_die();
		}
	}

	public static function get_instance(): FSRS_REQUESTS {

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

			self::$instance = new self;

		}

		return self::$instance;
	}
}

FSRS_REQUESTS::get_instance();