<?php
/**
 * Game Callback Handler for Huido Seamless Wallet
 * Receives bet data from SeamlessEndpoints.php and processes it against the game database
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

header('Content-Type: application/json; charset=utf-8');
date_default_timezone_set('Asia/Kolkata'); // Use IST

// Create logs directory if not exists
$log_dir = __DIR__ . '/apilogs';
if (!file_exists($log_dir)) {
    mkdir($log_dir, 0777, true);
}

/**
 * Log utility
 */
function writeLog($message) {
    global $log_dir;
    $log_file = $log_dir . '/game_callback_' . date('Y-m-d') . '.txt';
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($log_file, "[{$timestamp}] {$message}\n", FILE_APPEND);
    error_log($message);
}

writeLog("========================================");
writeLog("=== Game Callback Received ===");
writeLog("Request Method: " . $_SERVER['REQUEST_METHOD']);
writeLog("Request URI: " . $_SERVER['REQUEST_URI']);

include_once "conn.php";
include_once "functions2.php";

/**
 * JSON response sender
 */
function sendResponse($data, $status = 200) {
    writeLog("Response: " . json_encode($data));
    http_response_code($status);
    echo json_encode($data);
    exit;
}

// Only POST allowed
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(['code' => 1, 'msg' => 'Method not allowed'], 405);
}

// Read and parse JSON input
$raw_input = file_get_contents('php://input');
writeLog("Raw input: " . $raw_input);
$input = json_decode($raw_input, true);

if (!$input) {
    sendResponse(['code' => 1, 'msg' => 'Invalid JSON input'], 400);
}

writeLog("Parsed input: " . json_encode($input, JSON_PRETTY_PRINT));

// Validate fields
$required = ['user_id', 'game_code', 'bet_amount', 'win_amount', 'serial_number', 'game_round'];
foreach ($required as $field) {
    if (!isset($input[$field])) {
        sendResponse(['code' => 1, 'msg' => "Missing field: {$field}"], 400);
    }
}

$user_id        = $input['user_id'];
$game_code      = $input['game_code'];
$bet_amount_brl = floatval($input['bet_amount']);
$win_amount_brl = floatval($input['win_amount']);
$serial_number  = $input['serial_number'];
$game_round     = $input['game_round'];
$timestamp      = $input['timestamp'] ?? date('Y-m-d H:i:s');
$vendor_code    = $input['vendor_code'] ?? ''; // May be missing

// Vendor mapping
$vendor_map = [
    'CQ9' => 2,
    'JDB' => 6,
    'JILI' => 18,
    'MG' => 4,
    'PG' => 5,
    'TB_Chess' => 23,
    'SPRIBE' => 20,
    'BGAMING' => 46,
    'KoolBet' => 19,
    'V8Card' => 21,
    'AG_Electronic' => 12,
    'EVO_Electronic' => 17,
    'EVO_Video' => 16,
    'SEXY_Video' => 27,
    'MG_Video' => 38, // Fixed spelling
    'WM_Video' => 26,
    '9Sports' => 24,
    'SaBa' => 14,
    'Esports' => 92,
    'CMD' => 8,
];

// Detect vendor
if (isset($vendor_map[$vendor_code])) {
    $vendor_id = $vendor_map[$vendor_code];
} else {
    // Auto detect vendor from JSON files using game_code
    $data_dir = __DIR__ . "/data";
    $found_vendor = false;
    foreach (glob($data_dir . "/*.json") as $json_file) {
        $content = json_decode(file_get_contents($json_file), true);
        $list = $content['gameLists'] ?? $content ?? [];
        foreach ($list as $g) {
            if (isset($g['gameCode']) && strtolower($g['gameCode']) === strtolower($game_code)) {
                $vendor_code = basename($json_file, ".json");
                $vendor_id = $vendor_map[$vendor_code] ?? 23;
                $found_vendor = true;
                writeLog("Auto-detected vendor: {$vendor_code} for game_code {$game_code}");
                break 2;
            }
        }
    }

    if (!$found_vendor) {
        $vendor_code = 'TB_Chess';
        $vendor_id = 23;
        writeLog("Vendor fallback: TB_Chess (default)");
    }
}

