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

$uploadDir = 'uploads/';

// --- IMPORTANT: Update this to your actual API base URL path ---
$baseUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/api/' . $uploadDir;

$response = [];

// Check if the directory exists
if (!is_dir($uploadDir)) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Uploads directory not found on server.']);
    exit;
}

// Scan the directory for files
$files = scandir($uploadDir, SCANDIR_SORT_DESCENDING); // SCANDIR_SORT_DESCENDING for newest first

foreach ($files as $file) {
    // Ignore '.' and '..' and other non-image files
    if ($file === '.' || $file === '..') {
        continue;
    }

    $fileExtension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $allowedTypes = ['jpg', 'jpeg', 'png', 'gif']; // Add any other types you allow

    if (in_array($fileExtension, $allowedTypes)) {
        // For each image, create an object with the 'image_url' key,
        // which is what the Android app expects.
        $mediaItem = [
            'image_url' => $baseUrl . $file
        ];
        $response[] = $mediaItem;
    }
}

echo json_encode($response);
?>