<?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'];
$msg = "";

// --- 1. CALCULATE AVAILABLE BONUS ---
$p_bonus_q = $conn->query("SELECT SUM(amount) as total FROM personal_bonuses WHERE user_id=$uid AND status='pending'");
$p_bonus = $p_bonus_q->fetch_assoc()['total'] ?? 0;

$g_bonus_q = $conn->query("SELECT SUM(reward_amount) as total FROM global_bonuses WHERE is_active=1 AND id NOT IN (SELECT bonus_id FROM bonus_claims WHERE user_id=$uid)");
$g_bonus = $g_bonus_q->fetch_assoc()['total'] ?? 0;

$total_available = $p_bonus + $g_bonus;

// --- 2. HANDLE CLAIM ACTION ---
if (isset($_POST['claim_bonus']) && $total_available > 0) {
    $conn->begin_transaction();
    try {
        $conn->query("UPDATE users SET balance = balance + $total_available WHERE id=$uid");
        $conn->query("UPDATE personal_bonuses SET status='claimed' WHERE user_id=$uid AND status='pending'");
        
        $global_ids_q = $conn->query("SELECT id FROM global_bonuses WHERE is_active=1 AND id NOT IN (SELECT bonus_id FROM bonus_claims WHERE user_id=$uid)");
        if ($global_ids_q->num_rows > 0) {
            while ($row = $global_ids_q->fetch_assoc()) {
                $bid = $row['id'];
                $conn->query("INSERT INTO bonus_claims (user_id, bonus_id, claimed_at) VALUES ($uid, $bid, NOW())");
            }
        }

        $desc = "Real-time Bonus Claim";
        $conn->query("INSERT INTO transactions_fake (user_id, type, amount, method, status, created_at) VALUES ($uid, 'bonus', $total_available, '$desc', 'approved', NOW())");

        $conn->commit();
        $msg = "Bonus claimed successfully!";
        $total_available = 0; 
    } catch (Exception $e) {
        $conn->rollback();
        $msg = "Error claiming bonus.";
    }
}

// --- 3. FETCH STATS ---
$today_q = $conn->query("SELECT SUM(amount) as total FROM transactions_fake WHERE user_id=$uid AND type='bonus' AND DATE(created_at) = CURDATE()");
$claimed_today = $today_q->fetch_assoc()['total'] ?? 0;

$week_q = $conn->query("SELECT SUM(amount) as total FROM transactions_fake WHERE user_id=$uid AND type='bonus' AND YEARWEEK(created_at, 1) = YEARWEEK(CURDATE(), 1)");
$claimed_week = $week_q->fetch_assoc()['total'] ?? 0;

// --- 4. FETCH HISTORY ---
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'today';
$custom_date = isset($_GET['date']) ? $conn->real_escape_string($_GET['date']) : '';

$where_sql = "user_id=$uid AND type='bonus'";

if ($filter == 'today') {
    $where_sql .= " AND DATE(created_at) = CURDATE()";
} elseif ($filter == 'yesterday') {
    $where_sql .= " AND DATE(created_at) = CURDATE() - INTERVAL 1 DAY";
} elseif ($filter == 'week') {
    $where_sql .= " AND created_at >= CURDATE() - INTERVAL 7 DAY";
} elseif ($filter == 'custom' && !empty($custom_date)) {
    $where_sql .= " AND DATE(created_at) = '$custom_date'";
}

$history_q = $conn->query("SELECT * FROM transactions_fake WHERE $where_sql ORDER BY created_at DESC");

// Button Text Logic
$opt_btn_text = ($filter == 'custom' && !empty($custom_date)) ? $custom_date : 'Optional Date';
?>

