<?php

namespace Modules\Lpj\Services;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Laravel\Facades\Image;

class ImageResizeService
{
    /**
     * Resize an image and store it.
     *
     * @param string $originalPath
     * @param int $width
     * @param int|null $height
     * @param int $quality
     * @return string
     */
    public function resize(string $originalPath, ?int $width, ?int $height = null, int $quality = 80): string
    {
        if (empty($originalPath) || !Storage::disk('public')->exists($originalPath)) {
            Log::warning("Image Service: Original path is empty or does not exist: {$originalPath}");
            return '';
        }

        $height = null;

        $pathinfo = pathinfo($originalPath);

        // Kembali menggunakan direktori 'resized' dan menyertakan dimensi di nama file
        $resizedPath = "{$pathinfo['dirname']}/resized/{$pathinfo['filename']}_{$width}x{$height}_{$quality}.{$pathinfo['extension']}";

        if (Storage::disk('public')->exists($resizedPath)) {
            return $resizedPath;
        }

        try {
            $originalFullPath = Storage::disk('public')->path($originalPath);
            $newFullPath = Storage::disk('public')->path($resizedPath);

            $image = Image::read($originalFullPath);

            // Resize dengan menjaga aspek rasio jika height null
            if ($width && $height) {
                // Paksa resize ke dimensi yang ditentukan, abaikan aspek rasio
                $image->resize($width, $height);
            } elseif ($width && !$height) {
                // Resize hanya berdasarkan width, tinggi menyesuaikan aspek rasio
                $image->scale(width: $width);
            } elseif (!$width && $height) {
                // Resize hanya berdasarkan height, lebar menyesuaikan aspek rasio
                $image->scale(height: $height);
            }



            if (!Storage::disk('public')->exists(dirname($resizedPath))) {
                Storage::disk('public')->makeDirectory(dirname($resizedPath));
            }

            // Simpan dengan kualitas yang ditentukan
            $image->save($newFullPath, $quality);

            Log::info("Image Service: Successfully resized {$originalPath} to {$resizedPath} with quality {$quality}%.");

            return $resizedPath;
        } catch (\Exception $e) {
            Log::error("Image Service: Resize failed for {$originalPath}. Error: " . $e->getMessage());
            return $originalPath; // Fallback ke gambar asli jika gagal
        }
    }
}
