<?php
require_once 'config/db.php';
header('Content-Type: application/json');

// Ensure the request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode([
        "status" => 0,
        "msg" => "INVALID_REQUEST_METHOD"
    ]);
    exit;
}

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

file_put_contents('data.json', json_encode($input, JSON_PRETTY_PRINT));

$method = $input['method'] ?? null;
$extplayer = $input['user_code'] ?? null;

$query = "SELECT u.id, b.user_id, u.username, u.fullname, u.extplayer, b.total_balance, b.total_turnover, b.total_win 
          FROM user u 
          JOIN balance b ON u.id = b.user_id 
          WHERE u.extplayer = :extplayer";
$stmt = $db->prepare($query);
$stmt->bindValue(':extplayer', $extplayer);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo json_encode([
        "status" => 0,
        "msg" => "INVALID_USER"
    ]);
    exit;
}

if ($method === 'user_balance') {
    $user_balance = floatval($user['total_balance'] ?? 0);

    if ($user_balance < 0) {
        echo json_encode([
            "status" => 0,
            "user_balance" => 0,
            "msg" => "INSUFFICIENT_USER_FUNDS"
        ]);
        exit;
    }

    echo json_encode([
        "status" => 1,
        "user_balance" => $user_balance
    ]);
    exit;
}

if ($method === 'transaction') {
    $agent_balance = $input['agent_balance'] ?? null;
    $game_type = $input['game_type'] ?? null;

    // Pastikan game_type diberikan dan sesuai dengan struktur input
    if (!$game_type || !isset($input[$game_type])) {
        echo json_encode([
            "status" => 0,
            "msg" => "INVALID_GAME_TYPE"
        ]);
        exit;
    }

    // Ambil data dari struktur berdasarkan game_type: live, slot, dll.
    $game_data = $input[$game_type];

    $provider_code = $game_data['provider_code'] ?? '';
    $game_code = $game_data['game_code'] ?? '';
    $type = $game_data['type'] ?? '';
    $bet_money = floatval($game_data['bet_money'] ?? 0);
    $win_money = floatval($game_data['win_money'] ?? 0);
    $txn_id = $game_data['txn_id'] ?? '';
    $txn_type = $game_data['txn_type'] ?? '';

    // Validasi parameter wajib
    if (!$txn_id || !$txn_type || !$provider_code || !$game_code || !$type) {
        echo json_encode([
            "status" => 0,
            "msg" => "MISSING_PARAMS"
        ]);
        exit;
    }

    // Cek apakah transaksi sudah pernah dicatat
    $stmt = $db->prepare("SELECT id FROM game_history WHERE txn_id = ?");
    $stmt->execute([$txn_id]);
    if ($stmt->rowCount() > 0) {
        echo json_encode([
            "status" => 0,
            "msg" => "DUPLICATE_TXN_ID"
        ]);
        exit;
    }

    // Ambil data balance user
    $total_balance = floatval($user['total_balance'] ?? 0);
    $total_turnover = floatval($user['total_turnover'] ?? 0);
    $total_win = floatval($user['total_win'] ?? 0);

    // Validasi saldo
    if ($total_balance < 0) {
        echo json_encode([
            "status" => 0,
            "user_balance" => 0,
            "msg" => "INSUFFICIENT_USER_FUNDS"
        ]);
        exit;
    }

    // Hitung saldo akhir
    $finalWin = $win_money - $bet_money;
    $resultBalance = $total_balance + $finalWin;
    $resultTurnover = $total_turnover + $bet_money;
    $resultWin = $total_win + $finalWin;
    $created_at = date('Y-m-d H:i:s');

    // Simpan ke tabel game_history
    $stmt = $db->prepare("INSERT INTO game_history (
        user_id, game_category, provider_code, game_code, type, txn_id, txn_type,
        bet, win, user_balance_before, user_balance_after, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $user['id'], $game_type, $provider_code, $game_code, $type, $txn_id, $txn_type,
        $bet_money, $win_money, $total_balance, $resultBalance, $created_at
    ]);

    // Update saldo user
    $stmt = $db->prepare("UPDATE balance 
        SET total_balance = ?, total_turnover = ?, total_win = ?
        WHERE user_id = ?");
    $stmt->execute([
        $resultBalance, $resultTurnover, $resultWin, $user['id']
    ]);

    // Respon sukses
    echo json_encode([
        "status" => 1,
        "user_balance" => $resultBalance
    ]);
    exit;
}

