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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id'])) {
    echo json_encode(["code" => 401, "msg" => "Not Logged In", "isLoggedIn" => false, "data" => null]);
    exit;
}

try {
    global $pdo;
    $userId = $_SESSION['user_id'];
    
    // सीधा 'users' टेबल से सारा डेटा फेच कर रहे हैं 
    // (Kyuki aapki DB me balance users table me hi hai)
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        // Mobile number hide logic (Safe way)
        $mobile = !empty($user['mobile']) ? $user['mobile'] : '0000000000';
        $masked_mobile = strlen($mobile) >= 6 ? substr($mobile, 0, 2) . '****' . substr($mobile, -4) : '****';

        echo json_encode([
            "code" => 0, 
            "msg" => "Succeed", 
            "isLoggedIn" => true,
            "data" => [
                "username" => isset($user['username']) ? $user['username'] : 'Player',
                "mobile"   => $masked_mobile,
                "vipLevel" => isset($user['vip_level']) ? (int)$user['vip_level'] : 0,
                // Yahan seedha users table ka 'balance' fetch ho raha hai
                "balance"  => isset($user['balance']) ? (float)$user['balance'] : 0.00,
                "bonus"    => isset($user['bonus_balance']) ? (float)$user['bonus_balance'] : 0.00
            ]
        ]);
    } else {
        echo json_encode(["code" => 404, "msg" => "User Not Found", "isLoggedIn" => false]);
    }
} catch (Throwable $e) {
    echo json_encode(["code" => 500, "msg" => "Server Error", "data" => null]);
}
?>