<?php

/**
 * Reviews.
 * copyright Simple Direct Plugins - support@simpledirectplugins.com
 *
 * @author 			Simple Direct Plugins
 * @link			https://simpledirectplugins.com
 * @since			5.9.0
 * @package			SCOSWoo
 *
 */

defined ('ABSPATH') or exit;

if (!class_exists('SCOS_Review')) :

	Class SCOS_Review {

		const DEVEL   = false;
		const PREFIX  = 'scos_';
		const LINK    = 'https://wordpress.org/support/plugin/sdp-custom-order-status-for-woocommerce/reviews/#new-post';
		const SUPPORT = 'https://simpledirectplugins.com/contact/';
		const CPT     = SCOS_CPT::CPT;
		const ASSETS  = SCOS_ASSETS;
		const COUNT   = 2;
		const DAYS    = 3;
		const SCREENS = ['dashboard', 'plugins', self::CPT, 'edit-' . self::CPT];

		private array $texts;
		
		public function __construct () {

			if (!is_admin())
				return;

			$this->texts = [
				'notice'            => __('Is SDP Custom Order Status for WooCommerce helping you manage your orders more efficiently?', 'sdp-custom-order-status-for-woocommerce'),
				'positiveMessage'   => __('Great! Reviews help a lot. Would you mind leaving one?', 'sdp-custom-order-status-for-woocommerce'),
				'negativeMessage'   => __('Sorry to hear that. Would you like to send us feedback?', 'sdp-custom-order-status-for-woocommerce'),
				'leaveReview'       => __('Leave a review', 'sdp-custom-order-status-for-woocommerce'),
				'maybeLater'        => __('Maybe later', 'sdp-custom-order-status-for-woocommerce'),
				'sendFeedback'      => __('Send feedback', 'sdp-custom-order-status-for-woocommerce'),
				'dismiss'           => __('Dismiss', 'sdp-custom-order-status-for-woocommerce'),
				'yes' 		        => __('Yes, it’s helpful', 'sdp-custom-order-status-for-woocommerce'),
				'no'	            => __('Not really', 'sdp-custom-order-status-for-woocommerce'),
				];

			add_action ('admin_notices', [$this, 'review_notice']);
			add_action ('wp_ajax_' . self::PREFIX . 'review_action', [$this, 'ajax_review_action']);
			add_action ('admin_enqueue_scripts', [$this, 'script_reviews'], 10);
			}

		public function review_notice () {

			if (!$this->should_show_review_notice())
				return;

			printf ('<div class="notice notice-success" id="%sreview-notice">
					<p class="%sreview-message">%s</p>
					<p class="%sreview-actions">
						<a href="#" class="button button-primary" data-action="positive">👍 %s</a> 
						<a href="#" class="button button-secondary" data-action="negative">👎 %s</a> 
						<a href="#" class="button button-secondary" data-action="dismiss">%s</a>
					</p>
				</div>',
				esc_attr (self::PREFIX),
				esc_attr (self::PREFIX),
				esc_html ($this->texts['notice']),
				esc_attr (self::PREFIX),
				esc_html ($this->texts['yes']),
				esc_html ($this->texts['no']),
				esc_html ($this->texts['dismiss'])
				);
			}

		public function ajax_review_action () {

			check_ajax_referer (self::PREFIX . 'review_nonce', 'nonce');

			if (!current_user_can ('manage_options'))
				wp_send_json_error();

			$user_id = get_current_user_id();
			$action  = isset ($_POST['review_action']) ? sanitize_key (wp_unslash ($_POST['review_action'])) : '';

			switch ($action) {

				case 'dismiss':
					update_user_meta ($user_id, self::PREFIX . 'review_dismissed', 1);
					break;

				case 'later':
					update_user_meta ($user_id, self::PREFIX . 'review_later', time() + 30 * DAY_IN_SECONDS);
					break;

				case 'positive':
					update_user_meta ($user_id, self::PREFIX . 'review_positive', 1);
					break;

				case 'negative':
					update_user_meta ($user_id, self::PREFIX . 'review_negative', 1);
					break;

				case 'reviewed':
					update_user_meta ($user_id, self::PREFIX . 'review_dismissed', 1);
					update_user_meta ($user_id, self::PREFIX . 'review_reviewed', 1);
					break;

				case 'feedback':
					update_user_meta ($user_id, self::PREFIX . 'review_dismissed', 1);
					update_user_meta ($user_id, self::PREFIX . 'review_feedback', 1);
					break;

				default:
					wp_send_json_error ();
				}

			wp_send_json_success ();
			}

		private function should_show_review_notice () {

			if (!current_user_can ('manage_options'))
				return false;
			
			if (!$this->is_valid_screen())
				return false;
			
			if (defined ('WP_DEBUG') && WP_DEBUG && self::DEVEL)
				return true; //Temporal, para pruebas en desarrollo.

			$user_id = get_current_user_id();

			if (get_user_meta ($user_id, self::PREFIX . 'review_dismissed', true)) //Si el usuario ya descartó la petición, lo dejamos.
				return false;

			$time_now = time();

			if ($later = (int) get_user_meta ($user_id, self::PREFIX . 'review_later', true)) //Si ya pulsó el botón "Maybe later".
				return ($later > $time_now) ? false : true;

			$count = wp_count_posts (self::CPT);

			if (!isset ($count->publish) || $count->publish < self::COUNT) //Si aún no se han publicado COUNT o más, lo dejamos.
				return false;

			$activation = (int) get_option (self::PREFIX . 'activation', $time_now);

			if ($activation + self::DAYS * DAY_IN_SECONDS > $time_now) //Si no lleva aún al menos DAYS días usando el plugin, lo dejamos.
				return false;

			return true;
			}

		private function is_valid_screen () {

			if (!function_exists ('get_current_screen'))
				return false;

			$screen = get_current_screen();

			if (!$screen || !isset ($screen->id))
				return false;

			return in_array ($screen->id, self::SCREENS, true);
			}

		public function script_reviews () {

			if (!$this->should_show_review_notice())
				return;

			wp_enqueue_script (self::PREFIX . 'review', self::ASSETS . 'js/review.min.js', [], '1.0', true);

			wp_localize_script (
				self::PREFIX . 'review',
				self::PREFIX . 'review',
				[
					'prefix'        => self::PREFIX,
					'ajaxUrl'       => admin_url ('admin-ajax.php'),
					'nonce'         => wp_create_nonce (self::PREFIX . 'review_nonce'),
					'reviewUrl'     => self::LINK,
					'supportUrl'    => self::SUPPORT,
					'texts'         => $this->texts,
					]);
			}

		}

endif;