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

requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $betId = (int)($_POST['bet_id'] ?? 0);

    if (isset($_POST['force_status']) && $betId) {
        $newStatus = in_array($_POST['new_status'],['won','lost','pending']) ? $_POST['new_status'] : 'pending';
        $prev = $pdo->prepare("SELECT status, user_id, amount FROM bets WHERE id=?");
        $prev->execute([$betId]);
        $prevBet = $prev->fetch();
        $pdo->prepare("UPDATE bets SET status=? WHERE id=?")->execute([$newStatus, $betId]);
        if ($prevBet && $prevBet['status']==='pending') {
            if ($newStatus==='won') {
                $pdo->prepare("UPDATE users SET points=points+? WHERE id=?")->execute([$prevBet['amount'],$prevBet['user_id']]);
                $pdo->prepare("UPDATE user_stats SET won_bets=won_bets+1,total_bets=total_bets+1 WHERE user_id=?")->execute([$prevBet['user_id']]);
                addNotification($pdo,(int)$prevBet['user_id'],"Ton gage #{$betId} est GAGNE !","index.php");
            } elseif ($newStatus==='lost') {
                $pdo->prepare("UPDATE user_stats SET lost_bets=lost_bets+1,total_bets=total_bets+1 WHERE user_id=?")->execute([$prevBet['user_id']]);
                addNotification($pdo,(int)$prevBet['user_id'],"Ton gage #{$betId} est PERDU.","index.php");
            }
        }
        $msg = "Gage #{$betId} → " . strtoupper($newStatus);
    }

    if (isset($_POST['delete_bet']) && $betId) {
        $pdo->prepare("DELETE FROM bet_votes  WHERE bet_id=?")->execute([$betId]);
        $pdo->prepare("DELETE FROM bet_proofs WHERE bet_id=?")->execute([$betId]);
        $pdo->prepare("DELETE FROM bets       WHERE id=?")->execute([$betId]);
        $msg = "Gage #{$betId} supprimé.";
    }

    if (isset($_POST['hide_bet']) && $betId) {
        // Vérifier que la colonne hidden existe
        $colExists = $pdo->query("SHOW COLUMNS FROM bets LIKE 'hidden'")->fetch();
        if (!$colExists) {
            $pdo->exec("ALTER TABLE bets ADD COLUMN hidden TINYINT(1) DEFAULT 0");
        }
        $newHidden = (int)$_POST['hidden_val'];
        $pdo->prepare("UPDATE bets SET hidden=? WHERE id=?")->execute([$newHidden,$betId]);
        $msg = "Gage #{$betId} " . ($newHidden ? "masqué ✓" : "visible ✓");
    }
}

// Filtres
$search     = trim($_GET['q']      ?? '');
$fStatus    = $_GET['status']      ?? '';
$fCircle    = (int)($_GET['circle'] ?? 0);
$where = "WHERE 1=1";
$params = [];
if ($search)  { $where .= " AND (b.description LIKE ? OR u.username LIKE ?)"; $params = array_merge($params,["%$search%","%$search%"]); }
if ($fStatus) { $where .= " AND b.status=?"; $params[] = $fStatus; }
if ($fCircle) { $where .= " AND b.circle_id=?"; $params[] = $fCircle; }

// Vérifier tables optionnelles
$hasBetProofs = (bool)$pdo->query("SHOW TABLES LIKE 'bet_proofs'")->fetch();
$hasHidden    = (bool)$pdo->query("SHOW COLUMNS FROM bets LIKE 'hidden'")->fetch();
$hasIsGlobal  = (bool)$pdo->query("SHOW COLUMNS FROM bets LIKE 'is_global'")->fetch();

$photosSubq = $hasBetProofs ? "(SELECT COUNT(*) FROM bet_proofs bp WHERE bp.bet_id=b.id)" : "0";
$hiddenCol  = $hasHidden    ? ", b.hidden"    : ", 0 as hidden";
$globalCol  = $hasIsGlobal  ? ", b.is_global" : ", 0 as is_global";

