<?php

/**
 * Admin Asset Handler
 *
 * @package Licenzo\Hooks\Handler\Admin
 */

namespace Licenzo\Hooks\Handler\Admin;

use Licenzo\Hooks\Handler\BaseHandler;
use Licenzo\Framework\Asset\Vite;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Handles admin asset loading and localization
 */
class AssetHandler extends BaseHandler
{
    /**
     * Handle admin asset loading
     */
    public function handle(...$args)
    {
        $hook = $args[0] ?? '';

        // Only load on our admin pages
        if (strpos($hook, 'licenzo-app') === false) {
            return;
        }

        $this->enqueueAdminAssets();
    }

    private function enqueueAdminAssets()
    {
        // Enqueue admin assets using Vite class
        Vite::enqueue(
            'licenzo-app-admin',
            'resources/Admin/app.js',
            ['wp-element'], // Vue.js dependencies
            true // Load in footer
        );

        $this->localizeAdminScript();
    }

    /**
     * Localize an admin script with configuration
     */
    private function localizeAdminScript()
    {
        $commerceProvider = (string) \Licenzo\Helper\Settings::get('general_settings.commerce_provider', 'woocommerce');

        wp_localize_script('licenzo-app-admin', 'licenzo_app_admin_', [
            'api_url'           => rest_url('licenzo/v1/'),
            'nonce'             => wp_create_nonce('wp_rest'),
            'ajax_url'          => admin_url('admin-ajax.php'),
            'ajax_nonce'        => wp_create_nonce('LICENZO_admin'),
            'strings'           => $this->app->config('str', []),
            'version'           => $this->app->version(),
            'base_url'          => admin_url('admin.php?page=licenzo-app') . '#',
            'admin_url'         => admin_url(),
            'currency'          => function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : 'USD',
            'locale'            => str_replace('_', '-', get_locale()),
            'commerce_provider' => $commerceProvider,
        ]);
    }
}
