<?php

namespace Attributes\Core;

/**
 * Assets Management Class
 *
 * Handles registration and enqueuing of scripts and styles
 * with performance optimization and extension support.
 *
 * @package Attributes\Core
 * @since 1..0
 */
class Assets
{
    /**
     * Settings instance
     *
     * @var Settings
     */
    private Settings $settings;

    /**
     * Script and style handles
     *
     * @var array
     */
    private array $handles = [
        'styles' => [],
        'scripts' => []
    ];

    /**
     * Constructor
     *
     * @param Settings $settings Settings instance
     */
    public function __construct(Settings $settings)
    {
        $this->settings = $settings;
    }

    /**
     * Initialize assets management
     *
     * @return void
     */
    public function init(): void
    {
        // Register asset hooks
        add_action('wp_enqueue_scripts', [$this, 'attrua_register_frontend_assets']);
        add_action('wp_enqueue_scripts', [$this, 'attrua_enqueue_frontend_assets']);
        add_action('admin_enqueue_scripts', [$this, 'attrua_register_admin_assets']);
        add_action('admin_enqueue_scripts', [$this, 'attrua_enqueue_admin_assets']);

        // Allow extensions to register assets
        do_action('attrua_register_assets', $this);
    }

    /**
     * Register frontend assets
     *
     * @return void
     */
    public function attrua_register_frontend_assets(): void
    {
        // Register plugin styles
        $front_style_path = $this->attrua_get_asset_path('css', 'front');
        $this->attrua_register_style(
            'attrua-front',
            $front_style_path,
            ['tabler-icons'],
            ATTRUA_VERSION,
            ''
        );

        // Register Tabler Icons
        $tabler_style_path = $this->attrua_get_asset_path('css', 'tabler-icons-outline');
        $this->attrua_register_style(
            'tabler-icons',
            $tabler_style_path,
            [],
            ATTRUA_ICON_VERSION,
            'all'
        );

        // Register login validation script
        $validation_script_path = $this->attrua_get_asset_path('js', 'validation');
        $this->attrua_register_script(
            'attrua-validation',
            $validation_script_path,
            ['jquery']
        );

        // Localize script data
        wp_localize_script('attrua-validation', 'attruaFront', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('attrua_frontend'),
            'i18n' => [
                'invalidCredentials' => __('Invalid username or password.', 'attributes-user-access'),
                'loggingIn' => __('Logging in...', 'attributes-user-access')
            ]
        ]);

