<?php
require_once '../includes/db.php';
require_once '../includes/config.php';

$rawInput = file_get_contents('php://input');

$receivedData = [
    'timestamp' => date('Y-m-d H:i:s'),
    'method' => $_SERVER['REQUEST_METHOD'] ?? 'UNKNOWN',
    'url' => $_SERVER['REQUEST_URI'] ?? '',
    'headers' => getallheaders() ?: [],
    'raw_input' => $rawInput,
    'content_type' => $_SERVER['CONTENT_TYPE'] ?? '',
    'server_data' => [
        'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'] ?? '',
        'HTTP_USER_AGENT' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'] ?? '',
    ]
];

if (!empty($rawInput)) {
    $jsonDecoded = json_decode($rawInput, true);
    if ($jsonDecoded !== null) {
        $receivedData['json_decoded'] = $jsonDecoded;
        $receivedData['is_json'] = true;
    } else {
        $receivedData['is_json'] = false;
    }
} else {
    $receivedData['is_json'] = false;
}

$filename = 'game_callback_' . date('Y-m-d_H-i-s') . '_' . uniqid() . '.json';
$filepath = __DIR__ . '/logs/' . $filename;

function saveLog($receivedData, $apiResponse, $filepath) {
    $receivedData['api_response'] = $apiResponse;
    $receivedData['response_timestamp'] = date('Y-m-d H:i:s');
    $saveResult = file_put_contents($filepath, json_encode($receivedData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    
    if ($saveResult !== false) {
        error_log("Log salvo: {$filepath}");
    } else {
        error_log("Erro ao salvar log: {$filepath}");
    }
}

$apiResponse = [
    'status' => 0,
    'msg' => 'INTERNAL_ERROR'
];

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

if (!$receivedData['is_json'] || empty($rawInput)) {
    $apiResponse['msg'] = 'INVALID_JSON';
    error_log("[Game Callback] JSON inválido ou vazio");
    saveLog($receivedData, $apiResponse, $filepath);
    echo json_encode($apiResponse);
    exit;
}

$body = $receivedData['json_decoded'];

if (!isset($body['agent_secret']) || $body['agent_secret'] !== $AgentSecretRoyal) {
    $apiResponse['msg'] = 'INVALID_AGENT_SECRET';
    error_log("[Game Callback] Agent secret inválido");
    saveLog($receivedData, $apiResponse, $filepath);
    echo json_encode($apiResponse);
    exit;
}

if (!isset($body['user_code']) || empty($body['user_code'])) {
    $apiResponse['msg'] = 'USER_CODE_REQUIRED';
    error_log("[Game Callback] user_code não informado");
    saveLog($receivedData, $apiResponse, $filepath);
    echo json_encode($apiResponse);
    exit;
}

if (!isset($body['slot']) || !is_array($body['slot'])) {
    $apiResponse['msg'] = 'SLOT_DATA_REQUIRED';
    error_log("[Game Callback] Dados do slot não informados");
    saveLog($receivedData, $apiResponse, $filepath);
    echo json_encode($apiResponse);
    exit;
}

$userCode = $body['user_code'];
$slot = $body['slot'];
$betAmount = (float)($slot['bet'] ?? 0);
$winAmount = (float)($slot['win'] ?? 0);
$txnId = $slot['txn_id'] ?? '';

if ($betAmount < 0 || $winAmount < 0) {
    $apiResponse['msg'] = 'INVALID_BET_OR_WIN_AMOUNT';
    error_log("[Game Callback] Valores negativos detectados - User: {$userCode}, Bet: {$betAmount}, Win: {$winAmount}");
    saveLog($receivedData, $apiResponse, $filepath);
    echo json_encode($apiResponse);
    exit;
}

$netAmount = 0;

if ($betAmount > 0 && $winAmount == 0) {
    $netAmount = -$betAmount;
    error_log("[Game Callback] Tipo: Aposta sem ganho - User: {$userCode}, Bet: {$betAmount}, NetAmount: {$netAmount}");
} elseif ($betAmount == 0 && $winAmount > 0) {
    $netAmount = $winAmount;
    error_log("[Game Callback] Tipo: Ganho sem aposta - User: {$userCode}, Win: {$winAmount}, NetAmount: {$netAmount}");
} elseif ($betAmount > 0 && $winAmount > 0) {
    $netAmount = $winAmount - $betAmount;
    error_log("[Game Callback] Tipo: Aposta com ganho - User: {$userCode}, Bet: {$betAmount}, Win: {$winAmount}, NetAmount: {$netAmount}");
} elseif ($betAmount == 0 && $winAmount == 0) {
    $netAmount = 0;
    error_log("[Game Callback] Tipo: Transação neutra - User: {$userCode}, Bet: {$betAmount}, Win: {$winAmount}, NetAmount: {$netAmount}");
} else {
    $apiResponse['msg'] = 'INVALID_TRANSACTION';
    error_log("[Game Callback] Transação inválida - User: {$userCode}, Bet: {$betAmount}, Win: {$winAmount}");
    saveLog($receivedData, $apiResponse, $filepath);
    echo json_encode($apiResponse);
    exit;
}

try {
    $pdo->beginTransaction();
    
    $sql = "SELECT id, bet_saldo FROM bet_usuarios WHERE id = :user_code FOR UPDATE";
    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':user_code', $userCode, PDO::PARAM_INT);
    $stmt->execute();
    
    $usuario = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$usuario) {
        $pdo->rollback();
        $apiResponse['msg'] = 'USER_NOT_FOUND';
        error_log("[Game Callback] Usuário não encontrado: {$userCode}");
        saveLog($receivedData, $apiResponse, $filepath);
        echo json_encode($apiResponse);
        exit;
    }
    
    $currentBalance = (float)$usuario['bet_saldo'];
    
    if ($netAmount < 0 && abs($netAmount) > $currentBalance) {
        $pdo->rollback();
        $apiResponse['msg'] = 'INSUFFICIENT_USER_FUNDS';
        error_log("[Game Callback] Saldo insuficiente - User: {$userCode}, Saldo: {$currentBalance}, Requerido: " . abs($netAmount));
        saveLog($receivedData, $apiResponse, $filepath);
        echo json_encode($apiResponse);
        exit;
    }
    
    $newBalance = $currentBalance + $netAmount;
    $newBalance = max(0, round($newBalance, 2)); 
    
    $updateSql = "UPDATE bet_usuarios SET bet_saldo = :new_balance WHERE id = :user_code";
    $updateStmt = $pdo->prepare($updateSql);
    $updateStmt->bindValue(':new_balance', $newBalance, PDO::PARAM_STR);
    $updateStmt->bindValue(':user_code', $userCode, PDO::PARAM_INT);
    $updateStmt->execute();
    
    $pdo->commit();
    
    $apiResponse = [
        'status' => 1,
        'tnx' => $txnId,
        'user_balance' => $newBalance
    ];
    
    error_log("[Game Callback] Transação processada com sucesso - User: {$userCode}, Saldo anterior: {$currentBalance}, Novo saldo: {$newBalance}, Net: {$netAmount}");
    
} catch (Exception $e) {
    $pdo->rollback();
    $apiResponse = [
        'status' => 0,
        'msg' => 'INTERNAL_ERROR'
    ];
    error_log("[Game Callback] Erro na transação - User: {$userCode}, Erro: " . $e->getMessage());
}

saveLog($receivedData, $apiResponse, $filepath);

echo json_encode($apiResponse);
?> 