<!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>Real-Time Bonus</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">
    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/themes/dark.css">

    <style>
        body { background-color: #121619; color: #d1d5db; font-family: 'Roboto', sans-serif; padding-bottom: 80px; }
        
        .header-bg { background-color: #232a31; padding: 15px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #2f3840; }
        
        .bonus-card {
            background: radial-gradient(circle at center, #233329 0%, #15191d 100%);
            position: relative; overflow: hidden; text-align: center; padding: 30px 20px; border-bottom: 1px solid #2f3840;
        }
        .star {
            position: absolute; background: white; border-radius: 50%; opacity: 0.5;
            animation: twinkle 2s infinite ease-in-out;
        }
        @keyframes twinkle { 0%, 100% { opacity: 0.3; transform: scale(0.8); } 50% { opacity: 1; transform: scale(1.2); } }
        .money-icon { width: 80px; margin: 0 auto 10px; filter: drop-shadow(0 0 10px rgba(255,255,255,0.2)); }
        
        .btn-gold {
            background: linear-gradient(to bottom, #eab308, #ca8a04);
            color: white; font-weight: bold; padding: 10px 40px; border-radius: 6px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3); border: 1px solid #facc15; transition: transform 0.1s;
        }
        .btn-gold:active { transform: scale(0.95); }

        .stats-bar { display: flex; background-color: #1c2227; padding: 15px 0; border-bottom: 1px solid #2f3840; }
        .stat-item { flex: 1; text-align: center; border-right: 1px solid #2f3840; }
        .stat-item:last-child { border: none; }
        .stat-label { font-size: 11px; color: #9ca3af; margin-bottom: 5px; }
        .stat-val { font-size: 16px; color: #fff; font-weight: 500; }

        .sec-title { border-left: 3px solid #eab308; padding-left: 8px; font-size: 14px; color: #d1d5db; margin: 20px 15px 10px; font-weight: 500; }
        
        /* Filter Styles */
        .filter-row { 
            display: flex; gap: 8px; padding: 0 15px; margin-bottom: 15px; 
            overflow-x: auto; /* Small screens support */
        }
        /* Scrollbar hide for cleaner look */
        .filter-row::-webkit-scrollbar { display: none; }
        
        .filter-btn {
            background-color: #232a31; color: #9ca3af; font-size: 11px;
            padding: 6px 12px; border-radius: 4px; border: 1px solid #374151;
            flex: 1; text-align: center; cursor: pointer; white-space: nowrap; min-width: fit-content;
        }
        .filter-btn.active { background-color: #eab308; color: #000; border-color: #eab308; font-weight: bold; }
        
        .history-item { background-color: #1c2227; padding: 12px 15px; border-bottom: 1px solid #2f3840; display: flex; justify-content: space-between; align-items: center; }
        
        .no-data { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 200px; opacity: 0.3; }
        .clipboard-icon { width: 50px; 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; }

        /* Flatpickr Calendar Fix */
        .flatpickr-calendar {
            z-index: 9999 !important;
            background: #1c2227 !important;
            border: 1px solid #374151 !important;
            box-shadow: 0 10px 25px rgba(0,0,0,0.5) !important;
        }
        .flatpickr-day.selected {
            background: #eab308 !important;
            border-color: #eab308 !important;
            color: black !important;
            font-weight: bold;
        }
    </style>
</head>
<body>

    <div class="header-bg">
        <a href="account.php" class="text-xl text-white"><i class="fas fa-home"></i></a>
        <h1 class="text-white font-medium text-base">Real-Time Bonus</h1>
        <a href="dashboard.php" class="text-xl text-white"><i class="fas fa-times"></i></a>
    </div>

    <div class="bonus-card">
        <div class="star" style="top: 20%; left: 20%; width: 3px; height: 3px;"></div>
        <div class="star" style="top: 30%; right: 25%; width: 2px; height: 2px; animation-delay: 0.5s;"></div>
        <div class="star" style="top: 70%; left: 10%; width: 4px; height: 4px; animation-delay: 1s;"></div>
        
        <div class="relative z-10">
            <p class="text-sm text-gray-300 mb-2 flex justify-center items-center gap-2">
                <i class="fas fa-sparkles text-yellow-400"></i> Available Amount
            </p>
            <img src="https://cdn-icons-png.flaticon.com/512/2489/2489756.png" class="money-icon">
            <h2 class="text-3xl font-bold text-white mb-6">৳<?php echo number_format($total_available, 0); ?></h2>
            
            <form method="POST">
                <?php if($total_available > 0): ?>
                    <button type="submit" name="claim_bonus" class="btn-gold w-48">Claim</button>
                <?php else: ?>
                    <a href="index.php" class="btn-gold w-48 inline-block pt-2">Play Games</a>
                <?php endif; ?>
            </form>
            
            <?php if($msg): ?>
                <p class="text-green-400 text-xs mt-3"><?php echo $msg; ?></p>
            <?php endif; ?>
        </div>
    </div>

    <div class="stats-bar">
        <div class="stat-item">
            <p class="stat-label">Claimed Today</p>
            <p class="stat-val">৳<?php echo number_format($claimed_today, 0); ?></p>
        </div>
        <div class="stat-item">
            <p class="stat-label">Claimed This Week</p>
            <p class="stat-val">৳<?php echo number_format($claimed_week, 0); ?></p>
        </div>
    </div>

    <div class="sec-title">Summary</div>
    
    <div class="filter-row">
        <a href="?filter=today" class="filter-btn <?php echo $filter == 'today' ? 'active' : ''; ?>">Today</a>
        <a href="?filter=yesterday" class="filter-btn <?php echo $filter == 'yesterday' ? 'active' : ''; ?>">Yesterday</a>
        <a href="?filter=week" class="filter-btn <?php echo $filter == 'week' ? 'active' : ''; ?>">Last 7 days</a>
        
        <button type="button" id="optionalDateBtn" class="filter-btn <?php echo $filter == 'custom' ? 'active' : ''; ?>">
            <?php echo $opt_btn_text; ?>
        </button>
    </div>

    <div class="min-h-[300px]">
        <?php if($history_q && $history_q->num_rows > 0): ?>
            <?php while($row = $history_q->fetch_assoc()): ?>
                <div class="history-item">
                    <div>
                        <p class="text-white text-sm font-bold">Real-Time Bonus</p>
                        <p class="text-[10px] text-gray-500"><?php echo date('Y-m-d H:i', strtotime($row['created_at'])); ?></p>
                    </div>
                    <div class="text-right">
                        <p class="text-[#eab308] font-mono font-bold">+ ৳<?php echo $row['amount']; ?></p>
                        <p class="text-[10px] text-green-500">Success</p>
                    </div>
                </div>
            <?php endwhile; ?>
        <?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</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 src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        flatpickr("#optionalDateBtn", {
            dateFormat: "Y-m-d",
            maxDate: "today",
            theme: "dark",
            disableMobile: true, 
            defaultDate: "<?php echo ($filter == 'custom' && !empty($custom_date)) ? $custom_date : ''; ?>",
            onChange: function(selectedDates, dateStr, instance) {
                // Redirect on select
                window.location.href = '?filter=custom&date=' + dateStr;
            }
        });
    });
    </script>

</body>
</html>