<?php
require_once "../db.php";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['image']) && isset($_POST['section'])) {
        $section = intval($_POST['section']);

        $targetDir = __DIR__ . "/./uploads/";
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0777, true);
        }

        $fileName = time() . "_" . basename($_FILES["image"]["name"]);
        $targetFile = $targetDir . $fileName;
        $filePath = "/uploads/" . $fileName;

        if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
            $stmt = $conn->prepare("INSERT INTO gallery_images (image_url, section) VALUES (?, ?)");
            $stmt->bind_param("si", $filePath, $section);
            if ($stmt->execute()) {
                echo json_encode(["success" => true, "url" => $filePath]);
            } else {
                echo json_encode(["success" => false, "error" => $conn->error]);
            }
            $stmt->close();
        } else {
            echo json_encode(["success" => false, "error" => "File upload failed"]);
        }
    } else {
        echo json_encode(["success" => false, "error" => "No file or section provided"]);
    }
}

$conn->close();
