<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit;
}

if (!isset($_FILES["foto"])) {
    echo json_encode([
        "success" => false,
        "message" => "File foto belum dikirim",
        "data" => null
    ]);
    exit;
}

$file = $_FILES["foto"];

$allowedTypes = [
    "image/jpeg",
    "image/jpg",
    "image/png",
    "image/webp"
];

if (!in_array($file["type"], $allowedTypes)) {
    echo json_encode([
        "success" => false,
        "message" => "Format foto harus JPG, PNG, atau WEBP",
        "data" => null
    ]);
    exit;
}

$maxSize = 3 * 1024 * 1024;

if ($file["size"] > $maxSize) {
    echo json_encode([
        "success" => false,
        "message" => "Ukuran foto maksimal 3MB",
        "data" => null
    ]);
    exit;
}

$uploadDir = __DIR__ . "/../uploads/omprengan/";

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

$extension = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
$fileName = "omprengan_" . time() . "_" . rand(1000, 9999) . "." . $extension;
$targetPath = $uploadDir . $fileName;

if (!move_uploaded_file($file["tmp_name"], $targetPath)) {
    echo json_encode([
        "success" => false,
        "message" => "Gagal mengupload foto",
        "data" => null
    ]);
    exit;
}

$dbPath = "uploads/omprengan/" . $fileName;
$url = "http://localhost/backend/" . $dbPath;

echo json_encode([
    "success" => true,
    "message" => "Foto omprengan berhasil diupload",
    "data" => [
        "path" => $dbPath,
        "url" => $url
    ]
]);

?>