        /**
         * Action: attrua_after_register_frontend_assets
         * 
         * Allow extensions to register additional frontend assets
         */
        do_action('attrua_after_register_frontend_assets', $this);
    }

    /**
     * Register admin assets
     *
     * @return void
     */
    public function attrua_register_admin_assets(): void
    {
        // Register admin styles
        $admin_style_path = $this->attrua_get_asset_path('css', 'admin');
        $this->attrua_register_style(
            'attrua-admin',
            $admin_style_path,
            ['tabler-icons'],
            ATTRUA_VERSION,
            ''
        );

        // Register Tabler Icons (reuse the same path logic)
        $tabler_style_path = $this->attrua_get_asset_path('css', 'tabler-icons-outline');
        $this->attrua_register_style(
            'tabler-icons',
            $tabler_style_path,
            [],
            ATTRUA_ICON_VERSION,
            'all'
        );

        // Register admin script with fallback to non-minified version
        $admin_script_path = $this->attrua_get_asset_path('js', 'admin');
        $this->attrua_register_script(
            'attrua-admin',
            $admin_script_path,
            ['jquery'],
            '',
            true
        );

        /**
         * Action: attrua_after_register_admin_assets
         * 
         * Allow extensions to register additional admin assets
         */
        do_action('attrua_after_register_admin_assets', $this);
    }

    /**
     * Enqueue frontend assets
     *
     * @return void
     */
    public function attrua_enqueue_frontend_assets(): void
    {
        // Only enqueue on relevant pages
        if ($this->attrua_should_load_frontend_assets()) {
            wp_enqueue_style('attrua-front');
            wp_enqueue_script('attrua-validation');

            /**
             * Action: attrua_enqueue_frontend_assets
             * 
             * Allow extensions to enqueue additional frontend assets
             */
            do_action('attrua_enqueue_frontend_assets');
        }
    }

    /**
     * Enqueue admin assets
     *
     * @param string $hook_suffix The current admin page
     * @return void
     */
    public function attrua_enqueue_admin_assets(string $hook_suffix): void
    {
        // Only enqueue on plugin admin pages
        if ($this->attrua_is_plugin_admin_page($hook_suffix)) {
            wp_enqueue_style('attrua-admin');
            wp_enqueue_script('attrua-admin');

            /**
             * Action: attrua_enqueue_admin_assets
             * 
             * Allow extensions to enqueue additional admin assets
             * 
             * @param string $hook_suffix Current admin page hook
             */
            do_action('attrua_enqueue_admin_assets', $hook_suffix);
        }
    }

    /**
     * Register a style
     *
     * @param string $handle Style handle
     * @param string $path Path relative to assets directory
     * @param array $deps Dependencies
     * @param string|null $version Version string
     * @param string $media Media type
     * @return void
     */
    public function attrua_register_style(
        string $handle,
        string $path,
        array $deps = [],
        ?string $version = null,
        string $media = 'all'
    ): void {
        $this->handles['styles'][] = $handle;

        wp_register_style(
            $handle,
            ATTRUA_URL . 'assets/' . $path,
            $deps,
            $version ?? ATTRUA_VERSION,
            $media
        );
    }

    /**
     * Register a script
     *
     * @param string $handle Script handle
     * @param string $path Path relative to assets directory
     * @param array $deps Dependencies
     * @param string|null $version Version string
     * @param bool $in_footer Whether to enqueue in footer
     * @return void
     */
    public function attrua_register_script(
        string $handle,
        string $path,
        array $deps = [],
        ?string $version = null,
        bool $in_footer = true
    ): void {
        $this->handles['scripts'][] = $handle;

        wp_register_script(
            $handle,
            ATTRUA_URL . 'assets/' . $path,
            $deps,
            $version ?? ATTRUA_VERSION,
            $in_footer
        );
    }

    /**
     * Check if frontend assets should be loaded
     *
     * @return bool
     */
    private function attrua_should_load_frontend_assets(): bool
    {
        global $post;

        // Check if current post/page has login shortcode
        if ($post && has_shortcode($post->post_content, 'attributes_login_form')) {
            return true;
        }

        // Check if current page is plugin page
        $login_page_id = $this->settings->get('pages.login');
        if ($login_page_id && is_page($login_page_id)) {
            return true;
        }

        /**
         * Filter: attrua_load_frontend_assets
         * 
         * Allow extensions to determine if assets should be loaded
         * 
         * @param bool $load Whether to load assets
         */
        return apply_filters('attrua_load_frontend_assets', false);
    }

    /**
     * Check if current admin page is plugin page
     *
     * @param string $hook_suffix Current admin page hook
     * @return bool
     */
    public function attrua_is_plugin_admin_page(string $hook_suffix): bool
    {
        return strpos($hook_suffix, 'attributes-user-access') !== false;
    }

    /**
     * Get asset path with fallback to non-minified version
     *
     * @param string $type Asset type (css|js)
     * @param string $name Asset name without extension
     * @return string Asset path relative to assets directory
     */
    private function attrua_get_asset_path(string $type, string $name): string
    {
        $minified_path = "{$type}/min/{$name}.min.{$type}";
        $regular_path = "{$type}/{$name}.{$type}";

        // Check if minified version exists
        if (file_exists(ATTRUA_PATH . "assets/{$minified_path}")) {
            return $minified_path;
        }

        // Fallback to regular version
        return $regular_path;
    }

    /**
     * Get registered asset handles
     *
     * @param string $type Asset type (styles|scripts)
     * @return array Asset handles
     */
    public function attrua_get_handles(string $type = 'all'): array
    {
        if ($type === 'all') {
            return $this->handles;
        }
        return $this->handles[$type] ?? [];
    }
}
