<?php
declare(strict_types=1);

namespace App\Services;

final class CustomFieldService
{
    public static function optionsArray(?string $raw): array
    {
        $raw = trim((string) $raw);
        if ($raw === '') {
            return [];
        }

        $lines = preg_split('/\r\n|\r|\n/', $raw) ?: [];
        $result = [];

        foreach ($lines as $line) {
            $line = trim((string) $line);
            if ($line !== '') {
                $result[] = $line;
            }
        }

        return $result;
    }

    public static function validate(array $fields, array $input): array
    {
        $errors = [];

        foreach ($fields as $field) {
            $key = (string) $field['field_key'];
            $required = !empty($field['is_required']);
            $type = (string) $field['field_type'];
            $value = $input[$key] ?? null;

            if (is_array($value)) {
                $value = implode(',', $value);
            }

            $value = trim((string) $value);

            if ($required && $value === '') {
                $errors[$key] = 'required';
                continue;
            }

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

            if ($type === 'email' && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
                $errors[$key] = 'invalid_email';
            }

            if ($type === 'number' && !is_numeric($value)) {
                $errors[$key] = 'invalid_number';
            }
        }

        return $errors;
    }
}
