<?php

declare(strict_types=1);

namespace LinkFiliate\Assets;

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

use LinkFiliate\App\Traits\Singleton;
use LinkFiliate\Libs\Assets;

/**
 * Class Admin
 *
 * Handles admin functionalities for the Linkfiliate.
 *
 * @package LinkFiliate\Admin
 */
class Admin
{

	use Singleton;

	/**
	 * Script handle for Linkfiliate.
	 */
	const HANDLE = 'Linkfiliate';

	/**
	 * JS Object name for Linkfiliate.
	 */
	const OBJ_NAME = 'linkfiliate';

	/**
	 * Development script path for Linkfiliate.
	 */
	const DEV_SCRIPT = 'resources/src/admin/main.jsx';

	/**
	 * List of allowed screens for script enqueue.
	 *
	 * @var array
	 */
	private $allowed_screens = array(
		'toplevel_page_linkfiliate',
	);

	/**
	 * Frontend bootstrapper.
	 *
	 * @return void
	 */
	public function bootstrap()
	{
		add_action('admin_enqueue_scripts', array($this, 'enqueue_script'));
		add_action('admin_head', function () {
			// Only run on your plugin page
			$screen = get_current_screen();
			if (!isset($screen->id) || !in_array($screen->id, $this->allowed_screens, true)) {
				return;
			}

			// Remove all notices from other plugins
			remove_all_actions('admin_notices');
			remove_all_actions('all_admin_notices');
		});
	}

	/**
	 * Enqueue script based on the current screen.
	 *
	 * @param string $screen The current screen.
	 */
	public function enqueue_script($screen)
	{
		$current_screen     = $screen;


		if (in_array($current_screen, $this->allowed_screens, true)) {
			Assets\enqueue_asset(
				LINKFILIATE_PLUGIN_DIR . '/assets/admin/dist',
				self::DEV_SCRIPT,
				$this->get_config()
			);
			wp_localize_script(self::HANDLE, self::OBJ_NAME, $this->get_data());
			wp_enqueue_media();
		}
	}

	/**
	 * Get the script configuration.
	 *
	 * @return array The script configuration.
	 */
	public function get_config()
	{
		return array(
			'dependencies' => array('react', 'react-dom'),
			'handle'       => self::HANDLE,
			'in-footer'    => true,
		);
	}

	/**
	 * Get data for script localization.
	 *
	 * @return array The localized script data.
	 */
	public function get_data()
	{
		
		return array(
			'pluginName' => LINKFILIATE_PLUGIN_NAME,
			'isAdmin'   => is_admin(),
			'apiUrl'    => rest_url(),
			'pluginApiUrl' => rest_url() . LINKFILIATE_ROUTE_PREFIX,
			'userInfo'  => $this->get_user_data(),
			'logo'     => LINKFILIATE_ASSETS_URL,
			'nonce'     => wp_create_nonce('wp_rest'),
			'is_free'	=> 1,
		);
	}

	/**
	 * Get user data for script localization.
	 *
	 * @return array The user data.
	 */
	private function get_user_data()
	{
		$username   = '';
		$avatar_url = '';

		if (is_user_logged_in()) {
			// Get current user's data .
			$current_user = wp_get_current_user();

			// Get username.
			$username = $current_user->user_login; // or use user_nicename, display_name, etc.

			// Get avatar URL.
			$avatar_url = get_avatar_url($current_user->ID);
		}

		return array(
			'username' => $username,
			'avatar'   => $avatar_url,
		);
	}
}