$stmt = $pdo->prepare("
    SELECT b.*, u.username, c.name as circle_name,
    {$photosSubq} as nb_photos
    {$hiddenCol} {$globalCol}
    FROM bets b
    JOIN users u ON u.id=b.user_id
    LEFT JOIN circles c ON c.id=b.circle_id
    $where
    ORDER BY b.id DESC LIMIT 100
");
$stmt->execute($params);
$bets = $stmt->fetchAll();

$circles = $pdo->query("SELECT id,name FROM circles ORDER BY name")->fetchAll();

include 'header.php';
?>

<div class="container-fluid mt-4 px-4">
    <a href="admin.php" class="btn btn-outline-secondary btn-sm mb-3">&larr; Admin</a>
    <h5 class="oracle-text text-info mb-3"> GESTION DES GAGES</h5>

    <?php if ($msg): ?><div class="alert alert-success small py-2"><?= $msg ?></div><?php endif; ?>

    <form method="GET" class="row g-2 mb-3">
        <div class="col-md-4">
            <input type="text" name="q" class="form-control form-control-sm" placeholder="Rechercher description / membre…" value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-2">
            <select name="status" class="form-select form-select-sm">
                <option value="">Tous statuts</option>
                <option value="pending" <?= $fStatus==='pending'?'selected':'' ?>>En cours</option>
                <option value="won"     <?= $fStatus==='won'?'selected':'' ?>>Gagnés</option>
                <option value="lost"    <?= $fStatus==='lost'?'selected':'' ?>>Perdus</option>
            </select>
        </div>
        <div class="col-md-3">
            <select name="circle" class="form-select form-select-sm">
                <option value="">Tous les cercles</option>
                <?php foreach ($circles as $c): ?>
                    <option value="<?= $c['id'] ?>" <?= $fCircle===$c['id']?'selected':'' ?>><?= htmlspecialchars($c['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-primary btn-sm w-100">Filtrer</button>
        </div>
    </form>

    <div class="table-responsive">
        <table class="table table-dark table-hover table-sm small border-secondary">
            <thead>
                <tr><th>#</th><th>Membre</th><th>Cercle</th><th>Description</th><th class="text-center">Pts</th><th class="text-center">Photos</th><th class="text-center">Statut</th><th class="text-center">Masqué</th><th class="text-center">Actions</th></tr>
            </thead>
            <tbody>
            <?php foreach ($bets as $b): ?>
            <tr class="<?= ($b['hidden']??0)?'opacity-50':'' ?>">
                <td class="text-muted"><?= $b['id'] ?></td>
                <td><?= htmlspecialchars($b['username']) ?></td>
                <td><small class="text-info"><?= htmlspecialchars($b['circle_name']??'—') ?></small></td>
                <td><?= htmlspecialchars(mb_substr($b['description'],0,50)) ?><?= strlen($b['description'])>50?'…':'' ?></td>
                <td class="text-center text-success"><?= number_format((float)$b['amount'],0) ?></td>
                <td class="text-center"><?= $b['nb_photos'] ?></td>
                <td class="text-center"><?= getBetStatusBadge($b['status']) ?></td>
                <td class="text-center"><?= ($b['hidden']??0) ? '<span class="text-warning">OUI</span>' : '—' ?></td>
                <td class="text-center">
                    <button class="btn btn-xs btn-outline-warning py-0" data-bs-toggle="modal" data-bs-target="#editBet<?= $b['id'] ?>">
                        <i class="fa-solid fa-gear" style="font-size:0.6rem;"></i>
                    </button>
                </td>
            </tr>

            <div class="modal fade" id="editBet<?= $b['id'] ?>" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-sm modal-dialog-centered">
                    <div class="modal-content bg-dark border-warning text-white">
                        <div class="modal-header border-secondary py-2">
                            <h6 class="modal-title text-warning small">⚙️ Gage #<?= $b['id'] ?></h6>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body p-3">
                            <!-- Forcer statut -->
                            <form method="POST" class="mb-2">
                                <input type="hidden" name="bet_id" value="<?= $b['id'] ?>">
                                <small class="text-white d-block mb-1">Forcer le statut</small>
                                <div class="input-group input-group-sm">
                                    <select name="new_status" class="form-select">
                                        <option value="pending" <?= $b['status']==='pending'?'selected':'' ?>>En cours</option>
                                        <option value="won"     <?= $b['status']==='won'?'selected':'' ?>>Gagné</option>
                                        <option value="lost"    <?= $b['status']==='lost'?'selected':'' ?>>Perdu</option>
                                    </select>
                                    <button type="submit" name="force_status" class="btn btn-warning btn-sm">OK</button>
                                </div>
                            </form>
                            <!-- Masquer -->
                            <form method="POST" class="mb-2">
                                <input type="hidden" name="bet_id" value="<?= $b['id'] ?>">
                                <input type="hidden" name="hidden_val" value="<?= ($b['hidden']??0)?0:1 ?>">
                                <button type="submit" name="hide_bet" class="btn btn-outline-secondary btn-sm w-100">
                                    <?= ($b['hidden']??0) ? '️ Rendre visible' : ' Masquer' ?>
                                </button>
                            </form>
                            <!-- Supprimer -->
                            <form method="POST">
                                <input type="hidden" name="bet_id" value="<?= $b['id'] ?>">
                                <button type="submit" name="delete_bet" class="btn btn-danger btn-sm w-100"
                                        onclick="return confirm('Supprimer ce gage définitivement ?')">X️ Supprimer</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include 'footer.php'; ?>