writeLog("User ID: {$user_id}");
writeLog("Game Code: {$game_code}");
writeLog("Vendor Code: {$vendor_code}, Vendor ID: {$vendor_id}");
writeLog("Bet: {$bet_amount_brl} BRL, Win: {$win_amount_brl} BRL");

// Convert BRL → INR (1:1 demo)
$exchange_rate = 1.0;
$bet_amount_inr = $bet_amount_brl * $exchange_rate;
$win_amount_inr = $win_amount_brl * $exchange_rate;

// Check duplicate serial
$check_stmt = $conn->prepare("SELECT id FROM game_bet_logs WHERE serial_number = ?");
$check_stmt->bind_param("s", $serial_number);
$check_stmt->execute();
$duplicate_result = $check_stmt->get_result();

// Get balance
$balance_stmt = $conn->prepare("SELECT balance FROM argame_balances WHERE user_id = ?");
$balance_stmt->bind_param("s", $user_id);
$balance_stmt->execute();
$result = $balance_stmt->get_result();

if ($result->num_rows === 0) {
    sendResponse(['code' => 1, 'msg' => 'User not found'], 404);
}

$row = $result->fetch_assoc();
$current_balance_inr = floatval($row['balance']);
writeLog("Current Balance: {$current_balance_inr} INR");

// Handle duplicate
if ($duplicate_result && $duplicate_result->num_rows > 0) {
    writeLog("Duplicate serial_number {$serial_number}");
    sendResponse(['code' => 0, 'msg' => 'Duplicate', 'balance_inr' => $current_balance_inr]);
}

// Calculate new balance
$balance_change_inr = -$bet_amount_inr + $win_amount_inr;
$new_balance_inr = $current_balance_inr + $balance_change_inr;

if ($new_balance_inr < 0) {
    sendResponse(['code' => 1, 'msg' => 'Insufficient balance'], 400);
}

// Update balance
$update_stmt = $conn->prepare("UPDATE argame_balances SET balance = ?, updated_at = NOW() WHERE user_id = ?");
$update_stmt->bind_param("ds", $new_balance_inr, $user_id);
if (!$update_stmt->execute()) {
    sendResponse(['code' => 1, 'msg' => 'Balance update failed'], 500);
}

writeLog("Balance updated successfully");

// --- Game Name Lookup ---
$gameName = "ARGame";
$jsonFile = __DIR__ . "/data/{$vendor_code}.json";
if (file_exists($jsonFile)) {
    $jsonData = json_decode(file_get_contents($jsonFile), true);
    $gameList = $jsonData['gameLists'] ?? $jsonData ?? [];
    foreach ($gameList as $g) {
        if (isset($g['gameCode']) && strtolower($g['gameCode']) === strtolower($game_code)) {
            $gameName = $g['gameNameEn'] ?? 'ARGame';
            break;
        }
    }
}
writeLog("Game Name: {$gameName}");

// --- Insert Log ---
$profit_loss = $win_amount_inr - $bet_amount_inr;
$created_at = date('Y-m-d H:i:s');

try {
    $stmt = $conn->prepare("
        INSERT INTO game_bet_logs 
        (user_id, vendor_id, vendor_code, game_code, game_name_en, bet_amount, win_amount, profit_loss, balance_before, balance_after, serial_number, game_round, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param(
        "sisssdddddsss",
        $user_id,
        $vendor_id,
        $vendor_code,
        $game_code,
        $gameName,
        $bet_amount_inr,
        $win_amount_inr,
        $profit_loss,
        $current_balance_inr,
        $new_balance_inr,
        $serial_number,
        $game_round,
        $created_at
    );
    $stmt->execute();
    writeLog("Bet logged successfully: {$gameName}, Vendor: {$vendor_code}");
} catch (Exception $e) {
    writeLog("Error logging bet: " . $e->getMessage());
}

// Final response
sendResponse([
    'code' => 0,
    'msg' => 'Success',
    'balance_inr' => $new_balance_inr
]);
?>
