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

$userId     = isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0 ? (int)$_SESSION['user_id'] : 0;
$circleId   = (int)($_SESSION['circle_id'] ?? 1);
$isFullMember = $userId > 0 && isset($_SESSION['auth_method']) && $_SESSION['auth_method'] === 'password';

$hasHidden = (bool)$pdo->query("SHOW COLUMNS FROM bets LIKE 'hidden'")->fetch();
$hasGlobal = (bool)$pdo->query("SHOW COLUMNS FROM bets LIKE 'is_global'")->fetch();
$hiddenCond = $hasHidden ? "AND (b.hidden IS NULL OR b.hidden = 0)" : '';

// ── MODE GAGES PUBLICS (JSON pour le panel) ───────────────────────
if (isset($_GET['global']) && $_GET['global'] == '1') {
    header('Content-Type: application/json');
    $limit = min(200, max(1, (int)($_GET['limit'] ?? 100)));
    try {
        $stmt = $pdo->prepare("
            SELECT b.id, b.description, b.amount, b.bet_category, b.bet_subcategory, b.is_friend_bet, u.username
            FROM bets b
            JOIN users u ON u.id = b.user_id
            WHERE b.is_global = 1 AND b.status = 'pending'
              AND (b.parieur2_id IS NULL OR b.parieur2_id = 0)
              {$hiddenCond}
            ORDER BY b.id DESC
            LIMIT ?
        ");
        $stmt->execute([$limit]);
        $bets = $stmt->fetchAll();
        // Filtrer les mots interdits sur les descriptions
        foreach ($bets as &$b) {
            $b['description'] = filterBadWords($b['description'], $pdo);
        }
        echo json_encode(['bets' => $bets]);
    } catch (Exception $e) {
        echo json_encode(['bets' => [], 'error' => $e->getMessage()]);
    }
    exit;
}

// ── MODE CLASSIQUE (HTML paginé) ─────────────────────────────────
$offset     = max(0, (int)($_GET['offset'] ?? 10));
$globalCond = $hasGlobal ? "OR b.is_global = 1" : '';

try {
    if ($isFullMember) {
        $stmt = $pdo->prepare("
            SELECT b.*, u.username, c.name as circle_name, u2.username as parieur2_name
            FROM bets b
            JOIN users u ON u.id = b.user_id
            LEFT JOIN circles c ON c.id = b.circle_id
            LEFT JOIN users u2 ON u2.id = b.parieur2_id
            WHERE 1=1 {$hiddenCond}
              AND (b.circle_id = ? OR b.user_id = ? OR b.parieur2_id = ? {$globalCond}
                OR b.user_id IN (SELECT friend_id FROM friends WHERE user_id = ? AND status = 'active'))
            ORDER BY b.id DESC LIMIT 10 OFFSET ?
        ");
        $stmt->execute([$circleId, $userId, $userId, $userId, $offset]);
    } else {
        $stmt = $pdo->prepare("SELECT b.*, u.username, NULL as circle_name, NULL as parieur2_name
            FROM bets b JOIN users u ON u.id=b.user_id
            WHERE 1=1 {$hiddenCond} ORDER BY b.id DESC LIMIT 10 OFFSET ?");
        $stmt->execute([$offset]);
    }
    $bets = $stmt->fetchAll();
} catch (Exception $e) {
    $stmt = $pdo->prepare("SELECT * FROM bets ORDER BY id DESC LIMIT 10 OFFSET ?");
    $stmt->execute([$offset]);
    $bets = $stmt->fetchAll();
}

if (empty($bets)) { exit; }

foreach ($bets as $bet) {
    $status = strtolower($bet['status'] ?? 'pending');
    $badgeClass = $status === 'lost' ? 'bg-danger' : ($status === 'won' ? 'bg-success' : 'bg-warning text-dark');
    $statusLbl  = $status === 'lost' ? 'PERDU' : ($status === 'won' ? 'GAGNE' : 'EN COURS');
    $isOwner    = $userId && (int)$bet['user_id'] === $userId;
    $amount     = number_format((float)($bet['amount'] ?? 0), 0);
    $desc       = htmlspecialchars(filterBadWords($bet['description'] ?? '', $pdo));

    echo "<div class='card p-3 mb-3 bg-dark border-secondary shadow-sm small gage-card' id='bet-{$bet['id']}'>";
    echo "<div class='d-flex justify-content-between align-items-center mb-1'>";
    echo "<span class='text-info fw-bold' style='font-size:0.68rem;'>#{$bet['id']} | <span class='text-success'>{$amount} pts</span></span>";
    if (!empty($bet['circle_name'])) echo "<span class='badge bg-dark border border-info text-info ms-1' style='font-size:0.55rem;'>{$bet['circle_name']}</span>";
    echo "<span class='badge {$badgeClass}' style='font-size:0.52rem;'>{$statusLbl}</span>";
    echo "</div>";
    echo "<div class='text-white fw-bold mb-1'>{$desc}</div>";
    echo "<div class='text-muted' style='font-size:0.62rem;'>" . htmlspecialchars($bet['username'] ?? '') . "</div>";
    echo "</div>";
}
?>
