<?php

namespace CommerceBird\Admin;

use CommerceBird\Admin\Traits\Singleton;
use CommerceBird\API\CreateOrderWebhook;
use CommerceBird\API\ProductWebhook;
use CommerceBird\API\ShippingWebhook;

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

final class Template {
	use Singleton;

	const NAME = 'commercebird-app';

	public function __construct() {
		add_action( 'admin_menu', array( $this, 'menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'scripts' ) );
		add_action( 'admin_notices', array( $this, 'subscription_expired_notice' ) );
		add_action( 'admin_head', array( $this, 'admin_notice_styles' ) );
	}

	public function menu(): void {
		$svg = CMBIRD_URL . 'admin/commercebird-icon.svg';
		add_menu_page(
			__( 'CommerceBird', 'commercebird' ),
			__( 'CommerceBird', 'commercebird' ),
			'manage_woocommerce',
			self::NAME,
			function () {
				wp_enqueue_style( self::NAME );
				wp_enqueue_style( self::NAME . '-notify', CMBIRD_URL . 'admin/css/notyf.min.css', array(), CMBIRD_VERSION );
				// Pass version number to the Vue script.
				wp_localize_script(
					self::NAME,
					'cmbirdData',
					array(
						'version' => CMBIRD_VERSION,
					)
				);
				wp_enqueue_script( self::NAME );
				add_filter( 'script_loader_tag', array( $this, 'add_module' ), 10, 2 );
				printf( '<div id="%s">Loading...</div>', esc_attr( self::NAME ) );
			},
			$svg,
			29
		);
	}

	/**
	 * It will add module attribute to script tag.
	 *
	 * @param string $tag of script.
	 * @param string $id of script.
	 *
	 * @return string
	 */
	public function add_module( string $tag, string $id ): string {
		if ( self::NAME === $id ) {
			$tag = str_replace( '<script ', '<script type="module" ', $tag );
		}

		return $tag;
	}

	/**
	 * It loads scripts based on plugin's mode, dev or prod.
	 *
	 * @return void
	 */
	public function scripts(): void {
		global $wp_roles;
		wp_register_style( self::NAME, CMBIRD_URL . 'admin/assets/dist/index.css', array(), CMBIRD_VERSION );
		wp_register_script( self::NAME, CMBIRD_URL . 'admin/assets/dist/index.js', array(), CMBIRD_VERSION, true );
		wp_add_inline_style( self::NAME, '#wpcontent, .auto-fold # wpcontent{padding-left: 0px} #wpcontent .notice, #wpcontent #message{display: none} input[type=checkbox]:checked::before{content:unset}' );
		// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Using WordPress core filter.
		$active_plugins = apply_filters( 'active_plugins', get_option( 'active_plugins' ) );
		wp_localize_script(
			self::NAME,
			'commercebird_admin',
			array(
				'security_token' => wp_create_nonce( self::NAME ),
				'api_token' => get_option( 'cmbird_zi_webhook_password', false ),
				'webhooks' => array(
					'Items' => ProductWebhook::endpoint(),
					'Order Create' => CreateOrderWebhook::endpoint(),
					'Shipping Status' => ShippingWebhook::endpoint(),
				),
				'redirect_uri' => admin_url( 'admin.php?page=commercebird-app' ),
				'url' => admin_url( 'admin-ajax.php' ),
				'wc_tax_enabled' => is_plugin_active( 'woocommerce/woocommerce.php' ) ? wc_tax_enabled() : false,
				'roles' => $wp_roles->get_names(),
				'b2b_enabled' => class_exists( 'Addify_B2B_Plugin' ),
				'fileinfo_enabled' => extension_loaded( 'fileinfo' ),
				'acf_enabled'      => class_exists( 'ACF' ),
				'wcb2b_enabled'    => \CMBIRD_Common_Functions::is_wcb2b_active(),
				'wcb2b_groups'     => get_option( 'cmbird_wcb2b_groups' ),
				'site_url'         => site_url(),
				'eo_sync'          => get_option( 'cmbird_exact_online_sync_orders' ),
				'wc_countries'     => is_plugin_active( 'woocommerce/woocommerce.php' ) ? WC()->countries->get_countries() : array(),
			),
		);
	}

	/**
	 * Add custom styles for admin notices
	 *
	 * @return void
	 */
	public function admin_notice_styles(): void {
		?>
		<style>
			.cmbird-notice h3 {
				color: # d63638;
				margin: .75em 0 0 0;
			}

			.cmbird-notice p {
				margin: 0.5em 0;
			}

			.cmbird-license-notice {
				border-left-color: # d63638;
			}
		</style>
		<?php
	}

	/**
	 * Display subscription expired/on-hold notice in wp-admin
	 *
	 * @return void
	 */
	public function subscription_expired_notice(): void {
		// Only show on admin pages and to users who can manage woocommerce.
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		// Get subscription ID from options.
		$subscription_id = get_option( 'commercebird-subscription-id', 0 );
		if ( empty( $subscription_id ) ) {
			return;
		}

		// Check subscription status.
		$subscription_data = $this->get_subscription_status();

		if ( isset( $subscription_data['status'] ) && in_array( $subscription_data['status'], array( 'on-hold', 'expired', 'cancelled' ) ) ) {
			$class = 'notice notice-error cmbird-notice cmbird-license-notice';
			$exclamation_icon_url = CMBIRD_URL . 'admin/exclamation-triangle.svg';
			$renew_url = "https://commercebird.com/my-account/view-subscription/{$subscription_id}";

			$message = sprintf(
				'<h3 style="margin: .75em 0 0 0;"><img src="%s" style="vertical-align: text-top; width: 20px; margin-right: 7px;">%s</h3><p>%s</p><p><a href="%s" class="button-primary">%s</a> &nbsp;<a href="%s" class="button-secondary">%s</a></p>',
				esc_url( $exclamation_icon_url ),
				esc_html__( 'Heads up! Your CommerceBird license has expired.', 'commercebird' ),
				esc_html__( 'An active license is needed to use the Zoho & Exact Online integrations. It also provides access to new features, plugin updates (including security improvements), and our world class support!', 'commercebird' ),
				esc_url( $renew_url ),
				esc_html__( 'Renew Now', 'commercebird' ),
				esc_url( 'https://support.commercebird.com' ),
				esc_html__( 'Learn More', 'commercebird' )
			);

			printf( '<div class="%1$s" id="cmbird-notice-license-expired">%2$s</div>', esc_attr( $class ), wp_kses_post( $message ) );
		}
	}

	/**
	 * Get subscription status data
	 *
	 * @return array
	 */
	private function get_subscription_status(): array {
		// Check transient first to avoid excessive API calls.
		$transient = get_transient( 'subscription_details' );
		if ( ! empty( $transient ) && isset( $transient['status'] ) ) {
			return $transient;
		}

		// Fallback: try to get from a stored option or return empty.
		// This will need to be populated by the subscription check process.
		$stored_status = get_option( 'commercebird-subscription-status', '' );
		if ( ! empty( $stored_status ) ) {
			return array( 'status' => $stored_status );
		}

		return array();
	}
}
