<?php

namespace ModernFields\Settings\Hooks;

use ModernFields\Settings\Services\SettingsValidator;
use ModernFields\WordPress\Interfaces\Hooks;
use ModernFields\WordPress\Traits\ChecksPermissions;

use WP_REST_Response;
use WP_REST_Request;

defined('ABSPATH') || exit;

/**
 * Handles WordPress settings and API endpoints for Modern Fields.
 *
 * @since 1.0.0
 */
class AdminSettings implements Hooks
{
  use ChecksPermissions;

  /**
   * @since 1.0.0
   */
  public function registerHooks(): void
  {
    add_action('rest_api_init', [$this, 'registerRestEndpoints']);
  }

  /**
   * Script data for the Settings tab, merged into window.modernFields by the
   * single admin page (see AdminPageHooks::enqueueAppAssets).
   *
   * @since 1.0.5
   * @return array<string, mixed>
   */
  public function getScriptData(): array
  {
    return [
      'defaultPalette'  => $this->getDefaultColorPalette(),
      'pluginSettings'  => $this->getSettings(),
      'isACFInstalled'  => defined('ACF_VERSION'),
      'hasMfJsonFolder' => is_dir(get_stylesheet_directory() . '/mf-json'),
    ];
  }

  /**
   * @since 1.0.0
   */
  public function registerRestEndpoints(): void
  {
    register_rest_route(MODERN_FIELDS_REST_NAMESPACE, '/settings', [
      'methods'             => 'GET',
      'callback'            => [$this, 'getSettingsForRestApi'],
      'permission_callback' => [$this, 'checkPermissions'],
    ]);

    register_rest_route(MODERN_FIELDS_REST_NAMESPACE, '/settings', [
      'methods'             => 'POST',
      'callback'            => [$this, 'updateSettings'],
      'permission_callback' => [$this, 'checkPermissions'],
      'args'                => [
        'modern_fields_shorthand_functions' => [
          'type'              => 'boolean',
          'required'          => false,
          'sanitize_callback' => 'rest_sanitize_boolean',
        ],
        'modern_fields_color_palette' => [
          'type'              => 'array',
          'required'          => false,
          'sanitize_callback' => 'rest_sanitize_array',
          'validate_callback' => [SettingsValidator::class, 'validateColorPalette'],
        ],
        'modern_fields_onboarding_done' => [
          'type'              => 'boolean',
          'required'          => false,
          'sanitize_callback' => 'rest_sanitize_boolean',
        ],
      ],
    ]);
  }

  /**
   * @since 1.0.0
   */
  public function getSettings(): array
  {
    return [
      'modern_fields_shorthand_functions' => get_option('modern_fields_shorthand_functions', false),
      'modern_fields_color_palette'       => get_option('modern_fields_color_palette', []),
      'modern_fields_onboarding_done'     => (bool) get_option('modern_fields_onboarding_done', false),
    ];
  }

  /**
   * @since 1.0.0
   */
  public function getSettingsForRestApi(): WP_REST_Response
  {
    return rest_ensure_response($this->getSettings());
  }

  /**
   * @since 1.0.0
   */
  public function updateSettings(WP_REST_Request $request): WP_REST_Response
  {
    $params = $request->get_json_params();

    if (isset($params['modern_fields_shorthand_functions'])) {
      update_option('modern_fields_shorthand_functions', $params['modern_fields_shorthand_functions']);
    }
    if (isset($params['modern_fields_color_palette'])) {
      update_option('modern_fields_color_palette', $params['modern_fields_color_palette']);
    }
    if (isset($params['modern_fields_onboarding_done'])) {
      update_option('modern_fields_onboarding_done', $params['modern_fields_onboarding_done']);
    }

    return rest_ensure_response(['success' => true]);
  }

  /**
   * @since 1.0.0
   */
  protected function getDefaultColorPalette(): array
  {
    $palette = wp_get_global_settings(['color', 'palette']);

    return $palette['default'] ?? [];
  }
}
