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

$isAjax  = isset($_GET['ajax']);
$betId   = (int)($_GET['id'] ?? 0);
$vote    = $_GET['v'] ?? '';
$userId  = isset($_SESSION['user_id']) && $_SESSION['user_id'] > 0 ? (int)$_SESSION['user_id'] : null;
$ip      = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

// ----------------------------------------------------------------
// Fonction helper : retourner les stats de vote
// ----------------------------------------------------------------
function getVoteStats($pdo, $betId) {
    $s = $pdo->prepare("SELECT
        SUM(CASE WHEN vote IN ('1','oui') THEN 1 ELSE 0 END) as oui,
        SUM(CASE WHEN vote IN ('0','non') THEN 1 ELSE 0 END) as non,
        COUNT(*) as total
        FROM bet_votes WHERE bet_id = ?");
    $s->execute([$betId]);
    $v = $s->fetch();
    $oui   = (int)($v['oui']   ?? 0);
    $non   = (int)($v['non']   ?? 0);
    $total = (int)($v['total'] ?? 0);
    $p_oui = $total > 0 ? round($oui / $total * 100) : 0;
    $p_non = $total > 0 ? round($non / $total * 100) : 0;
    return ['p_oui' => $p_oui, 'p_non' => $p_non, 'total' => $total];
}

// ----------------------------------------------------------------
// Validation de base
// ----------------------------------------------------------------
if (!$betId || !in_array($vote, ['oui','non'])) {
    if ($isAjax) { echo json_encode(['error' => 'Paramètres invalides']); exit; }
    header("Location: index.php"); exit;
}

// Vérifier que le bet existe et est en cours
$stmtBet = $pdo->prepare("SELECT id, user_id, parieur2_id, status, echeance FROM bets WHERE id = ?");
$stmtBet->execute([$betId]);
$bet = $stmtBet->fetch();

if (!$bet || $bet['status'] !== 'pending') {
    if ($isAjax) {
        $stats = getVoteStats($pdo, $betId);
        echo json_encode(array_merge(['error' => 'Gage fermé'], $stats));
        exit;
    }
    header("Location: index.php"); exit;
}

// Vérifier si la date d'échéance est dépassée
if (!empty($bet['echeance']) && $bet['echeance'] !== '0000-00-00') {
    $echeance = strtotime($bet['echeance'] . ' 23:59:59');
    if ($echeance && time() > $echeance) {
        if ($isAjax) {
            $stats = getVoteStats($pdo, $betId);
            echo json_encode(array_merge(['error' => 'Votes terminés — date dépassée'], $stats));
            exit;
        }
        header("Location: index.php"); exit;
    }
}

// ----------------------------------------------------------------
// Vérifier si déjà voté (par user_id OU par IP pour les visiteurs)
// ----------------------------------------------------------------
$dejaVote = false;

if ($userId) {
    // Membre connecté : vérifier par user_id
    $chk = $pdo->prepare("SELECT id FROM bet_votes WHERE bet_id = ? AND voter_id = ?");
    $chk->execute([$betId, $userId]);
    if ($chk->fetch()) $dejaVote = true;
} else {
    // Visiteur : vérifier par IP
    $chk = $pdo->prepare("SELECT id FROM bet_votes WHERE bet_id = ? AND ip_address = ? AND voter_id IS NULL");
    $chk->execute([$betId, $ip]);
    if ($chk->fetch()) $dejaVote = true;
}

if ($dejaVote) {
    if ($isAjax) {
        $stats = getVoteStats($pdo, $betId);
        echo json_encode(array_merge(['error' => 'Déjà voté'], $stats));
        exit;
    }
    header("Location: index.php"); exit;
}

// ----------------------------------------------------------------
// Enregistrer le vote
// ----------------------------------------------------------------
$pdo->prepare("INSERT INTO bet_votes (bet_id, voter_id, vote, ip_address) VALUES (?, ?, ?, ?)")
    ->execute([$betId, $userId, $vote, $ip]);

// Points interaction si membre connecté
if ($userId) {
    addInteractionPoints($pdo, $userId, 'vote');
}

// ----------------------------------------------------------------
// Décision automatique si 3+ votes et majorité claire
// ----------------------------------------------------------------
$stats = getVoteStats($pdo, $betId);

if ($stats['total'] >= 3) {
    $sD = $pdo->prepare("SELECT
        SUM(CASE WHEN vote IN ('1','oui') THEN 1 ELSE 0 END) as oui,
        SUM(CASE WHEN vote IN ('0','non') THEN 1 ELSE 0 END) as non
        FROM bet_votes WHERE bet_id = ?");
    $sD->execute([$betId]);
    $vD = $sD->fetch();
    $vOui = (int)($vD['oui'] ?? 0);
    $vNon = (int)($vD['non'] ?? 0);

    if ($vOui > $vNon) {
        $pdo->prepare("UPDATE bets SET status='won' WHERE id=?")->execute([$betId]);
        $pdo->prepare("UPDATE users SET points=points+(SELECT amount FROM bets WHERE id=?) WHERE id=(SELECT user_id FROM bets WHERE id=?)")
            ->execute([$betId, $betId]);
        try {
            $pdo->prepare("UPDATE user_stats SET won_bets=won_bets+1, total_bets=total_bets+1 WHERE user_id=(SELECT user_id FROM bets WHERE id=?)")
                ->execute([$betId]);
        } catch (Exception $e) {}
        if ($userId) addNotification($pdo, (int)$bet['user_id'], " Ton gage #{$betId} est GAGNÉ !", "index.php");

    } elseif ($vNon > $vOui) {
        $pdo->prepare("UPDATE bets SET status='lost' WHERE id=?")->execute([$betId]);
        try {
            $pdo->prepare("UPDATE user_stats SET lost_bets=lost_bets+1, total_bets=total_bets+1 WHERE user_id=(SELECT user_id FROM bets WHERE id=?)")
                ->execute([$betId]);
        } catch (Exception $e) {}
        if ($userId) addNotification($pdo, (int)$bet['user_id'], "❌ Ton gage #{$betId} est PERDU.", "index.php");
    }

    // Recalculer les stats après la décision
    $stats = getVoteStats($pdo, $betId);
}

// ----------------------------------------------------------------
// Réponse
// ----------------------------------------------------------------
if ($isAjax) {
    header('Content-Type: application/json');
    echo json_encode($stats);
    exit;
}

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