<?php
/**
 * Mersal Suite — per-plugin account helpers (connect URLs + sidebar footer).
 *
 * @package Mersal_Suite
 */

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

if ( class_exists( 'Mersal_Suite_Account' ) ) {
	return;
}

/**
 * Per-plugin Mersal.it account helpers for the Suite shell.
 */
class Mersal_Suite_Account {

	const KEYS = array(
		'sso_token',
		'api_key',
		'mersal_user',
		'site_url',
		'gateways',
		'sso_unlinked',
	);

	/** @var array<string,string> */
	private static $prefixes = array(
		'otp' => 'motp_',
		'cm'  => 'mcamp_',
		'nt'  => 'mnotif_',
	);

	/** @var array<string,string> */
	private static $connect_routes = array(
		'otp' => 'otp.connect',
		'cm'  => 'cm.connect',
		'nt'  => 'nt.connect',
	);

	/** @var array<string,string> */
	private static $sync_params = array(
		'otp' => 'motp_sync_gateways',
		'cm'  => 'mcamp_sync_gateways',
		'nt'  => 'mnotif_sync_gateways',
	);

	/** @var array<string,string> */
	private static $legacy_pages = array(
		'otp' => 'motp_page',
		'cm'  => 'mcamp_page',
		'nt'  => 'mnotif_page',
	);

	/** @var array<string,string> */
	private static $menu_slugs = array(
		'otp' => 'MOTP_MENU_SLUG',
		'cm'  => 'MCAMP_MENU_SLUG',
		'nt'  => 'MNOTIF_MENU_SLUG',
	);

	/** @var bool */
	private static $booted = false;

	/**
	 * One-time migration from unified storage back to per-plugin options.
	 */
	public static function init() {
		if ( self::$booted ) {
			return;
		}
		self::$booted = true;
		self::maybe_migrate_split();
	}

	/**
	 * Suite connect page URL for a plugin.
	 *
	 * @param string $plugin_id otp|cm|nt.
	 * @param string $tab       Optional OTP motp_tab value.
	 * @return string
	 */
	public static function connect_url( $plugin_id, $tab = '' ) {
		if ( ! class_exists( 'Mersal_Suite' ) ) {
			return '';
		}
		$route = isset( self::$connect_routes[ $plugin_id ] ) ? self::$connect_routes[ $plugin_id ] : 'otp.connect';
		$url   = Mersal_Suite::instance()->url( $route );
		if ( '' !== $tab && 'otp' === $plugin_id ) {
			return add_query_arg( 'motp_tab', $tab, $url );
		}
		return $url;
	}

