<?php
// Aktifkan pencatatan error ke file log
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/upload_errors.log');

// Inisialisasi response
$response = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_FILES['photos']['name'][0])) {
        $uploadDir = 'uploads/';
        
        // Buat folder upload jika belum ada
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $totalFiles = count($_FILES['photos']['name']);
        $uploaded = 0;
        $errors = [];

        for ($i = 0; $i < $totalFiles; $i++) {
            $fileName = basename($_FILES['photos']['name'][$i]);
            $tmpName = $_FILES['photos']['tmp_name'][$i];
            $targetFilePath = $uploadDir . $fileName;

            if (!file_exists($tmpName)) {
                $errorMsg = "File temp tidak ditemukan untuk: $fileName";
                $errors[] = $errorMsg;
                error_log($errorMsg);
                continue;
            }

            if (move_uploaded_file($tmpName, $targetFilePath)) {
                $uploaded++;
            } else {
                $errorMsg = "Gagal mengupload file: $fileName";
                $errors[] = $errorMsg;
                error_log($errorMsg);
            }
        }

        if ($uploaded > 0) {
            $response .= "Berhasil mengupload $uploaded file.<br>";
        }

        if (!empty($errors)) {
            $response .= "Beberapa file gagal diupload:<br>" . implode('<br>', $errors);
        }
    } else {
        $response = "Tidak ada file yang dipilih untuk diupload.";
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Upload File</title>
</head>
<body>
    <h2>Upload Beberapa File</h2>
    <?php if (!empty($response)) echo "<p>$response</p>"; ?>

    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="photos[]" multiple>
        <button type="submit">Upload</button>
    </form>
</body>
</html>
