<?php

namespace App\Support;

class LoginCredentials
{
    /**
     * Bidirectional marks and other invisible characters browsers may inject
     * into inputs when the document direction is RTL.
     */
    private const BIDI_AND_INVISIBLE = '/[\x{200E}\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}\x{00AD}\x{200B}-\x{200D}\x{FEFF}]/u';

    /**
     * @var array<string, string>
     */
    private const EASTERN_DIGITS = [
        '۰' => '0', '۱' => '1', '۲' => '2', '۳' => '3', '۴' => '4',
        '۵' => '5', '۶' => '6', '۷' => '7', '۸' => '8', '۹' => '9',
        '٠' => '0', '١' => '1', '٢' => '2', '٣' => '3', '٤' => '4',
        '٥' => '5', '٦' => '6', '٧' => '7', '٨' => '8', '٩' => '9',
    ];

    public static function sanitizeEmail(mixed $email): string
    {
        $value = self::toAsciiDigits(self::stripInvisible((string) $email));

        return strtolower(trim($value));
    }

    public static function sanitizePassword(mixed $password): string
    {
        return self::stripInvisible((string) $password);
    }

    private static function stripInvisible(string $value): string
    {
        return (string) preg_replace(self::BIDI_AND_INVISIBLE, '', $value);
    }

    private static function toAsciiDigits(string $value): string
    {
        return strtr($value, self::EASTERN_DIGITS);
    }
}
