<?php

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

class FSRS_PUBLIC_INIT {
	private $fsrs;

	/**
	 * FSRS_PUBLIC_INIT constructor.
	 *
	 * @param $fsrs
	 */
	public function __construct( $fsrs ) {
		$this->fsrs = $fsrs;
	}

	public function enqueue_styles() {
		$design_settings = get_option( DESIGN_OPTION_NAME,
			FULL_SCHEMA_RICH_SNIPPET_SETTINGS::design_def_settings() );


		wp_enqueue_style( $this->fsrs, FSRS_CSS_DIR . 'main.css', false,
			FULL_SCHEMA_RICH_SNIPPET_VERSION );
		wp_enqueue_style( $this->fsrs, FSRS_ADMIN_URL . 'css/sweetalert2.min.css', false,
			FULL_SCHEMA_RICH_SNIPPET_VERSION );
		wp_add_inline_style( $this->fsrs, $this->inline_css() );
	}

	public function enqueue_scripts() {
		$this->litespeed_nonce();
		$design_settings    = get_option( DESIGN_OPTION_NAME,
			FULL_SCHEMA_RICH_SNIPPET_SETTINGS::design_def_settings() );
		$marketing_settings = get_option( MARKETING_OPTION_NAME,
			FULL_SCHEMA_RICH_SNIPPET_SETTINGS::marketing_def_settings() );
		$email_error_message = $marketing_settings['email_error_message'] ?? '';
		if ( $email_error_message === null ) {
			$marketing_settings = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::marketing_def_settings();
		}

		wp_enqueue_script( 'fsrs_star_lib_script', FSRS_JS_DIR . 'fsrs-star-rating.js',
			false, FULL_SCHEMA_RICH_SNIPPET_VERSION, true );


		wp_enqueue_script( $this->fsrs, FSRS_ADMIN_URL . 'js/sweetalert2.all.min.js' );
		wp_register_script( 'fsrs_main_script', FSRS_JS_DIR . 'main.js', false,
			FULL_SCHEMA_RICH_SNIPPET_VERSION, true );
		$nonce       = wp_create_nonce( "fsrs_nonce" );
		$stars_texts = get_option( 'fsrs_star_texts', FULL_SCHEMA_RICH_SNIPPET_SETTINGS::star_texts() );
		$post_title  = get_the_title( get_the_ID() );
		wp_localize_script( 'fsrs_main_script', 'fsrs_object', array(
			'ajax_url'             => admin_url( 'admin-ajax.php' ),
			'_wpnonce'             => $nonce,
			'share_linkedin'       => __( 'اشتراک در لینکدین', 'full-schema' ),
			'share_facebook'       => __( 'اشتراک در فیسبوک', 'full-schema' ),
			'share_twitter'        => __( 'اشتراک در توییتر', 'full-schema' ),
			'share_telegram'       => __( 'اشتراک در تلگرام', 'full-schema' ),
			'share_email'          => __( 'اشتراک با ایمیل', 'full-schema' ),
			'star1'                => __( esc_html( $stars_texts['star1'] ), 'full-schema' ),
			'star2'                => __( esc_html( $stars_texts['star2'] ), 'full-schema' ),
			'star3'                => __( esc_html( $stars_texts['star3'] ), 'full-schema' ),
			'star4'                => __( esc_html( $stars_texts['star4'] ), 'full-schema' ),
			'star5'                => __( esc_html( $stars_texts['star5'] ), 'full-schema' ),
			'thanks_text'          => __( esc_html( $design_settings['fsrs_st_down_thanks_text'] ), 'full-schema' ),
			'email_error_message'  => __( esc_html( $marketing_settings['fsrs_email_error_text'] ), 'full-schema' ),
			'show_top_star_option' => __( esc_html( $marketing_settings['fsrs_email_error_text'] ), 'full-schema' ),
			'post_title'           => esc_attr( $post_title )
		) );
		wp_enqueue_script( 'fsrs_main_script' );
	}

