<?php
// =================== CONFIG ===================
include "../../conn.php";
include "../../functions2.php";

header('Content-Type: application/json; charset=utf-8');
header('Strict-Transport-Security: max-age=31536000');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header('Access-Control-Allow-Credentials: true');
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
header('Access-Control-Allow-Origin: ' . $origin);
header('vary: Origin');

date_default_timezone_set("Asia/Kolkata");
$now = date("Y-m-d H:i:s");

$response = [
  "code" => 1,
  "msg" => "Invalid Request",
  "msgCode" => 1,
  "data" => [],
  "serviceNowTime" => $now
];

$input = file_get_contents('php://input');
$payload = json_decode($input, true);

// =================== AUTH ===================
$auth = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!$auth || !str_starts_with($auth, 'Bearer ')) {
  $response['msg'] = 'Missing token';
  echo json_encode($response); exit;
}
$token = str_replace('Bearer ', '', $auth);

$is_jwt_valid = is_jwt_valid($token);
$data_auth = json_decode($is_jwt_valid, true);
if ($data_auth['status'] !== 'Success') {
  $response['msg'] = 'Invalid token';
  echo json_encode($response); exit;
}

$uid = $data_auth['payload']['id'];

// =================== BALANCE ===================
$balance = 0;
$sql = "SELECT motta FROM shonu_kaichila WHERE balakedara = ? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $uid);
$stmt->execute();
$res = $stmt->get_result();
if ($res->num_rows > 0) {
  $row = $res->fetch_assoc();
  $balance = $row['motta'];
}

// =================== GAME LIST ===================
$fileMap = [
    2 => '../../data/cq9.json',
    6 => '../../data/jdb.json',
    18 => '../../data/jili.json',
    17 => '../../data/evo.json',
    9 => '../../data/km.json',
    57 => '../../data/eg.json',
    101 => '../../data/idg.json',
    21 => '../../data/v8.json'
];

global $games;
$games = [];
foreach ($fileMap as $path) {
    if (file_exists($path)) {
        $json = file_get_contents($path);
        $parsed = json_decode($json, true);
        if (is_array($parsed)) {
            $games = array_merge($games, $parsed);
        }
    }
}

// =================== FINAL RESPONSE ===================
$response = [
    "code" => 0,
    "msg" => "Succeed",
    "msgCode" => 0,
    "serviceNowTime" => $now,
    "data" => [
        "uid" => $uid,
        "balance" => $balance,
        "games" => $games
    ]
];

echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
