<?php

namespace App\Traits;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

trait ImageUploadTrait
{
    /**
     * Upload image or document.
     *
     * @param UploadedFile $file
     * @param string $path
     * @param int|null $width
     * @param int|null $height
     * @return string
     */
    public function uploadImage(UploadedFile $file, string $path = 'uploads', ?int $width = null, ?int $height = null): string
    {
        // 1. Check if file is NOT an image (e.g. PDF, Doc)
        $mime = $file->getMimeType();
        $isImage = str_starts_with($mime, 'image/');

        // Ensure directory exists
        if (!Storage::disk('public')->exists($path)) {
            Storage::disk('public')->makeDirectory($path);
        }

        // 2. If it is a Document (PDF, etc.), simply save it directly
        if (!$isImage) {
            $filename = uniqid() . '_' . time() . '.' . $file->getClientOriginalExtension();
            return $file->storeAs($path, $filename, 'public');
        }

        // 3. If it IS an Image, process it (Resize & Convert to WebP)
        $filename = uniqid() . '_' . time() . '.webp';
        $fullPath = $path . '/' . $filename;

        try {
            // Use ImageManager directly (assuming GD driver)
            $manager = new \Intervention\Image\ImageManager(
                new \Intervention\Image\Drivers\Gd\Driver()
            );

            $image = $manager->read($file);

            if ($width || $height) {
                // Resize delicately
                $image->scale(width: $width, height: $height);
            }
            
            // Save as WebP
            Storage::disk('public')->put($fullPath, (string) $image->toWebp(80));

            return $fullPath;

        } catch (\Exception $e) {
            // Fallback: If image processing fails, save original file
            $filename = uniqid() . '_' . time() . '.' . $file->getClientOriginalExtension();
            return $file->storeAs($path, $filename, 'public');
        }
    }

    /**
     * Delete image from storage.
     *
     * @param string|null $path
     * @return bool
     */
    public function deleteImage(?string $path): bool
    {
        if ($path && Storage::disk('public')->exists($path)) {
            return Storage::disk('public')->delete($path);
        }
        return false;
    }
}
