<?php

namespace App\Support;

use Illuminate\Support\Facades\Storage;

class ImageHelper
{
    /**
     * Create a JPEG thumbnail for a file stored on a given disk.
     * Returns the relative path (on the same disk) or null on failure.
     */
    public static function makeThumbnailOnDisk(string $disk, string $sourcePath, string $destPath, int $maxEdge = 600, int $quality = 82): ?string
    {
        try {
            $fullSrc = Storage::disk($disk)->path($sourcePath);
            if (! file_exists($fullSrc)) {
                return null;
            }

            $data = @file_get_contents($fullSrc);
            if ($data === false) {
                return null;
            }

            // Prefer robust decode via GD from string (handles jpeg/png/webp if compiled)
            $src = @imagecreatefromstring($data);
            if (! $src) {
                return null;
            }

            $w = imagesx($src);
            $h = imagesy($src);
            if ($w === 0 || $h === 0) {
                imagedestroy($src);
                return null;
            }

            $scale = min(1.0, $maxEdge / max($w, $h));
            $tw = (int) max(1, round($w * $scale));
            $th = (int) max(1, round($h * $scale));

            $dst = imagecreatetruecolor($tw, $th);
            imagecopyresampled($dst, $src, 0, 0, 0, 0, $tw, $th, $w, $h);

            // Ensure destination directory exists
            $destDir = dirname($destPath);
            Storage::disk($disk)->makeDirectory($destDir);
            $fullDest = Storage::disk($disk)->path($destPath);

            // Encode JPEG
            @imagejpeg($dst, $fullDest, $quality);

            imagedestroy($dst);
            imagedestroy($src);

            // Confirm file written
            if (! file_exists($fullDest)) {
                return null;
            }

            return $destPath;
        } catch (\Throwable $e) {
            // Silent failure; caller can fall back to original
            return null;
        }
    }
}

