<?php

declare(strict_types=1);

namespace App\Core;

class Validator
{
    public static function validate(array $data, array $rules): array
    {
        $errors = [];

        foreach ($rules as $field => $ruleString) {
            $value = $data[$field] ?? null;
            $ruleParts = explode('|', $ruleString);

            foreach ($ruleParts as $rule) {
                [$name, $param] = array_pad(explode(':', $rule, 2), 2, null);

                if ($name === 'required' && ($value === null || $value === '')) {
                    $errors[$field][] = 'El campo es obligatorio.';
                }

                if ($value === null || $value === '') {
                    continue;
                }

                if ($name === 'email' && !filter_var((string) $value, FILTER_VALIDATE_EMAIL)) {
                    $errors[$field][] = 'Formato de correo inválido.';
                }

                if ($name === 'min' && strlen((string) $value) < (int) $param) {
                    $errors[$field][] = 'Debe tener al menos ' . (int) $param . ' caracteres.';
                }

                if ($name === 'max' && strlen((string) $value) > (int) $param) {
                    $errors[$field][] = 'Debe tener máximo ' . (int) $param . ' caracteres.';
                }

                if ($name === 'numeric' && !is_numeric($value)) {
                    $errors[$field][] = 'Debe ser un valor numérico.';
                }
            }
        }

        return $errors;
    }
}
