<?php
session_start();
require_once("db.php");

$trxID = $_POST['trxID'];

$sql = "SELECT status, amount, email FROM payment WHERE trxID = :trxID";
$query = $dbh->prepare($sql);
$query->bindParam(':trxID', $trxID);
$query->execute();
$result = $query->fetch(PDO::FETCH_OBJ);

if ($result && $result->status === "approved") {
    // ব্যালেন্স আপডেট করার আগে চেক করুন যেন একবারই হয়
    $checkSql = "SELECT COUNT(*) FROM balance_log WHERE trxID = :trxID";
    $checkQuery = $dbh->prepare($checkSql);
    $checkQuery->bindParam(':trxID', $trxID);
    $checkQuery->execute();
    $exists = $checkQuery->fetchColumn();

    if (!$exists) {
        // আপডেট এবং লগ রাখুন
        $sql = "UPDATE users SET balance = balance + :amount WHERE email = :email";
        $query = $dbh->prepare($sql);
        $query->bindParam(':amount', $result->amount);
        $query->bindParam(':email', $result->email);
        $query->execute();

        // ব্যালেন্স লগ রাখুন
        $logSql = "INSERT INTO balance_log (email, trxID, amount) VALUES (:email, :trxID, :amount)";
        $logQuery = $dbh->prepare($logSql);
        $logQuery->bindParam(':email', $result->email);
        $logQuery->bindParam(':trxID', $trxID);
        $logQuery->bindParam(':amount', $result->amount);
        $logQuery->execute();
    }

    echo "approved";
} else {
    echo "pending";
}
?>
