<?php
include_once "../db.php";

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $result = $conn->query("SELECT * FROM gallery_images ORDER BY section, created_at DESC");
    $sections = [1 => [], 2 => [], 3 => []];
    while ($row = $result->fetch_assoc()) {
        $sections[(int)$row["section"]][] = $row;
    }
    echo json_encode($sections);
}

if ($method === 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
    if (isset($data["image_url"], $data["section"])) {
        $stmt = $conn->prepare("INSERT INTO gallery_images (image_url, section) VALUES (?, ?)");
        $stmt->bind_param("si", $data["image_url"], $data["section"]);
        if ($stmt->execute()) {
            echo json_encode(["success" => true, "id" => $conn->insert_id]);
        } else {
            echo json_encode(["success" => false, "error" => $conn->error]);
        }
        $stmt->close();
    }
}

if ($method === 'DELETE') {
    parse_str($_SERVER['QUERY_STRING'], $params);
    if (isset($params["id"])) {
        $id = intval($params["id"]);
        $stmt = $conn->prepare("DELETE FROM gallery_images WHERE id=?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            echo json_encode(["success" => true]);
        } else {
            echo json_encode(["success" => false, "error" => $conn->error]);
        }
        $stmt->close();
    }
}

$conn->close();
