<?php

namespace App\Http\Controllers\Api\Admin;

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

class AdminUploadController extends Controller
{
    public function upload(Request $request): JsonResponse
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,webp,svg|max:10240',
            'folder' => 'nullable|string',
        ]);

        $folder = $request->input('folder', 'uploads');
        $file = $request->file('image');

        $filename = time() . '_' . Str::random(8) . '.' . $file->getClientOriginalExtension();
        $targetDirectory = public_path("uploads/{$folder}");

        if (!file_exists($targetDirectory)) {
            mkdir($targetDirectory, 0777, true);
        }

        $file->move($targetDirectory, $filename);
        $fullUrl = asset("uploads/{$folder}/{$filename}");

        return response()->json([
            'success' => true,
            'message' => 'Image uploaded successfully',
            'url' => $fullUrl,
        ]);
    }
}
