<?php
// Simple upload receiver for server-level testing. Saves to public/uploads/.
// Enhanced logging to public/upload_test.log for debugging large upload failures.
header('Content-Type: application/json');

error_reporting(E_ALL);
ini_set('display_errors', '0');

$logFile = __DIR__ . '/upload_test.log';
function log_msg($msg) {
    global $logFile;
    $time = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$time] " . $msg . "\n", FILE_APPEND | LOCK_EX);
}

// Shutdown handler to capture fatal errors
register_shutdown_function(function() use ($logFile) {
    $err = error_get_last();
    if ($err) {
        $time = date('Y-m-d H:i:s');
        $text = "[$time] SHUTDOWN ERROR: " . json_encode($err);
        file_put_contents($logFile, $text . "\n", FILE_APPEND | LOCK_EX);
    }
});

log_msg('---- REQUEST START ----');
log_msg('REMOTE_ADDR: ' . ($_SERVER['REMOTE_ADDR'] ?? '')); 
log_msg('REQUEST_METHOD: ' . ($_SERVER['REQUEST_METHOD'] ?? '')); 
log_msg('HTTP_PROTOCOL: ' . ($_SERVER['SERVER_PROTOCOL'] ?? '')); 
log_msg('CONTENT_LENGTH: ' . ($_SERVER['CONTENT_LENGTH'] ?? '')); 
log_msg('HTTP2: ' . (isset($_SERVER['HTTP2']) ? 'yes' : 'no'));
log_msg('Available disk space (bytes): ' . disk_free_space(__DIR__));

$uploadDir = __DIR__ . '/uploads';
if (!is_dir($uploadDir)) {
    if (!mkdir($uploadDir, 0755, true)) {
        log_msg('Failed to create upload dir: ' . $uploadDir);
    } else {
        log_msg('Created upload dir: ' . $uploadDir);
    }
}

log_msg('FILES: ' . json_encode(array_map(function($f){
    return isset($f['name']) ? ['name'=>$f['name'],'size'=>$f['size']??null,'error'=>$f['error']??null] : $f;
}, $_FILES)));

if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    $code = $_FILES['file']['error'] ?? null;
    log_msg('No file uploaded or upload error, code=' . json_encode($code));
    http_response_code(400);
    echo json_encode(['error' => 'No file uploaded or upload error', 'code' => $code]);
    log_msg('---- REQUEST END ----');
    exit;
}

$fname = basename($_FILES['file']['name']);
$target = $uploadDir . '/' . time() . '_' . $fname;

if (!move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
    log_msg('move_uploaded_file failed. tmp_name=' . ($_FILES['file']['tmp_name'] ?? '')); 
    http_response_code(500);
    echo json_encode(['error' => 'Failed to move uploaded file']);
    log_msg('---- REQUEST END ----');
    exit;
}

$size = filesize($target);
log_msg('Upload saved: ' . $target . ' size=' . $size);
echo json_encode(['success' => true, 'path' => str_replace(__DIR__, '', $target), 'size' => $size]);
log_msg('---- REQUEST END ----');
