<?php

namespace ModernFields\Settings\Services;

use WP_REST_Request;
use WP_Error;

defined('ABSPATH') || exit;

/**
 * Validates settings values submitted via the REST API.
 *
 * @since 1.0.0
 */
abstract class SettingsValidator
{
  /**
   * Validates the color palette.
   *
   * Validates that the color palette is an array of objects, where each object
   * contains 'name', 'color', and 'slug' properties. The 'color' must be a valid
   * hex color code (e.g., #RRGGBB or #RGB).
   *
   * @since 1.0.0
   * @param mixed           $palette The color palette to validate.
   * @param WP_REST_Request $request The REST request object.
   * @param string          $param   The parameter name being validated.
   * @return bool|WP_Error
   */
  public static function validateColorPalette($palette, WP_REST_Request $request, string $param): bool|WP_Error
  {
    if (!is_array($palette)) {
      return new WP_Error(
        'invalid_palette',
        __('Color palette must be an array.', 'modern-fields'),
        ['status' => 400]
      );
    }

    foreach ($palette as $index => $item) {
      if (!is_array($item)) {
        return new WP_Error(
          'invalid_palette_item',
          sprintf(__('Palette item at index %d must be an array.', 'modern-fields'), $index),
          ['status' => 400]
        );
      }

      foreach (['name', 'color', 'slug'] as $key) {
        if (!isset($item[$key])) {
          return new WP_Error(
            'missing_palette_key',
            sprintf(__('Palette item at index %d is missing required key: %s.', 'modern-fields'), $index, $key),
            ['status' => 400]
          );
        }
      }

      if (!is_string($item['name'])) {
        return new WP_Error(
          'invalid_palette_name',
          sprintf(__('Palette item at index %d: name must be a string.', 'modern-fields'), $index),
          ['status' => 400]
        );
      }

      if (!is_string($item['slug'])) {
        return new WP_Error(
          'invalid_palette_slug',
          sprintf(__('Palette item at index %d: slug must be a string.', 'modern-fields'), $index),
          ['status' => 400]
        );
      }

      if (!is_string($item['color'])) {
        return new WP_Error(
          'invalid_palette_color',
          sprintf(__('Palette item at index %d: color must be a string.', 'modern-fields'), $index),
          ['status' => 400]
        );
      }

      if (!preg_match('/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/', $item['color'])) {
        return new WP_Error(
          'invalid_palette_color_format',
          sprintf(__('Palette item at index %d: color must be a valid hex color code (e.g., #RRGGBB or #RGB).', 'modern-fields'), $index),
          ['status' => 400]
        );
      }
    }

    return true;
  }
}
