<?php

namespace Core\App\Controllers\Admin;

use Core\App\Services\UploadService;

class UploadController
{
    private UploadService $uploads;

    public function __construct()
    {
        $this->uploads = new UploadService(ROOT_PATH . '/uploads', '/uploads');
    }

    public function image()
    {
        $file = $_FILES['upload'] ?? null;
        if (!$file || empty($file['tmp_name'])) {
            http_response_code(400);
            echo json_encode(['error' => 'No file']);
            exit;
        }

        try {
            $path = $this->uploads->storeImage($file, 'editor');
            echo json_encode(['url' => $path]);
        } catch (\Throwable $e) {
            http_response_code(400);
            echo json_encode(['error' => 'Upload failed']);
        }
        exit;
    }

    public function editorjsImage()
    {
        $file = $_FILES['image'] ?? $_FILES['file'] ?? $_FILES['upload'] ?? null;
        if (!$file || empty($file['tmp_name'])) {
            http_response_code(400);
            echo json_encode(['success' => 0, 'message' => 'No file received']);
            exit;
        }

        try {
            $path = $this->uploads->storeImage($file, 'editor');
            echo json_encode(['success' => 1, 'file' => ['url' => $path]]);
        } catch (\Throwable $e) {
            http_response_code(400);
            echo json_encode(['success' => 0, 'message' => 'Upload failed']);
        }
        exit;
    }
}
