<?php
/**
 * Admin Interface
 *
 * @package SureDonation
 */

namespace SureDonation\Inc\Admin;

use SureDonation\Inc\Traits\Get_Instance;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Admin class.
 *
 * @since 0.0.1
 */
class Admin {
	use Get_Instance;

	/**
	 * Constructor.
	 *
	 * @since 0.0.1
	 */
	public function __construct() {
		add_action( 'admin_menu', [ $this, 'register_menu' ] );
		add_action( 'admin_menu', [ $this, 'hide_forms_submenu' ], 999 );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_scripts' ] );
	}

	/**
	 * Enqueue admin scripts and styles.
	 *
	 * @param string $hook Current admin page hook.
	 * @return void
	 * @since 0.0.1
	 */
	public function enqueue_admin_scripts( $hook ) {
		// Only load on our plugin pages.
		if ( strpos( $hook, 'suredonation' ) === false ) {
			return;
		}

		$asset_file = SUREDONATION_DIR . 'assets/build/admin.asset.php';

		if ( ! file_exists( $asset_file ) ) {
			return;
		}

		$asset = include $asset_file;

		// Enqueue WordPress editor for TinyMCE support.
		wp_enqueue_editor();

		// Enqueue editor buttons style (needed for TinyMCE icons).
		wp_enqueue_style( 'editor-buttons' );

		// Enqueue admin app script.
		wp_enqueue_script(
			'suredonation-admin',
			SUREDONATION_URL . 'assets/build/admin.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);

		// Enqueue admin app styles.
		wp_enqueue_style(
			'suredonation-admin',
			SUREDONATION_URL . 'assets/build/admin.css',
			[],
			$asset['version']
		);

		// Localize script with plugin data.
		wp_localize_script(
			'suredonation-admin',
			'suredonation_admin',
			[
				'version'                   => SUREDONATION_VER,
				'apiUrl'                    => rest_url( 'suredonation/v1' ),
				'nonce'                     => wp_create_nonce( 'wp_rest' ),
				'docsURL'                   => 'https://suredonation.com/docs/',
				'plugin_url'                => SUREDONATION_URL,
				'site_url'                  => site_url(),
				'admin_url'                 => admin_url(),
				'is_first_campaign_created' => $this->has_campaigns(),
				'rotating_plugin_banner'    => $this->get_rotating_plugin_banner(),
			]
		);
	}

	/**
	 * Register admin menu.
	 *
	 * @return void
	 * @since 0.0.1
	 */
	public function register_menu() {
		$menu_slug = 'suredonation';

		// Main menu page.
		add_menu_page(
			__( 'SureDonation', 'suredonation' ),
			__( 'SureDonation', 'suredonation' ),
			'manage_options',
			$menu_slug,
			[ $this, 'render_dashboard' ],
			'dashicons-money-alt',
			25
		);

		// Register submenus.
		$this->register_submenus( $menu_slug );
	}

	/**
	 * Render dashboard page.
	 *
	 * @return void
	 * @since 0.0.1
	 */
	public function render_dashboard() {
		?>
		<div id="suredonation-admin-root"></div>
		<?php
	}

	/**
	 * Hide the "All Forms" submenu item.
	 *
	 * WordPress automatically adds a submenu for the suredonation_form CPT.
	 * We hide it since forms are managed through campaigns.
	 *
	 * @return void
	 * @since 0.0.1
	 */
	public function hide_forms_submenu() {
		remove_submenu_page( 'suredonation', 'edit.php?post_type=suredonation_form' );
	}

	/**
	 * Check if any campaigns have been created.
	 *
	 * @return bool True if at least one campaign exists.
	 * @since 0.0.1
	 */
	private function has_campaigns() {
		$campaigns = get_posts(
			[
				'post_type'      => 'suredonation_cmpgn',
				'posts_per_page' => 1,
				'post_status'    => [ 'publish', 'draft', 'private' ],
				'fields'         => 'ids',
			]
		);

		return ! empty( $campaigns );
	}

	/**
	 * Get rotating plugin banner data.
	 *
	 * @return array<string,mixed> Plugin banner data or null if not available.
	 * @since 0.0.1
	 */
	private function get_rotating_plugin_banner() {
		// Get SVG logo as base64.
		$logo_svg  = file_get_contents( SUREDONATION_DIR . 'images/surerank.svg' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Local file read.
		$logo_data = $logo_svg ? 'data:image/svg+xml;base64,' . base64_encode( $logo_svg ) : ''; // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode

		// SureRank plugin data.
		return [
			'slug'                  => 'flavor',
			'title'                 => 'SureRank',
			'singleLineDescription' => __( 'SEO Made Easy for Your Website', 'suredonation' ),
			'subtitle'              => __( 'Beautiful pages, persuasive content, and custom code in seconds. The possibilities are endless!', 'suredonation' ),
			'logo'                  => $logo_data,
			'status'                => $this->get_plugin_status( 'flavor/flavor.php' ),
		];
	}

	/**
	 * Get plugin installation status.
	 *
	 * @param string $plugin_file Plugin file path (e.g., 'plugin-folder/plugin-file.php').
	 * @return string Plugin status: 'Activated', 'Installed', or 'Install'.
	 * @since 0.0.1
	 */
	private function get_plugin_status( $plugin_file ) {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			include_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		if ( is_plugin_active( $plugin_file ) ) {
			return 'Activated';
		}

		$all_plugins = get_plugins();
		if ( isset( $all_plugins[ $plugin_file ] ) ) {
			return 'Installed';
		}

		return 'Install';
	}

	/**
	 * Register submenus.
	 *
	 * @param string $menu_slug Menu slug.
	 * @return void
	 * @since 0.0.1
	 */
	private function register_submenus( $menu_slug ) {
		$capability = 'manage_options';

		$submenus = [
			[
				'id'         => $menu_slug,
				'page_title' => __( 'Dashboard', 'suredonation' ),
			],
			[
				'id'         => 'suredonation#/campaigns',
				'page_title' => __( 'Campaigns', 'suredonation' ),
			],
			[
				'id'         => 'suredonation#/donations',
				'page_title' => __( 'Donations', 'suredonation' ),
			],
			[
				'id'         => 'suredonation#/settings',
				'page_title' => __( 'Settings', 'suredonation' ),
			],
		];

		// Register the submenus.
		foreach ( $submenus as $submenu ) {
			add_submenu_page(
				$menu_slug,
				$submenu['page_title'],
				$submenu['page_title'],
				$capability,
				$submenu['id'],
				[ $this, 'render_dashboard' ]
			);
		}
	}
}
