<?php 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

$user_id=false;

$host = 'localhost';
$dbname = 'blacrhdy_bet1';
$username = 'blacrhdy_bet1';
$password = 'blacrhdy_bet1';
$charset = 'utf8mb4';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=$charset", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // Hataları yakala
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // Verileri dizi olarak getir
        PDO::ATTR_EMULATE_PREPARES => false // SQL enjeksiyonuna karşı önlem
    ]);

    if (isset($_SESSION['users_id'])) {
        $stmt = $pdo->prepare("SELECT * FROM kullanicilar WHERE id = :users_id");
        $stmt->execute([':users_id' => $_SESSION['users_id']]);
        $user = $stmt->fetch();

        if (!$user) {
            $user_id=true;
        }
    }

} catch (PDOException $e) {
    die("Veritabanı bağlantı hatası: " . $e->getMessage());
}





// Log fonksiyonu: Gelen ve giden verileri kaydeder
function logRequestResponse($request, $response) {
    $logData = "====================\n";
    $logData .= "Timestamp: " . date('Y-m-d H:i:s') . "\n";
    $logData .= "Request: " . print_r($request, true) . "\n";
    $logData .= "Response: " . print_r($response, true) . "\n";
    $logData .= "====================\n\n";
    file_put_contents('requests_log.txt', $logData, FILE_APPEND);
}

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $rawData = file_get_contents('php://input');
    $postData = json_decode($rawData, true);
    $data = json_encode($postData);

    $response = [];

    if(isset($postData['method'])){
        $method = $postData['method'];

        switch($method) {
            case 'account_details':
                $response = accountDetails($postData);
                break;
            case 'user_balance':
                $response = GetBalance($postData);
                break;
            case 'transaction_bet':
                $response = SetTransactionBet($postData);
                break;
            case 'transaction_win':
                $response = SetTransactionWin($postData);
                break;
            case 'refund':
                $response = SetRefund($postData); 
                break;
            default:
                $response = array('status' => 0, 'message' => 'Invalid method');
                break;
        }
    } else {
        $response = array('status' => 0, 'message' => 'method required');
    }

    logRequestResponse($postData, $response);
    echo json_encode($response);
} else {
    $response = array('status' => 0, 'message' => 'no request found');
    logRequestResponse($_REQUEST, $response);
    echo json_encode($response);
}
function accountDetails($request){
    global $pdo;
    $user = $request['user_id'];

    // Nick ve balance birlikte çekiliyor
    $stmt = $pdo->prepare("SELECT users_id, ana_bakiye FROM kullanicilar WHERE id = :user_id");
    $stmt->bindParam(':user_id', $user);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        $name = $row['users_nick'];
        $balance = $row['ana_bakiye'];
        return json_encode(array(
            'email' => '', 
            'name_jogador' => $name, 
            'balance' => $balance, 
            'date' => time()
        ));
    } else {
        return json_encode(array(
            'error' => 'User not found'
        ));
    }
}

function GetBalance($request){
    global $pdo;
    $user = $request['user_id'];

    $stmt = $pdo->prepare("SELECT ana_bakiye FROM kullanicilar WHERE id = :user_id");
    $stmt->bindParam(':user_id', $user);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $balance = $row['ana_bakiye'];

    return json_encode(array('status' => 1, 'balance' => $balance));
}


function SetTransactionBet($request) {
    global $pdo;

    if (!isset($request['transaction_id'], $request['round_id'], $request['user_id'], $request['bet'])) {
        return json_encode(array('status' => 0, 'message' => 'Missing parameters for bet'));
    }

    $transactionid = $request['transaction_id'];
    $roundid = $request['round_id'];
    $user_id = $request['user_id'];
    $bet = $request['bet'];
    $game_code = $request['game'] ?? null;

    $stmt = $pdo->prepare("SELECT ana_bakiye FROM kullanicilar WHERE id = :user_id");
    $stmt->bindParam(':user_id', $user_id);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row && $row['ana_bakiye'] >= $bet) {
        try {
            $pdo->beginTransaction();

            $stmt = $pdo->prepare("UPDATE kullanicilar SET ana_bakiye = ana_bakiye - :bet WHERE id = :user_id");
            $stmt->bindParam(':bet', $bet);
            $stmt->bindParam(':user_id', $user_id);
            $stmt->execute();

            $stmt = $pdo->prepare("
                INSERT INTO live_bet (transaction_id, round_id, bet_amount, users_id, game_code, created_at) 
                VALUES (:transaction_id, :round_id, :bet, :user_id, :game_code, NOW())
            ");
            $stmt->bindParam(':transaction_id', $transactionid);
            $stmt->bindParam(':round_id', $roundid);
            $stmt->bindParam(':bet', $bet);
            $stmt->bindParam(':user_id', $user_id);
            $stmt->bindParam(':game_code', $game_code);
            $stmt->execute();

            $pdo->commit();

            $stmt = $pdo->prepare("SELECT ana_bakiye FROM kullanicilar WHERE id = :user_id");
            $stmt->bindParam(':user_id', $user_id);
            $stmt->execute();
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            $balance = $row['ana_bakiye'];

            return json_encode(array('status' => 1, 'balance' => $balance));
        } catch (Exception $e) {
            $pdo->rollBack();
            return json_encode(array('status' => 0, 'message' => "Error: " . $e->getMessage()));
        }
    } else {
        return json_encode(array('status' => 0, 'message' => "Insufficient balance or user not found"));
    }
}

