<?php
define('UPLOAD_DIR', __DIR__ . '/pdf');
define('MAX_UPLOAD_BYTES', 20 * 1024 * 1024); // 20 MB

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

// Size limit
if ($_FILES['pdf']['size'] > MAX_UPLOAD_BYTES) {
    http_response_code(413);
    echo 'File too large';
    exit;
}

// MIME type validation
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime  = $finfo->file($_FILES['pdf']['tmp_name']) ?: '';
if ($mime !== 'application/pdf') {
    http_response_code(415);
    echo 'Only PDF files are accepted';
    exit;
}

// Extension validation
$ext = strtolower(pathinfo($_FILES['pdf']['name'], PATHINFO_EXTENSION));
if ($ext !== 'pdf') {
    http_response_code(415);
    echo 'Only PDF files are accepted';
    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, 0775, true);
}

// Safe filename — never trust the original name
$safe_name   = preg_replace('/[^a-zA-Z0-9._-]/', '_', basename($_FILES['pdf']['name']));
$target_path = $save_dir . '/' . $safe_name;

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