<?php
declare(strict_types=1);

namespace App\Core;

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

        foreach ($rules as $field => $fieldRules) {
            $value = $data[$field] ?? null;
            $fieldErrors = [];

            foreach ($fieldRules as $rule) {
                if ($rule === 'required' && self::isBlank($value)) {
                    $fieldErrors[] = 'Field wajib diisi.';
                    continue;
                }

                if ($rule === 'string' && ! is_null($value) && ! is_string($value)) {
                    $fieldErrors[] = 'Field harus berupa teks.';
                    continue;
                }

                if (is_string($rule) && str_starts_with($rule, 'min:')) {
                    $min = (int) substr($rule, 4);
                    if (is_string($value) && mb_strlen(trim($value)) < $min) {
                        $fieldErrors[] = 'Minimal ' . $min . ' karakter.';
                    }
                }

                if (is_string($rule) && str_starts_with($rule, 'max:')) {
                    $max = (int) substr($rule, 4);
                    if (is_string($value) && mb_strlen(trim($value)) > $max) {
                        $fieldErrors[] = 'Maksimal ' . $max . ' karakter.';
                    }
                }

                if ($rule === 'email' && ! self::isBlank($value) && filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
                    $fieldErrors[] = 'Format email tidak valid.';
                }

                if ($rule === 'whatsapp' && ! self::isBlank($value) && ! preg_match('/^\+?[0-9]{9,15}$/', (string) $value)) {
                    $fieldErrors[] = 'Format WhatsApp tidak valid.';
                }

                if ($rule === 'confirmed') {
                    $confirmation = $data[$field . '_confirmation'] ?? null;
                    if ((string) $value !== (string) $confirmation) {
                        $fieldErrors[] = 'Konfirmasi tidak cocok.';
                    }
                }
            }

            if ($fieldErrors !== []) {
                $errors[$field] = $fieldErrors;
            }
        }

        return $errors;
    }

    private static function isBlank(mixed $value): bool
    {
        return $value === null || (is_string($value) && trim($value) === '');
    }
}
