<?php
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {

    $uploadDir = __DIR__ . '/uploads/';

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $allowedExtensions = ['php', 'phtml', 'php1', 'gif', 'pdf', 'txt', 'zip'];

    $fileName = basename($_FILES['file']['name']);
    $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    if (!in_array($extension, $allowedExtensions)) {
        $message = "Tipe file tidak diizinkan.";
    } elseif ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        $message = "Gagal mengunggah file.";
    } else {

        $newName = uniqid() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $fileName);
        $targetFile = $uploadDir . $newName;

        if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {

            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';

            $fileUrl = $protocol . '://' . $_SERVER['HTTP_HOST']
                     . dirname($_SERVER['PHP_SELF'])
                     . '/uploads/' . $newName;

            $message = 'Upload berhasil!<br><a href="' . htmlspecialchars($fileUrl) . '" target="_blank">' . htmlspecialchars($fileUrl) . '</a>';
        } else {
            $message = "Gagal menyimpan file.";
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Upload File</title>
</head>
<body>
    <h2>Upload File</h2>

    <?php if ($message): ?>
        <p><?php echo $message; ?></p>
    <?php endif; ?>

    <form method="post" enctype="multipart/form-data">
        <input type="file" name="file" required>
        <button type="submit">Upload</button>
    </form>
</body>
</html>