<?php
$host = 'localhost';
$dbname = 'blacrhdy_bet1';
$user = 'blacrhdy_bet1';
$pass = 'blacrhdy_bet1';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    sendResponse('error', 'Database connection failed', 500);
}

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

function sendResponse($status, $message, $httpCode, $additionalData = array()) {
    $response = array('status' => $status, 'message' => $message);
    if (!empty($additionalData)) {
        $response = array_merge($response, $additionalData);
    }
    header('Content-Type: application/json');
    http_response_code($httpCode);
    echo json_encode($response);
    exit;
}

function getUserFromDatabase($user_id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM kullanicilar WHERE id = :user_id");
    $stmt->execute(['user_id' => $user_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function updateUserBalance($user_id, $new_balance) {
    global $pdo;
    $stmt = $pdo->prepare("UPDATE kullanicilar SET ana_bakiye = :balance WHERE id = :user_id");
    $stmt->execute(['balance' => $new_balance, 'user_id' => $user_id]);
}

if (isset($data['method'])) {
    $user_id = isset($data['user_id']) ? (int)$data['user_id'] : null;

    switch ($data['method']) {
        case 'account_details':
            if ($user_id) {
                $user = getUserFromDatabase($user_id);
                if ($user) {
                    $response = array(
                        'user_id' => $user['id'],
                        'email' => $user['email'],
                        'name_jogador' => $user['username']
                    );
                    sendResponse('success', 'User details retrieved successfully', 200, $response);
                } else {
                    sendResponse('error', 'User not found', 404, array('provided_user_id' => $user_id));
                }
            } else {
                sendResponse('error', 'User ID is required', 400);
            }
            break;

        case 'user_balance':
            if ($user_id) {
                $user = getUserFromDatabase($user_id);
                if ($user) {
                    $response = array(
                        'status' => 1,
                        'balance' => number_format($user['ana_bakiye'], 2, '.', '')
                    );
                    sendResponse('success', 'User balance retrieved successfully', 200, $response);
                } else {
                    sendResponse('error', 'User not found', 404, array('provided_user_id' => $user_id));
                }
            } else {
                sendResponse('error', 'User ID is required', 400);
            }
            break;

        case 'transaction_bet':
            $bet_amount = isset($data['bet']) ? (float)$data['bet'] : null;
            $betReferenceNum = isset($data['bet_reference_num']) ? $data['bet_reference_num'] : null;
            $transactionID = isset($data['transaction_id']) ? $data['transaction_id'] : null;
            $game = isset($data['game']) ? $data['game'] : null;
            $roundID = isset($data['round_id']) ? $data['round_id'] : null;

            if ($user_id && $bet_amount !== null) {
                $user = getUserFromDatabase($user_id);
                if ($user) {
                    $new_balance = $user['ana_bakiye'] - $bet_amount;
                    if ($new_balance >= 0) {
                        // Kullanıcı bakiyesini güncelle
                        updateUserBalance($user_id, $new_balance);

                        // Bahis işlemini ekle
                        $stmt = $pdo->prepare("
                            INSERT INTO transactions 
                            (user_id, session_id, transaction_id, type, type_money, amount, providers, game, game_uuid, round_id)
                            VALUES (:user_id, :session_id, :transaction_id, :type, :type_money, :amount, :providers, :game, :game_uuid, :round_id)
                        ");
                        $stmt->execute([
                            'user_id' => $user_id,
                            'session_id' => $betReferenceNum,
                            'transaction_id' => $transactionID,
                            'type' => 'bet',
                            'type_money' => 0, 
                            'amount' => $bet_amount, 
                            'providers' => 'drakon',
                            'game' => $game,
                            'game_uuid' => $game,
                            'round_id' => $roundID
                        ]);

                        $response = array(
                            'status' => 1,
                            'balance' => number_format($new_balance, 2, '.', '')
                        );
                        sendResponse('success', 'Bet transaction successful', 200, $response);
                    } else {
                        sendResponse('error', 'Insufficient balance', 400, array(
                            'provided_user_id' => $user_id,
                            'provided_bet_amount' => $bet_amount
                        ));
                    }
                } else {
                    sendResponse('error', 'User not found', 404, array(
                        'provided_user_id' => $user_id,
                        'provided_bet_amount' => $bet_amount
                    ));
                }
            } else {
                sendResponse('error', 'User ID and bet amount are required', 400);
            }
            break;

        case 'transaction_win':
            $win_amount = isset($data['win']) ? (float)$data['win'] : null;
            $transactionID = isset($data['transaction_id']) ? $data['transaction_id'] : null;

            if ($user_id === null || $win_amount === null || $transactionID === null) {
                sendResponse('error', 'User ID, win amount, and transaction ID are required', 400);
            }

            if ($user_id && $win_amount !== null) {
                $user = getUserFromDatabase($user_id);

                if ($user) {
                    $new_balance = $user['ana_bakiye'] + $win_amount;

                    updateUserBalance($user_id, $new_balance);

                    $stmt = $pdo->prepare("
                        INSERT INTO transactions 
                        (user_id, session_id, transaction_id, type, type_money, amount, providers, game, game_uuid, round_id)
                        VALUES (:user_id, :session_id, :transaction_id, :type, :type_money, :amount, :providers, :game, :game_uuid, :round_id)
                    ");
                    $stmt->execute([
                        'user_id' => $user_id,
                        'session_id' => null, 
                        'transaction_id' => $transactionID,
                        'type' => 'win',
                        'type_money' => $win_amount, 
                        'amount' => 0, 
                        'providers' => 'drakon',
                        'game' => null, 
                        'game_uuid' => null,
                        'round_id' => null
                    ]);

                    $response = array(
                        'status' => 1,
                        'balance' => number_format($new_balance, 2, '.', '')
                    );

                    sendResponse('success', 'Win transaction successful', 200, $response);
                } else {
                    sendResponse('error', 'User not found', 404, array(
                        'provided_user_id' => $user_id,
                        'provided_win_amount' => $win_amount
                    ));
                }
            }
            break;

        default:
            sendResponse('error', 'Invalid method', 400);
            break;
    }
} else {
    sendResponse('error', 'Method is required', 400);
}
?>
