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

requireLogin();
$userId = (int)$_SESSION['user_id'];
$betId  = (int)($_GET['id'] ?? 0);

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

// Charger le gage
$stmt = $pdo->prepare("SELECT * FROM bets WHERE id = ?");
$stmt->execute([$betId]);
$bet = $stmt->fetch();

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

$isOwner   = (int)$bet['user_id']     === $userId || (int)($bet['owner_id'] ?? 0) === $userId;
$isGageur2 = (int)($bet['parieur2_id'] ?? 0) === $userId;

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

// Vérifier que le vote est fermé
$echeance    = $bet['echeance'] ?? '';
$votesClosed = in_array($bet['status'], ['won','lost'])
    || (!empty($echeance) && $echeance !== '0000-00-00' && strtotime($echeance . ' 23:59:59') < time());

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

// Déjà signalé ?
if (!empty($bet['not_honored'])) { header("Location: index.php"); exit; }

// Ajouter colonne si absente
try {
    $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS not_honored TINYINT(1) DEFAULT 0");
    $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS not_honored_by INT(11) DEFAULT NULL");
    $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS not_honored_at TIMESTAMP NULL DEFAULT NULL");
} catch (Exception $e) {}

// Marquer non honoré
$pdo->prepare("UPDATE bets SET not_honored=1, not_honored_by=?, not_honored_at=NOW() WHERE id=?")
    ->execute([$userId, $betId]);

// Identifier le responsable (celui qui devait honorer = le perdant)
// Si status=won : le user_id a gagné → parieur2 devait honorer
// Si status=lost : user_id a perdu → user_id devait honorer
$loser = null;
if ($bet['status'] === 'won') {
    $loser = (int)($bet['parieur2_id'] ?? 0);
} elseif ($bet['status'] === 'lost') {
    $loser = (int)$bet['user_id'];
} else {
    // Vote pas encore tranché — on marque les 2
    $loser = $isOwner ? (int)($bet['parieur2_id'] ?? 0) : (int)$bet['user_id'];
}

// Mettre à jour user_stats pour le perdant
if ($loser > 0) {
    try {
        // Vérifier colonne refused dans user_stats
        $pdo->exec("CREATE TABLE IF NOT EXISTS user_stats (
            user_id      INT(11) NOT NULL PRIMARY KEY,
            won_bets     INT(11) DEFAULT 0,
            lost_bets    INT(11) DEFAULT 0,
            total_bets   INT(11) DEFAULT 0,
            refused      INT(11) DEFAULT 0
        )");
        $pdo->exec("ALTER TABLE user_stats ADD COLUMN IF NOT EXISTS refused INT(11) DEFAULT 0");

        // Incrémenter refused
        $pdo->prepare("INSERT INTO user_stats (user_id, refused, total_bets) VALUES (?,1,0)
                       ON DUPLICATE KEY UPDATE refused=refused+1")->execute([$loser]);

        // Notifier le perdant
        $reporter = $pdo->prepare("SELECT username FROM users WHERE id=?");
        $reporter->execute([$userId]);
        $reporterName = $reporter->fetchColumn();

        addNotification($pdo, $loser,
            "{$reporterName} a signale que le gage #{$betId} n a pas ete honore. Ton score de fiabilite est affecte.",
            "index.php");

        // Notifier l'oracle du cercle
        $circleId = (int)($bet['circle_id'] ?? 1);
        $oracleStmt = $pdo->prepare("SELECT oracle_id FROM circles WHERE id=?");
        $oracleStmt->execute([$circleId]);
        $oracleId = (int)$oracleStmt->fetchColumn();
        if ($oracleId && $oracleId !== $userId) {
            addNotification($pdo, $oracleId,
                "Litige sur le gage #{$betId} : non honore signale par {$reporterName}.",
                "oracle_judge.php");
        }
    } catch (Exception $e) {}
}

header("Location: index.php?msg=non_honore");
exit;
?>
