<?php

namespace App\Helpers;

class Validator
{
    private array $errors = [];

    public function required(string $field, mixed $value, string $label = ''): self
    {
        if (empty(trim((string) $value))) {
            $this->errors[$field] = ($label ?: $field) . ' jest wymagane.';
        }
        return $this;
    }

    public function url(string $field, mixed $value, string $label = ''): self
    {
        if (!empty($value) && !filter_var($value, FILTER_VALIDATE_URL)) {
            $this->errors[$field] = ($label ?: $field) . ' musi być prawidłowym URL.';
        }
        return $this;
    }

    public function integer(string $field, mixed $value, string $label = ''): self
    {
        if (!empty($value) && !ctype_digit((string) $value)) {
            $this->errors[$field] = ($label ?: $field) . ' musi być liczbą całkowitą.';
        }
        return $this;
    }

    public function minLength(string $field, mixed $value, int $min, string $label = ''): self
    {
        if (!empty($value) && mb_strlen((string) $value) < $min) {
            $this->errors[$field] = ($label ?: $field) . " musi mieć co najmniej {$min} znaków.";
        }
        return $this;
    }

    public function email(string $field, mixed $value, string $label = ''): self
    {
        if (!empty($value) && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
            $this->errors[$field] = ($label ?: $field) . ' musi być prawidłowym adresem e-mail.';
        }
        return $this;
    }

    public function isValid(): bool
    {
        return empty($this->errors);
    }

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

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