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

// Check Login
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$userId = $_SESSION['user_id'];
global $pdo;

try {
    // 1. FETCH USER INFO
    $stmt = $pdo->prepare("SELECT username, vip_level FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    $username = $user['username'] ?: 'Member' . strtoupper(substr(md5($userId), 0, 8));
    $currentVip = (int)($user['vip_level'] ?? 1);

    // 2. FETCH TOTAL EXP (Total Bet Amount)
    // DHYAN DEIN: Agar aapke paas 'bets' table nahi hai, toh yeh error dega. 
    // Agar bet table ka naam kuch aur hai (jaise 'bet_history'), toh usko yahan change karein.
    $stmtExp = $pdo->prepare("SELECT SUM(amount) FROM bets WHERE user_id = ?");
    $stmtExp->execute([$userId]);
    $userExp = (float)$stmtExp->fetchColumn() ?: 0;

    // 3. FETCH VIP LEVELS FROM DB
    $lvlQ = $pdo->query("SELECT * FROM vip_levels ORDER BY level ASC");
    $vipLevels = $lvlQ->fetchAll(PDO::FETCH_ASSOC);

    // Fallback if table is empty
    if(empty($vipLevels)) {
        for($i=1; $i<=10; $i++) {
            $vipLevels[] = [
                'level' => $i, 
                'required_recharge' => ($i == 1) ? 0 : pow(10, $i+2), 
                'monthly_bonus' => $i * 10
            ];
        }
    }

    // 4. CALCULATE BONUSES & PROGRESS
    $monthlyBonus = 0;
    $levelUpBonus = 0;
    $nextLevelExp = 1000;
    $rebateRate = "0.05%"; // Default rebate rate

    $formattedLevels = [];
    foreach($vipLevels as $lvl) {
        $lNum = (int)$lvl['level'];
        $reqExp = (float)$lvl['required_recharge'];
        
        if ($lNum == $currentVip) {
            $monthlyBonus = (float)$lvl['monthly_bonus'];
            $levelUpBonus = (float)$lvl['level_up_bonus']; // Ab ye Admin Panel (DB) se aayega!
        }
        if ($lNum == $currentVip + 1) {
            $nextLevelExp = $reqExp;
        }

        $safeReqExp = ($reqExp > 0) ? $reqExp : 1; 
        $prog = ($userExp / $safeReqExp) * 100;
        if($reqExp == 0 || $prog > 100) { $prog = 100; }

        $formattedLevels[] = [
            'level' => $lNum,
            'required_exp' => $reqExp,
            'progress_percent' => round($prog, 2),
            'is_achieved' => ($userExp >= $reqExp)
        ];
    }

    // Safe Global Progress
    $safeNextExp = ($nextLevelExp > 0) ? $nextLevelExp : 1;
    $globalProgress = ($userExp / $safeNextExp) * 100;
    if($globalProgress > 100) { $globalProgress = 100; }

    // 5. FETCH VIP HISTORY
    $histStmt = $pdo->prepare("SELECT title, description, exp_change, type, created_at FROM vip_history WHERE user_id = ? ORDER BY created_at DESC LIMIT 20");
    $histStmt->execute([$userId]);
    $vipHistory = $histStmt->fetchAll(PDO::FETCH_ASSOC);

    // RETURN JSON RESPONSE
    echo json_encode([
        'success' => true,
        'user' => [
            'username' => $username,
            'vip_level' => $currentVip,
            'exp' => $userExp
        ],
        'benefits' => [
            'level_up_bonus' => $levelUpBonus,
            'monthly_bonus' => $monthlyBonus,
            'rebate_rate' => $rebateRate
        ],
        'progress' => [
            'next_level_exp' => $nextLevelExp,
            'percentage' => round($globalProgress, 2)
        ],
        'levels_data' => $formattedLevels,
        'history' => $vipHistory
    ]);

} catch (Exception $e) {
    // YAHAN MAINE ERROR MESSAGE KO PRINT KARWAA DIYA HAI
    echo json_encode(['success' => false, 'message' => 'SQL Error: ' . $e->getMessage()]);
}
?>