<?php
/**
 * CMS TinyMCE File Upload Handler
 */
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['userid'])) {
    http_response_code(401);
    exit(json_encode(['error' => 'Unauthorized']));
}

$upload_dir = '../../web/uploads/media/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

// Check if file was uploaded
if ($_FILES['file']) {
    $file = $_FILES['file'];
    $filename = time() . '_' . basename($file['name']);
    $target_file = $upload_dir . $filename;

    // Validate type (Images only for now)
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!in_array($file['type'], $allowed_types)) {
        exit(json_encode(['error' => 'Invalid file type']));
    }

    if (move_uploaded_file($file['tmp_name'], $target_file)) {
        // Return relative path for front-end
        $location = 'uploads/media/' . $filename;
        echo json_encode(['location' => $location]);
    } else {
        echo json_encode(['error' => 'Upload failed']);
    }
} else {
    echo json_encode(['error' => 'No file uploaded']);
}
?>