<?php
/**
 * Handles Admin Area setup for the RANK AI plugin.
 */

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

class Rank_Admin {

    /**
     * Initialize admin hooks.
     */
    public static function init() {
        add_action( 'admin_menu', array( __CLASS__, 'register_menu' ) );
        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
        add_action( 'admin_init', array( __CLASS__, 'register_settings' ) ); // Moved settings registration here too
        add_action( 'update_option_rank_api_key', array( __CLASS__, 'handle_api_key_update' ), 10, 3 );
    }

    /**
     * Register the admin menu page.
     */
    public static function register_menu() {
        // Assuming RANK_PLUGIN_FILE is defined in your main plugin file pointing to it.
        // If not, you might need to adjust the second argument of plugins_url(),
        // e.g., plugins_url( 'admin/Rank.webp', dirname( RANK_PLUGIN_DIR ) . '/your-main-plugin-file.php' )
        $icon_url = plugins_url( '../admin/Rank-mini.webp', __FILE__ ); // Use plugins_url relative to this file

        add_menu_page(
            'RANK AI by Morningscore',
            'RANK AI',
            'manage_options',
            'rank-admin', // Slug
            array( __CLASS__, 'render_page' ), // Callback to render page
            $icon_url, // Use the custom icon URL
            100
        );
    }

    /**
     * Render the admin page content by including the template file.
     */
    public static function render_page() {
        // Ensure this path is correct based on your structure
        require_once RANK_PLUGIN_DIR . 'admin/admin-page.php';
    }

    /**
     * Enqueue admin-specific CSS and JavaScript.
     *
     * @param string $hook The current admin page hook.
     */
    public static function enqueue_scripts( $hook ) {
        // Only load on our plugin's page (assuming $hook is like 'toplevel_page_rank-admin')
        if ( 'toplevel_page_rank-admin' !== $hook ) {
            return;
        }

        // Enqueue Admin CSS
        wp_enqueue_style(
            'rank-admin-css',
            RANK_PLUGIN_URL . 'admin/css/admin.css',
            array(),
            filemtime( RANK_PLUGIN_DIR . 'admin/css/admin.css' )
        );

        // Enqueue Fixes Tab CSS (only if the tab exists/is relevant)
        // We can enqueue it always for simplicity, or add a check for the current tab if needed
        wp_enqueue_style(
            'rank-admin-fixes-css',
            RANK_PLUGIN_URL . 'admin/css/admin-fixes.css',
            array(),
            filemtime( RANK_PLUGIN_DIR . 'admin/css/admin-fixes.css' )
        );

        // Enqueue API Key Notice JS
        wp_enqueue_script(
            'rank-api-key-notice-js',
            RANK_PLUGIN_URL . 'admin/js/api-key-notice.js',
            array('jquery'),
            filemtime( RANK_PLUGIN_DIR . 'admin/js/api-key-notice.js' ),
            true
        );
        
        // Enqueue Sequential Health Issues JS
        wp_enqueue_script(
            'rank-sequential-health-issues-js',
            RANK_PLUGIN_URL . 'admin/js/modules/sequential-health-issues.js',
            array('jquery'),
            filemtime( RANK_PLUGIN_DIR . 'admin/js/modules/sequential-health-issues.js' ),
            true
        );
        
        // Enqueue URL List Modal JS
        wp_enqueue_script(
            'rank-url-list-modal-js',
            RANK_PLUGIN_URL . 'admin/js/modules/url-list-modal.js',
            array('jquery', 'rank-sequential-health-issues-js'),
            filemtime( RANK_PLUGIN_DIR . 'admin/js/modules/url-list-modal.js' ),
            true
        );

        // Add WordPress Dashicons as a dependency if not already loaded
        wp_enqueue_style( 'dashicons' );
    }

    /**
     * Register plugin settings.
     */
    public static function register_settings() {
        register_setting( 'rank_options_group', 'rank_api_key', array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => '',
        ) );
        
        register_setting( 'rank_options_group', 'rank_debug_enabled', array(
            'type'              => 'boolean',
            'sanitize_callback' => 'rest_sanitize_boolean',
            'default'           => false,
        ) );
        
        // Register other settings here if needed in the future
    }

    /**
     * Handles actions to perform after the API key is updated.
     * Specifically, clears transients that depend on the API key.
     *
     * @param mixed $old_value The old option value.
     * @param mixed $value The new option value.
     * @param string $option_name The option name.
     */
    public static function handle_api_key_update( $old_value, $value, $option_name ) {
        // New API key is $value, old was $old_value
        // We clear these transients regardless of whether the key changed to be safe,
        // as this hook runs after the option is updated.
        if ($old_value !== $value) {
            delete_transient( 'rank_domain_identifier' );
            delete_transient( 'rank_health_issue_counts' );
            // Potentially log this or add admin notice: error_log('RANK API Key changed, transients cleared.');
        }
    }
}