<?php

namespace App\Http\Controllers\Concerns;

use Illuminate\Http\Request;
use Illuminate\Support\Str;

trait HandlesImageUploads
{
    /**
     * Store an uploaded image under public/uploads/{folder} and return its
     * relative path (e.g. "uploads/rooms/abc123.jpg"), or null if no file.
     * Files live in public/ so they are served by both Apache (via the
     * root "uploads" junction) and `artisan serve`.
     */
    protected function saveImage(Request $request, string $field, string $folder): ?string
    {
        if (! $request->hasFile($field)) {
            return null;
        }

        $request->validate([
            $field => 'image|mimes:jpg,jpeg,png,webp,gif|max:4096',
        ]);

        $file = $request->file($field);
        $name = Str::lower(Str::random(20)) . '.' . $file->getClientOriginalExtension();

        $file->move(public_path("uploads/{$folder}"), $name);

        return "uploads/{$folder}/{$name}";
    }
}