	/**
	 * Is the current admin request a plugin connect screen?
	 *
	 * @param string|null $plugin_id Limit to one plugin, or null for any.
	 * @return bool
	 */
	public static function is_connect_screen( $plugin_id = null ) {
		if ( ! is_admin() ) {
			return false;
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! isset( $_GET['page'] ) ) {
			return false;
		}

		$check = static function ( $id ) {
			if ( ! class_exists( 'Mersal_Suite' ) ) {
				return false;
			}
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$page = sanitize_key( wp_unslash( $_GET['page'] ) );
			if ( Mersal_Suite::MENU_SLUG === $page ) {
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended
				$route = isset( $_GET['route'] ) ? sanitize_key( wp_unslash( $_GET['route'] ) ) : 'hub';
				$want  = isset( self::$connect_routes[ $id ] ) ? self::$connect_routes[ $id ] : '';
				if ( $want && $route === $want ) {
					return true;
				}
				$sync = isset( self::$sync_params[ $id ] ) ? self::$sync_params[ $id ] : '';
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended
				if ( $sync && ! empty( $_GET[ $sync ] ) ) {
					return true;
				}
			}
			$slug_const = isset( self::$menu_slugs[ $id ] ) ? self::$menu_slugs[ $id ] : '';
			if ( $slug_const && defined( $slug_const ) ) {
				$menu = constant( $slug_const );
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended
				if ( $menu === $page ) {
					$legacy = isset( self::$legacy_pages[ $id ] ) ? self::$legacy_pages[ $id ] : '';
					// phpcs:ignore WordPress.Security.NonceVerification.Recommended
					$sub = $legacy && isset( $_GET[ $legacy ] ) ? sanitize_key( wp_unslash( $_GET[ $legacy ] ) ) : '';
					return 'mersal' === $sub;
				}
			}
			return false;
		};

		if ( null !== $plugin_id ) {
			return $check( $plugin_id );
		}
		foreach ( array_keys( self::$connect_routes ) as $id ) {
			if ( $check( $id ) ) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Sidebar footer chip for the active plugin context.
	 *
	 * @param string $plugin_id suite|otp|cm|nt.
	 * @return array{connected:bool,title:string,subtitle:string,initials:string,url:string}
	 */
	public static function footer_for_plugin( $plugin_id ) {
		$ar = class_exists( 'Mersal_Suite' ) && 'ar' === Mersal_Suite::instance()->lang();

		if ( 'suite' === $plugin_id ) {
			$unlinked = 0;
			foreach ( array_keys( self::$connect_routes ) as $id ) {
				$st = self::connect_status( $id );
				if ( empty( $st['connected'] ) ) {
					$unlinked++;
				}
			}
			if ( 0 === $unlinked ) {
				return array(
					'connected' => true,
					'title'     => $ar ? 'حسابات مرسال' : 'Mersal accounts',
					'subtitle'  => $ar ? '٣ إضافات متصلة' : '3 plugins connected',
					'initials'  => 'م',
					'url'       => class_exists( 'Mersal_Suite' ) ? Mersal_Suite::instance()->url( 'hub' ) : '',
				);
			}
			$first = null;
			foreach ( array_keys( self::$connect_routes ) as $id ) {
				$st = self::connect_status( $id );
				if ( empty( $st['connected'] ) ) {
					$first = $id;
					break;
				}
			}
			return array(
				'connected' => false,
				'title'     => $ar ? 'ربط حسابات مرسال' : 'Connect Mersal accounts',
				'subtitle'  => $ar
					? sprintf( '%d إضافة غير مربوطة', $unlinked )
					: sprintf( '%d plugin(s) not linked', $unlinked ),
				'initials'  => 'م',
				'url'       => $first ? self::connect_url( $first ) : ( class_exists( 'Mersal_Suite' ) ? Mersal_Suite::instance()->url( 'hub' ) : '' ),
			);
		}

		$st = self::connect_status( $plugin_id );
		$st['url'] = self::connect_url( $plugin_id );
		return $st;
	}

	/**
	 * Read connection status for one plugin.
	 *
	 * @param string $plugin_id otp|cm|nt.
	 * @return array{connected:bool,title:string,subtitle:string,initials:string}
	 */
	private static function connect_status( $plugin_id ) {
		$ar = class_exists( 'Mersal_Suite' ) && 'ar' === Mersal_Suite::instance()->lang();

		$classes = array(
			'otp' => 'Mersal_OTP_Connect',
			'cm'  => 'Mersal_Campaign_Connect',
			'nt'  => 'Mersal_Notif_Connect',
		);
		$labels = array(
			'otp' => array( $ar ? 'مرسال OTP' : 'Mersal OTP', $ar ? 'ربط حساب OTP' : 'Connect OTP account' ),
			'cm'  => array( $ar ? 'مرسال للحملات' : 'Mersal Campaigns', $ar ? 'ربط حساب الحملات' : 'Connect Campaigns account' ),
			'nt'  => array( $ar ? 'مرسال للإشعارات' : 'Mersal Notifications', $ar ? 'ربط حساب الإشعارات' : 'Connect Notifications account' ),
		);

		if ( ! isset( $classes[ $plugin_id ] ) || ! class_exists( $classes[ $plugin_id ] ) ) {
			$lab = isset( $labels[ $plugin_id ] ) ? $labels[ $plugin_id ] : array( 'Mersal', 'Connect Mersal' );
			return array(
				'connected' => false,
				'title'     => $lab[1],
				'subtitle'  => $ar ? 'غير متصل' : 'Not connected',
				'initials'  => 'م',
			);
		}

		$connect = new $classes[ $plugin_id ]();
		$lab     = $labels[ $plugin_id ];
		if ( ! $connect->is_connected() ) {
			return array(
				'connected' => false,
				'title'     => $lab[1],
				'subtitle'  => $lab[0] . ' · ' . ( $ar ? 'غير متصل' : 'Not connected' ),
				'initials'  => 'م',
			);
		}

		$host = wp_parse_url( $connect->site_url(), PHP_URL_HOST );
		$host = $host ? $host : 'mersal.it';
		$name = $connect->account_name();
		return array(
			'connected' => true,
			'title'     => $name ? $name : $lab[0],
			'subtitle'  => $host . ' · ' . ( $ar ? 'متصل' : 'Connected' ),
			'initials'  => $connect->account_initials(),
		);
	}

	/**
	 * Copy unified mersal_suite_* values into per-plugin prefixes when empty.
	 */
	private static function maybe_migrate_split() {
		if ( get_option( 'mersal_suite_account_split_migrated', false ) ) {
			return;
		}
		$has_shared = false;
		foreach ( self::KEYS as $key ) {
			$val = get_option( 'mersal_suite_' . $key, false );
			if ( false !== $val && '' !== $val && array() !== $val ) {
				$has_shared = true;
				break;
			}
		}
		if ( ! $has_shared ) {
			update_option( 'mersal_suite_account_split_migrated', 1, false );
			return;
		}
		foreach ( self::$prefixes as $pfx ) {
			foreach ( self::KEYS as $key ) {
				$legacy = $pfx . $key;
				$cur    = get_option( $legacy, false );
				if ( false !== $cur && '' !== $cur && array() !== $cur ) {
					continue;
				}
				$shared = get_option( 'mersal_suite_' . $key, false );
				if ( false === $shared || '' === $shared || array() === $shared ) {
					continue;
				}
				update_option( $legacy, $shared, false );
			}
		}
		update_option( 'mersal_suite_account_split_migrated', 1, false );
	}
}
