<?php

declare(strict_types=1);

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

/**
 * Admin review request banner.
 *
 * Shows a dismissible notice asking the user to rate the plugin after 7 days of use.
 * - "Rate" → dismisses permanently and opens wp.org review page.
 * - "Later" → hides for 7 days.
 * - "Support" → opens wp.org support forum (banner stays).
 */
final class CRToday_Review_Banner {
	private const OPT_INSTALLED_AT = 'crtoday_installed_at';
	private const OPT_DISMISSED    = 'crtoday_review_dismissed';
	private const OPT_REMIND_AT    = 'crtoday_review_remind_at';
	private const DELAY_DAYS       = 7;
	private const REMIND_DAYS      = 7;

	/**
	 * Return current review-banner state for debug introspection.
	 *
	 * @return array{installed_at: int, dismissed: bool, remind_at: int, delay_days: int, remind_days: int}
	 */
	public static function get_state(): array {
		return [
			'installed_at' => (int) get_option(self::OPT_INSTALLED_AT, 0),
			'dismissed'    => get_option(self::OPT_DISMISSED) === '1',
			'remind_at'    => (int) get_option(self::OPT_REMIND_AT, 0),
			'delay_days'   => self::DELAY_DAYS,
			'remind_days'  => self::REMIND_DAYS,
		];
	}

	/**
	 * Reset review-banner state so it can be triggered again.
	 */
	public static function reset_state(): void {
		delete_option(self::OPT_DISMISSED);
		delete_option(self::OPT_REMIND_AT);
		/* Set installed_at far enough in the past to pass the delay check */
		update_option(self::OPT_INSTALLED_AT, time() - (self::DELAY_DAYS + 1) * DAY_IN_SECONDS, 'no');
	}

	public static function register(): void {
		add_action('admin_notices', [self::class, 'maybe_show_banner']);
		add_action('wp_ajax_crtoday_review_action', [self::class, 'handle_ajax']);

		/* Record installation timestamp on first load */
		if (get_option(self::OPT_INSTALLED_AT) === false) {
			add_option(self::OPT_INSTALLED_AT, time(), '', 'no');
		}
	}

	/**
	 * Cleanup all review-related options (called from uninstall.php).
	 */
	public static function delete_all_data(): void {
		delete_option(self::OPT_INSTALLED_AT);
		delete_option(self::OPT_DISMISSED);
		delete_option(self::OPT_REMIND_AT);
	}

	/* ── Banner visibility logic ── */

	public static function maybe_show_banner(): void {
		if (! current_user_can('manage_options')) {
			return;
		}

		/* Already dismissed permanently */
		if (get_option(self::OPT_DISMISSED) === '1') {
			return;
		}

		/* Postponed — check remind_at */
		$remind_at = (int) get_option(self::OPT_REMIND_AT, 0);
		if ($remind_at > 0 && time() < $remind_at) {
			return;
		}

		/* Not enough time since installation */
		$installed_at = (int) get_option(self::OPT_INSTALLED_AT, 0);
		if ($installed_at <= 0 || (time() - $installed_at) < self::DELAY_DAYS * DAY_IN_SECONDS) {
			return;
		}

		self::render_banner();
	}

	/* ── AJAX handler ── */

	public static function handle_ajax(): void {
		if (! current_user_can('manage_options')) {
			wp_send_json_error('Forbidden', 403);
		}

		check_ajax_referer('crtoday_review_action', 'nonce');

		$action = isset($_POST['banner_action'])
			? sanitize_key(wp_unslash($_POST['banner_action']))
			: '';

		if ($action === 'rate') {
			update_option(self::OPT_DISMISSED, '1', 'no');
			wp_send_json_success(['redirect' => 'https://wordpress.org/support/plugin/currencyrate-today-currency-blocks/reviews/#new-post']);
		}

		if ($action === 'later') {
			update_option(self::OPT_REMIND_AT, time() + self::REMIND_DAYS * DAY_IN_SECONDS, 'no');
			wp_send_json_success();
		}

		wp_send_json_error('Unknown action', 400);
	}

	/* ── Render ── */

