<?php
session_start();
require_once 'config.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || !isset($_POST['period'])) {
    echo json_encode(["success" => false]); exit;
}

$userId = $_SESSION['user_id'];
$period = $_POST['period'];

try {
    global $pdo;
    $pdo->beginTransaction();

    $stmt = $pdo->prepare("SELECT * FROM bets WHERE user_id = ? AND period = ? AND status = 'pending'");
    $stmt->execute([$userId, $period]);
    $bets = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (count($bets) == 0) {
        $pdo->commit();
        echo json_encode(["success" => true, "played" => false]);
        exit;
    }

    $winNumber = rand(0, 9);
    $winSize = ($winNumber >= 5) ? 'Big' : 'Small';
    $winColors = [];
    if ($winNumber == 0) $winColors = ['Red', 'Violet'];
    elseif ($winNumber == 5) $winColors = ['Green', 'Violet'];
    elseif ($winNumber % 2 == 0) $winColors = ['Red'];
    else $winColors = ['Green'];

    $totalWinAmount = 0;
    $totalBetAmount = 0; // Loss amount nikalne ke liye
    $isWin = false;

    foreach ($bets as $bet) {
        $betWin = 0;
        $sel = $bet['selection'];
        $amt = $bet['amount'];
        $totalBetAmount += $amt; // Total kitna lagaya gaya

        if (is_numeric($sel) && $sel == $winNumber) {
            $betWin = $amt * 9; 
        } elseif (in_array($sel, $winColors)) {
            if (($sel == 'Red' && $winNumber == 0) || ($sel == 'Green' && $winNumber == 5)) {
                $betWin = $amt * 1.5; 
            } else {
                $betWin = $amt * 2; 
            }
        } elseif ($sel == $winSize) {
            $betWin = $amt * 2; 
        }

        if ($betWin > 0) {
            $isWin = true;
            $totalWinAmount += $betWin;
            $pdo->prepare("UPDATE bets SET status = 'win', win_amount = ? WHERE id = ?")->execute([$betWin, $bet['id']]);
        } else {
            $pdo->prepare("UPDATE bets SET status = 'lose' WHERE id = ?")->execute([$bet['id']]);
        }
    }

    if ($totalWinAmount > 0) {
        $pdo->prepare("UPDATE wallets SET main_balance = main_balance + ? WHERE user_id = ?")->execute([$totalWinAmount, $userId]);
    }
    
    $newBal = $pdo->query("SELECT main_balance FROM wallets WHERE user_id = $userId")->fetchColumn();

    $pdo->commit();

    echo json_encode([
        "success" => true,
        "played" => true,
        "isWin" => $isWin,
        "winAmount" => $totalWinAmount,
        "totalBet" => $totalBetAmount, // Ye important hai Loss show karne ke liye
        "winNumber" => $winNumber,
        "winSize" => $winSize,
        "new_balance" => $newBal
    ]);

} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
?>