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

if (!isset($_SESSION['admin_logged_in'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$uploadDir  = realpath(__DIR__ . '/../../uploads') . '/';
$allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
$images     = [];

if (is_dir($uploadDir)) {
    $files = scandir($uploadDir);
    rsort($files); // newest first
    foreach ($files as $f) {
        if ($f === '.' || $f === '..') continue;
        $ext = strtolower(pathinfo($f, PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExt)) continue;
        $size = filesize($uploadDir . $f);
        $images[] = [
            'name'  => $f,
            'url'   => '/bm/uploads/' . rawurlencode($f),
            'size'  => $size,
            'date'  => date('Y-m-d', filemtime($uploadDir . $f)),
        ];
    }
}

echo json_encode(['success' => true, 'images' => $images]);
?>
