<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
// Define upload directory
$targetDir = "uploads/";

// ✅ Check if the folder exists; if not, create it with full permissions
if (!file_exists($targetDir)) {
    mkdir($targetDir, 0777, true); // true = recursive, so intermediate directories are created if needed
}

// ✅ Handle uploaded file
if ($_FILES["file"]["error"] === UPLOAD_ERR_OK) {
    $tmpName = $_FILES["file"]["tmp_name"];
    $fileName = basename($_FILES["file"]["name"]);
    $targetFile = $targetDir . $fileName;

    // ✅ Move uploaded file to the target location
    if (move_uploaded_file($tmpName, $targetFile)) {
        echo json_encode(["status" => "success", "path" => $targetFile]);
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to save file"]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Upload error", "code" => $_FILES["file"]["error"]]);
}
?>
