<?php
declare(strict_types=1);

namespace App\Core;

final class Validator
{
    private array $errors = [];

    public function required(array $data, array $fields): self
    {
        foreach ($fields as $field => $label) {
            $value = $data[$field] ?? '';
            if (trim((string) $value) === '') {
                $this->errors[$field] = $label . ' is required.';
            }
        }
        return $this;
    }

    public function email(array $data, string $field, string $label, bool $optional = true): self
    {
        $value = trim((string) ($data[$field] ?? ''));
        if ($value === '' && $optional) {
            return $this;
        }
        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
            $this->errors[$field] = $label . ' is not a valid email.';
        }
        return $this;
    }

    public function max(array $data, string $field, int $len, string $label): self
    {
        $value = (string) ($data[$field] ?? '');
        if (mb_strlen($value) > $len) {
            $this->errors[$field] = $label . ' is too long.';
        }
        return $this;
    }

    public function add(string $field, string $message): self
    {
        $this->errors[$field] = $message;
        return $this;
    }

    public function fails(): bool
    {
        return $this->errors !== [];
    }

    public function errors(): array
    {
        return $this->errors;
    }

    public function first(): string
    {
        return (string) reset($this->errors);
    }
}
