<?php
// Simpan/Timpa ini di file: upload_handler.php
header('Content-Type: application/json');

// Pastikan folder icons ada
$targetDir = "icons/";
if (!file_exists($targetDir)) {
    mkdir($targetDir, 0777, true);
}

$uploadedFiles = [];
$errors = [];

if (isset($_FILES['file_icon'])) {
    $total = count($_FILES['file_icon']['name']);
    for ($i = 0; $i < $total; $i++) {
        $fileName = basename($_FILES['file_icon']['name'][$i]);
        
        // PERBAIKAN DI SINI:
        // Menambahkan spasi " " di dalam filter agar tidak dihapus.
        // Regex sekarang mengizinkan: Huruf, Angka, Titik(.), Underscore(_), Strip(-), dan SPASI( )
        $fileName = preg_replace("/[^a-zA-Z0-9\._\- ]/", "", $fileName);
        
        $targetFile = $targetDir . $fileName;

        if (move_uploaded_file($_FILES['file_icon']['tmp_name'][$i], $targetFile)) {
            $uploadedFiles[] = $fileName;
        } else {
            $errors[] = "Gagal upload: " . $_FILES['file_icon']['name'][$i];
        }
    }
    echo json_encode(["status" => "success", "files" => $uploadedFiles, "errors" => $errors]);
} else {
    echo json_encode(["status" => "error", "message" => "Tidak ada file yang dikirim"]);
}
?>