<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['admin_logged_in'])) {
    http_response_code(403);
    echo json_encode(['success' => 0, 'message' => 'Unauthorized']);
    exit;
}

if (empty($_FILES['image']) && empty($_FILES['file'])) {
    echo json_encode(['success' => 0, 'message' => 'No file uploaded']);
    exit;
}

// EditorJS sends the file as 'image', fallback to 'file'
$fileKey = !empty($_FILES['image']) ? 'image' : 'file';
$file = $_FILES[$fileKey];

if ($file['error'] !== UPLOAD_ERR_OK) {
    $errors = [
        UPLOAD_ERR_INI_SIZE   => 'File too large (server limit)',
        UPLOAD_ERR_FORM_SIZE  => 'File too large (form limit)',
        UPLOAD_ERR_PARTIAL    => 'File partially uploaded',
        UPLOAD_ERR_NO_FILE    => 'No file uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'No temp directory',
        UPLOAD_ERR_CANT_WRITE => 'Cannot write to disk',
        UPLOAD_ERR_EXTENSION  => 'Upload blocked by extension',
    ];
    $msg = $errors[$file['error']] ?? 'Upload error code: ' . $file['error'];
    echo json_encode(['success' => 0, 'message' => $msg]);
    exit;
}

// Validate MIME type
$allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime  = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!in_array($mime, $allowedMimes)) {
    echo json_encode(['success' => 0, 'message' => 'Invalid file type: ' . $mime]);
    exit;
}

// Get extension safely
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (empty($ext)) $ext = 'jpg';

// Create uploads dir if needed
$uploadDir = realpath(__DIR__ . '/..') . '/uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$filename    = md5(uniqid(rand(), true)) . '.' . $ext;
$destination = $uploadDir . $filename;

if (!move_uploaded_file($file['tmp_name'], $destination)) {
    echo json_encode(['success' => 0, 'message' => 'Failed to move uploaded file']);
    exit;
}

// Return format EditorJS ImageTool expects
echo json_encode([
    'success' => 1,
    'file'    => [
        'url' => '/bm/uploads/' . $filename
    ]
]);
?>