	/**
	 * Add rating schema in header
	 *
	 * @return void
	 */
	public function print_rating_schema() {
		$rating  = get_post_meta( get_the_ID(), '_fsrs_schema', true );
		$post_id = get_the_ID();
		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 = '$post_id'";
		$rate_res     = $wpdb->get_results( $sql, 'ARRAY_A' );
		$rating_value = '5';
		$seen_count   = '1';
		foreach ( $rate_res as $row ) {
			$rating_value = (string) round( $row['rating'], 1 );
			if ( $rating_value === '0' ) {
				$rating_value = '5';
			}
			$seen_count = (string) $row['count'];
			if ( $seen_count === '0' ) {
				$seen_count = '1';
				add_post_meta( $post_id, '_fsrs_rating', 5 );
			}
		}
		$aggregateRating = array(
			'@type'       => 'AggregateRating',
			'ratingValue' => $rating_value,
			'bestRating'  => '5',
			'ratingCount' => $seen_count,
			'worstRating' => '1'
		);
		if ( empty( $rating ) ) {
			$rating = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::default_options( $post_id, get_the_title( $post_id ),
				$aggregateRating
			);
		} else {
			$post_options = get_post_meta( get_the_ID(), '_fsrs_schema', true );
			$schema_type  = $post_options['@type'] ?? '';
			$title        = $post_options['name'] ?? '';
			$desc         = $post_options['description'] ?? '';
			$duration     = $post_options['duration'] ?? '';
			$content_url  = $post_options['contentUrl'] ?? '';

			if ( $schema_type === 'VideoObject' ) {
				$rating = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::video_object_options( get_the_ID(),
					$title, $desc, $duration,
					$content_url, $aggregateRating );
			} else if ( $schema_type === 'AudioObject' ) {
				$rating = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::audio_object_options( $duration,
					$title, $desc, $content_url,
					$aggregateRating );
			} else if ( $schema_type === 'MediaObject' ) {
				$rating = FULL_SCHEMA_RICH_SNIPPET_SETTINGS::default_options( $post_id,
					get_the_title( $post_id ),
					$aggregateRating
				);
			}
		}
		if ( is_singular( 'post' ) ) {
			?>
            <script type="application/ld+json" class="safine-full-schema-rich-snippet">
				[<?php echo wp_json_encode( $rating ) ?>]
            </script>
			<?php
		}

		if ( ! is_singular( 'post' ) ) {
			$result = get_post_meta( get_the_ID(), '_fsrs_page_star_option', true );
			if ( ! empty( $result ) && $result['showOption'] === '1' ) {
				?>
                <script type="application/ld+json" class="safine-full-schema-rich-snippet">
				[<?php echo wp_json_encode( $rating ) ?>]
                </script>
				<?php
			}
		}
	}

	/**
	 * Add user custom script or css ... in header
	 */
	public function add_header_script() {
		$fsrs_script = get_post_meta( get_the_ID(), '_fsrs_script', true );
		echo $fsrs_script['header'] ?? '';
	}

	/**
	 * Add user custom script or css ... in footer
	 *
	 */
	public function add_footer_script() {
		$fsrs_script = get_post_meta( get_the_ID(), '_fsrs_script', true );
		echo $fsrs_script['footer'] ?? '';
	}

	/**
	 * Add FAQ schema in footer
	 *
	 * @return void
	 */
	public function print_faq_schema() {
		$faqs = get_post_meta( get_the_ID(), '_fsrs_faq_schema', true );
		if ( ! is_singular() && ! is_tax() && ! is_category() && ! is_tag() ) {
			return;
		}
		if ( is_tax() || is_category() || is_tag() ) {
			$term = get_queried_object();
			$faqs = get_term_meta( $term->term_id, '_fsrs_faq_schema', true );
		}
		if ( empty( $faqs ) ) {
			return;
		}

		$schema_array = [
			'@context'   => 'https://schema.org',
			'@type'      => 'FAQPage',
			'mainEntity' => [],
		];

		foreach ( $faqs as $faq ) {
			$schema_array['mainEntity'][] = [
				'@type'          => 'Question',
				'name'           => $faq['q'],
				'acceptedAnswer' => [
					'@type' => 'Answer',
					'text'  => $faq['a'],
				],
			];
		}
		?>
        <script type="application/ld+json" class="safine-full-schema-rich-snippet">
        [<?php echo wp_json_encode( $schema_array ); ?>]
        </script>
		<?php
	}


