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

$user   = getConnectedUser($pdo);
$userId = (int)$user['id'];
$betId  = (int)($_GET['id'] ?? 0);

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

// Charger le gage
$stmt = $pdo->prepare("SELECT b.*, u.username as owner_name, c.oracle_id, c.creator_id, c.name as circle_name
    FROM bets b
    JOIN users u ON u.id = b.user_id
    LEFT JOIN circles c ON c.id = b.circle_id
    WHERE b.id = ?");
$stmt->execute([$betId]);
$bet = $stmt->fetch();

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

// Vérifier que l'user est bien le perdant
$isGageur2 = (int)($bet['parieur2_id'] ?? 0) === $userId;
$isOwner   = (int)$bet['user_id'] === $userId;
$isLoser   = ($bet['status'] === 'won' && $isGageur2)
          || ($bet['status'] === 'lost' && $isOwner);

if (!$isLoser && !isAdmin($user)) {
    header("Location: index.php?error=not_authorized"); exit;
}

$msg = ''; $error = '';

// Traitement de la demande d'arbitrage
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_arbitrage'])) {
    $reason = trim(htmlspecialchars($_POST['reason'] ?? ''));
    if (strlen($reason) < 10) {
        $error = "Veuillez expliquer la situation (minimum 10 caractères).";
    } else {
        // Déterminer qui notifier: Oracle du cercle → sinon admin
        $notifyId = (int)($bet['oracle_id'] ?: $bet['creator_id'] ?: 0);
        // Si pas d'oracle, notifier tous les admins
        if (!$notifyId) {
            $adminStmt = $pdo->query("SELECT id FROM users WHERE admin=1 LIMIT 1");
            $adminRow  = $adminStmt->fetch();
            $notifyId  = $adminRow ? (int)$adminRow['id'] : 0;
        }

        // Sauvegarder la demande d'arbitrage
        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
            )");
            $pdo->prepare("INSERT INTO bet_arbitrages (bet_id, requester_id, reason) VALUES (?,?,?)")
                ->execute([$betId, $userId, $reason]);
        } catch(Exception $e) {}

        // Notifier l'Oracle/Admin
        if ($notifyId) {
            $uname = htmlspecialchars($user['username'] ?? 'Un membre');
            $desc  = mb_substr($bet['description'], 0, 50);
            addNotification($pdo, $notifyId,
                "⚖️ Demande d'arbitrage de $uname sur le gage \"$desc\"",
                "admin_arbitrages.php"
            );
        }

        $msg = "✅ Demande d'arbitrage envoyée à " . ($bet['oracle_id'] ? "l'Oracle du cercle" : "l'Admin") . ".";
    }
}

include 'header.php';
?>
<div class="container mt-4 mb-5" style="max-width:640px;">
    <div class="card bg-dark border-warning shadow">
        <div class="card-header py-2 fw-bold" style="background:#1a1200;color:#ffc107;letter-spacing:1px;">
            <i class="fa-solid fa-scale-balanced me-2"></i>DEMANDE D'ARBITRAGE
        </div>
        <div class="card-body">

            <?php if ($msg): ?>
            <div class="alert alert-success"><?= $msg ?></div>
            <a href="index.php" class="btn btn-outline-secondary">← Retour</a>
            <?php else: ?>

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

            <!-- Info gage -->
            <div class="p-3 mb-3 rounded" style="background:#0a0a14;border:1px solid #333;">
                <div class="text-muted" style="font-size:0.65rem;">GAGE #<?= $betId ?></div>
                <div class="fw-bold text-white"><?= htmlspecialchars($bet['description']) ?></div>
                <div class="mt-1" style="font-size:0.7rem;color:#aaa;">
                    Lancé par <span class="text-info"><?= htmlspecialchars($bet['owner_name']) ?></span>
                    <?php if ($bet['circle_name']): ?>
                    · Cercle <span class="text-info"><?= htmlspecialchars($bet['circle_name']) ?></span>
                    <?php endif; ?>
                </div>
                <div class="mt-1">
                    <span class="badge bg-danger" style="font-size:0.6rem;">❌ Non-honoré</span>
                </div>
            </div>

            <div class="alert py-2 mb-3" style="background:rgba(255,193,7,0.08);border:1px solid #ffc107;font-size:0.72rem;color:#ffc107;">
                <i class="fa-solid fa-circle-info me-1"></i>
                L'arbitrage sera envoyé à <?= $bet['oracle_id'] ? "l'Oracle du cercle <strong>".htmlspecialchars($bet['circle_name'])."</strong>" : "l'Administrateur" ?>.
                Expliquez pourquoi vous contestez le verdict.
            </div>

            <form method="POST">
                <div class="mb-3">
                    <label class="small text-muted d-block mb-1" style="font-size:0.65rem;">VOTRE EXPLICATION</label>
                    <textarea name="reason" rows="5"
                        class="form-control bg-dark text-white border-secondary"
                        placeholder="Ex: J'ai bien rempli ma part du gage car... La preuve est disponible dans les médias du gage..."
                        required style="font-size:0.8rem;"><?= htmlspecialchars($_POST['reason'] ?? '') ?></textarea>
                </div>
                <div class="d-flex gap-2">
                    <button type="submit" name="submit_arbitrage" class="btn btn-warning fw-bold">
                        <i class="fa-solid fa-scale-balanced me-1"></i>Envoyer la demande
                    </button>
                    <a href="index.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
