<?php
session_start();
$db_path = file_exists('includes/db.php') ? 'includes/db.php' : '../includes/db.php';

if (file_exists($db_path)) {
    require $db_path;
} else {
    $conn = new mysqli('localhost', 'root', '', 'bajipari');
}

// Auth Check
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$uid = $_SESSION['user_id'];

// --- Fetch Real Data (from game_bet_history) ---

// 1. Active Turnover (Pending Bets)
$active_sql = "SELECT * FROM game_bet_history WHERE user_id=$uid AND status='pending' ORDER BY created_at DESC LIMIT 50";
$active_res = $conn->query($active_sql);

// 2. Completed Turnover (Settled Bets: Win/Loss)
$comp_sql = "SELECT * FROM game_bet_history WHERE user_id=$uid AND status!='pending' ORDER BY created_at DESC LIMIT 50";
$comp_res = $conn->query($comp_sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Turnover</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">

    <style>
        body { 
            background-color: #121619; 
            color: #d1d5db; 
            font-family: 'Roboto', sans-serif; 
            padding-bottom: 80px;
        }

        /* --- Header --- */
        .header-bg { 
            background-color: #232a31; 
            padding: 15px; 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            position: sticky; 
            top: 0; 
            z-index: 50; 
            border-bottom: 1px solid #2f3840; 
        }
        .close-btn { 
            position: absolute; 
            right: 15px; 
            font-size: 18px; 
            color: #9ca3af; 
        }

        /* --- Tabs --- */
        .tabs-container { 
            display: flex; 
            background-color: #232a31; 
            border-bottom: 1px solid #2f3840; 
        }
        .tab-btn { 
            flex: 1; 
            text-align: center; 
            padding: 12px 0; 
            font-size: 14px; 
            font-weight: 500; 
            color: #9ca3af; 
            cursor: pointer; 
            border-bottom: 2px solid transparent; 
            transition: all 0.3s; 
        }
        .tab-btn.active { 
            color: #fff; 
            font-weight: bold; 
            border-bottom: 2px solid #fff; 
        }

        /* --- Content Area --- */
        .tab-content { display: none; }
        .tab-content.active { display: block; }

        /* Empty State (Loader) */
        .loader-container { 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            height: 60vh; 
        }
        .spinner { 
            width: 40px; 
            height: 40px; 
            border: 4px solid #2f3840; 
            border-top: 4px solid #4b5563; 
            border-radius: 50%; 
            animation: spin 1s linear infinite; 
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

        /* Data Card */
        .data-card { 
            background-color: #1c2227; 
            padding: 15px; 
            border-bottom: 1px solid #2f3840; 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
        }
        .data-label { font-size: 12px; color: #9ca3af; }
        .data-val { font-size: 14px; color: #fff; font-weight: bold; }

        /* Bottom Nav */
        .bottom-nav { background-color: #000; border-top: 1px solid #222; }
        .nav-item { color: #6b7280; } .nav-item.active { color: #facc15; }
    </style>
</head>
<body>

    <div class="header-bg">
        <h1 class="text-white font-medium text-base">Turnover</h1>
        <a href="account.php" class="close-btn"><i class="fas fa-times"></i></a>
    </div>

    <div class="tabs-container sticky top-[57px] z-40">
        <div id="tab-active-btn" class="tab-btn active" onclick="switchTab('active', this)">Active</div>
        <div id="tab-completed-btn" class="tab-btn" onclick="switchTab('completed', this)">Completed</div>
    </div>

    <div id="active" class="tab-content active">
        <?php if($active_res && $active_res->num_rows > 0): ?>
            <?php while($row = $active_res->fetch_assoc()): 
                $gameName = !empty($row['game_name']) ? $row['game_name'] : 'Casino Game';
            ?>
                <div class="data-card">
                    <div>
                        <p class="data-val"><?php echo htmlspecialchars($gameName); ?></p>
                        <p class="data-label"><?php echo date('Y-m-d H:i', strtotime($row['created_at'])); ?></p>
                    </div>
                    <div class="text-right">
                        <p class="text-[#facc15] font-mono font-bold">৳ <?php echo number_format($row['bet_amount'], 2); ?></p>
                        <p class="text-xs text-yellow-600">Running</p>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="flex flex-col items-center justify-center py-20 opacity-50">
                <i class="fas fa-history text-4xl mb-2 text-gray-600"></i>
                <p class="text-xs text-gray-500">No active bets found.</p>
            </div>
        <?php endif; ?>
    </div>

    <div id="completed" class="tab-content">
        <?php if($comp_res && $comp_res->num_rows > 0): ?>
            <?php while($row = $comp_res->fetch_assoc()): 
                $bet = floatval($row['bet_amount']);
                $win = floatval($row['win_amount'] ?? 0);
                
                // Profit Calculation
                $profit = $win - $bet;
                $isWin = ($profit >= 0);
                
                $color = $isWin ? 'text-[#10b981]' : 'text-[#ef4444]';
                $sign = $isWin ? '+' : '';
                $statusTxt = ucfirst($row['status']);
                $gameName = !empty($row['game_name']) ? $row['game_name'] : 'Casino Game';
            ?>
                <div class="data-card">
                    <div>
                        <p class="data-val"><?php echo htmlspecialchars($gameName); ?></p>
                        <p class="data-label">Turnover: ৳ <?php echo number_format($bet, 2); ?></p>
                    </div>
                    <div class="text-right">
                        <p class="<?php echo $color; ?> font-mono font-bold">
                            <?php echo $sign . ' ৳ ' . number_format($profit, 2); ?>
                        </p>
                        <p class="text-xs text-gray-500"><?php echo $statusTxt; ?></p>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="flex flex-col items-center justify-center py-20 opacity-50">
                <i class="fas fa-clipboard-list text-4xl mb-2 text-gray-600"></i>
                <p class="text-xs text-gray-500">No history found.</p>
            </div>
        <?php endif; ?>
    </div>

    <div class="fixed bottom-0 left-0 w-full h-[60px] bottom-nav z-50 flex justify-between items-center px-6">
        <a href="index.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-home text-lg mb-1"></i>
            <span class="text-[10px]">Home</span>
        </a>
        <a href="promotions.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-gift text-lg mb-1"></i>
            <span class="text-[10px]">Promotions</span>
        </a>
        <a href="deposit.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-wallet text-lg mb-1"></i>
            <span class="text-[10px]">Deposit</span>
        </a>
        <a href="account.php" class="flex flex-col items-center justify-center nav-item active">
            <i class="fas fa-user text-lg mb-1"></i>
            <span class="text-[10px]">My Account</span>
        </a>
    </div>

    <script>
        function switchTab(tabId, btn) {
            // Hide Contents
            document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
            // Remove Active Class from Tabs
            document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
            
            // Show Target
            document.getElementById(tabId).classList.add('active');
            btn.classList.add('active');
        }
    </script>

</body>
</html>