<?php
require_once '../includes/db.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() ?: [],
    'get_data' => $_GET,
    'post_data' => $_POST,
    'raw_input' => $rawInput,
    'content_type' => $_SERVER['CONTENT_TYPE'] ?? '',
    'server_data' => [
        'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'] ?? '',
        'HTTP_USER_AGENT' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        'HTTP_REFERER' => $_SERVER['HTTP_REFERER'] ?? '',
        'QUERY_STRING' => $_SERVER['QUERY_STRING'] ?? '',
        'REQUEST_METHOD' => $_SERVER['REQUEST_METHOD'] ?? '',
        'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? '',
        'REQUEST_SCHEME' => $_SERVER['REQUEST_SCHEME'] ?? '',
        'SERVER_PROTOCOL' => $_SERVER['SERVER_PROTOCOL'] ?? '',
    ]
];

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 = 'received_data_' . date('Y-m-d_H-i-s') . '_' . uniqid() . '.json';
$filepath = __DIR__ . '/logs/' . $filename;


$apiResponse = [
    'status' => false,
    'user_balance' => 0,
    'error' => null
];

if (!empty($rawInput) && $receivedData['is_json']) {
    $jsonData = $receivedData['json_decoded'];
    
    if (isset($jsonData['user_code']) && !empty($jsonData['user_code'])) {
        $userCode = $jsonData['user_code'];
        
        try {
            $sql = "SELECT id, bet_saldo FROM bet_usuarios WHERE id = :user_code LIMIT 1";
            $stmt = $pdo->prepare($sql);
            $stmt->bindValue(':user_code', $userCode, PDO::PARAM_INT);
            $stmt->execute();
            
            $usuario = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($usuario) {
                $apiResponse = [
                    'status' => 1,
                    'user_balance' => (float)$usuario['bet_saldo']
                ];
                error_log("Usuário encontrado: ID={$userCode}, Saldo={$usuario['bet_saldo']}");
            } else {
                $apiResponse['error'] = 'Usuário não encontrado';
                error_log("Usuário não encontrado: ID={$userCode}");
            }
            
        } catch (Exception $e) {
            $apiResponse['error'] = 'Erro na consulta: ' . $e->getMessage();
            error_log("Erro SQL: " . $e->getMessage());
        }
        
    } else {
        $apiResponse['error'] = 'user_code não informado ou inválido';
        error_log("user_code não informado nos dados JSON");
    }
} else {
    $apiResponse['error'] = 'Dados JSON inválidos ou vazios';
    error_log("Dados JSON inválidos ou vazios");
}

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

$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 (isset($_GET['debug']) || $saveResult === false) {
    $apiResponse['debug_info'] = [
        'method' => $receivedData['method'],
        'has_raw_input' => !empty($rawInput),
        'raw_input_length' => strlen($rawInput),
        'is_json' => $receivedData['is_json'],
        'content_type' => $receivedData['content_type'],
        'file_saved' => $saveResult !== false,
        'file' => $filename,
        'filepath' => $filepath,
        'received_at' => $receivedData['timestamp']
    ];
    
    if ($saveResult === false || empty($rawInput) || !$receivedData['is_json']) {
        $apiResponse['received_data'] = $receivedData;
    }
}

if ($saveResult !== false) {
    error_log("Arquivo salvo com sucesso: {$filepath}");
} else {
    error_log("Erro ao salvar arquivo: {$filepath}");
}

echo json_encode($apiResponse, JSON_PRETTY_PRINT);
?> 