<?php
require_once __DIR__ . '/../../cors.php'; // Enable CORS for React Native
// GET /api/gallery — public gallery (no auth required)
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../middleware/auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') jsonError('Method not allowed', 405);

$db    = getDB();
$items = $db->query(
    'SELECT * FROM gallery WHERE is_active = 1 ORDER BY created_at DESC'
)->fetchAll();

// Fix image_url: prepend full server URL if relative
$baseUrl = 'http://' . $_SERVER['HTTP_HOST'];
foreach ($items as &$item) {
    if (!empty($item['image_url']) && str_starts_with($item['image_url'], '/')) {
        $item['image_url'] = $baseUrl . $item['image_url'];
    }

    if (empty($item['media_type'])) {
        $path = strtolower(parse_url((string)($item['image_url'] ?? ''), PHP_URL_PATH) ?? '');
        $ext = pathinfo($path, PATHINFO_EXTENSION);
        $item['media_type'] = in_array($ext, ['mp4', 'webm', 'ogg'], true) ? 'video' : 'image';
    }
}
unset($item);

jsonResponse($items);
