<?php
/**
 * File: app/Admin/Wizard/Wizard.php
 *
 * @package KimaAI
 * @since 1.4.0
 */

declare(strict_types=1);

namespace KimaAI\Admin\Wizard;

use KimaAI\Helper;
use WP_REST_Response;

defined('ABSPATH') || exit;

final class Wizard {

  public const PAGE_SLUG = 'kimaai-wizard';
  private const OPTION_STATE = 'kimaai_wizard_state';
  private const TRANSIENT_REDIRECT = 'kimaai_wizard_activation_redirect';

  /**
   * Registers wizard admin hooks.
   */
  public function registerHooks(): void {
    add_action('admin_menu', [$this, 'registerPage']);
  }

  /**
   * Registers the wizard admin page.
   */
  public function registerPage(): void {
    // Dedicated page/URL, but still under KimaAI menu
    add_submenu_page(
      'kimaai',
      __('Setup Wizard', 'kimaai'),
      __('Setup Wizard', 'kimaai'),
      'manage_options',
      self::PAGE_SLUG,
      [$this, 'renderPage']
    );
  }

  /**
   * Renders the wizard page shell.
   */
  public function renderPage(): void {
    echo '<div class="wrap"><div id="kimaai-wizard"></div></div>';
  }

  /**
   * Registers wizard REST routes.
   */
  public function registerRoutes(): void {
    register_rest_route('kimaai/v1', '/wizard/config', [
      'methods' => 'GET',
      'callback' => fn() => new WP_REST_Response($this->getConfig(), 200),
      'permission_callback' => fn() => current_user_can('manage_options'),
    ]);

    register_rest_route('kimaai/v1', '/wizard/state', [
      'methods' => 'GET',
      'callback' => fn() => new WP_REST_Response($this->getState(), 200),
      'permission_callback' => fn() => current_user_can('manage_options'),
    ]);

    register_rest_route('kimaai/v1', '/wizard/complete', [
      'methods' => 'POST',
      'callback' => function () {
        $st = get_option(self::OPTION_STATE, []);
        if (!is_array($st)) {
          $st = [];
        }

        $cfg = $this->getConfig();
        $st['completed'] = true;
        $st['completed_at'] = time();
        $st['version'] = (int) ($cfg['version'] ?? 1);

        update_option(self::OPTION_STATE, $st, false);

        return new WP_REST_Response($this->getState(), 200);
      },
      'permission_callback' => fn() => current_user_can('manage_options'),
    ]);

    register_rest_route('kimaai/v1', '/wizard/reset', [
      'methods' => 'POST',
      'callback' => function () {
        $st = get_option(self::OPTION_STATE, []);
        if (!is_array($st)) {
          $st = [];
        }
        $st['completed'] = false;
        unset($st['completed_at']);
        update_option(self::OPTION_STATE, $st, false);
        return new WP_REST_Response($this->getState(), 200);
      },
      'permission_callback' => fn() => current_user_can('manage_options'),
    ]);
  }

  /**
   * Gets the wizard configuration.
   */
  private function getConfig(): array {
    $file = KIMAAI_PLUGIN_PATH . 'app/Admin/Wizard/config.php';
    $cfg = is_readable($file) ? include $file : [];
    if (!is_array($cfg)) {
      $cfg = [];
    }

    // Optional filter hook if you want to let addons modify wizard
    return apply_filters('kimaai_wizard_config', $cfg);
  }

  /**
   * Gets the wizard state.
   */
  private function getState(): array {
    $st = get_option(self::OPTION_STATE, []);
    if (!is_array($st)) {
      $st = [];
    }

    $cfg = $this->getConfig();
    $configured = Helper::hasApiKey();

    return [
      'completed' => !empty($st['completed']),
      'completed_at' => isset($st['completed_at']) ? (int) $st['completed_at'] : null,
      'version' => isset($st['version']) ? (int) $st['version'] : (int) ($cfg['version'] ?? 1),
      'configured' => $configured,
    ];
  }
}