	/**
	 * Force-render the banner unconditionally (for debug tab).
	 */
	public static function force_render(): void {
		self::render_banner();
	}

	private static function render_banner(): void {
		$nonce      = wp_create_nonce('crtoday_review_action');
		$ajax_url   = admin_url('admin-ajax.php');
		$support_url = 'https://wordpress.org/support/plugin/currencyrate-today-currency-blocks/';
		?>
		<div class="notice notice-info is-dismissible crtoday-review-banner" id="crtoday-review-banner" style="padding:12px 16px;border-left-color:#dba617;">
			<div style="display:flex;align-items:flex-start;gap:12px;">
				<span class="dashicons dashicons-star-filled" style="color:#dba617;font-size:24px;width:24px;height:24px;margin-top:2px;flex-shrink:0;"></span>
				<div style="flex:1;">
					<p style="margin:0 0 6px;font-size:14px;">
						<strong><?php esc_html_e('Enjoying CurrencyRate.Today - Currency Blocks and Widgets?', 'currencyrate-today-currency-blocks'); ?></strong>
					</p>
					<p style="margin:0 0 12px;color:#2271b1;">
						<?php esc_html_e('Please leave a review to help others discover the plugin. If something isn\'t working, contact support first — we\'ll fix it quickly!', 'currencyrate-today-currency-blocks'); ?>
					</p>
					<div style="display:flex;gap:8px;flex-wrap:wrap;">
						<button type="button" class="button button-primary crtoday-review-btn" data-action="rate" style="display:inline-flex;align-items:center;gap:4px;">
							<span class="dashicons dashicons-star-filled" style="font-size:16px;width:16px;height:16px;"></span>
							<?php esc_html_e('Rate the plugin', 'currencyrate-today-currency-blocks'); ?>
						</button>
						<button type="button" class="button crtoday-review-btn" data-action="later" style="display:inline-flex;align-items:center;gap:4px;">
							<span class="dashicons dashicons-clock" style="font-size:16px;width:16px;height:16px;"></span>
							<?php esc_html_e('Remind me later', 'currencyrate-today-currency-blocks'); ?>
						</button>
						<a href="<?php echo esc_url($support_url); ?>" target="_blank" rel="noopener noreferrer" class="button" style="display:inline-flex;align-items:center;gap:4px;">
							<span class="dashicons dashicons-sos" style="font-size:16px;width:16px;height:16px;"></span>
							<?php esc_html_e('Get support', 'currencyrate-today-currency-blocks'); ?>
						</a>
					</div>
				</div>
			</div>
		</div>
		<?php
		wp_register_script('crtoday-review-banner', false, [], CRTODAY_PLUGIN_VERSION, ['in_footer' => true]); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.NotInFooter
		wp_enqueue_script('crtoday-review-banner');

		$js = '(function(){'
			. 'var banner=document.getElementById("crtoday-review-banner");'
			. 'if(!banner)return;'
			. 'function sendBannerAction(a){'
			.   'if(!a)return;'
			.   'var xhr=new XMLHttpRequest();'
			.   'xhr.open("POST",' . wp_json_encode(esc_url($ajax_url)) . ');'
			.   'xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");'
			.   'xhr.onload=function(){'
			.     'if(xhr.status===200){'
			.       'try{var res=JSON.parse(xhr.responseText);if(res.data&&res.data.redirect){window.open(res.data.redirect,"_blank");}}catch(ex){}'
			.       'banner.style.display="none";'
			.     '}'
			.   '};'
			.   'xhr.send("action=crtoday_review_action&banner_action="+encodeURIComponent(a)+"&nonce=" + ' . wp_json_encode(esc_js($nonce)) . ');'
			. '}'
			. 'banner.addEventListener("click",function(e){'
			.   'var d=e.target.closest(".notice-dismiss");'
			.   'if(d){sendBannerAction("later");return;}'
			.   'var btn=e.target.closest(".crtoday-review-btn");'
			.   'if(!btn)return;'
			.   'sendBannerAction(btn.getAttribute("data-action"));'
			. '});'
			. '})();';

		wp_add_inline_script('crtoday-review-banner', $js);
	}
}
