<?php
// Settings
define('UPLOAD_DIR', __DIR__ . '/pdf');
define('SECRET_TOKEN', 'MY_SECRET_TOKEN');

// Check token
/*
if ($_POST['token'] !== SECRET_TOKEN) {
    http_response_code(403);
    echo 'Invalid token';
    exit;
}
*/
file_put_contents('upload_debug.log', print_r($_FILES, true) . print_r($_POST, true));

// Check file
if (!isset($_FILES['pdf']) || $_FILES['pdf']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo 'PDF upload failed';
    exit;
}

// Validate metadata
$uuid = preg_replace('/[^a-zA-Z0-9\-]/', '_', $_POST['uuid'] ?? '');
$council_reference = preg_replace('/[^a-zA-Z0-9\-]/', '_', $_POST['council_reference'] ?? '');

if (!$uuid || !$council_reference) {
    http_response_code(400);
    echo 'Missing UUID or council reference';
    exit;
}

// Ensure upload directory exists
$save_dir = UPLOAD_DIR . '/' . $uuid;
if (!is_dir($save_dir)) {
    mkdir($save_dir, 0777, true);
}

// Save the uploaded PDF
$filename = basename($_FILES['pdf']['name']);
$target_path = $save_dir . '/' . $filename;

if (move_uploaded_file($_FILES['pdf']['tmp_name'], $target_path)) {
    http_response_code(200);
    echo "Uploaded: $filename";
} else {
    http_response_code(500);
    echo 'Failed to save file';
}
