<?php

namespace Yuvayana\AcadlixImporter\Admin;

use Yuvayana\AcadlixImporter\Helper\Helper;

defined('ABSPATH') || exit();

class Menu
{
  private static $_instance = null;

  public function __construct()
  {
    add_action('admin_menu', [$this, 'add_menu']);
  }

  public function add_menu()
  {
    $page = add_menu_page(
      __('Acadlix Importer', 'acadlix-importer'),
      __('Acadlix Importer', 'acadlix-importer'),
      'manage_options',
      ACADLIXIMPORTER_SLUG,
      [$this, 'callback'],
      '',
      50
    );

    add_action("admin_print_scripts-{$page}", [$this, 'admin_print_scripts']);
  }

  public function callback()
  {
    echo '<div id="acadlix-importer"><h2>' . esc_html__('Loading...', 'acadlix-importer') . '</h2></div>';
  }

  public function admin_print_scripts()
  {
    $runtime_dependency = require_once ACADLIXIMPORTER_PLUGIN_DIR . '/build/runtime.asset.php';
    $runtime_data = [
      'src' => plugins_url('build/runtime.js', ACADLIXIMPORTER_PLUGIN_FILE),
      'version' => $runtime_dependency['version'],
      'deps' => $runtime_dependency['dependencies'],
      'in_footer' => true,
    ];
    wp_enqueue_script('acadlix-importer-runtime-script', $runtime_data['src'], $runtime_data['deps'], $runtime_data['version'], true);
    $dependencies = require_once ACADLIXIMPORTER_PLUGIN_DIR . '/build/index.asset.php';
    $data = [
      'src' => plugins_url('build/index.js', ACADLIXIMPORTER_PLUGIN_FILE),
      'version' => $dependencies['version'],
      'deps' => $dependencies['dependencies'],
    ];

    wp_enqueue_script('acadlix-importer-script', $data['src'], $data['deps'], $data['version'], true);
    wp_localize_script('acadlix-importer-script', 'importerOptions', array(
      'api_url' => esc_url_raw(rest_url('acadlix-importer/v1')),
      'max_execution_time' => ini_get('max_execution_time') * 1000,
      'options' => Helper::instance()->acadlix_importer_get_all_options(),
      'acadlix_pro' => function_exists('acadlix') && acadlix()->pro,
      'is_wp_pro_quiz_active' => Helper::instance()->is_wp_pro_quiz_active(),
      'is_wp_adv_quiz_active' => Helper::instance()->is_wp_adv_quiz_active(),
    ));
  }

  public static function instance()
  {
    if (is_null(self::$_instance)) {
      self::$_instance = new self();
    }

    return self::$_instance;
  }
}