<?php
include __DIR__ . "/deepanshu/conn.php";
include __DIR__ . "/deepanshu/functions2.php";
header('Content-Type: application/json; charset=utf-8');

$bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION'] ?? '');
$author = $bearer[1] ?? '';
$is_jwt_valid = is_jwt_valid($author);
$data_auth = json_decode($is_jwt_valid, true);

if (($data_auth['status'] ?? '') !== 'Success') {
    echo json_encode(['code' => 1, 'msg' => 'Unauthorized', 'items' => []]);
    exit;
}

$userId = $data_auth['payload']['id'];
$type = $_GET['type'] ?? 'deposit';
$items = [];

if ($type === 'deposit') {
    $result = $conn->query("SELECT motta, dinankavannuracisi, sthiti FROM thevani WHERE balakedara = '$userId' ORDER BY shonu DESC LIMIT 50");
    while ($row = $result->fetch_assoc()) {
        $items[] = [
            'amount' => number_format($row['motta'], 2),
            'date' => $row['dinankavannuracisi'],
            'status' => (string)$row['sthiti']
        ];
    }
} elseif ($type === 'betting') {
    // ✅ নতুন যোগ — User-এর নিজের আসল Game-Betting-History
    // (game_bet_logs Table থেকে, Callback.php যা Save করে)
    $stmt = $conn->prepare("SELECT game_code, bet_amount, win_amount, profit_loss, created_at FROM game_bet_logs WHERE user_id = ? ORDER BY created_at DESC LIMIT 50");
    $stmt->bind_param("s", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $items[] = [
            'game_code' => $row['game_code'],
            'bet_amount' => number_format($row['bet_amount'], 2),
            'win_amount' => number_format($row['win_amount'], 2),
            'profit_loss' => number_format($row['profit_loss'], 2),
            'date' => $row['created_at']
        ];
    }
} else {
    $result = $conn->query("SELECT motta, dinankavannuracisi, sthiti FROM hintegedukolli WHERE balakedara = '$userId' ORDER BY shonu DESC LIMIT 50");
    while ($row = $result->fetch_assoc()) {
        $items[] = [
            'amount' => number_format($row['motta'], 2),
            'date' => $row['dinankavannuracisi'],
            'status' => (string)$row['sthiti']
        ];
    }
}

echo json_encode(['code' => 0, 'items' => $items]);
