<?php
/**
 * get_detailed_history.php
 * User-এর Betting-History, Session-Grouped (কোন Game, কতক্ষণ
 * খেলেছে, কত Loss/Profit) — Premium, বিস্তারিত Format-এ।
 */
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' => 'Login করা নেই']);
    exit;
}

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

// ✅ ধাপ ১ — সব Vendor-JSON থেকে, gameCode → gameName এর
// একটা Map বানানো (যাতে শুধু Code না, আসল নাম দেখানো যায়)
$dataDir = __DIR__ . '/deepanshu/api/webapi/data/';
$vendorFiles = ['jili.json', 'jdb.json', 'pgsoft.json', 'cq9.json', 'mg.json', 'g9.json',
    '5g.json', '2j.json', 'bng.json', 'btg.json', '100hp.json', 'eazygame.json',
    'fastspin.json', 'inout.json', 'bgaming.json', 'turbo.json', 'v8.json',
    'idg.json', 'km.json', 'eg.json', 'evolive.json', 'casino.json', 'all_game.json'];

$gameNameMap = [];
foreach ($vendorFiles as $file) {
    $path = $dataDir . $file;
    if (!file_exists($path)) continue;
    $json = json_decode(@file_get_contents($path), true);
    $games = $json['data']['gameLists'] ?? $json['gameLists'] ?? $json ?? [];
    if (!is_array($games)) continue;
    foreach ($games as $g) {
        $code = $g['gameCode'] ?? $g['gameID'] ?? '';
        $name = $g['gameNameEn'] ?? '';
        if ($code !== '' && $name !== '') {
            $gameNameMap[$code] = $name;
        }
    }
}

// ✅ ধাপ ২ — User-এর সব Bet-Record আনা (সময়ের ক্রম অনুযায়ী)
$stmt = $conn->prepare("SELECT game_code, bet_amount, win_amount, profit_loss, serial_number, created_at FROM game_bet_logs WHERE user_id = ? ORDER BY created_at ASC LIMIT 500");
$stmt->bind_param("s", $userId);
$stmt->execute();
$result = $stmt->get_result();

$allBets = [];
while ($row = $result->fetch_assoc()) {
    $allBets[] = $row;
}

// ✅ ধাপ ৩ — একই Game-এ পরপর Bet-কে, একটা "Session"-এ Group করা
// (যদি ৫ মিনিটের বেশি Gap হয়, নতুন Session ধরা হবে)
$sessions = [];
$currentSession = null;

foreach ($allBets as $bet) {
    $gap = $currentSession ? (strtotime($bet['created_at']) - strtotime($currentSession['end_time'])) : 999999;

    if ($currentSession && $currentSession['game_code'] === $bet['game_code'] && $gap <= 300) {
        // ✅ একই Session-এ যোগ হচ্ছে
        $currentSession['end_time'] = $bet['created_at'];
        $currentSession['total_bet'] += (float)$bet['bet_amount'];
        $currentSession['total_win'] += (float)$bet['win_amount'];
        $currentSession['total_profit_loss'] += (float)$bet['profit_loss'];
        $currentSession['round_count']++;
    } else {
        // ✅ নতুন Session শুরু
        if ($currentSession) $sessions[] = $currentSession;
        $currentSession = [
            'game_code' => $bet['game_code'],
            'game_name' => $gameNameMap[$bet['game_code']] ?? $bet['game_code'],
            'start_time' => $bet['created_at'],
            'end_time' => $bet['created_at'],
            'total_bet' => (float)$bet['bet_amount'],
            'total_win' => (float)$bet['win_amount'],
            'total_profit_loss' => (float)$bet['profit_loss'],
            'round_count' => 1
        ];
    }
}
if ($currentSession) $sessions[] = $currentSession;

// ✅ ধাপ ৪ — প্রতিটা Session-এর Duration Calculate করা, Format ঠিক করা
foreach ($sessions as &$s) {
    $durationSec = strtotime($s['end_time']) - strtotime($s['start_time']);
    $minutes = floor($durationSec / 60);
    $seconds = $durationSec % 60;
    $s['duration'] = $minutes > 0 ? "{$minutes} মিনিট {$seconds} সেকেন্ড" : "{$seconds} সেকেন্ড";
    $s['duration_seconds'] = $durationSec;
    $s['total_bet'] = round($s['total_bet'], 2);
    $s['total_win'] = round($s['total_win'], 2);
    $s['total_profit_loss'] = round($s['total_profit_loss'], 2);
}
unset($s);

// ✅ সবচেয়ে সাম্প্রতিক Session আগে দেখানো
$sessions = array_reverse($sessions);

echo json_encode(['code' => 0, 'sessions' => $sessions, 'total' => count($sessions)]);
