<?php
session_start();
require_once 'config.php';
require_once 'functions.php';
requireLogin();
$user = getConnectedUser($pdo);
if (!isAdmin($user)) { header("Location: index.php"); exit; }

$msg = '';

// Créer table
try { $pdo->exec("CREATE TABLE IF NOT EXISTS bet_arbitrages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    bet_id INT NOT NULL,
    requester_id INT NOT NULL,
    reason TEXT NOT NULL,
    status ENUM('pending','resolved','dismissed') DEFAULT 'pending',
    resolution TEXT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    resolved_at TIMESTAMP NULL
)"); } catch(Exception $e) {}

// Résoudre un arbitrage
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['resolve'])) {
    $aid       = (int)$_POST['arb_id'];
    $resolution = trim(htmlspecialchars($_POST['resolution'] ?? ''));
    $status    = $_POST['arb_status'] ?? 'resolved';
    if ($aid && $resolution) {
        $pdo->prepare("UPDATE bet_arbitrages SET status=?,resolution=?,resolved_at=NOW() WHERE id=?")
            ->execute([$status, $resolution, $aid]);
        // Notifier le demandeur
        $arb = $pdo->prepare("SELECT ba.*, u.username FROM bet_arbitrages ba JOIN users u ON u.id=ba.requester_id WHERE ba.id=?");
        $arb->execute([$aid]); $arbRow = $arb->fetch();
        if ($arbRow) {
            $verdict = $status === 'resolved' ? 'acceptée' : 'rejetée';
            addNotification($pdo, $arbRow['requester_id'],
                "⚖️ Votre demande d'arbitrage sur le gage #{$arbRow['bet_id']} a été $verdict. Résolution: $resolution",
                "index.php"
            );
        }
        $msg = "Arbitrage traité.";
    }
}

// Charger les demandes
$arbs = $pdo->query("
    SELECT ba.*, u.username as requester, b.description as bet_desc, b.status as bet_status
    FROM bet_arbitrages ba
    JOIN users u ON u.id = ba.requester_id
    JOIN bets b ON b.id = ba.bet_id
    ORDER BY ba.status='pending' DESC, ba.created_at DESC
    LIMIT 50
")->fetchAll();

include 'header.php';
?>
<div class="container-fluid mt-3 mb-5" style="max-width:900px;">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="admin.php" class="btn btn-outline-secondary btn-sm">← Admin</a>
        <h4 class="text-warning mb-0" style="letter-spacing:2px;"><i class="fa-solid fa-scale-balanced me-2"></i>ARBITRAGES</h4>
        <span class="badge bg-warning text-dark"><?= count(array_filter($arbs, fn($a)=>$a['status']==='pending')) ?> en attente</span>
    </div>
    <?php if ($msg): ?><div class="alert alert-success py-2 small"><?= $msg ?></div><?php endif; ?>

    <?php foreach ($arbs as $a): ?>
    <div class="card bg-dark mb-3" style="border-color:<?= $a['status']==='pending'?'#ffc107':'#333' ?>;">
        <div class="card-body p-3">
            <div class="d-flex justify-content-between align-items-start mb-2">
                <div>
                    <span class="fw-bold text-info"><?= htmlspecialchars($a['requester']) ?></span>
                    <span class="text-muted ms-2" style="font-size:0.65rem;">Gage #<?= $a['bet_id'] ?></span>
                    <span class="badge ms-2 <?= $a['status']==='pending'?'bg-warning text-dark':($a['status']==='resolved'?'bg-success':'bg-secondary') ?>" style="font-size:0.55rem;">
                        <?= $a['status']==='pending'?'EN ATTENTE':($a['status']==='resolved'?'RÉSOLU':'REJETÉ') ?>
                    </span>
                </div>
                <span class="text-muted" style="font-size:0.6rem;"><?= date('d M Y H:i', strtotime($a['created_at'])) ?></span>
            </div>
            <div class="small text-muted mb-2" style="font-size:0.68rem;">
                <strong class="text-white">Gage:</strong> <?= htmlspecialchars(mb_substr($a['bet_desc'],0,80)) ?>
            </div>
            <div class="p-2 rounded mb-2" style="background:#0a0a14;border:1px solid #222;font-size:0.72rem;color:#ddd;">
                <strong style="font-size:0.6rem;color:#888;">MOTIF:</strong><br><?= nl2br(htmlspecialchars($a['reason'])) ?>
            </div>
            <?php if ($a['status'] !== 'pending'): ?>
            <div class="p-2 rounded" style="background:#0d1a0d;border:1px solid #28a745;font-size:0.72rem;color:#aaa;">
                <strong style="font-size:0.6rem;color:#888;">RÉSOLUTION:</strong><br><?= nl2br(htmlspecialchars($a['resolution'] ?? '')) ?>
            </div>
            <?php else: ?>
            <form method="POST" class="mt-2">
                <input type="hidden" name="arb_id" value="<?= $a['id'] ?>">
                <textarea name="resolution" rows="2" placeholder="Votre décision..." required
                    class="form-control form-control-sm bg-dark text-white border-secondary mb-2" style="font-size:0.72rem;"></textarea>
                <div class="d-flex gap-2">
                    <select name="arb_status" class="form-select form-select-sm bg-dark text-white border-secondary" style="max-width:150px;font-size:0.65rem;">
                        <option value="resolved">✓ Accepter l'arbitrage</option>
                        <option value="dismissed">✕ Rejeter l'arbitrage</option>
                    </select>
                    <button type="submit" name="resolve" class="btn btn-warning btn-sm fw-bold" style="font-size:0.65rem;">
                        Rendre le verdict
                    </button>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    <?php if (empty($arbs)): ?>
    <div class="text-center text-muted py-5">Aucune demande d'arbitrage.</div>
    <?php endif; ?>
</div>
<?php include 'footer.php'; ?>
