<?php
declare(strict_types=1);
namespace Validators;

final class Validator
{
    public static function validate(array $data, array $rules): array
    {
        $errors = [];
        foreach ($rules as $field => $fieldRules) {
            $value = $data[$field] ?? null;
            foreach (explode('|', $fieldRules) as $rule) {
                if ($rule === 'required' && ($value === null || $value === '')) $errors[$field][] = 'Required';
                if ($rule === 'email' && $value && !filter_var($value, FILTER_VALIDATE_EMAIL)) $errors[$field][] = 'Invalid email';
                if (str_starts_with($rule, 'min:') && is_string($value) && strlen($value) < (int)substr($rule, 4)) $errors[$field][] = "Minimum {$rule} characters";
                if ($rule === 'array' && $value !== null && !is_array($value)) $errors[$field][] = 'Must be array';
                if ($rule === 'numeric' && $value !== null && !is_numeric($value)) $errors[$field][] = 'Must be numeric';
            }
        }
        return $errors;
    }
}
