<?php

namespace App\Services\Admin;

use App\Models\Setting;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

/**
 * رفع شعار المنصة وأيقونة التطبيق (قرص public).
 */
final class AppBrandingService
{
    private const LOGO_MAX_KB = 2048;

    private const ICON_MAX_KB = 1024;

    public function storeLogo(UploadedFile $file, Setting $settings): string
    {
        $this->deleteStoredFile($settings->app_logo_path);

        $path = $file->storeAs('branding', $this->buildFilename('logo', $file), 'public');
        $settings->update(['app_logo_path' => $path]);
        $this->mirrorToPublicImages($path, 'madarx-logo');

        return $path;
    }

    public function storeIcon(UploadedFile $file, Setting $settings): string
    {
        $this->deleteStoredFile($settings->app_icon_path);

        $path = $file->storeAs('branding', $this->buildFilename('icon', $file), 'public');
        $settings->update(['app_icon_path' => $path]);
        $this->mirrorToPublicImages($path, 'madarx-icon');

        return $path;
    }

    public function removeLogo(Setting $settings): void
    {
        $this->deleteStoredFile($settings->app_logo_path);
        $settings->update(['app_logo_path' => null]);
    }

    public function removeIcon(Setting $settings): void
    {
        $this->deleteStoredFile($settings->app_icon_path);
        $settings->update(['app_icon_path' => null]);
    }

    public static function logoUrl(?Setting $settings = null): string
    {
        $settings ??= Setting::current();

        return self::publicUrl($settings->app_logo_path, 'images/madarx-logo.png');
    }

    public static function iconUrl(?Setting $settings = null): string
    {
        $settings ??= Setting::current();

        return self::publicUrl($settings->app_icon_path, 'images/madarx-icon.png');
    }

    private static function publicUrl(?string $path, string $fallbackAsset): string
    {
        if ($path !== null && $path !== '' && Storage::disk('public')->exists($path)) {
            return Storage::disk('public')->url($path);
        }

        return asset($fallbackAsset);
    }

    private function deleteStoredFile(?string $path): void
    {
        if ($path !== null && $path !== '' && Storage::disk('public')->exists($path)) {
            Storage::disk('public')->delete($path);
        }
    }

    private function buildFilename(string $prefix, UploadedFile $file): string
    {
        $ext = strtolower($file->getClientOriginalExtension() ?: $file->extension() ?: 'png');

        return $prefix.'-'.now()->format('YmdHis').'-'.Str::random(6).'.'.$ext;
    }

    /**
     * نسخة ثابتة في public/images لتوافق الروابط القديمة والفافيكون.
     */
    private function mirrorToPublicImages(string $storagePath, string $basename): void
    {
        $ext = pathinfo($storagePath, PATHINFO_EXTENSION) ?: 'png';
        $target = public_path('images/'.$basename.'.'.$ext);

        if (! is_dir(public_path('images'))) {
            mkdir(public_path('images'), 0755, true);
        }

        $contents = Storage::disk('public')->get($storagePath);
        file_put_contents($target, $contents);
    }
}
