<?php

declare(strict_types=1);

if (!defined('ABSPATH')) {
  exit;
}

class KLCNN_Loader
{
  private static $instance = null;

  public static function get_instance(): self
  {
    if (null === self::$instance) {
      self::$instance = new self();
    }
    return self::$instance;
  }

  private function __construct()
  {
    $this->init_hooks();
    new KLCNN_Product_Fields();
  }

  private function init_hooks(): void
  {
    add_action('admin_menu', [$this, 'add_admin_menu']);
    add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
    add_action('rest_api_init', [$this, 'init_rest_api']);
  }

  public function add_admin_menu(): void
  {
    add_menu_page(
      esc_html__('EasyConnect for Kaufland', 'easyconnect-for-kaufland'),
      esc_html__('EasyConnect for Kaufland', 'easyconnect-for-kaufland'),
      'manage_woocommerce',
      'easyconnect-for-kaufland',
      [$this, 'render_admin_page'],
      'dashicons-store',
      56
    );
  }

  public function render_admin_page(): void
  {
    echo '<div id="klcnn-admin-app">';
    echo '</div>';
  }

  public function enqueue_admin_assets($hook): void
  {
    if ('toplevel_page_easyconnect-for-kaufland' !== $hook) {
      return;
    }

    wp_enqueue_style(
      'klcnn-admin',
      KLCNN_URL . 'assets/css/admin.css',
      [],
      KLCNN_VERSION
    );

    wp_enqueue_script(
      'klcnn-admin',
      KLCNN_URL . 'assets/js/admin.js',
      ['wp-element', 'wp-components', 'wp-api-fetch'],
      KLCNN_VERSION,
      true
    );

    wp_localize_script('klcnn-admin', 'klcnnData', [
      'apiUrl' => rest_url('klcnn/v1'),
      'root' => esc_url_raw(rest_url()),
      'nonce' => wp_create_nonce('wp_rest'),
      'storeLocation' => [
        'country' => WC()->countries->get_base_country(),
        'state' => WC()->countries->get_base_state(),
      ],
    ]);
  }

  public function init_rest_api(): void
  {
    $rest = new KLCNN_Register_Routes();
    $rest->register_routes();
  }
}
