<?php

declare(strict_types=1);

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

/**
 * Admin review request banner.
 *
 * Shows a dismissible notice asking the user to rate the plugin right after activation.
 * - "Rate" → dismisses permanently and opens wp.org review page.
 * - "Later" / dismiss (×) → hides for 14 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       = 0;
	private const REMIND_DAYS      = 14;

	/**
	 * 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();
		}

		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/';
		$review_url  = 'https://wordpress.org/support/plugin/currencyrate-today-currency-blocks/reviews/#new-post';
		?>
		<style>
			#crtoday-review-banner{
				position:relative;
				margin:16px 20px 16px 2px;
				padding:0;
				border:none;
				border-radius:14px;
				background:linear-gradient(135deg,#eef2ff 0%,#f5f3ff 50%,#faf5ff 100%);
				box-shadow:0 10px 26px rgba(15,23,42,.08);
				overflow:hidden;
			}
			#crtoday-review-banner::before{
				content:"";
				position:absolute;
				inset:0;
				border:1px solid rgba(99,102,241,.18);
				border-radius:inherit;
				pointer-events:none;
			}
			#crtoday-review-banner .crtoday-rb-inner{
				position:relative;
				display:flex;
				align-items:flex-start;
				gap:18px;
				padding:22px 26px;
			}
			#crtoday-review-banner .crtoday-rb-icon{
				flex-shrink:0;
				width:44px;height:44px;
				display:flex;align-items:center;justify-content:center;
				border-radius:12px;
				background:linear-gradient(135deg,#6366f1 0%,#8b5cf6 100%);
				box-shadow:0 4px 14px rgba(99,102,241,.3);
			}
			#crtoday-review-banner .crtoday-rb-icon svg{
				width:22px;height:22px;fill:#fff;
			}
			#crtoday-review-banner .crtoday-rb-title{
				margin:0 0 4px;
				font-size:15px;font-weight:700;
				color:#0f172a;line-height:1.35;
				letter-spacing:-.01em;
			}
			#crtoday-review-banner .crtoday-rb-desc{
				margin:0 0 16px;
				font-size:13.5px;line-height:1.55;
				color:#475569;
			}
			#crtoday-review-banner .crtoday-rb-actions{
				display:flex;gap:10px;flex-wrap:wrap;
			}
			#crtoday-review-banner .crtoday-rb-btn{
				display:inline-flex;align-items:center;gap:6px;
				padding:8px 18px;
				border:none;border-radius:8px;
				font-size:13px;font-weight:600;
				line-height:1.4;cursor:pointer;
				transition:all .2s ease;
				text-decoration:none;
			}
			#crtoday-review-banner .crtoday-rb-btn:focus-visible{
				outline:none;
				box-shadow:0 0 0 3px rgba(99,102,241,.25);
			}
			#crtoday-review-banner .crtoday-rb-btn--rate{
				background:linear-gradient(135deg,#6366f1 0%,#7c3aed 100%);
				color:#fff;
				box-shadow:0 4px 14px rgba(99,102,241,.28);
			}
			#crtoday-review-banner .crtoday-rb-btn--rate:hover{
				transform:translateY(-1px);
				box-shadow:0 6px 20px rgba(99,102,241,.36);
			}
			#crtoday-review-banner .crtoday-rb-btn--rate:active{
				transform:translateY(0);
			}
			#crtoday-review-banner .crtoday-rb-btn--later{
				background:#fff;
				color:#475569;
				box-shadow:0 1px 3px rgba(15,23,42,.08);
				border:1px solid #d1d8e0;
			}
			#crtoday-review-banner .crtoday-rb-btn--later:hover{
				color:#0f172a;
				border-color:#94a3b8;
				transform:translateY(-1px);
				box-shadow:0 3px 10px rgba(15,23,42,.1);
			}
			#crtoday-review-banner .crtoday-rb-btn--later:active{
				transform:translateY(0);
			}
			#crtoday-review-banner .crtoday-rb-btn--support{
				background:transparent;
				color:#6366f1;
				padding:8px 12px;
			}
			#crtoday-review-banner .crtoday-rb-btn--support:hover{
				background:rgba(99,102,241,.08);
				transform:translateY(-1px);
			}
			#crtoday-review-banner .crtoday-rb-btn--support:active{
				transform:translateY(0);
			}
			#crtoday-review-banner .crtoday-rb-btn svg{
				width:15px;height:15px;flex-shrink:0;
			}
			#crtoday-review-banner .crtoday-rb-dismiss{
				position:absolute;top:12px;right:12px;
				width:28px;height:28px;
				display:flex;align-items:center;justify-content:center;
				border:none;border-radius:8px;
				background:transparent;cursor:pointer;
				color:#94a3b8;
				transition:all .2s ease;
			}
			#crtoday-review-banner .crtoday-rb-dismiss:hover{
				background:rgba(15,23,42,.06);color:#475569;
			}
			#crtoday-review-banner .crtoday-rb-dismiss svg{
				width:16px;height:16px;
			}
			#crtoday-review-banner .crtoday-rb-stars{
				position:absolute;top:14px;right:50px;
				display:flex;gap:2px;opacity:.18;
			}
			#crtoday-review-banner .crtoday-rb-stars svg{
				width:14px;height:14px;fill:#6366f1;
			}
		</style>
		<div id="crtoday-review-banner">
			<div class="crtoday-rb-inner">
				<div class="crtoday-rb-icon">
					<svg viewBox="0 0 24 24"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.56 5.82 22 7 14.14l-5-4.87 6.91-1.01z"/></svg>
				</div>
				<div style="flex:1;min-width:0;">
					<p class="crtoday-rb-title"><?php esc_html_e('Enjoying CurrencyRate.Today - Currency Blocks and Widgets?', 'currencyrate-today-currency-blocks'); ?></p>
					<p class="crtoday-rb-desc"><?php esc_html_e('Please leave a review to help us keep the plugin up to date. If something isn\'t working, contact support first — we\'ll fix it quickly!', 'currencyrate-today-currency-blocks'); ?></p>
					<div class="crtoday-rb-actions">
						<button type="button" class="crtoday-rb-btn crtoday-rb-btn--rate crtoday-review-btn" data-action="rate" data-review-url="<?php echo esc_url($review_url); ?>">
							<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 22 12 18.56 5.82 22 7 14.14l-5-4.87 6.91-1.01z"/></svg>
							<?php esc_html_e('Rate the plugin', 'currencyrate-today-currency-blocks'); ?>
						</button>
						<button type="button" class="crtoday-rb-btn crtoday-rb-btn--later crtoday-review-btn" data-action="later">
							<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
							<?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="crtoday-rb-btn crtoday-rb-btn--support">
							<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
							<?php esc_html_e('Get support', 'currencyrate-today-currency-blocks'); ?>
						</a>
					</div>
				</div>
			</div>

			<button type="button" class="crtoday-rb-dismiss crtoday-review-btn" data-action="later" aria-label="<?php esc_attr_e('Dismiss', 'currencyrate-today-currency-blocks'); ?>">
				<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
			</button>
		</div>
		<script>
		(function(){
			var banner=document.getElementById("crtoday-review-banner");
			if(!banner)return;
			var ajaxUrl=<?php echo wp_json_encode( esc_url( $ajax_url ) ); ?>;
			var nonce=<?php echo wp_json_encode( $nonce ); ?>;
			function sendAction(a,btn){
				if(!a)return;
				if(a==="rate"&&btn){var u=btn.getAttribute("data-review-url");if(u)window.open(u,"_blank");}
				banner.style.transition="opacity .3s ease,transform .3s ease";
				banner.style.opacity="0";
				banner.style.transform="translateY(-8px)";
				setTimeout(function(){banner.style.display="none";},300);
				var xhr=new XMLHttpRequest();
				xhr.open("POST",ajaxUrl);
				xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				xhr.send("action=crtoday_review_action&banner_action="+encodeURIComponent(a)+"&nonce="+encodeURIComponent(nonce));
			}
			banner.addEventListener("click",function(e){
				var dismiss=e.target.closest(".crtoday-rb-dismiss");
				if(dismiss){e.preventDefault();sendAction("later");return;}
				var btn=e.target.closest(".crtoday-review-btn");
				if(!btn)return;
				sendAction(btn.getAttribute("data-action"),btn);
			});
		})();
		</script>
		<?php
	}
}
