<?php
session_start();
include "config.php";
include "functions.php";

header('Content-Type: application/json');

$response = [
    'success' => false,
    'step'    => 'init',
    'msg'     => '',
    'api'     => null,
    'data'    => []
];

// ===== VALIDASI USER =====
if(empty($_SESSION['username'])){
    $response['step'] = 'session';
    $response['msg']  = 'User belum login';
    echo json_encode($response);
    exit;
}

$user_code = $_SESSION['username'];
$game_type = $_GET['game_type'] ?? 'slot';
$provider  = $_GET['provider'] ?? '';
$page      = intval($_GET['page'] ?? 0);

// ===== RANGE WAKTU =====v
$end   = date('Y-m-d 23:59:59');
$start = date('Y-m-d 00:00:00', strtotime('-1 day'));

$response['step'] = 'call_api';

// ===== CALL API =====
$res = getBetHistory($user_code, $game_type, $start, $end, $page);

// ===== SIMPAN RAW RESPONSE (DEBUG) =====
if(DEBUG_API){
    $response['api'] = $res;
}

// ===== CEK STATUS API =====
// ===== PARSE DATA =====
if (!isset($res['slot']) || !is_array($res['slot'])) {
    $response['step'] = 'no_data';
    $response['msg']  = 'Bet history kosong / format API berubah';
    echo json_encode($response);
    exit;
}

foreach ($res['slot'] as $row) {

    if ($provider && strtolower($row['provider_code'] ?? '') != strtolower($provider)) {
        continue;
    }

    $response['data'][] = [
        'date'     => $row['created_at'] ?? '-',
        'trx'      => $row['txn_id'] ?? '-',
        'game'     => $row['game_code'] ?? '-',
        'provider' => strtoupper($row['provider_code'] ?? '-'),
        'bet'      => $row['bet_money'] ?? 0,
        'win'      => $row['win_money'] ?? 0,
        'status'   => $row['txn_type'] ?? '-'
    ];
}

$response['success'] = true;
$response['step']    = 'done';

echo json_encode($response);