<?php
session_start();
require_once 'config.php';

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

// Mode ALL : photos du cercle + publiques
if (isset($_GET['all'])) {
    $circleId = (int)($_SESSION['circle_id'] ?? 1);
    $isPublic = isset($_GET['public']);
    try {
        if ($isPublic) {
            // Médias du cercle OU gages globaux (publics)
            $stmt = $pdo->prepare("
                SELECT bp.file_path, bp.bet_id, b.description,
                       u.username,
                       CASE WHEN b.is_global=1 THEN 'public' ELSE 'cercle' END as source
                FROM bet_proofs bp
                JOIN bets b ON b.id = bp.bet_id
                JOIN users u ON u.id = b.user_id
                WHERE (b.circle_id = ? OR b.is_global = 1)
                  AND b.hidden = 0
                ORDER BY bp.id DESC LIMIT 200
            ");
            $stmt->execute([$circleId]);
        } else {
            $stmt = $pdo->prepare("
                SELECT bp.file_path, bp.bet_id, b.description, u.username
                FROM bet_proofs bp
                JOIN bets b ON b.id = bp.bet_id
                JOIN users u ON u.id = b.user_id
                WHERE b.circle_id = ?
                ORDER BY bp.id DESC LIMIT 100
            ");
            $stmt->execute([$circleId]);
        }
        echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
    } catch (Exception $e) { echo '[]'; }
    exit;
}

// Mode GAGE : photos d'un gage spécifique
$betId = (int)($_GET['bet_id'] ?? 0);
if (!$betId) { echo '[]'; exit; }
try {
    $stmt = $pdo->prepare("SELECT file_path, bet_id FROM bet_proofs WHERE bet_id = ? ORDER BY id ASC");
    $stmt->execute([$betId]);
    echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
} catch (Exception $e) { echo '[]'; }
?>