function SetTransactionWin($request) {
    global $pdo;

    if (!isset($request['transaction_id'], $request['round_id'], $request['user_id'], $request['win'])) {
        return json_encode(array('status' => 0, 'message' => 'Missing parameters for win'));
    }

    $transactionid = $request['transaction_id'];
    $roundid = $request['round_id'];
    $user_id = $request['user_id'];
    $win = $request['win'];
    $game_code = $request['game'] ?? null;

    try {
        $pdo->beginTransaction();

        $stmt = $pdo->prepare("
            INSERT INTO live_bet (transaction_id, round_id, bet_amount, get_amount, users_id, game_code, created_at) 
            VALUES (:transaction_id, :round_id, 0, :win, :user_id, :game_code, NOW())
        ");
        $stmt->bindParam(':transaction_id', $transactionid);
        $stmt->bindParam(':round_id', $roundid);
        $stmt->bindParam(':win', $win);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->bindParam(':game_code', $game_code);
        $stmt->execute();

        $stmt = $pdo->prepare("UPDATE kullanicilar SET ana_bakiye = ana_bakiye + :bet WHERE id = :user_id");
        $stmt->bindParam(':bet', $win);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->execute();

        $pdo->commit();

        $stmt = $pdo->prepare("SELECT ana_bakiye FROM kullanicilar WHERE id = :user_id");
        $stmt->bindParam(':user_id', $user_id);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $balance = $row['ana_bakiye'];

        return json_encode(array('status' => 1, 'balance' => $balance));
    } catch (Exception $e) {
        $pdo->rollBack();
        return json_encode(array('status' => 0, 'message' => "Error: " . $e->getMessage()));
    }
}

function SetRefund($request) {
    global $pdo;
    
 

    $user_id = $request['user_id'];
    $transaction_id = $request['transaction_id'];
    $refund_amount = $request['refund'];
    $game_code = $request['game'] ?? null;

    try {
        $pdo->beginTransaction();

        // Önce kullanıcının mevcut bakiyesini al
        $stmt = $pdo->prepare("SELECT ana_bakiye FROM kullanicilar WHERE id = :user_id");
        $stmt->bindParam(':user_id', $user_id);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            $pdo->rollBack();
            return json_encode(array('status' => 0, 'message' => 'User not found'));
        }

        $current_balance = $row['ana_bakiye'];
        $new_balance = $current_balance + $refund_amount;

        // Bakiyeyi güncelle
        $stmt = $pdo->prepare("UPDATE kullanicilar SET ana_bakiye = :new_balance WHERE id = :user_id");
        $stmt->bindParam(':new_balance', $new_balance);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->execute();

        // İade işlemini kaydet
        $stmt = $pdo->prepare("
            INSERT INTO live_bet (transaction_id, round_id, bet_amount, get_amount, users_id, game_code, created_at) 
            VALUES (:transaction_id, 0, 0, :refund_amount, :user_id, :game_code, NOW())
        ");
        $stmt->bindParam(':transaction_id', $transaction_id);
        $stmt->bindParam(':refund_amount', $refund_amount);
        $stmt->bindParam(':user_id', $user_id);
        $stmt->bindParam(':game_code', $game_code);
        $stmt->execute();

        $pdo->commit();

        return json_encode(array('status' => 1, 'balance' => $new_balance));
    } catch (Exception $e) {
        $pdo->rollBack();
        return json_encode(array('status' => 0, 'message' => "Error: " . $e->getMessage()));
    }
}
?>