<?php

/**
 * @package storzen
 * @since   1.1.0
 */

if (! defined('ABSPATH')) {
	exit;
}

if (! class_exists('Storzen_Review_Notice')) {

	/**
	 * Shows a "leave a review" admin notice once the plugin has been
	 * active for 7+ days, unless the site owner already dismissed it.
	 */
	class Storzen_Review_Notice
	{

		public function __construct()
		{
			add_action('admin_init', array($this, 'maybe_set_installed_date'));
			add_action('admin_init', array($this, 'maybe_dismiss'));
			add_action('admin_notices', array($this, 'render_notice'));
		}

		/**
		 * Fallback for sites where the plugin was already active before this
		 * option existed (register_activation_hook only fires on activation).
		 */
		public function maybe_set_installed_date()
		{
			if (false === get_option('storzen_installed_date')) {
				add_option('storzen_installed_date', time());
			}
		}

		/**
		 * Handles the "Dismiss" link click on the review notice.
		 */
		public function maybe_dismiss()
		{
			if (! isset($_GET['storzen_dismiss_review'])) {
				return;
			}

			if (! isset($_GET['_wpnonce']) || ! wp_verify_nonce(sanitize_key($_GET['_wpnonce']), 'storzen_dismiss_review')) {
				return;
			}

			if (! current_user_can('manage_options')) {
				return;
			}

			update_option('storzen_review_dismissed', 1);

			wp_safe_redirect(remove_query_arg(array('storzen_dismiss_review', '_wpnonce')));
			exit;
		}

		public function render_notice()
		{
			if (! current_user_can('manage_options')) {
				return;
			}

			$installed_date = (int) get_option('storzen_installed_date');

			if (! $installed_date || $installed_date > strtotime('-7 days') || get_option('storzen_review_dismissed')) {
				return;
			}

			$dismiss_url = wp_nonce_url(
				add_query_arg('storzen_dismiss_review', '1'),
				'storzen_dismiss_review'
			);

			printf(
				'<div class="notice notice-info storzen-review-notice"><p>%1$s <a href="%2$s" target="_blank" rel="noopener noreferrer">%3$s</a> &nbsp;|&nbsp; <a href="%4$s">%5$s</a></p></div>',
				esc_html__('Enjoying Storzen? Please leave a ★★★★★ review, it really helps us!', 'storzen'),
				esc_url('https://wordpress.org/plugins/storzen/#reviews'),
				esc_html__('Leave a Review', 'storzen'),
				esc_url($dismiss_url),
				esc_html__('Dismiss', 'storzen')
			);
		}
	}
}
