<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class FileUploadController extends Controller
{
    public function upload(Request $request)
    {
        $validatedData = $request->validate([
            'file' => 'required|file|max:51200',
        ]);

        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $originalName = $file->getClientOriginalName();
            $mimeType = $file->getMimeType();
            $fileSize = $file->getSize();

            try {
                $path = Storage::putFileAs('files', $file, 'file.' . $file->getClientOriginalExtension());

                return response()->json([
                    'message' => 'File uploaded successfully',
                    'path' => $path,
                    'url' => Storage::url($path),
                ], 200);
            } catch (\Exception $e) {
                return response()->json([
                    'message' => 'File upload failed',
                    'error' => $e->getMessage(),
                ], 500);
            }
        }

        // Respons jika file tidak ditemukan dalam permintaan
        Log::warning('No file found in request');
        return response()->json(['message' => 'No file uploaded'], 400);
    }
}
