<?php
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error_log.txt');

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

function json_response($success, $message, $filePath = null) {
    $response = ['success' => $success, 'message' => $message];
    if ($filePath) {
        $response['filePath'] = $filePath;
    }
    echo json_encode($response);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.');
}

if (!isset($_FILES['document']) || $_FILES['document']['error'] == UPLOAD_ERR_NO_FILE) {
    json_response(false, 'No file was uploaded.');
}

$file = $_FILES['document'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    $upload_errors = [
        UPLOAD_ERR_INI_SIZE   => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
        UPLOAD_ERR_FORM_SIZE  => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
        UPLOAD_ERR_PARTIAL    => 'The uploaded file was only partially uploaded.',
        UPLOAD_ERR_NO_FILE    => 'No file was uploaded.',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
        UPLOAD_ERR_EXTENSION  => 'A PHP extension stopped the file upload.',
    ];
    $error_message = $upload_errors[$file['error']] ?? 'Unknown upload error.';
    json_response(false, $error_message);
}

$upload_dir = __DIR__ . '/uploads/';
if (!is_dir($upload_dir)) {
    if (!mkdir($upload_dir, 0775, true)) {
        json_response(false, 'Failed to create upload directory.');
    }
}

$file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$file_name = uniqid('doc_') . '.' . $file_extension;
$target_path = $upload_dir . $file_name;

if (move_uploaded_file($file['tmp_name'], $target_path)) {
    
    $web_path = '/uploads/' . $file_name;
    json_response(true, 'File uploaded successfully.', $web_path);
} else {
    json_response(false, 'Failed to move uploaded file.');
}
?>
