<?php
/**
 * Admin class.
 *
 * @package LoginPageCustomizerAndDesigner
 */

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

/**
 * Class LPCD_Admin
 *
 * Registers admin menus and enqueues editor/settings React apps.
 */
class LPCD_Admin {

	/**
	 * Overview page hook suffix.
	 *
	 * @var string
	 */
	private $overview_hook = '';

	/**
	 * Editor page hook suffix.
	 *
	 * @var string
	 */
	private $editor_hook = '';

	/**
	 * Settings page hook suffix.
	 *
	 * @var string
	 */
	private $settings_hook = '';

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'register_menus' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'wp_ajax_lpcd_toggle_enabled', array( $this, 'ajax_toggle_enabled' ) );
		add_action( 'wp_ajax_lpcd_install_plugin', array( $this, 'ajax_install_plugin' ) );
		add_action( 'wp_ajax_lpcd_activate_plugin', array( $this, 'ajax_activate_plugin' ) );
		add_action( 'in_admin_header', array( $this, 'hide_admin_notices' ) );
	}

	/**
	 * Hide all admin notices on plugin pages.
	 */
	public function hide_admin_notices() {
		$screen = get_current_screen();
		if ( ! $screen ) {
			return;
		}

		// Check if we are on any of our plugin pages.
		$plugin_pages = array( $this->overview_hook, $this->editor_hook, $this->settings_hook );
		if ( in_array( $screen->id, $plugin_pages, true ) ) {
			remove_all_actions( 'admin_notices' );
			remove_all_actions( 'all_admin_notices' );
		}
	}

	/**
	 * Register admin menu items.
	 */
	public function register_menus() {
		// Top-level menu points to Overview.
		add_menu_page(
			__( 'Login Page Customizer', 'login-page-customizer-and-designer' ),
			__( 'Login Customizer', 'login-page-customizer-and-designer' ),
			'manage_options',
			'lpcd-overview',
			array( $this, 'render_overview_page' ),
			'dashicons-align-pull-right',
			80
		);

		// Overview submenu (auto-created by WP, just rename).
		$this->overview_hook = add_submenu_page(
			'lpcd-overview',
			__( 'Overview', 'login-page-customizer-and-designer' ),
			__( 'Overview', 'login-page-customizer-and-designer' ),
			'manage_options',
			'lpcd-overview',
			array( $this, 'render_overview_page' )
		);

		$this->editor_hook = add_submenu_page(
			'lpcd-overview',
			__( 'Editor', 'login-page-customizer-and-designer' ),
			__( 'Editor', 'login-page-customizer-and-designer' ),
			'manage_options',
			'lpcd-editor',
			array( $this, 'render_editor_page' )
		);

		$this->settings_hook = add_submenu_page(
			'lpcd-overview',
			__( 'Settings', 'login-page-customizer-and-designer' ),
			__( 'Settings', 'login-page-customizer-and-designer' ),
			'manage_options',
			'lpcd-settings',
			array( $this, 'render_settings_page' )
		);
	}

	/**
	 * Render the editor page (React mount point).
	 */
	public function render_overview_page() {
		require_once LPCD_DIR . 'admin/views/overview-page.php';
	}

	/**
	 * Render the editor page (React mount point).
	 */
	public function render_editor_page() {
		echo '<div id="lpcd-editor-root" class="lpcd-admin-wrapper"></div>';
	}

	/**
	 * Render the settings page (React mount point).
	 */
	public function render_settings_page() {
		echo '<div id="lpcd-settings-root" class="lpcd-admin-wrapper"></div>';
	}

	/**
	 * Enqueue scripts and styles for admin pages.
	 *
	 * @param string $hook_suffix Current admin page hook.
	 */
	public function enqueue_scripts( $hook_suffix ) {
		// Overview page.
		if ( $hook_suffix === $this->overview_hook ) {
			$this->enqueue_overview_assets();
			return;
		}

		// Editor page.
		if ( $hook_suffix === $this->editor_hook ) {
			$this->enqueue_editor_assets();
			return;
		}

		// Settings page.
		if ( $hook_suffix === $this->settings_hook ) {
			$this->enqueue_settings_assets();
			return;
		}
	}

	/**
	 * Enqueue editor React app assets.
	 */
	private function enqueue_editor_assets() {
		$asset_file = LPCD_DIR . 'build/editor.asset.php';

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

		$asset = include $asset_file;

		wp_enqueue_style(
			'lpcd-editor',
			LPCD_URL . 'build/editor.css',
			array( 'wp-components' ),
			$asset['version']
		);

		wp_enqueue_script(
			'lpcd-editor',
			LPCD_URL . 'build/editor.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);

		// WP media for image uploads.
		wp_enqueue_media();

		wp_localize_script(
			'lpcd-editor',
			'lpcdEditor',
			array(
				'restUrl'      => esc_url_raw( rest_url( 'lpcd/v1/' ) ),
				'nonce'        => wp_create_nonce( 'wp_rest' ),
				'previewNonce' => wp_create_nonce( 'lpcd_preview_nonce' ),
				'loginUrl'     => esc_url( wp_login_url() ),
				'pluginUrl'    => esc_url( LPCD_URL ),
				'maxTemplates' => LPCD_Template_Manager::MAX_CUSTOM_TEMPLATES,
				'isPro'        => lpcd_is_pro(),
			)
		);
	}

	/**
	 * Enqueue settings React app assets.
	 */
	private function enqueue_settings_assets() {
		$asset_file = LPCD_DIR . 'build/settings.asset.php';

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

		$asset = include $asset_file;

		wp_enqueue_style(
			'lpcd-settings',
			LPCD_URL . 'build/settings.css',
			array( 'wp-components' ),
			$asset['version']
		);

		wp_enqueue_script(
			'lpcd-settings',
			LPCD_URL . 'build/settings.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);

		// WP media for favicon/image uploads.
		wp_enqueue_media();

		wp_localize_script(
			'lpcd-settings',
			'lpcdSettings',
			array(
				'restUrl' => esc_url_raw( rest_url( 'lpcd/v1/' ) ),
				'nonce'   => wp_create_nonce( 'wp_rest' ),
				'version' => defined( 'LPCD_VERSION' ) ? LPCD_VERSION : '1.0.0',
				'isPro'   => lpcd_is_pro(),
			)
		);
	}

	/**
	 * Enqueue overview page assets.
	 */
	private function enqueue_overview_assets() {
		wp_enqueue_style(
			'lpcd-overview',
			LPCD_URL . 'assets/css/lpcd-overview.css',
			array(),
			LPCD_VERSION
		);

		wp_enqueue_script(
			'lpcd-overview',
			LPCD_URL . 'assets/js/lpcd-overview.js',
			array(),
			LPCD_VERSION,
			true
		);

		wp_localize_script(
			'lpcd-overview',
			'lpcdOverview',
			array(
				'ajaxUrl'     => admin_url( 'admin-ajax.php' ),
				'toggleNonce' => wp_create_nonce( 'lpcd_toggle_enabled' ),
				'pluginNonce' => wp_create_nonce( 'lpcd_plugin_manage' ),
				'i18n'        => array(
					'active'      => esc_html__( 'Custom Login Active', 'login-page-customizer-and-designer' ),
					'inactive'    => esc_html__( 'Custom Login Inactive', 'login-page-customizer-and-designer' ),
					'installing'  => esc_html__( 'Installing...', 'login-page-customizer-and-designer' ),
					'activating'  => esc_html__( 'Activating...', 'login-page-customizer-and-designer' ),
					'activate'    => esc_html__( 'Activate', 'login-page-customizer-and-designer' ),
					'activeLabel' => esc_html__( 'Active', 'login-page-customizer-and-designer' ),
					'error'       => esc_html__( 'Error', 'login-page-customizer-and-designer' ),
				),
			)
		);
	}

	/**
	 * AJAX handler for toggling the plugin enabled state.
	 */
	public function ajax_toggle_enabled() {
		check_ajax_referer( 'lpcd_toggle_enabled' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
		}

		$enabled = isset( $_POST['enabled'] ) ? absint( $_POST['enabled'] ) : 0;
		LPCD_Settings_Manager::save( array( 'pluginEnabled' => (bool) $enabled ) );

		wp_send_json_success( array( 'enabled' => (bool) $enabled ) );
	}

	/**
	 * AJAX handler for installing a recommended plugin.
	 */
	public function ajax_install_plugin() {
		check_ajax_referer( 'lpcd_plugin_manage' );

		if ( ! current_user_can( 'install_plugins' ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
		}

		$slug = isset( $_POST['slug'] ) ? sanitize_text_field( wp_unslash( $_POST['slug'] ) ) : '';
		if ( empty( $slug ) ) {
			wp_send_json_error( array( 'message' => 'Missing slug' ) );
		}

		// Only allow our own plugins.
		$allowed = array( 'uply-scroll-to-top-and-progress-bar', 'smartwait-animated-preloader' );
		if ( ! in_array( $slug, $allowed, true ) ) {
			wp_send_json_error( array( 'message' => 'Plugin not allowed' ) );
		}

		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		require_once ABSPATH . 'wp-admin/includes/plugin-install.php';

		$api = plugins_api(
			'plugin_information',
			array(
				'slug'   => $slug,
				'fields' => array( 'sections' => false ),
			)
		);

		if ( is_wp_error( $api ) ) {
			wp_send_json_error( array( 'message' => $api->get_error_message() ) );
		}

		$upgrader = new Plugin_Upgrader( new WP_Ajax_Upgrader_Skin() );
		$result   = $upgrader->install( $api->download_link );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		if ( ! $result ) {
			wp_send_json_error( array( 'message' => 'Installation failed' ) );
		}

		wp_send_json_success();
	}

	/**
	 * AJAX handler for activating a recommended plugin.
	 */
	public function ajax_activate_plugin() {
		check_ajax_referer( 'lpcd_plugin_manage' );

		if ( ! current_user_can( 'activate_plugins' ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
		}

		$file = isset( $_POST['file'] ) ? sanitize_text_field( wp_unslash( $_POST['file'] ) ) : '';
		if ( empty( $file ) ) {
			wp_send_json_error( array( 'message' => 'Missing file' ) );
		}

		// Only allow our own plugins.
		$allowed = array(
			'uply-scroll-to-top-and-progress-bar/uply-scroll-to-top-and-progress-bar.php',
			'smartwait-animated-preloader/smartwait-animated-preloader.php',
		);
		if ( ! in_array( $file, $allowed, true ) ) {
			wp_send_json_error( array( 'message' => 'Plugin not allowed' ) );
		}

		$result = activate_plugin( $file );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( array( 'message' => $result->get_error_message() ) );
		}

		wp_send_json_success();
	}
}
