<?php

namespace App\Traits;

use App\Facades\Settings;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;
use Mtc\MercuryDataModels\Tenant;

trait ResolvesSiteFavicon
{
    /**
     * Resolve a tenant's favicon into an icon array for API output.
     *
     * Falls back to a generated ui-avatars placeholder when no favicon is
     * saved or the stored file cannot be resolved on the media disk, so the
     * same site always yields the same icon regardless of the requesting
     * account type. Must be called with the tenant's context initialised so
     * the setting reads the correct tenant.
     */
    protected function resolveSiteFavicon(Tenant $site): array
    {
        try {
            $favicon = Settings::get('site-favicon');
        } catch (\Exception) {
            $favicon = null;
        }

        $path = $favicon['path'] ?? null;
        $disk = Config::get('filesystems.default_media');

        if (!empty($path) && !empty($favicon['url']) && Storage::disk($disk)->exists($path)) {
            return $favicon;
        }

        return $this->faviconPlaceholder($site);
    }

    /**
     * Generate the fallback initials placeholder icon for a tenant.
     */
    protected function faviconPlaceholder(Tenant $site): array
    {
        return [
            'url' => 'https://ui-avatars.com/api/?name=' . urlencode($site->name)
                . '&color=7F9CF5&background=EBF4FF',
        ];
    }
}
