<?php
session_start();

// Include configuration
$config = include __DIR__ . '/../config.php';

header('Content-Type: application/json');

// Allow only POST with multipart/form-data
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

if (empty($_FILES) || !isset($_POST['field'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No file or field specified']);
    exit;
}

$field = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_POST['field']);
$fileKey = array_key_first($_FILES);
$file = $_FILES[$fileKey];

// Validate upload
if ($file['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Upload failed']);
    exit;
}

// Enforce size limit (10MB)
$maxSize = 10 * 1024 * 1024;
if ($file['size'] > $maxSize) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'File too large (max 10MB)']);
    exit;
}

// Validate mime type
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
$allowed = [
    'application/pdf' => 'pdf',
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/webp' => 'webp'
];

if (!isset($allowed[$mime])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Unsupported file type']);
    exit;
}

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

// Build safe filename
$ext = $allowed[$mime];
$sessionId = isset($_POST['sessionId']) ? preg_replace('/[^A-Z0-9]/', '', $_POST['sessionId']) : 'ANON';
$base = $sessionId . '_' . $field . '_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4));
$target = $uploadDir . '/' . $base . '.' . $ext;

if (!move_uploaded_file($file['tmp_name'], $target)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to save file']);
    exit;
}

// Build public URL (assuming built-in server serves project root)
$publicPath = 'uploads/' . basename($target);
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost:8000';
$url = $scheme . '://' . $host . '/' . $publicPath;

echo json_encode([
    'success' => true,
    'field' => $field,
    'url' => $url,
]);
?>


