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

requireLogin();
$user = getConnectedUser($pdo);
if (!$user) { header("Location: index.php"); exit; }
$userId      = (int)$user['id'];
$circleId    = (int)($_SESSION['circle_id'] ?? 1);
$isAdminUser = isAdmin($user);
$isOracleU   = isOracle($user, $circleId, $pdo);

if (!$isAdminUser && !$isOracleU) { header("Location: index.php"); exit; }

$msg = '';

// --- ACTION : Nommer un nouvel Oracle ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['set_new_oracle'])) {
    $newOracleId = (int)$_POST['new_oracle_id'];
    $targetCircle = (int)($_POST['circle_id_oracle'] ?? $circleId);
    // Seulement le créateur ou admin peut nommer
    $ci2 = $pdo->prepare("SELECT creator_id FROM circles WHERE id=?");
    $ci2->execute([$targetCircle]);
    $ci2Row = $ci2->fetch();
    if ($newOracleId && ($isAdminUser || (int)($ci2Row['creator_id']??-1) === $userId)) {
        $pdo->prepare("UPDATE circles SET oracle_id=? WHERE id=?")->execute([$newOracleId, $targetCircle]);
        $oracleName2 = $pdo->prepare("SELECT username FROM users WHERE id=?");
        $oracleName2->execute([$newOracleId]);
        $newName = $oracleName2->fetchColumn();
        addNotification($pdo, $newOracleId, "Tu es maintenant l'Oracle du cercle !", "oracle_judge.php");
        $msg = htmlspecialchars($newName) . " est le nouvel Oracle !";
    }
}

// --- ACTION : Forcer un résultat ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_judge'])) {
    $betId     = (int)$_POST['bet_id'];
    $newStatus = $_POST['new_status'] ?? '';

    if ($betId && in_array($newStatus, ['won','lost','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'], "⚖️ L'Oracle a décidé : ton gage #{$betId} est GAGNÉ !", "index.php");
                notifyUser(
                    $pdo->query("SELECT email FROM users WHERE id={$prevBet['user_id']}")->fetchColumn(),
                    "L'Oracle a tranché — Gage #{$betId}",
                    "Bonjour, l'Oracle a décidé : ton gage #{$betId} est <strong>GAGNÉ</strong> !"
                );
            } 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'], "⚖️ L'Oracle a décidé : ton gage #{$betId} est PERDU.", "index.php");
            }
        }
        $msg = "Gage #{$betId} mis à jour → " . strtoupper($newStatus);
    }
}

// --- ACTION : Marquer "Pas honoré" ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_dishonor'])) {
    $betId  = (int)$_POST['bet_id'];
    $target = (int)$_POST['target_user_id'];
    try {
        if (!(bool)$pdo->query("SHOW COLUMNS FROM bets LIKE 'honored'")->fetch())
            $pdo->exec("ALTER TABLE bets ADD COLUMN honored TINYINT(1) DEFAULT 0");
        if (!(bool)$pdo->query("SHOW COLUMNS FROM user_stats LIKE 'refused_bets'")->fetch())
            $pdo->exec("ALTER TABLE user_stats ADD COLUMN refused_bets INT(11) DEFAULT 0");
        $pdo->prepare("UPDATE bets SET honored = -1 WHERE id = ?")->execute([$betId]);
        $pdo->prepare("UPDATE user_stats SET refused_bets = refused_bets + 1 WHERE user_id = ?")->execute([$target]);
        addNotification($pdo, $target, "L'Oracle t'a marque comme n'ayant pas honore le gage #{$betId}.", "index.php");
        $msg = "Gage #{$betId} — perdant marque non-honorable.";
    } catch (Exception $e) { $msg = "Erreur: " . $e->getMessage(); }
}

