<?php
$uploadDir = __DIR__ . '../../../uploads/';
$uploadUrl = 'http://localhost/website/uploads/';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['upload'])) {
    $file = $_FILES['upload'];
    $filename = uniqid() . '_' . basename($file['name']);
    $targetFile = $uploadDir . $filename;

    if (move_uploaded_file($file['tmp_name'], $targetFile)) {
        $response = [
            'uploaded' => true,
            'url' => $uploadUrl . $filename
        ];
    } else {
        $response = [
            'uploaded' => false,
            'error' => ['message' => 'Gagal mengunggah file.']
        ];
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
} else {
    echo json_encode([
        'uploaded' => false,
        'error' => ['message' => 'Metode tidak didukung.']
    ]);
}
?>