<?php

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

final class IComm_SM_Purchase {

	public const PRODUCT_SLUG = 'icomm-metrix';
	public const SITE_QUERY_KEY = 'lic_site';
	public const REDEEM_ACTION = 'icomm_sm_redeem_purchase';
	public const REDEEM_NONCE = 'icomm_sm_redeem_purchase';
	public const DEFAULT_NET_ILS = 600;
	public const DEFAULT_VAT_RATE = 0.18;

	public static function init(): void {
		add_action('admin_init', [__CLASS__, 'maybe_show_redeem_bridge'], 4);
		add_action('admin_post_' . self::REDEEM_ACTION, [__CLASS__, 'handle_redeem_purchase']);
	}

	public static function market_base_url(): string {
		return untrailingslashit((string) apply_filters('icomm_sm_market_base_url', 'https://icomm.market'));
	}

	public static function checkout_url(): string {
		if (!current_user_can('manage_options')) {
			return '';
		}
		$site = untrailingslashit(home_url('/'));
		if ($site === '') {
			return '';
		}
		return add_query_arg([
			'plugin' => self::PRODUCT_SLUG,
			self::SITE_QUERY_KEY => untrailingslashit(esc_url_raw($site)),
		], self::market_base_url() . '/icomm-lic-buy/');
	}

	/**
	 * @return array{net_ils:int,vat_rate:float,vat_percent:int,vat_ils:int,gross_ils:int,price_agorot:int,years:int}
	 */
	public static function pricing(): array {
		$defaults = [
			'net_ils' => self::DEFAULT_NET_ILS,
			'vat_rate' => self::DEFAULT_VAT_RATE,
			'years' => 1,
		];
		$raw = apply_filters('icomm_sm_pro_pricing', $defaults);
		if (!is_array($raw)) {
			$raw = $defaults;
		}
		$net = max(0, (int) ($raw['net_ils'] ?? self::DEFAULT_NET_ILS));
		$vat = max(0.0, (float) ($raw['vat_rate'] ?? self::DEFAULT_VAT_RATE));
		$gross = (int) round($net * (1 + $vat));
		return [
			'net_ils' => $net,
			'vat_rate' => $vat,
			'vat_percent' => (int) round($vat * 100),
			'vat_ils' => $gross - $net,
			'gross_ils' => $gross,
			'price_agorot' => $gross * 100,
			'years' => max(1, (int) ($raw['years'] ?? 1)),
		];
	}

