<?php
/**
 * Admin-specific functionality.
 *
 * @package MasterQuiz
 * @since   1.0.0
 */

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

/**
 * Class MasterQuiz_Admin
 *
 * Handles admin menu, settings page rendering, and admin asset enqueueing.
 *
 * @since 1.0.0
 */
class MasterQuiz_Admin {

	/**
	 * The settings instance.
	 *
	 * @var MasterQuiz_Settings
	 */
	private $settings;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param MasterQuiz_Settings $settings The settings instance.
	 */
	public function __construct( MasterQuiz_Settings $settings ) {
		$this->settings = $settings;
	}

	/**
	 * Register the admin menu page.
	 *
	 * @since 1.0.0
	 */
	public function add_menu_page() {
		add_menu_page(
			esc_html__( 'MasterQuiz AI', 'masterquiz-ai' ),
			esc_html__( 'MasterQuiz AI', 'masterquiz-ai' ),
			'manage_options',
			MasterQuiz_Settings::PAGE_SLUG,
			array( $this, 'render_settings_page' ),
			'dashicons-welcome-learn-more',
			30
		);
	}

	/**
	 * Render the settings page.
	 *
	 * @since 1.0.0
	 */
	public function render_settings_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		include MASTERQUIZ_PLUGIN_DIR . 'admin/views/settings-page.php';
	}

	/**
	 * Enqueue admin assets.
	 *
	 * @since 1.0.0
	 *
	 * @param string $hook The current admin page hook.
	 */
	public function enqueue_assets( $hook ) {
		// Only load on our settings page.
		if ( 'toplevel_page_' . MasterQuiz_Settings::PAGE_SLUG !== $hook ) {
			return;
		}

		wp_enqueue_style(
			'masterquiz-admin',
			MASTERQUIZ_PLUGIN_URL . 'admin/css/masterquiz-admin.css',
			array(),
			MASTERQUIZ_VERSION
		);

		wp_enqueue_script(
			'masterquiz-admin',
			MASTERQUIZ_PLUGIN_URL . 'admin/js/masterquiz-admin.js',
			array( 'jquery' ),
			MASTERQUIZ_VERSION,
			true
		);

		wp_localize_script( 'masterquiz-admin', 'masterquizAdmin', array(
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce( 'masterquiz_nonce' ),
			'i18n'    => array(
				'testing'    => esc_html__( 'Testing...', 'masterquiz-ai' ),
				'success'    => esc_html__( 'Connection successful!', 'masterquiz-ai' ),
				'failed'     => esc_html__( 'Connection failed.', 'masterquiz-ai' ),
				'error'      => esc_html__( 'An error occurred.', 'masterquiz-ai' ),
			),
		) );
	}

	/**
	 * Add settings link to the plugins page.
	 *
	 * @since 1.0.0
	 *
	 * @param array $links Existing plugin action links.
	 * @return array Modified links.
	 */
	public function add_settings_link( $links ) {
		$settings_link = sprintf(
			'<a href="%s">%s</a>',
			esc_url( admin_url( 'admin.php?page=' . MasterQuiz_Settings::PAGE_SLUG ) ),
			esc_html__( 'Settings', 'masterquiz-ai' )
		);

		array_unshift( $links, $settings_link );

		return $links;
	}
}