	/**
	 * @param $content
	 *
	 * @return string
	 */
	public function fsrs_rating_show_in_content( $content ): string {
		$pre = '';
		if ( is_singular( 'product' ) || is_home() ) {
			return $content;
		}
		if ( is_singular( 'post' ) ) {
			$pre .= $this->show_top_rating();
			$pre .= $content;
			$pre .= $this->show_rating_view();
		}
		if ( ! ( get_post_type() === 'post' ) ) {
			$result = get_post_meta( get_the_ID(), '_fsrs_page_star_option', true );
			if ( ! empty( $result ) && $result['showOption'] === '1' ) {
				$pre .= $this->show_top_rating();
				$pre .= $content;
				$pre .= $this->show_rating_view();
			}
		}
		if ( $pre === '' ) {
			return $content;
		}

		return $pre;
	}

	public function inline_css(): string {
	    ob_start();
		include_once FSRS_PUB_DIR . 'FSRS_INLINE_CSS.php';
		return  trim( preg_replace( '/\t+/', '', $this->remove_line_breaks( ob_get_clean() ) ) );
	}

	private function show_top_rating(): string {
		$top_rating    = '';
		$star_settings = get_option( 'fsrs_def_settings', FULL_SCHEMA_RICH_SNIPPET_SETTINGS::design_def_settings() );
		$rating_data   = FSRS_COMMON::get_post_rating( get_the_ID() );
		if ( ( get_post_type( get_the_ID() ) === 'page' && $star_settings['fsrs_page_st_up_star_show'] === '1' ) ||
		     ( is_singular( 'post' ) && $star_settings['fsrs_post_st_up_star_show'] === '1' ) ) {

			if ( $star_settings['fsrs_star_direction'] === 'rtl' ) {
				$star_direction = 'rtl';
			} else {
				$star_direction = 'ltr';
			}
			$top_rating = '<div class="fsrs-star-rating fsrs-rating-top" id="fsrs-rating-top" 
			style="direction: ' . $star_direction . '">
                  <li class="fsrs-rating-icons-container readonly"
                    id="fsrs-rating-before-content" fsrs-data-rating="' . $rating_data['rating'] . '"></li> 
                   </div>';
		}

		return $top_rating;
	}

	public function show_rating_view() {
	    $design_options = get_option(DESIGN_OPTION_NAME, FULL_SCHEMA_RICH_SNIPPET_SETTINGS::design_def_settings());
		ob_start();
		$star_theme = $design_options['fsrs_star_theme'];
		if (is_null($star_theme)) {
		    $star_theme = 'default_temp';
		}

		if ($star_theme === 'default_temp') {
			new FSRS_DEFAULT_RATING_TEMP($design_options);
		} else if ($star_theme === 'right_temp') {
		    include FSRS_PUB_DIR . 'template/fsrs-rating-view-inline-right.php';
		} else if($star_theme === 'emoji_temp') {
			include FSRS_PUB_DIR . 'template/fsrs-rating-view-emoji-ico.php';
		} else {
			new FSRS_DEFAULT_RATING_TEMP($design_options);
		}

		return $this->remove_line_breaks( ob_get_clean() );
	}

    // remove line breaks from a string to avoid issues with wpautop
	private function remove_line_breaks( $string ) {
		return str_replace( array( "\r", "\n" ), '', $string );
	}


    // prevents nonce issues with litespeed cache plugin
	private function litespeed_nonce() {
		if ( method_exists( 'LiteSpeed_Cache_API', 'nonce_action' ) ) {
			LiteSpeed_Cache_API::nonce_action( 'fsrs_public_nonce' );
		}
	}

}

