<?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 {
    // ডাটাবেস ফাইল না পেলে স্ক্রিপ্ট বন্ধ হয়ে যাবে (নিরাপত্তার জন্য)
    die("Database connection file not found.");
}

// লগিন চেক
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$tab = isset($_GET['tab']) ? $_GET['tab'] : 'settled';

// ২. ডাটা ফেচিং লজিক (JOIN সহ - গেমের নাম দেখানোর জন্য)
$records = [];

// আমরা game_bet_history এর সাথে games টেবিল জয়েন করছি game_uid দিয়ে
// gbh = game_bet_history, g = games
if ($tab == 'settled') {
    $sql = "SELECT gbh.*, g.name AS game_name, g.provider_id AS provider_name
            FROM game_bet_history gbh
            LEFT JOIN games g ON gbh.game_uid = g.game_uid
            WHERE gbh.user_id = $user_id AND gbh.status != 'pending' 
            ORDER BY gbh.created_at DESC LIMIT 50";
} else {
    $sql = "SELECT gbh.*, g.name AS game_name, g.provider_id AS provider_name
            FROM game_bet_history gbh
            LEFT JOIN games g ON gbh.game_uid = g.game_uid
            WHERE gbh.user_id = $user_id AND gbh.status = 'pending' 
            ORDER BY gbh.created_at DESC";
}

$result = $conn->query($sql);

if ($result && $result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $records[] = $row;
    }
}
?>

