<?php
session_start();
ini_set('display_errors', 0);
error_reporting(0);
require_once 'config.php';
require_once 'functions.php';

requireLogin();
$user   = getConnectedUser($pdo);
if (!$user) { header("Location: index.php"); exit; }
$userId = (int)$user['id'];
$isAdm  = isAdmin($user);
$betId  = (int)($_GET['id']     ?? 0);
$action = $_GET['action'] ?? '';

if (!$betId || !in_array($action, ['accept','refuse'])) {
    header("Location: index.php"); exit;
}

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

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

// Gage global : n'importe qui peut accepter (devient parieur2)
$hasGlobal = (bool)$pdo->query("SHOW COLUMNS FROM bets LIKE 'is_global'")->fetch();
$isGlobalBet = $hasGlobal && (int)($bet['is_global'] ?? 0) === 1;

if ($isGlobalBet && empty($bet['parieur2_id']) && $action === 'accept') {
    // Devenir le parieur2
    $pdo->prepare("UPDATE bets SET parieur2_id = ?, acceptance_status = 'accepted' WHERE id = ?")
        ->execute([$userId, $betId]);
    addNotification($pdo, (int)$bet['user_id'],
        "{$user['username']} a accepte ton gage ouvert #{$betId} !", "index.php");
    header("Location: index.php"); exit;
}

// Admin peut forcer, sinon doit être parieur2
if (!$isAdm && (int)$bet['parieur2_id'] !== $userId) {
    header("Location: index.php"); exit;
}

// Vérifier colonnes optionnelles
$hasAcceptStatus = (bool)$pdo->query("SHOW COLUMNS FROM bets LIKE 'acceptance_status'")->fetch();
$hasUserStats    = true;
try { $pdo->query("SELECT 1 FROM user_stats LIMIT 1"); } catch (Exception $e) { $hasUserStats = false; }

if ($action === 'accept') {
    // Vérifier que le parieur2 a assez de jetons si mise requise
    $walletStakeReq = (int)($bet['wallet_stake'] ?? 0);
    if ($walletStakeReq > 0) {
        $myWallet = (int)$pdo->query("SELECT wallet_points FROM users WHERE id={$userId}")->fetchColumn();
        if ($myWallet < $walletStakeReq) {
            // Pas assez de jetons - rediriger vers boutique avec message
            $_SESSION['wallet_error'] = "Vous avez besoin de {$walletStakeReq} jetons pour accepter ce gage. Vous en avez {$myWallet}.";
            header("Location: wallet_shop.php?need={$walletStakeReq}&bet={$betId}");
            exit;
        }
        // Débiter les jetons du parieur2 aussi
        $pdo->prepare("UPDATE users SET wallet_points=GREATEST(0,wallet_points-?) WHERE id=?")->execute([$walletStakeReq, $userId]);
        try {
            $pdo->prepare("INSERT INTO wallet_transactions (user_id,amount,type,description,ref_id) VALUES (?,?,?,?,?)")
                ->execute([$userId, -$walletStakeReq, 'bet_stake', "Mise gage #{$betId}", $betId]);
        } catch (Exception $e) {}
    }
    if ($hasAcceptStatus) {
        $pdo->prepare("UPDATE bets SET acceptance_status='accepted' WHERE id=?")->execute([$betId]);
    }
    addNotification($pdo, (int)$bet['user_id'],
        "✅ {$user['username']} a accepté ton gage #{$betId} !", "index.php");
    if ($hasUserStats) {
        try { $pdo->prepare("UPDATE user_stats SET total_bets=total_bets+1 WHERE user_id=?")->execute([$userId]); } catch (Exception $e) {}
    }
} else {
    if ($hasAcceptStatus) {
        $pdo->prepare("UPDATE bets SET acceptance_status='refused' WHERE id=?")->execute([$betId]);
    }
    addNotification($pdo, (int)$bet['user_id'],
        "❌ {$user['username']} a refusé ton gage #{$betId}.", "index.php");
    if ($hasUserStats) {
        try { $pdo->prepare("UPDATE user_stats SET refused_bets=refused_bets+1 WHERE user_id=?")->execute([$userId]); } catch (Exception $e) {}
    }
    // Rembourser la mise en jetons au gageur1 si refus
    $walletStake = (int)($bet['wallet_stake'] ?? 0);
    if ($walletStake > 0) {
        try {
            $pdo->prepare("UPDATE users SET wallet_points=wallet_points+? WHERE id=?")
                ->execute([$walletStake, (int)$bet['user_id']]);
            $pdo->prepare("INSERT INTO wallet_transactions (user_id,amount,type,description,ref_id) VALUES (?,?,?,?,?)")
                ->execute([$bet['user_id'], $walletStake, 'bet_stake', "Remboursement mise gage #{$betId} (refusé)", $betId]);
            addNotification($pdo, (int)$bet['user_id'],
                "💰 Ta mise de {$walletStake} jetons sur le gage #{$betId} t'a été remboursée (gage refusé).", "wallet.php");
        } catch(Exception $e) {}
    }
}

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