<?php
include 'db_connect.php';

$limit = 12; // Number of images per batch
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$category = isset($_GET['category']) ? $_GET['category'] : 'all';
$offset = ($page - 1) * $limit;

// Prepare Query
if ($category == 'all') {
    $sql = "SELECT * FROM gallery ORDER BY id DESC LIMIT $limit OFFSET $offset";
    $count_sql = "SELECT COUNT(*) as total FROM gallery";
} else {
    $category = $conn->real_escape_string($category);
    $sql = "SELECT * FROM gallery WHERE category = '$category' ORDER BY id DESC LIMIT $limit OFFSET $offset";
    $count_sql = "SELECT COUNT(*) as total FROM gallery WHERE category = '$category'";
}

// Get Images
$result = $conn->query($sql);
$images = [];
while ($row = $result->fetch_assoc()) {
    // Set default title if empty
    $row['title'] = !empty($row['title']) ? $row['title'] : $row['category'];
    $images[] = $row;
}

// Get Total Count (to know if we should hide the Load More button)
$total_result = $conn->query($count_sql);
$total_rows = $total_result->fetch_assoc()['total'];
$has_more = ($offset + $limit) < $total_rows;

// Return JSON
header('Content-Type: application/json');
echo json_encode(['images' => $images, 'has_more' => $has_more]);
?>