<?php

namespace App\Services;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Throwable;

class ImageUploadService
{
    /**
     * Upload gambar ke disk public.
     * Selalu berhasil — langsung simpan file tanpa kompresi jika GD/Imagick tidak tersedia.
     *
     * @param UploadedFile $file
     * @param string $folder
     * @param string|null $oldPath Path lama yang perlu dihapus
     * @return string Path relatif yang disimpan di storage/app/public
     */
    public function upload(UploadedFile $file, string $folder, ?string $oldPath = null): string
    {
        // Hapus file lama jika ada dan bukan URL external
        if ($oldPath && !str_starts_with($oldPath, 'http')) {
            try {
                if (Storage::disk('public')->exists($oldPath)) {
                    Storage::disk('public')->delete($oldPath);
                }
            } catch (Throwable $e) {
                Log::warning("ImageUploadService: gagal hapus file lama [{$oldPath}]: " . $e->getMessage());
            }
        }

        // Coba kompresi dengan Intervention Image jika ekstensi tersedia
        if (extension_loaded('gd') || extension_loaded('imagick')) {
            try {
                $filename = Str::uuid() . '.webp';
                $path = $folder . '/' . $filename;

                // Lazy load Intervention Image agar tidak crash jika package tidak ada
                $imageClass = 'Intervention\\Image\\Laravel\\Facades\\Image';
                if (class_exists($imageClass)) {
                    $image   = $imageClass::read($file);
                    $image->scaleDown(width: 1280);
                    $encoded = $image->toWebp(quality: 80);
                    Storage::disk('public')->put($path, (string) $encoded);
                    return $path;
                }
            } catch (Throwable $e) {
                Log::warning("ImageUploadService: kompresi gagal, fallback ke upload langsung. Error: " . $e->getMessage());
            }
        }

        // ===== FALLBACK: simpan file asli langsung — SELALU BERHASIL =====
        return $this->storeRaw($file, $folder);
    }

    /**
     * Simpan file asli tanpa kompresi apapun.
     */
    public function storeRaw(UploadedFile $file, string $folder): string
    {
        $ext      = $file->getClientOriginalExtension() ?: 'jpg';
        $filename = Str::random(20) . '.' . $ext;
        $path     = $file->storeAs($folder, $filename, 'public');

        if (!$path) {
            throw new \RuntimeException("Gagal menyimpan file ke storage/{$folder}/{$filename}");
        }

        return $path;
    }

    /**
     * Hapus gambar dari storage.
     */
    public function delete(?string $path): void
    {
        if ($path && !str_starts_with($path, 'http')) {
            try {
                if (Storage::disk('public')->exists($path)) {
                    Storage::disk('public')->delete($path);
                }
            } catch (Throwable $e) {
                Log::warning("ImageUploadService: gagal hapus file [{$path}]: " . $e->getMessage());
            }
        }
    }
}
