<?php

namespace App\Http\Controllers\SystemSettings;

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

class EditorUploadController extends Controller
{
    /**
     * Handle Image Upload from CKEditor 5 (Simple Upload Adapter)
     */
    public function upload(Request $request)
    {
        if (! $request->hasFile('upload')) {
            return response()->json(['error' => ['message' => 'No file uploaded.']], 400);
        }

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

        try {
            $file = $request->file('upload');
            $fileName = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();

            // Generate clean filename
            $name = Str::slug(pathinfo($fileName, PATHINFO_FILENAME));
            $finalName = 'editor_'.$name.'_'.time().'.'.$extension;

            // Store to public disk (storage/app/public/editor)
            $path = $file->storeAs('editor', $finalName, 'public');

            return response()->json([
                'uploaded' => 1,
                'fileName' => $finalName,
                'url' => '/storage/'.$path,
            ]);

        } catch (\Exception $e) {
            return response()->json(['error' => ['message' => 'Upload failed: '.$e->getMessage()]], 500);
        }
    }
}
