<?php
include 'database.php';
header('Content-Type: application/json');



if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit(json_encode(['status' => 'error', 'msg' => 'Sadece POST desteklenir']));
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input || !isset($input['method'])) {
    http_response_code(400);
    exit(json_encode(['status' => 'error', 'msg' => 'method parametresi gerekli']));
}

$method = $input['method'];


$logFile = 'response_log.txt';
$logData = "[" . date('Y-m-d H:i:s') . "]\n" . json_encode($input, JSON_PRETTY_PRINT) . "\n\n";
file_put_contents($logFile, $logData, FILE_APPEND);

$stmt_limit = $pdo->prepare("SELECT max_win FROM root_settings WHERE root_id = :root_id");
$stmt_limit->execute([':root_id' => 1]);

$result = $stmt_limit->fetch(PDO::FETCH_ASSOC);

$max_limit = $result['max_win'];



function getUser($pdo, $userCode) {
    $stmt = $pdo->prepare("SELECT user_id, user_balance, user_nick FROM users WHERE user_id = :userCode");
    $stmt->execute([':userCode' => $userCode]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

function updateBalance($pdo, $userId, $newBalance) {
    $stmt = $pdo->prepare("UPDATE users SET user_balance = :balance WHERE user_id = :id");
    $stmt->execute([':balance' => number_format($newBalance, 2, '.', ''), ':id' => $userId]);
}

function logApiResponse($response) {
  //  $logFile = 'response_log.txt';
//    $logData = "[" . date('Y-m-d H:i:s') . "]\n" . json_encode($response, JSON_PRETTY_PRINT) . "\n\n";
  //  file_put_contents($logFile, $logData, FILE_APPEND);
}

class ApiOperator {
    protected $serverUrl;
    protected $token;
    protected $agentCode = "toskabet";  
    protected $userCode;
    protected $nickName;
    protected $vendorCode;
    protected $language = "tr";
    
    public function __construct($serverUrl, $userCode, $token = null, $vendorCode = null) {
    $this->serverUrl = $serverUrl;
    $this->userCode = $userCode;
    $this->token = $token;  
    $this->vendorCode = $vendorCode;
}



    protected function sendPostRequest($data) {
        $url = Utils::buildUrl($this->serverUrl, "api/casinoapi");

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode != 200) {
            error_log("API Hatası: HTTP Kodu $httpCode, Yanıt: $response");
            return null;
        }

        $responseDecoded = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log("JSON Hatası: " . json_last_error_msg());
            return null;
        }

        return $responseDecoded;
    }

    public function getBalance() {
        $data = [
            'method' => 'GetBalance',
            'token' => $this->token,
            'agentCode' => $this->agentCode,
            'userCode' => $this->userCode,
            'nickName' => $this->nickName,
            'vendorCode' => $this->vendorCode,
            'currencyCode' => 'TRY',
            'language' => $this->language,
        ];

        return $this->sendPostRequest($data);
    }

    public function changeBalance($txnType, $txnCode, $wagerId, $amount, $gameRoundId = null) {
        $data = [
            'method' => 'ChangeBalance',
            'token' => $this->token,
            'userCode' => $this->userCode,
            'currencyCode' => 'TRY',
            'vendorCode' => $this->vendorCode,
            'txnType' => $txnType,
            'txnCode' => $txnCode,
            'wagerId' => $wagerId,
            'amount' => $amount,
            'gameRoundId' => $gameRoundId,
        ];

        return $this->sendPostRequest($data);
        
       
        
        
    }

    public function updateDetail($wagerId, $detail) {
        $data = [
            'method' => 'UpdateDetail',
            'token' => $this->token,
            'wagerId' => $wagerId,
            'detail' => $detail,
        ];

        return $this->sendPostRequest($data);
    }
}

class Utils {
    public static function buildUrl(...$urlParts) {
        $result = "";
        foreach ($urlParts as $part) {
            if ($part == null) continue;
            if (strlen($result) > 0) $result .= "/";
            $result .= trim($part, '/');
        }
        return $result;
    }
}

