<?php

namespace App\Support;

use App\Models\Organization;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class OrganizationBranding
{
    public const DEFAULT_LOGO = 'images/logo/ladillcare-logo.svg';

    public static function logoUrl(Organization $organization): string
    {
        if ($organization->logo_path && Storage::disk('public')->exists($organization->logo_path)) {
            $version = $organization->updated_at?->getTimestamp() ?? time();

            return Storage::disk('public')->url($organization->logo_path).'?v='.$version;
        }

        $path = public_path(self::DEFAULT_LOGO);

        return asset(self::DEFAULT_LOGO).'?v='.(@filemtime($path) ?: '1');
    }

    public static function logoAlt(Organization $organization): string
    {
        return $organization->logo_path ? $organization->name : 'Ladill Care';
    }

    public static function hasCustomLogo(Organization $organization): bool
    {
        return $organization->logo_path !== null
            && Storage::disk('public')->exists($organization->logo_path);
    }

    public static function storeLogo(Organization $organization, UploadedFile $file): string
    {
        self::deleteStoredLogo($organization);

        return $file->store('care/organizations/'.$organization->id, 'public');
    }

    public static function deleteStoredLogo(Organization $organization): void
    {
        if ($organization->logo_path) {
            Storage::disk('public')->delete($organization->logo_path);
        }
    }

    public static function emailLogoUrl(Organization $organization): ?string
    {
        if (! self::hasCustomLogo($organization)) {
            return null;
        }
        $ext = strtolower(pathinfo($organization->logo_path, PATHINFO_EXTENSION));
        if ($ext === 'svg') {
            return null;
        }
        $version = $organization->updated_at?->getTimestamp() ?? time();

        return Storage::disk('public')->url($organization->logo_path).'?v='.$version;
    }

    public static function wrapEmailHtml(string $bodyHtml, Organization $organization): string
    {
        return view('email.customer-branded', [
            'logoUrl' => self::emailLogoUrl($organization),
            'companyName' => $organization->name,
            'bodyHtml' => $bodyHtml,
        ])->render();
    }
}
