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

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());
    http_response_code(500);
    die(json_encode(['status' => '500', 'message' => 'Database connection failed']));
}

// JSON verisini al
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Gerekli alanların kontrolü
if (!isset($data['status']) || !isset($data['token']) || !isset($data['amount']) || 
    !isset($data['username']) || !isset($data['userid']) || !isset($data['type']) || 
    !isset($data['customer_transaction_id'])) {
    die(json_encode(['status' => '303'])); // Incomplete post data
}

// Verileri değişkenlere ata
$status = $data['status'];
$amount = $data['amount'];
$userid = $data['userid'];
$transaction_id = $data['customer_transaction_id'];
$username = $data['username'];
$type = $data['type'];
$received_token = $data['token'];

// Token doğrulama
$calculated_token = sha1(md5($status.$amount.$userid.$transaction_id));
if ($calculated_token !== $received_token) {
    die(json_encode(['status' => '301'])); // Incorrect token information
}

// İşlemin daha önce işlenip işlenmediğini kontrol et
try {
    $stmt = $pdo->prepare("SELECT id FROM payment_callbacks WHERE transaction_id = ?");
    $stmt->execute([$transaction_id]);
    if ($stmt->rowCount() > 0) {
        die(json_encode(['status' => '300'])); // Callback already sent previously
    }
} catch (PDOException $e) {
    error_log('Query failed: ' . $e->getMessage());
    http_response_code(500);
    die(json_encode(['status' => '500', 'message' => 'Database query failed']));
}

// İşlem başarılı ise kullanıcının bakiyesini güncelle
if ($status === 'confirmed') {
    try {
        $pdo->beginTransaction();

        // Callback kaydını ekle
        $stmt = $pdo->prepare("INSERT INTO payment_callbacks (transaction_id, user_id, amount, status, type, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
        $stmt->execute([$transaction_id, $userid, $amount, $status, $type]);

        // Kullanıcının ana_bakiye'sini güncelle
        $stmt = $pdo->prepare("UPDATE kullanicilar SET ana_bakiye = ana_bakiye + ? WHERE id = ?");
        $stmt->execute([$amount, $userid]);

        // İşlem geçmişini kaydet
        $stmt = $pdo->prepare("INSERT INTO transaction_history (user_id, amount, type, status, transaction_id, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
        $stmt->execute([$userid, $amount, 'deposit', 'success', $transaction_id]);

        $pdo->commit();
        echo json_encode(['status' => '200']); // Başarılı
    } catch (PDOException $e) {
        $pdo->rollBack();
        error_log('Transaction failed: ' . $e->getMessage());
        http_response_code(500);
        die(json_encode(['status' => '500', 'message' => 'Transaction failed']));
    }
} elseif ($status === 'declined') {
    try {
        // Reddedilen işlemi kaydet
        $stmt = $pdo->prepare("INSERT INTO payment_callbacks (transaction_id, user_id, amount, status, type, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
        $stmt->execute([$transaction_id, $userid, $amount, $status, $type]);

        // İşlem geçmişini kaydet
        $stmt = $pdo->prepare("INSERT INTO transaction_history (user_id, amount, type, status, transaction_id, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
        $stmt->execute([$userid, $amount, 'deposit', 'declined', $transaction_id]);

        echo json_encode(['status' => '200']); // İşlem başarıyla kaydedildi
    } catch (PDOException $e) {
        error_log('Query failed: ' . $e->getMessage());
        http_response_code(500);
        die(json_encode(['status' => '500', 'message' => 'Database query failed']));
    }
} else {
    die(json_encode(['status' => '302'])); // Incorrect transaction_id or invalid status
}
?> 