<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Services\ImageOptimizer; 

class ProfilePhotoController extends Controller
{
    public function update(Request $request)
    {
        $request->validate([
            'photo' => ['required', 'image', 'max:5120'], 
            'type' => ['required', 'string', 'in:avatar,cover'],
        ]);

        $user = $request->user();
        $type = $request->input('type');
        $pathKey = "{$type}_path";
        $folder = "{$type}s"; 

        if ($user->{$pathKey}) {
            Storage::disk('public')->delete($user->{$pathKey});
        }

        // Use Optimizer to shrink cropped profile pictures
        $path = ImageOptimizer::upload($request->file('photo'), $folder);

        $user->update([$pathKey => $path]);

        return back()->with('success', ucfirst($type) . ' updated successfully.');
    }
}