<?php
header("Content-Type: application/json");

if (session_status() === PHP_SESSION_NONE) {
    require_once(__DIR__ . "/../../includes/session.php");
    session_start();
}

if (
    empty($_SESSION["sub_admin_id"]) &&
    empty($_SESSION["village_admin_id"]) &&
    empty($_SESSION["super_admin_id"])
) {
    http_response_code(401);
    echo json_encode(["status" => false, "message" => "Login required."]);
    exit;
}

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    echo json_encode(["status" => false, "message" => "Invalid request method."]);
    exit;
}

if (empty($_FILES["image"]) || $_FILES["image"]["error"] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(["status" => false, "message" => "Image file is required."]);
    exit;
}

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

$tmpName = $_FILES["image"]["tmp_name"];
$mime = mime_content_type($tmpName);

if (!isset($allowedMime[$mime])) {
    http_response_code(400);
    echo json_encode(["status" => false, "message" => "Only JPG, PNG, and WEBP images are allowed."]);
    exit;
}

$folder = __DIR__ . "/../../uploads/";
if (!is_dir($folder) && !mkdir($folder, 0777, true)) {
    http_response_code(500);
    echo json_encode(["status" => false, "message" => "Upload folder could not be created."]);
    exit;
}

$field = preg_replace("/[^a-zA-Z0-9_-]/", "", $_POST["field"] ?? "visitor");
$filename = time() . "_" . random_int(1000, 9999) . "_" . $field . "." . $allowedMime[$mime];
$target = $folder . $filename;

if (!move_uploaded_file($tmpName, $target)) {
    http_response_code(500);
    echo json_encode(["status" => false, "message" => "Image could not be saved."]);
    exit;
}

echo json_encode([
    "status" => true,
    "message" => "Image uploaded.",
    "path" => "uploads/" . $filename,
    "size" => filesize($target),
]);
