<?php

namespace App\Providers\Filament;

use Filament\AvatarProviders\Contracts\AvatarProvider as BaseAvatarProvider;
use Filament\Facades\Filament;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class AvatarProvider implements BaseAvatarProvider
{
    public function get(Model|Authenticatable $record): string
    {
        $name = str(Filament::getNameForDefaultAvatar($record))
            ->trim()
            ->explode(' ')
            ->map(fn(string $segment): string => filled($segment) ? mb_substr($segment, 0, 1) : '')
            ->join(' ');
        if (Str::doesntContain($name, range('A', 'Z'), true)) {
            $name = Str::reverse($name);
        }
        $font = __DIR__ . '/avatar.ttf';
        $im = imagecreatetruecolor(128, 128);
        $black = imagecolorallocate($im, 0, 0, 0);
        $white = imagecolorallocate($im, 255, 255, 255);
        imagefill($im, 0, 0, $black);
        $size = 28;
        $box = imagettfbbox($size, 0, $font, $name);
        imagettftext($im, $size, 0, (128 - $box[4]) / 2, (128 - $box[5]) / 2, $white, $font, $name);
        ob_start();
        imagepng($im, quality: 9);
        $image = ob_get_clean();
        imagedestroy($im);
        return 'data:image/png;base64,' . base64_encode($image);
    }
}
