<?php
header("Content-Type: application/json; charset=UTF-8");

$UPLOAD_DIR = __DIR__ . "/uploads/";

if(!isset($_FILES['image'])){
  echo json_encode(["ok"=>false,"error"=>"File tidak ada"]);
  exit;
}

$file = $_FILES['image'];

if($file['error'] !== UPLOAD_ERR_OK){
  echo json_encode(["ok"=>false,"error"=>"Upload error"]);
  exit;
}

/* VALIDASI TIPE */
$allowed = ["image/jpeg","image/png","image/webp","image/gif"];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$type = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if(!in_array($type,$allowed)){
  echo json_encode(["ok"=>false,"error"=>"Format tidak didukung"]);
  exit;
}

/* BUAT NAMA FILE */
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$name = "img_" . date("Ymd_His") . "_" . rand(1000,9999) . "." . $ext;
$target = $UPLOAD_DIR . $name;

/* PINDAHKAN FILE */
if(!move_uploaded_file($file['tmp_name'],$target)){
  echo json_encode(["ok"=>false,"error"=>"Gagal simpan file"]);
  exit;
}

/* URL RELATIF */
$url = "uploads/" . $name;

echo json_encode([
  "ok"=>true,
  "url"=>$url
]);