<?php
header('Content-Type: application/json');

$uploadDir = "uploads/"; // Folder untuk menyimpan gambar

// Buat folder jika belum ada
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// Pastikan ada file yang diunggah
if (isset($_FILES["upload"])) {
    $fileName = time() . "_" . basename($_FILES["upload"]["name"]);
    $targetFilePath = $uploadDir . $fileName;
    
    // Cek apakah file adalah gambar
    $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
    $allowedTypes = ["jpg", "jpeg", "png", "gif"];

    if (in_array(strtolower($fileType), $allowedTypes)) {
        if (move_uploaded_file($_FILES["upload"]["tmp_name"], $targetFilePath)) {
            // Kirim URL gambar kembali ke CKEditor untuk ditampilkan
            echo json_encode([
                "uploaded" => 1,
                "fileName" => $fileName,
                "url" => $uploadDir . $fileName
            ]);
            exit;
        } else {
            echo json_encode(["uploaded" => 0, "error" => ["message" => "Gagal mengunggah gambar."]]);
            exit;
        }
    } else {
        echo json_encode(["uploaded" => 0, "error" => ["message" => "Format file tidak didukung."]]);
        exit;
    }
} else {
    echo json_encode(["uploaded" => 0, "error" => ["message" => "Tidak ada file yang diunggah."]]);
    exit;
}
?>
