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

$api_key = 'mdbpbh91b9i15dde9beee974musGBErKDBItrvCew6yaEMGhnC'; 

session_start();

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    error_log('Connection failed: ' . $e->getMessage());
    exit();
}

$username = $_SESSION['username'];

try {
    $stmt = $pdo->prepare("SELECT id, first_name, surname, username, password, spor_bonus, spor_freebet FROM kullanicilar WHERE username = :username");
    $stmt->execute(['username' => $username]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user) {
        $user_id = $user['id'];
        $adsoyad = $user['first_name'] . ' ' . $user['surname'];
        $username = $user['username']; 
        $password = $user['password']; 

    } else {
        echo json_encode(array("error" => "User not found"));
        exit();
    }
} catch (PDOException $e) {
    error_log('Query failed: ' . $e->getMessage());
    echo json_encode(array("error" => "Database query failed"));
    exit();
}

// Benzersiz transaction hash oluştur
$transhash = uniqid('TRANS_', true);

// Güvenlik hash'ini oluştur
$encryptedhash = sha1(md5($username.$adsoyad.$user_id.$transhash.$api_key));

$data = array(
    "username" => $username,
    "customername" => $adsoyad,
    "userid" => $user_id,
    "transactionhash" => $transhash,
    "apikey" => $api_key,
    "encryptedhash" => $encryptedhash
);

echo "<h3>Gönderilen Veri:</h3>";
echo "<pre>";
print_r($data); 
echo "</pre>";

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://lyizbet.vldbfire.pro/deposit/bank',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json'
    ),
));

$response = curl_exec($curl);

if(curl_errno($curl)) {
    echo json_encode(array("error" => curl_error($curl)));
    curl_close($curl);
    exit();
}

curl_close($curl);

// API yanıtını JSON olarak ayrıştır
$responseData = json_decode($response, true);

// Eğer yanıt başarılıysa ve redirect_url varsa, kullanıcıyı yönlendir
if ($responseData['status'] == '200' && isset($responseData['redirect_url'])) {
    header('Location: ' . $responseData['redirect_url']);
    exit();
} else {
    echo "<h3>API Yanıtı:</h3>";
    echo "<pre>";
    print_r($responseData);
    echo "</pre>";
}
?>
