<?php

namespace App\Http\Middleware;

use App\Support\PersianDigits;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class NormalizePersianDigits
{
    /** @var list<string> */
    private const FIELDS = ['mobile', 'code', 'postal_code'];

    public function handle(Request $request, Closure $next): Response
    {
        $normalized = [];

        foreach (self::FIELDS as $field) {
            if (!$request->has($field)) {
                continue;
            }

            $value = $request->input($field);

            if (is_string($value)) {
                $normalized[$field] = PersianDigits::toEnglish($value);
            }
        }

        if ($normalized !== []) {
            $request->merge($normalized);
        }

        return $next($request);
    }
}
