<?php
/**
 * Admin theme preference for KimaAI admin screens.
 *
 * @package KimaAI\Admin
 */

declare(strict_types=1);

namespace KimaAI\Admin;

use KimaAI\KimaAI;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

final class AdminTheme {

  private const USER_META_KEY = 'kimaai_admin_theme';
  private const DEFAULT_THEME = 'light';
  private const ALLOWED_THEMES = ['light', 'dark'];

  /**
   * Registers admin theme REST routes.
   */
  public function registerRoutes(): void {
    register_rest_route(KimaAI::PREFIX . '/' . KimaAI::API_VERSION, '/admin-theme', [
      [
        'methods' => 'GET',
        'callback' => [$this, 'getThemeResponse'],
        'permission_callback' => [$this, 'canManageAdminTheme'],
      ],
      [
        'methods' => 'POST',
        'callback' => [$this, 'updateThemeResponse'],
        'args' => [
          'theme' => [
            'required' => true,
            'type' => 'string',
            'enum' => self::ALLOWED_THEMES,
            'default' => self::DEFAULT_THEME,
          ],
        ],
        'permission_callback' => [$this, 'canManageAdminTheme'],
      ],
    ]);
  }

  /**
   * Gets the current user's admin theme.
   */
  public function getCurrentTheme(): string {
    $user_id = get_current_user_id();
    if ($user_id <= 0) {
      return self::DEFAULT_THEME;
    }

    $stored = get_user_meta($user_id, self::USER_META_KEY, true);
    return is_string($stored) ? $stored : self::DEFAULT_THEME;
  }

  /**
   * Returns the current admin theme response.
   */
  public function getThemeResponse(): WP_REST_Response {
    return new WP_REST_Response([
      'theme' => $this->getCurrentTheme(),
    ], 200);
  }

  /**
   * Updates the current admin theme.
   *
   * @param WP_REST_Request $request The REST request.
   */
  public function updateThemeResponse(WP_REST_Request $request): WP_Error|WP_REST_Response {
    $theme = $request->get_param('theme');

    $user_id = get_current_user_id();
    if ($user_id <= 0) {
      return new WP_Error(
        'kimaai_invalid_admin_user',
        __('Unable to resolve the current user.', 'kimaai'),
        ['status' => 403]
      );
    }

    update_user_meta($user_id, self::USER_META_KEY, $theme);

    return new WP_REST_Response([
      'theme' => $theme,
    ], 200);
  }

  /**
   * Checks if the current user can manage the admin theme.
   */
  public function canManageAdminTheme(): bool {
    return current_user_can('manage_options');
  }
}
