<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require __DIR__ . '/auth.php';

/* ---- Sicherheit: nur eingeloggte Admins ---- */
if (!is_admin()) {
    http_response_code(403);
    echo json_encode(['error' => 'Nicht eingeloggt']);
    exit;
}

/* ---- Upload-Ordner ---- */
$uploadDir = __DIR__ . '/uploads/';
$uploadUrl = dirname($_SERVER['SCRIPT_NAME']) . '/uploads/';

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0775, true);
}

if (!is_writable($uploadDir)) {
    http_response_code(500);
    echo json_encode(['error' => 'Upload-Verzeichnis nicht beschreibbar']);
    exit;
}

/* ---- TinyMCE sendet FILE unter "file" ---- */
if (empty($_FILES['file'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Keine Datei empfangen']);
    exit;
}

$file = $_FILES['file'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['error' => 'Upload-Fehler: ' . $file['error']]);
    exit;
}

/* ---- Dateiname säubern ---- */
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed = ['jpg','jpeg','png','gif','webp'];

if (!in_array($ext, $allowed)) {
    http_response_code(400);
    echo json_encode(['error' => 'Dateityp nicht erlaubt']);
    exit;
}

$filename = uniqid('img_', true) . '.' . $ext;
$target = $uploadDir . $filename;

/* ---- Datei verschieben ---- */
if (!move_uploaded_file($file['tmp_name'], $target)) {
    http_response_code(500);
    echo json_encode(['error' => 'Datei konnte nicht gespeichert werden']);
    exit;
}

/* ---- KORREKTE TinyMCE-JSON-ANTWORT ---- */
echo json_encode([
    'location' => $uploadUrl . $filename
]);
