<?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, $data) {
    $response = ['success' => $success];
    if (is_string($data)) {
        $response['message'] = $data;
    } elseif (is_array($data)) {
        $response = array_merge($response, $data);
    }
    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)) {
    
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://";
    $domain_name = $_SERVER['HTTP_HOST'];
    $web_path = $protocol . $domain_name . '/uploads/' . $file_name;
    json_response(true, ['path' => $web_path, 'message' => 'File uploaded successfully.']);
} else {
    json_response(false, 'Failed to move uploaded file.');
}
?>
