<?php

/**
 * Review request
 *
 * @package  Cookie_Law_Info
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
class Cookie_Law_Info_Review_Request {

	/**
	 * config options
	 */
	private $plugin_title        = 'GDPR Cookie Consent (CCPA Ready)';
	private $review_url          = 'https://wordpress.org/support/plugin/cookie-law-info/reviews/#new-post';
	private $plugin_prefix       = 'wt_cli'; /* must be unique name */
	private $days_to_show_banner = 60; /* when did the banner to show */
	private $remind_days         = 60; /* remind interval in days */



	private $start_date               = 0; /* banner to show count start date. plugin installed date, remind me later added date */
	private $current_banner_state     = 2; /* 1: active, 2: waiting to show(first after installation), 3: closed by user/not interested to review, 4: user done the review, 5:remind me later */
	private $banner_state_option_name = ''; /* WP option name to save banner state */
	private $start_date_option_name   = ''; /* WP option name to save start date */
	private $banner_css_class         = ''; /* CSS class name for Banner HTML element. */
	private $banner_message           = ''; /* Banner message. */
	private $later_btn_text           = ''; /* Remind me later button text */
	private $never_btn_text           = ''; /* Never review button text. */
	private $review_btn_text          = ''; /* Review now button text. */
	private $ajax_action_name         = ''; /* Name of ajax action to save banner state. */
	private $allowed_action_type_arr  = array(
		'later', /* remind me later */
		'never', /* never */
		'review', /* review now */
		'closed', /* not interested */
	);

	public function __construct() {
		// Set config vars
		$this->set_vars();

		register_activation_hook( CLI_PLUGIN_FILENAME, array( $this, 'on_activate' ) );
		register_deactivation_hook( CLI_PLUGIN_FILENAME, array( $this, 'on_deactivate' ) );

		if ( $this->check_condition() ) { /* checks the banner is active now */
			
			add_action( 'init', array( $this, 'init' ) );
			add_action( 'admin_notices', array( $this, 'show_banner' ) ); /* show banner */
			add_action( 'admin_print_footer_scripts', array( $this, 'add_banner_scripts' ) ); /* add banner scripts */
			add_action( 'wp_ajax_' . $this->ajax_action_name, array( $this, 'process_user_action' ) ); /* process banner user action */
		}
		add_filter( 'admin_footer_text', array( $this, 'add_footer_review_link' ) );
	}

	public function init() {
		/* translators: %1$s: opening bold tag, %2$s: closing bold tag */
		$this->banner_message = sprintf( __( 'Hey, we at %1$sCookieYes%2$s would like to thank you for using our plugin. We would really appreciate if you could take a moment to drop a quick review that will inspire us to keep going.', 'cookie-law-info' ), '<b>', '</b>' );

		/* button texts */
		$this->later_btn_text  = __( 'Remind me later', 'cookie-law-info' );
		$this->never_btn_text  = __( 'Never show again', 'cookie-law-info' );
		$this->review_btn_text = __( 'Review now', 'cookie-law-info' );
	}

	/**
	 *  Set config vars
	 */
	public function set_vars() {
		$this->ajax_action_name         = $this->plugin_prefix . '_process_user_review_action';
		$this->banner_state_option_name = $this->plugin_prefix . '_review_request';
		$this->start_date_option_name   = $this->plugin_prefix . '_start_date';
		$this->banner_css_class         = $this->plugin_prefix . '_review_request';

		$this->start_date           = absint( get_option( $this->start_date_option_name ) );
		$banner_state               = absint( get_option( $this->banner_state_option_name ) );
		$this->current_banner_state = ( $banner_state == 0 ? $this->current_banner_state : $banner_state );
	}

	/**
	 *  Actions on plugin activation
	 *  Saves activation date
	 */
	public function on_activate() {
		if ( $this->start_date == 0 ) {
			$this->reset_start_date();
		}
	}

	/**
	 *  Actions on plugin deactivation
	 *  Removes activation date
	 */
	public function on_deactivate() {
		delete_option( $this->start_date_option_name );
	}

	/**
	 *  Reset the start date.
	 */
	private function reset_start_date() {
		update_option( $this->start_date_option_name, time() );
	}

	/**
	 *  Update the banner state
	 */
	private function update_banner_state( $val ) {
		update_option( $this->banner_state_option_name, $val );
	}

	/**
	 *  Prints the banner
	 */
	public function show_banner() {
		// Check if we are on plugin screens or WordPress plugins page
		$screen = get_current_screen();
		if ( ! ( preg_match( '/cookielawinfo/' , $screen->id ) || $screen->id === 'plugins' ) ) {
			return;
		}

		$this->update_banner_state( 1 ); /* update banner active state */
		?>
		<div class="<?php echo esc_attr( $this->banner_css_class ); ?> notice-info notice is-dismissible">
			<p>
				<?php echo wp_kses_post( $this->banner_message ); ?>
			</p>
			<p>
				<a class="button button-secondary" style="color:#333; border-color:#ccc; background:#efefef;" data-type="never"><?php echo esc_html( $this->never_btn_text ); ?></a>
				<a class="button button-primary" data-type="review"><?php echo esc_html( $this->review_btn_text ); ?></a>
			</p>
		</div>
		<?php
	}

	/**
	 *  Ajax hook to process user action on the banner
	 */
	public function process_user_action() {
		check_ajax_referer( $this->plugin_prefix );
		if ( isset( $_POST['wt_review_action_type'] ) ) {
			$action_type = sanitize_text_field( wp_unslash( $_POST['wt_review_action_type'] ) );

			/* current action is in allowed action list */
			if ( in_array( $action_type, $this->allowed_action_type_arr ) ) {
				if ( $action_type == 'never' ) {
					$new_banner_state = 3;
				} elseif ( $action_type == 'review' ) {
					$new_banner_state = 1;
				} else {
					/* reset start date to current date */
					$this->reset_start_date();
					$new_banner_state = 5; /* remind me later */
				}
				$this->update_banner_state( $new_banner_state );
			}
		}
		exit();
	}

	/**
	 *  Add banner JS to admin footer
	 */
	public function add_banner_scripts() {
		$ajax_url = admin_url( 'admin-ajax.php' );
		$nonce    = wp_create_nonce( $this->plugin_prefix );
		?>
		<script type="text/javascript">
			(function($) {
				"use strict";

				/* prepare data object */
				var data_obj = {
					_wpnonce: '<?php echo esc_js( $nonce ); ?>',
					action: '<?php echo esc_js( $this->ajax_action_name ); ?>',
					wt_review_action_type: ''
				};

				$(document).on('click', '.<?php echo esc_js( $this->banner_css_class ); ?> a.button', function(e) {
					e.preventDefault();
					var elm = $(this);
					var btn_type = elm.attr('data-type');
					if (btn_type == 'review') {
						window.open('<?php echo esc_js( $this->review_url ); ?>');
					} else {
						elm.parents('.<?php echo esc_js( $this->banner_css_class ); ?>').hide();
					}

					data_obj['wt_review_action_type'] = btn_type;
					$.ajax({
						url: '<?php echo esc_js( $ajax_url ); ?>',
						data: data_obj,
						type: 'POST'
					});

				}).on('click', '.<?php echo esc_js( $this->banner_css_class ); ?> .notice-dismiss', function(e) {
					e.preventDefault();
					data_obj['wt_review_action_type'] = 'closed';
					$.ajax({
						url: '<?php echo esc_js( $ajax_url ); ?>',
						data: data_obj,
						type: 'POST',
					});

				}).on('click', '.cli-button-review', function(e) {
					e.preventDefault();
					window.open('<?php echo esc_js( $this->review_url ); ?>');
					data_obj['wt_review_action_type'] = "review";
					$.ajax({
						url: '<?php echo esc_js( $ajax_url ); ?>',
						data: data_obj,
						type: 'POST'
					});
				});

			})(jQuery)
		</script>
		<?php
	}

	/**
	 *  Checks the condition to show the banner
	 */
	private function check_condition() {

		if ( $this->current_banner_state == 1 ) { /* currently showing then return true */
			return true;
		}

		if ( $this->current_banner_state == 2 || $this->current_banner_state == 5 ) { /* only waiting/remind later state */
			if ( $this->start_date == 0 ) { /*
				unable to get activated date */
				/* set current date as activation date*/
				$this->reset_start_date();
				return false;
			}

			$days = ( $this->current_banner_state == 2 ? $this->days_to_show_banner : $this->remind_days );

			$date_to_check = $this->start_date + ( 86400 * $days );
			if ( $date_to_check <= time() ) { /* time reached to show the banner */
				return true;
			} else {
				return false;
			}
		}

		return false;
	}

	function add_footer_review_link($footer_text) {
		// Check if we are on the plugin page
		$screen = get_current_screen();
		if ( preg_match( '/cookielawinfo/' , $screen->id ) ) {
			$link_text = esc_html__( 'Give us a 5-star rating!', 'cookie-law-info' );
			$link1 = sprintf(
				'<a class="cli-button-review" href="%2$s" title="%1$s" target="_blank">&#9733;&#9733;&#9733;&#9733;&#9733;</a>',
				$link_text,
				$this->review_url
			);
			$link2 = sprintf(
				'<a class="cli-button-review" href="%2$s" title="%1$s" target="_blank">WordPress.org</a>',
				$link_text,
				$this->review_url
			);

			return sprintf(
				/* translators: %1$s: CookieYes plugin name in bold, %2$s: star rating link, %3$s: WordPress.org link */
				esc_html__(
					'Please rate %1$s %2$s on %3$s to help us spread the word. Thank you from the team CookieYes!',
					'cookie-law-info'
				),
				sprintf( '<strong>%1$s</strong>', 'CookieYes' ),
				wp_kses_post( $link1 ),
				wp_kses_post( $link2 )
			);
		}
		return $footer_text;
	}
}
new Cookie_Law_Info_Review_Request();