<!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>Betting Records</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: 90px; }
        .header-bg { background-color: #232a31; padding: 15px; display: flex; justify-content: center; align-items: center; position: sticky; top: 0; z-index: 40; border-bottom: 1px solid #2f3840; }
        .close-btn { position: absolute; right: 15px; font-size: 18px; color: #9ca3af; }
        .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; }
        .tab-btn.active { color: #fff; border-bottom: 2px solid #fff; }
        .filter-bar { display: flex; justify-content: space-between; align-items: center; padding: 10px 15px; background-color: #1c2227; border-bottom: 1px solid #2f3840; position: relative; z-index: 30; }
        .date-btn { background-color: #2a343b; color: #b0b3b8; font-size: 12px; padding: 6px 12px; border-radius: 4px; border: 1px solid #374151; display: flex; align-items: center; gap: 5px; }
        .filter-icon { color: #b0b3b8; font-size: 16px; cursor: pointer; padding: 5px; }
        .dropdown-menu { display: none; position: absolute; top: 45px; left: 15px; background-color: #2a343b; border: 1px solid #374151; border-radius: 6px; width: 140px; box-shadow: 0 4px 15px rgba(0,0,0,0.5); z-index: 50; }
        .dropdown-menu.show { display: block; }
        .dropdown-item { display: block; padding: 10px 15px; color: #d1d5db; font-size: 12px; border-bottom: 1px solid #374151; cursor: pointer; }
        .dropdown-item:last-child { border-bottom: none; }
        .dropdown-item:hover { background-color: #374151; color: white; }
        .table-header { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; background-color: #2f3b43; padding: 8px 5px; font-size: 11px; color: #b0b3b8; text-align: center; border-bottom: 1px solid #374151; }
        .col-item { border-right: 1px solid #374151; }
        .col-item:last-child { border-right: none; }
        .data-row { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; padding: 12px 5px; font-size: 11px; text-align: center; border-bottom: 1px solid #232a31; align-items: center; }
        .profit-win { color: #10b981; }
        .profit-loss { color: #ef4444; }
        .no-data { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 300px; opacity: 0.4; }
        .clipboard-icon { width: 60px; margin-bottom: 10px; filter: invert(1); }
        .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">Betting Records</h1>
        <a href="account.php" class="close-btn"><i class="fas fa-times"></i></a>
    </div>

    <div class="tabs-container">
        <a href="?tab=settled" class="tab-btn <?php echo $tab == 'settled' ? 'active' : ''; ?>">Settled</a>
        <a href="?tab=unsettled" class="tab-btn <?php echo $tab == 'unsettled' ? 'active' : ''; ?>">Unsettled</a>
    </div>

    <div class="filter-bar relative">
        <button class="date-btn" onclick="toggleDropdown()">
            <span id="selectedDate">Last 7 days</span> 
            <i class="fas fa-caret-down ml-1"></i>
        </button>
        
        <div id="dateDropdown" class="dropdown-menu">
            <div class="dropdown-item" onclick="selectDate('Last 7 days')">Last 7 days</div>
            <div class="dropdown-item" onclick="selectDate('Last 1 month')">Last 1 month</div>
            <div class="dropdown-item" onclick="selectDate('All time')">All time</div>
        </div>

        <button class="filter-icon" onclick="openApiModal()">
            <i class="fas fa-filter"></i>
        </button>
    </div>

    <div class="table-header">
        <div class="col-item">Platform</div>
        <div class="col-item">Game Type</div>
        <div class="col-item"><?php echo $tab == 'settled' ? 'Turnover' : 'Game'; ?></div>
        <div class="col-item"><?php echo $tab == 'settled' ? 'Profit/Loss' : 'Bet'; ?></div>
    </div>

    <div class="min-h-[50vh]">
        <?php if (!empty($records)): ?>
            <?php foreach($records as $rec): 
                // ক্যালকুলেশন লজিক
                $bet = floatval($rec['bet_amount']);
                $win = floatval($rec['win_amount'] ?? 0);
                
                // Profit Calculation
                $profit = $win - $bet;
                
                // কালার লজিক
                $p_class = $profit >= 0 ? 'profit-win' : 'profit-loss';
                $p_sign = $profit >= 0 ? '+' : '';
                
                // নাম এবং প্রোভাইডার চেক (JOIN এর মাধ্যমে পাওয়া ডাটা)
                // যদি ডাটাবেস থেকে জয়েন না হয়, তাহলে 'Unknown' দেখাবে
                $provider = !empty($rec['provider_name']) ? $rec['provider_name'] : 'Unknown'; 
                $game_name = !empty($rec['game_name']) ? $rec['game_name'] : '-';
            ?>
            <div class="data-row">
                <div class="text-white font-bold truncate px-1"><?php echo htmlspecialchars($provider); ?></div>
                <div class="text-gray-400 truncate px-1" title="<?php echo htmlspecialchars($game_name); ?>"><?php echo htmlspecialchars($game_name); ?></div>
                
                <?php if($tab == 'settled'): ?>
                    <div class="text-white font-mono"><?php echo number_format($bet, 2); ?></div>
                    
                    <div class="<?php echo $p_class; ?> font-mono font-bold">
                        <?php echo $p_sign . number_format($profit, 2); ?>
                    </div>
                <?php else: ?>
                    <div class="text-white truncate px-1"><?php echo htmlspecialchars($game_name); ?></div>
                    <div class="text-yellow-500 font-mono"><?php echo number_format($bet, 2); ?></div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        
        <?php else: ?>
            <div class="no-data">
                <img src="https://cdn-icons-png.flaticon.com/512/7486/7486747.png" class="clipboard-icon">
                <p class="text-xs text-gray-500">No Data Found</p>
            </div>
        <?php endif; ?>
    </div>

    <div id="apiModal" class="fixed inset-0 z-[100] hidden bg-black/95 flex flex-col items-center justify-center p-4 backdrop-blur-sm">
        <div class="text-center w-full max-w-sm">
            <div class="mb-6 h-20 flex items-center justify-center">
                <div class="relative">
                    <i class="fas fa-wifi text-red-600 text-6xl opacity-50"></i>
                    <i class="fas fa-exclamation-circle text-white absolute -top-2 -right-2 bg-red-600 rounded-full p-1 text-sm"></i>
                </div>
            </div>
            <h3 class="text-red-500 text-lg font-bold mt-2 leading-relaxed tracking-wide">
                Filter Option Not Available
            </h3>
            <button onclick="document.getElementById('apiModal').classList.add('hidden')" class="mt-10 bg-gray-800 border border-gray-600 text-white px-8 py-2 rounded-full text-sm hover:bg-gray-700 transition">
                Close
            </button>
        </div>
    </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 toggleDropdown() {
            const dropdown = document.getElementById('dateDropdown');
            dropdown.classList.toggle('show');
        }

        function selectDate(text) {
            document.getElementById('selectedDate').innerText = text;
            document.getElementById('dateDropdown').classList.remove('show');
        }

        window.onclick = function(event) {
            if (!event.target.closest('.date-btn')) {
                var dropdowns = document.getElementsByClassName("dropdown-menu");
                for (var i = 0; i < dropdowns.length; i++) {
                    var openDropdown = dropdowns[i];
                    if (openDropdown.classList.contains('show')) {
                        openDropdown.classList.remove('show');
                    }
                }
            }
        }

        function openApiModal() {
            document.getElementById('apiModal').classList.remove('hidden');
        }
    </script>
</body>
</html>