<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\File;

class UploadController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $tenant = app('tenant');

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

        $file = $request->file('image');
        $fileName = time() . '_' . Str::random(10) . '.' . $file->getClientOriginalExtension();

        // Match legacy path logic exactly:
        $destinationPath = public_path('uploads');
        if (!File::isDirectory($destinationPath)) {
            File::makeDirectory($destinationPath, 0755, true, true);
        }

        $file->move($destinationPath, $fileName);

        $url = '/uploads/' . $fileName;

        return response()->json([
            'success' => true,
            'url' => $url,
            'path' => $url // Some legacy codes might look for path instead of url
        ]);
    }
}