// API işlemleri
switch ($method) {
    case 'GetBalance':
       if (!isset($input['userCode'])) {
    exit(json_encode(['status' => 'error', 'msg' => 'userCode gerekli']));
}

        $user = getUser($pdo, $input['userCode']);
        if (!$user) {
            exit(json_encode(['status' => 'error', 'msg' => 'Kullanıcı bulunamadı']));
        }

        $responseData = [
            'status' => 0,
            'msg' => 'SUCCESS',
            'balance' => $user['user_balance'],
        ];

        logApiResponse($responseData);

        echo json_encode($responseData);
        break;

    case 'ChangeBalance':
        if (!isset($input['userCode'], $input['vendorCode'], $input['amount'], $input['wagerId'], $input['txnCode'], $input['txnType'])) {
            exit(json_encode(['status' => 'error', 'msg' => 'userCode, vendorCode, amount, wagerId, txnCode ve txnType gerekli']));
        }

        $user = getUser($pdo, $input['userCode']);
        if (!$user) {
            exit(json_encode(['status' => 'error', 'msg' => 'Kullanıcı bulunamadı']));
        }

        if ($user['user_balance'] + $input['amount'] >= 0) {
            $newBalance = $user['user_balance'] + $input['amount'];
            updateBalance($pdo, $user['user_id'], $newBalance);

            $responseData = [
                'status' => 0,
                'msg' => 'SUCCESS',
                'balance' => $newBalance,
            ];

            // Bet history kaydı
            $stmt = $pdo->prepare("
                INSERT INTO bet_history
                (
                transaction_id,
                bet_type,
                round_id,
                game_code,
                bet_amount,
                win_amount,
                user_id,
                created_at
                )
                VALUES
                (:transaction_id, 
                'casino', 
                :round_id,
                :game_code,
                :bet_amount,
                :win_amount,
                :user_id,
                NOW())
            ");

            $betAmount = ($input['txnType'] == 0) ? abs($input['amount']) : 0;
            $getAmount = ($input['txnType'] == 1) ? $input['amount'] : 0;

            $stmt->execute([
                ':transaction_id' => $input['txnCode'],
                ':round_id' => $input['wagerId'],
                ':game_code' => $input['gameCode'] ?? 'UNKNOWN',
                ':bet_amount' => $betAmount,
                ':win_amount' => $getAmount,
                ':user_id' => $user['user_id'],
            ]);
            
            
            
      if (isset($input['freeRoundCount'])) {
    $freeRoundCount = $input['freeRoundCount'];
    $fs_user_id = $user['user_id'];  // 'user' dizisini doğru şekilde aldığınızdan emin olun
    $gameCodes = $input['gameCode'];
    $max_status = 0; // 'status' olarak 0'ı kullanıyorsunuz.

    // Freespin tablosunda user_id'ye göre freespin_max güncellenmesi
    $stmt_update = $pdo->prepare("UPDATE user_bonuses_code SET max_limit = :fsmax WHERE user_id = :user_id AND game_name = :game_name AND status = :status");
    $stmt_update->bindParam(':user_id', $fs_user_id);
    $stmt_update->bindParam(':game_name', $gameCodes);
    $stmt_update->bindParam(':status', $max_status);
    $stmt_update->bindParam(':fsmax', $freeRoundCount);
    $stmt_update->execute();

    // Eğer freeRoundCount 0 ise, status'u güncelle
    if ($freeRoundCount == 0) {
        $stmt_status_update = $pdo->prepare("UPDATE user_bonuses_code SET status = '2' WHERE user_id = :user_id AND game_name = :game_name AND status = :status");
        $stmt_status_update->bindParam(':user_id', $fs_user_id); // Doğru user_id'yi kullandık
        $stmt_status_update->bindParam(':game_name', $gameCodes);
        $stmt_status_update->bindParam(':status', $max_status);
        $stmt_status_update->execute();
    }
}
        
        if ((float)$newBalance >= $max_limit) {

    $stmt = $pdo->prepare("
        UPDATE users 
        SET 
            user_bonuses_balance = :bonus,
            user_balance = 0.00
        WHERE user_id = :id
    ");

    $stmt->execute([
        ':bonus' => $max_limit,
        ':id' => $user['user_id']
    ]);
}


        } else {
            $responseData = [
                'status' => 5,
                'msg' => 'Yetersiz bakiye',
            ];
        }

        logApiResponse($responseData);

        echo json_encode($responseData);
        break;

    case 'UpdateDetail':
        if (!isset($input['wagerId'], $input['detail'])) {
            exit(json_encode(['status' => 'error', 'msg' => 'wagerId ve detail gerekli']));
        }

        $serverUrl = "https://api.apigate.network/api/casinoapi";
        $opr = new ApiOperator($serverUrl, $input['userCode'], $input['token']);

        $response = $opr->updateDetail($input['wagerId'], $input['detail']);

        if ($response && isset($response['status']) && $response['status'] == 0) {
            $responseData = [
                'status' => 0,
                'msg' => 'Oyun detayları başarıyla teslim edildi',
            ];
        } else {
            $responseData = [
                'status' => 5,
                'msg' => 'API hatası: ' . ($response['msg'] ?? 'Bilinmeyen hata'),
            ];
        }

        logApiResponse($responseData);

        echo json_encode($responseData);
        break;

    default:
        exit(json_encode(['status' => 'error', 'msg' => 'Geçersiz method: ' . htmlspecialchars($method)]));
}
?>