// Charger les gages en attente du cercle
$stmt = $pdo->prepare("
    SELECT b.*, u.username,
           (SELECT COUNT(*) FROM bet_votes bv WHERE bv.bet_id = b.id AND bv.vote IN ('1','oui')) as vote_oui,
           (SELECT COUNT(*) FROM bet_votes bv WHERE bv.bet_id = b.id AND bv.vote IN ('0','non')) as vote_non
    FROM bets b
    JOIN users u ON u.id = b.user_id
    WHERE b.circle_id = ? AND b.status = 'pending'
    ORDER BY b.id DESC
");
$stmt->execute([$circleId]);
$pending = $stmt->fetchAll();

// Gages terminés — pour marquer pas honoré
try {
    $doneStmt = $pdo->prepare("
        SELECT b.*, u.username as owner_name, u2.username as parieur2_name
        FROM bets b
        JOIN users u ON u.id = b.user_id
        LEFT JOIN users u2 ON u2.id = b.parieur2_id
        WHERE b.circle_id = ? AND b.status IN ('won','lost')
          AND (b.honored IS NULL OR b.honored = 0)
        ORDER BY b.id DESC LIMIT 20
    ");
    $doneStmt->execute([$circleId]);
    $finishedBets = $doneStmt->fetchAll();
} catch (Exception $e) { $finishedBets = []; }

// Classement honorabilité
try {
    $honorRank = $pdo->query("
        SELECT u.id, u.username,
               COALESCE(us.total_bets,0) as total,
               (COALESCE(us.refused,0) + (
                   SELECT COUNT(*) FROM bets bnh
                   WHERE bnh.not_honored = 1
                   AND (bnh.user_id = u.id OR bnh.parieur2_id = u.id)
                   AND COALESCE(bnh.not_honored_by,0) != u.id
               )) as refused,
               CASE WHEN COALESCE(us.total_bets,0) > 0
                    THEN GREATEST(0, ROUND((1 - (
                        COALESCE(us.refused,0) + (
                            SELECT COUNT(*) FROM bets bnh2
                            WHERE bnh2.not_honored = 1
                            AND (bnh2.user_id = u.id OR bnh2.parieur2_id = u.id)
                            AND COALESCE(bnh2.not_honored_by,0) != u.id
                        )
                    ) / GREATEST(COALESCE(us.total_bets,1),1)) * 100))
                    ELSE 100 END as honor_pct
        FROM users u
        LEFT JOIN user_stats us ON us.user_id = u.id
        ORDER BY honor_pct DESC, total DESC
        LIMIT 10
    ")->fetchAll();
} catch (Exception $e) { $honorRank = []; }

include 'header.php';
?>

<div class="container mt-4">
    <a href="index.php" class="btn btn-outline-secondary btn-sm mb-3">&larr; Dashboard</a>
    <h5 class="oracle-text text-warning mb-1">ARBITRAGE — L'ORACLE</h5>
    <p class="text-muted small mb-3">Gages en attente de décision dans le cercle.</p>

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

    <div class="row g-3">
    <div class="col-md-8">

    <!-- GAGES EN ATTENTE -->
    <?php if (empty($pending)): ?>
        <div class="alert alert-secondary small">Aucun gage en attente. L'Oracle se repose.</div>
    <?php else: ?>
    <div class="table-responsive mb-3">
        <table class="table table-dark table-hover small border-secondary">
            <thead>
                <tr class="border-secondary">
                    <th>#</th><th>Gageur</th><th>Description</th>
                    <th class="text-center">Pts</th><th class="text-center">Votes</th>
                    <th class="text-center">Decision</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($pending as $bet): ?>
                <tr>
                    <td class="text-muted"><?= $bet['id'] ?></td>
                    <td><?= htmlspecialchars($bet['username']) ?></td>
                    <td><?= htmlspecialchars(mb_substr($bet['description'],0,60)) ?><?= strlen($bet['description'])>60?'…':'' ?></td>
                    <td class="text-center text-success"><?= number_format((float)$bet['amount'],0) ?></td>
                    <td class="text-center">
                        <span class="text-success"><?= $bet['vote_oui'] ?> O</span> /
                        <span class="text-danger"><?= $bet['vote_non'] ?> N</span>
                    </td>
                    <td class="text-center">
                        <div class="d-flex gap-1 justify-content-center">
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="bet_id" value="<?= $bet['id'] ?>">
                                <input type="hidden" name="new_status" value="won">
                                <button type="submit" name="action_judge" class="btn btn-xs btn-success py-0 px-2">WIN</button>
                            </form>
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="bet_id" value="<?= $bet['id'] ?>">
                                <input type="hidden" name="new_status" value="lost">
                                <button type="submit" name="action_judge" class="btn btn-xs btn-danger py-0 px-2">LOST</button>
                            </form>
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="bet_id" value="<?= $bet['id'] ?>">
                                <input type="hidden" name="new_status" value="pending">
                                <button type="submit" name="action_judge" class="btn btn-xs btn-secondary py-0 px-2">EN COURS</button>
                            </form>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>

    <!-- GAGES TERMINES — Marquer pas honoré -->
    <?php if (!empty($finishedBets)): ?>
    <div class="card bg-dark border-danger shadow mb-3">
        <div class="card-header py-2 text-danger fw-bold small">Marquer "Pas honore" — perdant n'a pas tenu parole</div>
        <div class="table-responsive">
            <table class="table table-dark table-sm small mb-0">
                <thead><tr><th>#</th><th>Gage</th><th>Statut</th><th>Perdant</th><th></th></tr></thead>
                <tbody>
                <?php foreach ($finishedBets as $fb):
                    // Le perdant = user_id si lost, parieur2_id si won
                    $loser = $fb['status'] === 'lost'
                        ? ['id'=>$fb['user_id'],    'name'=>$fb['owner_name']]
                        : ['id'=>$fb['parieur2_id'], 'name'=>$fb['parieur2_name']];
                    if (!$loser['id']) continue;
                ?>
                <tr>
                    <td class="text-muted"><?= $fb['id'] ?></td>
                    <td><?= htmlspecialchars(mb_substr($fb['description'],0,40)) ?>...</td>
                    <td><span class="badge <?= $fb['status']==='won'?'bg-success':'bg-danger' ?>"><?= strtoupper($fb['status']) ?></span></td>
                    <td class="text-warning"><?= htmlspecialchars($loser['name'] ?? '?') ?></td>
                    <td>
                        <form method="POST" class="d-inline">
                            <input type="hidden" name="bet_id" value="<?= $fb['id'] ?>">
                            <input type="hidden" name="target_user_id" value="<?= $loser['id'] ?>">
                            <button type="submit" name="action_dishonor"
                                    class="btn btn-xs btn-outline-danger py-0"
                                    onclick="return confirm('Marquer <?= htmlspecialchars(addslashes($loser['name']??'')) ?> comme non-honorable ?')">
                                Pas honore
                            </button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    </div><!-- col-md-8 -->

    <!-- CLASSEMENT HONORABILITE + VOTE ORACLE -->
    <div class="col-md-4">
        <div class="card bg-dark border-warning shadow mb-3">
            <div class="card-header py-2 text-warning fw-bold small">% Honorabilite</div>
            <table class="table table-dark table-sm small mb-0">
                <thead><tr><th>#</th><th>Membre</th><th class="text-center">%</th></tr></thead>
                <tbody>
                <?php foreach ($honorRank as $i => $hr): ?>
                <tr>
                    <td class="text-muted"><?= $i+1 ?></td>
                    <td><?= htmlspecialchars($hr['username']) ?>
                        <small class="text-muted">(<?= $hr['refused'] ?>/<?= $hr['total'] ?>)</small>
                    </td>
                    <td class="text-center">
                        <span class="badge <?= $hr['honor_pct']>=90?'bg-success':($hr['honor_pct']>=70?'bg-warning text-dark':'bg-danger') ?>">
                            <?= $hr['honor_pct'] ?>%
                        </span>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($honorRank)): ?>
                    <tr><td colspan="3" class="text-center text-muted py-2">Aucune donnee</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php
        // Infos du cercle
        $circleInfo = $pdo->prepare("SELECT creator_id, oracle_id, name FROM circles WHERE id=?");
        $circleInfo->execute([$circleId]);
        $ci = $circleInfo->fetch();
        $isCreator = $ci && (int)$ci['creator_id'] === $userId;

        // S'assurer que le créateur est Oracle #1
        if ($isCreator && $ci && (int)$ci['oracle_id'] !== $userId) {
            $pdo->prepare("UPDATE circles SET oracle_id=? WHERE id=?")->execute([$userId, $circleId]);
            $ci['oracle_id'] = $userId;
        }

        // Membres pour vote Oracle (sauf le créateur)
        $membersVote = $pdo->prepare("
            SELECT u.id, u.username FROM users u
            JOIN circle_members cm ON cm.circle_id=? AND cm.user_id=u.id
            WHERE u.id != ? ORDER BY u.username ASC
        ");
        $membersVote->execute([$circleId, $ci['creator_id'] ?? 0]);
        $mvList = $membersVote->fetchAll();

        // Oracle actuel
        $oracleInfo = $pdo->prepare("SELECT username FROM users WHERE id=?");
        $oracleInfo->execute([$ci['oracle_id'] ?? 0]);
        $oracleName = $oracleInfo->fetchColumn() ?: '—';
        ?>

        <?php if ($isAdminUser || $isCreator): ?>
        <div class="card bg-dark border-info shadow">
            <div class="card-header py-2 text-info fw-bold small">Oracle du cercle</div>
            <div class="card-body py-2">
                <div class="text-white small mb-2">
                    Oracle actuel : <span class="text-warning fw-bold"><?= htmlspecialchars($oracleName) ?></span>
                    <?php if ((int)($ci['oracle_id']??0) === (int)($ci['creator_id']??0)): ?>
                    <span class="badge bg-warning text-dark ms-1" style="font-size:0.55rem;">Proprietaire</span>
                    <?php endif; ?>
                </div>
                <hr class="border-secondary my-2">
                <div class="text-white small mb-2">Nommer un nouvel Oracle :</div>
                <form method="POST">
                    <input type="hidden" name="circle_id_oracle" value="<?= $circleId ?>">
                    <select name="new_oracle_id" class="form-select form-select-sm bg-dark text-white border-secondary mb-2">
                        <option value="">-- Choisir --</option>
                        <?php foreach ($mvList as $mv): ?>
                        <option value="<?= $mv['id'] ?>"><?= htmlspecialchars($mv['username']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" name="set_new_oracle" class="btn btn-info btn-sm fw-bold w-100">Nommer Oracle</button>
                </form>
            </div>
        </div>
        <?php endif; ?>

    </div>

    </div><!-- row -->
</div>

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