<?php
// Mengaktifkan tampilan error (hanya saat pengembangan)
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Folder untuk menyimpan file
$upload_dir = 'uploads/';

// Menangani pengiriman form untuk upload file
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload'])) {
    $target_file = $upload_dir . basename($_FILES['fileToUpload']['name']);
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    // Cek apakah file adalah dokumen yang diizinkan
    if ($fileType != "xls" && $fileType != "xlsx" && $fileType != "doc" && $fileType != "docx") {
        echo "Hanya file Excel dan Word yang diizinkan.";
        $uploadOk = 0;
    }

    // Cek jika $uploadOk diatur ke 0 oleh kesalahan
    if ($uploadOk == 0) {
        echo "Maaf, file tidak dapat diupload.";
    } else {
        // Jika semuanya baik-baik saja, coba untuk meng-upload file
        if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) {
            echo "File ". htmlspecialchars(basename($_FILES['fileToUpload']['name'])). " telah diupload.";
        } else {
            echo "Maaf, terjadi kesalahan saat mengupload file.";
        }
    }
}

// Membaca file yang ada di folder uploads
$files = array_diff(scandir($upload_dir), array('..', '.'));

include_once('includes/header.php');
?>

<div class="container">
    <h2>File Manager</h2>

    <!-- Form untuk upload file -->
    <form action="" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label for="fileToUpload">Pilih file untuk diupload (Excel/Word):</label>
            <input type="file" name="fileToUpload" id="fileToUpload" class="form-control" required>
        </div>
        <button type="submit" class="btn btn-primary">Upload</button>
    </form>

    <h3>Daftar File</h3>
    <ul class="list-group">
        <?php foreach ($files as $file): ?>
            <li class="list-group-item">
                <a href="<?php echo $upload_dir . htmlspecialchars($file); ?>" target="_blank">
                    <?php echo htmlspecialchars($file); ?>
                </a>
                <a href="edit_spreadsheet.php?file=<?php echo urlencode($file); ?>" class="btn btn-warning btn-sm float-right">Edit</a>
            </li>
        <?php endforeach; ?>
    </ul>
</div>

<?php include_once('includes/footer.php'); ?>
