<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class UploadController extends Controller
{
    /**
     * Upload a file.
     *
     * Accepts any file type with field name "file"
     */
    public function upload(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|file|max:10240', // 10MB max
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        $file = $request->file('file');

        // Generate unique filename
        $filename = time().'-'.uniqid().'.'.$file->getClientOriginalExtension();

        // Store file in public/uploads directory
        $path = $file->storeAs('uploads', $filename, 'public');

        // Get file info
        $fileInfo = [
            'filename' => $filename,
            'original_name' => $file->getClientOriginalName(),
            'mime_type' => $file->getMimeType(),
            'size' => $file->getSize(),
            'url' => '/storage/'.$path,
            'path' => $path,
        ];

        return response()->json([
            'success' => true,
            'message' => 'File uploaded successfully',
            'data' => $fileInfo,
        ], 201);
    }
}
