<?php
/**
 * Admin Class
 *
 * @package VariationHub
 */

namespace VariationHub\Admin;

defined('ABSPATH') || exit;

/**
 * Admin class
 */
class Admin {
    /**
     * Singleton instance
     *
     * @var Admin
     */
    private static $instance = null;

    /**
     * Get singleton instance
     *
     * @return Admin
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct() {
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_menu_page(
            __('Variation Hub', 'variation-hub'),
            __('Variation Hub', 'variation-hub'),
            'manage_woocommerce',
            'variation-hub',
            [$this, 'render_admin_page'],
            'dashicons-grid-view',
            56 // Position after WooCommerce
        );
    }

    /**
     * Enqueue scripts and styles
     *
     * @param string $hook Current admin page hook
     */
    public function enqueue_scripts($hook) {
        // Only load on our admin page
        if ('toplevel_page_variation-hub' !== $hook) {
            return;
        }

        // Enqueue WordPress dependencies FIRST (before our React app)
        // These are required for wp.media to work properly
        wp_enqueue_script('jquery');
        wp_enqueue_script('underscore'); // CRITICAL: Required for wp.media
        wp_enqueue_script('backbone');   // CRITICAL: Required for wp.media
        
        // WordPress Media Library (depends on underscore & backbone)
        wp_enqueue_media();

        // Check if production build exists (main.js file)
        $main_js = VARIHU_PLUGIN_DIR . 'assets/main.js';
        
        if (file_exists($main_js)) {
            // Production build
            $this->enqueue_production_assets();
        } else {
            // Development mode (Vite dev server must be running!)
            $this->enqueue_development_assets();
        }

        // Localize script with config
        wp_localize_script('variation-hub-app', 'varihuConfig', [
            'restUrl' => rest_url('variation-hub/v1'),
            'nonce' => wp_create_nonce('wp_rest'),
            'locale' => get_locale(), // Use WordPress site locale (not user-specific)
            'ajaxUrl' => admin_url('admin-ajax.php'), // ✅ SECURITY FIX: Dynamic Ajax URL for nonce refresh
            'currentUser' => [
                'id' => get_current_user_id(),
                'name' => wp_get_current_user()->display_name,
                'email' => wp_get_current_user()->user_email,
            ],
            'pluginUrl' => VARIHU_PLUGIN_URL,
            'version' => VARIHU_VERSION,
        ]);
    }

    /**
     * Enqueue production assets
     */
    private function enqueue_production_assets() {
        // Direct file loading (no manifest - library mode build)
        $main_js = VARIHU_PLUGIN_DIR . 'assets/main.js';
        $main_css_pattern = VARIHU_PLUGIN_DIR . 'assets/assets/main-*.css';
        
        // Find CSS file (glob pattern)
        $css_files = glob($main_css_pattern);
        $main_css = !empty($css_files) ? $css_files[0] : null;
        
        // Enqueue JS
        if (file_exists($main_js)) {
            wp_enqueue_script(
                'variation-hub-app',
                VARIHU_PLUGIN_URL . 'assets/main.js',
                ['jquery', 'underscore', 'backbone'], // WordPress dependencies
                VARIHU_VERSION . '-' . filemtime($main_js), // Cache busting with file timestamp
                true // Load in footer
            );
        }
        
        // Enqueue CSS
        if ($main_css && file_exists($main_css)) {
            $css_filename = basename($main_css);
            wp_enqueue_style(
                'variation-hub-app',
                VARIHU_PLUGIN_URL . 'assets/assets/' . $css_filename,
                [],
                VARIHU_VERSION . '-' . filemtime($main_css) // Cache busting
            );
        }
    }

    /**
     * Enqueue development assets (Vite dev server)
     */
    private function enqueue_development_assets() {
        // Development server URL (only used when assets/main.js doesn't exist)
        // This is for plugin developers during development, not for end users
        $vite_url = 'http://localhost:5173';
        
        // Note: WordPress dependencies (jquery, underscore, backbone) are already
        // enqueued in enqueue_scripts() method before this is called
        
        wp_enqueue_script(
            'variation-hub-vite-client',
            $vite_url . '/@vite/client',
            [], // No dependencies - but WordPress deps are already loaded
            VARIHU_VERSION, // Use plugin version for cache busting
            false // Load in HEAD instead of footer
        );
        
        wp_enqueue_script(
            'variation-hub-app',
            $vite_url . '/src/main.tsx',
            ['variation-hub-vite-client'], // Depends on Vite client
            VARIHU_VERSION, // Use plugin version for cache busting
            false // Load in HEAD instead of footer
        );
        
        // Add module type - Filter is the correct WordPress way to modify script tags
        add_filter('script_loader_tag', function($tag, $handle, $src) {
            if ('variation-hub-vite-client' === $handle || 'variation-hub-app' === $handle) {
                // WordPress.WP.EnqueuedResources.NonEnqueuedScript - This is NOT a manual script tag
                // This filter modifies enqueued scripts to add type="module" for Vite compatibility
                // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- Modifying enqueued script tag via filter
                return '<script type="module" crossorigin src="' . esc_url($src) . '"></script>' . "\n";
            }
            return $tag;
        }, 10, 3);
    }

    /**
     * Render admin page
     */
    public function render_admin_page() {
        // Load the admin page template
        require_once VARIHU_PLUGIN_DIR . 'includes/admin/views/admin-page.php';
    }
}
