<?php
/**
 * Assets
 *
 * @class Assets
 * @package KimaAI\Admin
 * @since 1.0.0
 */

declare(strict_types=1);

namespace KimaAI\Admin;

use KimaAI\ChatBot\ChatbotTheme;
use KimaAI\Helper;

defined('ABSPATH') || exit;

class Assets {

  /**
   * Assets constructor.
   *
   * @param Helper $helper The plugin helper.
   * @param Settings $settings The admin settings service.
   * @param AdminTheme $admin_theme The admin theme service.
   */
  public function __construct(
    public Helper $helper,
    public Settings $settings,
    public AdminTheme $admin_theme
  ) {
  }

  /**
   * Registers asset hooks.
   */
  public function registerHooks(): void {
    add_action('admin_enqueue_scripts', [$this, 'enqueue']);
  }

  /**
   * Enqueues the admin assets.
   *
   * @param string $hook_suffix The current admin page.
   * @hook admin_enqueue_scripts
   */
  public function enqueue(string $hook_suffix): void {
    $allowed = [
      'toplevel_page_kimaai',
      'kimaai_page_kimaai-wizard', // submenu page slug => PAGE_SLUG
      'kimaai_page_kimaai-feedback-analytics',
    ];

    if (!in_array($hook_suffix, $allowed, true)) {
      return;
    }

    $asset_info = include_once KIMAAI_PLUGIN_PATH . 'build/admin/index.asset.php';

    wp_enqueue_style('wp-components');

    /*
    * Load WooCommerce frontend assets in this admin screen because the conversation
    * preview can render WooCommerce-based templates/renderables (for example product
    * lists). Those templates rely on WooCommerce’s own frontend styles/scripts to
    * display correctly, even when shown inside wp-admin.
    */
    if (class_exists('\WC_Frontend_Scripts')) {
      \WC_Frontend_Scripts::load_scripts();
    }

    wp_enqueue_style(
      'kimaai-admin',
      KIMAAI_PLUGIN_ADMIN_ASSETS . 'admin.css',
      [],
      $asset_info['version']
    );

    // Enable WP's built-in CodeMirror (Code Editor API) for PHP snippets.
    $code_editor_settings = wp_enqueue_code_editor([
      'type' => 'text/x-php', // PHP mode
    ]);

    $deps = $asset_info['dependencies'];

    if ($code_editor_settings !== false) {
      // Loads the WP code editor bootstrap + CodeMirror assets
      wp_enqueue_script('code-editor');
      wp_enqueue_style('code-editor');

      if (!in_array('code-editor', $deps, true)) {
        $deps[] = 'code-editor';
      }
    }

    wp_enqueue_script(
      'kimaai-admin',
      KIMAAI_PLUGIN_ADMIN_ASSETS . 'index.js',
      $deps,
      $asset_info['version'],
      true
    );

    if ($code_editor_settings !== false) {
      wp_add_inline_script(
        'kimaai-admin',
        'window.__KIMAAI_CODE_EDITOR_SETTINGS__ = ' . wp_json_encode($code_editor_settings) . ';',
        'before'
      );
    }

    wp_localize_script(
      'kimaai-admin',
      'kimaaiAdmin',
      [
        'api' => esc_url_raw(rest_url('kimaai/v1')),
        'nonce' => wp_create_nonce('wp_rest'),
        'schemaSettings' => $this->settings->raw_schema,
        'version' => $this->helper->getVersion(),
        'isPremium' => $this->helper->isPremium(),
        'adminTheme' => $this->admin_theme->getCurrentTheme(),
        'i18n' => [
          'lang' => SettingsI18n::getCurrentLang(),
          'defaultLang' => SettingsI18n::getDefaultLang(),
          'i18nActive' => SettingsI18n::isIntegrationActive(),
          'provider' => SettingsI18n::isWpmlActive() ? 'wpml' : (SettingsI18n::isPolylangActive() ? 'polylang' : null),
          'urls' => [
            'wpml' => admin_url('admin.php?page=wpml-string-translation/menu/string-translation.php'),
            'polylang' => admin_url('admin.php?page=mlang_strings&s&group=KimaAI&lang=all'),
          ],
        ],
        'chatbotTheme' => ChatbotTheme::jsConfig(),
        'urls' => [
          'settings' => admin_url('admin.php?page=kimaai'),
          'wizard' => admin_url('admin.php?page=kimaai-wizard'),
          'feedbackAnalytics' => admin_url('admin.php?page=kimaai-feedback-analytics'),
        ],
      ]
    );

    wp_set_script_translations(
      'kimaai-admin',
      'kimaai',
      KIMAAI_PLUGIN_PATH . 'languages'
    );

    if (is_rtl()) {
      wp_enqueue_style(
        'kimaai-admin-rtl',
        KIMAAI_PLUGIN_URL . 'assets/fonts/persian/yekan-font.css',
        [],
        $asset_info['version']
      );
    }
  }
}
