<?php

$file = "database.json";
$uploadDir = "uploads/";

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$link = $_POST["link"] ?? "";

if (!isset($_FILES["image"])) {
    http_response_code(400);
    exit("No image");
}

$ext = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
$allow = ["jpg","jpeg","png","webp"];

if (!in_array($ext,$allow)) {
    exit("Invalid file");
}

$name = time()."_".rand(1000,9999).".".$ext;
$path = $uploadDir.$name;

move_uploaded_file($_FILES["image"]["tmp_name"], $path);

$data = [];

if (file_exists($file)) {
  $data = json_decode(file_get_contents($file), true);
}

$data[] = [
  "image" => $path,
  "link"  => $link
];

file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));