	public static function maybe_show_redeem_bridge(): void {
		if (!is_admin() || !current_user_can('manage_options')) {
			return;
		}
		if (empty($_GET['icomm_lic_redeem']) || empty($_GET['icomm_lic_plugin'])) {
			return;
		}
		$code = sanitize_text_field(wp_unslash($_GET['icomm_lic_redeem']));
		$plugin = sanitize_key(wp_unslash($_GET['icomm_lic_plugin']));
		if ($code === '' || $plugin !== self::PRODUCT_SLUG) {
			return;
		}

		$action_url = admin_url('admin-post.php');
		$nonce_field = wp_nonce_field(self::REDEEM_NONCE, '_wpnonce', true, false);
		nocache_headers();
		status_header(200);
		header('Content-Type: text/html; charset=utf-8');

		$title = esc_html__('משלימים הפעלת רישיון…', 'icomm-metrix');
		$lead = esc_html__('רגע אחד - מפעילים את הרישיון באתר.', 'icomm-metrix');
		$btn = esc_html__('הפעל רישיון עכשיו', 'icomm-metrix');
		$hint = esc_html__('אם העמוד לא ממשיך אוטומטית, לחצו על הכפתור. אם ההפעלה נכשלת, העתיקו את מספר הרישיון מהמייל והפעילו ידנית בהגדרות.', 'icomm-metrix');

		echo '<!DOCTYPE html><html lang="he" dir="rtl"><head><meta charset="utf-8" />';
		echo '<meta name="viewport" content="width=device-width, initial-scale=1" /><title>' . $title . '</title>';
		echo '<style>body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;background:#f0f0f1;margin:0;padding:48px 16px;color:#1d2327;text-align:right}.box{max-width:480px;margin:0 auto;background:#fff;border:1px solid #c3c4c7;border-radius:4px;padding:28px 24px;box-shadow:0 1px 1px rgba(0,0,0,.04)}h1{font-size:1.25rem;margin:0 0 10px}p{margin:0 0 14px;line-height:1.5;color:#50575e}.button{display:inline-block;background:#2271b1;color:#fff;border:none;border-radius:3px;padding:10px 18px;font-size:14px;cursor:pointer}.button:hover{background:#135e96}.hint{font-size:13px;margin-top:18px}</style></head><body>';
		echo '<div class="box"><h1>' . $title . '</h1><p>' . $lead . '</p>';
		echo '<form id="icomm-sm-redeem-form" method="post" action="' . esc_url($action_url) . '">';
		echo '<input type="hidden" name="action" value="' . esc_attr(self::REDEEM_ACTION) . '" />' . $nonce_field;
		echo '<input type="hidden" name="icomm_lic_redeem" value="' . esc_attr($code) . '" />';
		echo '<input type="hidden" name="icomm_lic_plugin" value="' . esc_attr($plugin) . '" />';
		echo '<button type="submit" class="button">' . $btn . '</button></form><p class="hint">' . $hint . '</p></div>';
		echo '<script>(function(){var f=document.getElementById("icomm-sm-redeem-form");if(!f){return;}window.setTimeout(function(){try{f.submit();}catch(e){}},80);})();</script></body></html>';
		exit;
	}

	public static function handle_redeem_purchase(): void {
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('אין הרשאה.', 'icomm-metrix'), '', ['response' => 403]);
		}
		check_admin_referer(self::REDEEM_NONCE);

		$code = isset($_POST['icomm_lic_redeem']) ? sanitize_text_field(wp_unslash($_POST['icomm_lic_redeem'])) : '';
		$plugin = isset($_POST['icomm_lic_plugin']) ? sanitize_key(wp_unslash($_POST['icomm_lic_plugin'])) : '';
		$redirect = add_query_arg('page', 'icomm-metrix-settings', admin_url('admin.php'));

		if ($code === '' || $plugin !== self::PRODUCT_SLUG) {
			wp_safe_redirect(add_query_arg('icomm_sm_lic_msg', 'redeem_error', $redirect . '#icomm-sm-license'));
			exit;
		}

		$res = wp_remote_post(IComm_SM_License::endpoint_base() . '/redeem-purchase', [
			'timeout' => 20,
			'headers' => ['Content-Type' => 'application/json; charset=UTF-8'],
			'body' => wp_json_encode([
				'code' => $code,
				'site_url' => home_url('/'),
				'plugin' => $plugin,
			]),
		]);

		if (is_wp_error($res)) {
			wp_safe_redirect(add_query_arg('icomm_sm_lic_msg', 'redeem_error', $redirect . '#icomm-sm-license'));
			exit;
		}
		$data = json_decode((string) wp_remote_retrieve_body($res), true);
		if (!is_array($data) || empty($data['ok'])) {
			wp_safe_redirect(add_query_arg('icomm_sm_lic_msg', 'redeem_error', $redirect . '#icomm-sm-license'));
			exit;
		}

		$s = IComm_SM_License::get_settings();
		$s['license_key'] = strtoupper(trim((string) ($data['license_key'] ?? '')));
		$s['license_token'] = trim((string) ($data['token'] ?? ''));
		$s['license_expires_at'] = (int) ($data['expires_at'] ?? 0);
		$s['license_status'] = 'active';
		$s['license_last_ok'] = current_time('timestamp');
		$s['license_last_error'] = '';
		IComm_SM_License::save_settings($s);

		wp_safe_redirect(add_query_arg('icomm_sm_lic_msg', 'purchase_ok', $redirect . '#icomm-sm-license'));
		exit;
	}
}
