<?php
/**
 * get_rebate_breakdown.php
 * User-এর আসল Betting-Data (game_bet_logs), Category-Wise
 * ভাগ করে দেখানোর জন্য। প্রতিটা game_code, Vendor-JSON
 * File-গুলোতে Match করে, Category (Slot/Fish/Live) বের করে।
 *
 * ✅ ঠিক করা হলো — Safe Error-Handling যোগ করা হয়েছে,
 * যাতে কোনো PHP-Error, HTML-Output না দিয়ে সবসময় Valid
 * JSON-Response দেয় (আগে "Unexpected token '<'" Error হতো)
 */
error_reporting(E_ALL);
ini_set('display_errors', 0);
ob_start();
header('Content-Type: application/json; charset=utf-8');
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    ob_end_clean();
    echo json_encode(['code' => 1, 'msg' => "PHP-Error: $errstr (Line: $errline)"]);
    exit;
});
register_shutdown_function(function() {
    $error = error_get_last();
    if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        if (ob_get_level() > 0) ob_end_clean();
        echo json_encode(['code' => 1, 'msg' => "Fatal-Error: " . $error['message']]);
    } else {
        if (ob_get_level() > 0) ob_end_flush();
    }
});

include __DIR__ . "/deepanshu/conn.php";
include __DIR__ . "/deepanshu/functions2.php";
if (isset($conn)) { $conn->set_charset("utf8mb4"); }

$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']);
    exit;
}

$userId = $data_auth['payload']['id'];
$dataDir = __DIR__ . '/deepanshu/api/webapi/data/';

// ✅ Vendor-File → Category Mapping (Best-Effort, Available
// Data অনুযায়ী)
$fishFiles = ['mg_fish.json'];
$liveCasinoFiles = ['evolive.json', 'casino.json'];
$slotFiles = ['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'];

// ✅ প্রতিটা Category-File থেকে, সব Game-Code একটা Set-এ জমা করা
function collectGameCodes($dataDir, $files) {
    $codes = [];
    foreach ($files 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'] ?? $g['gameId'] ?? '';
            if ($code !== '') $codes[$code] = true;
        }
    }
    return $codes;
}

$slotCodes = collectGameCodes($dataDir, $slotFiles);
$fishCodes = collectGameCodes($dataDir, $fishFiles);
$liveCodes = collectGameCodes($dataDir, $liveCasinoFiles);

// ✅ User-এর আজকের সব Bet আনা
$stmt = $conn->prepare("SELECT game_code, bet_amount FROM game_bet_logs WHERE user_id = ? AND DATE(created_at) = CURDATE()");
$stmt->bind_param("s", $userId);
$stmt->execute();
$result = $stmt->get_result();

$breakdown = ['slot' => 0, 'fish' => 0, 'live' => 0, 'sport' => 0, 'poker' => 0, 'other' => 0];
$total = 0;

while ($row = $result->fetch_assoc()) {
    $code = $row['game_code'];
    $amount = (float)$row['bet_amount'];
    $total += $amount;

    if (isset($slotCodes[$code])) {
        $breakdown['slot'] += $amount;
    } elseif (isset($fishCodes[$code])) {
        $breakdown['fish'] += $amount;
    } elseif (isset($liveCodes[$code])) {
        $breakdown['live'] += $amount;
    } else {
        // ✅ Sport/Poker — এই মুহূর্তে কোনো Vendor-Data নেই,
        // তাই Match না হওয়া সব Game "other"-এ পড়বে
        $breakdown['other'] += $amount;
    }
}

foreach ($breakdown as $k => $v) {
    $breakdown[$k] = round($v, 2);
}

echo json_encode([
    'code' => 0,
    'breakdown' => $breakdown,
    'total' => round($total, 2),
    'date' => date('Y-m-d')
]);
