<?php include ("../serive/samparka.php"); ?>

<?php
// Function to log errors
function logError($message) {
    file_put_contents('bsdpay.txt', date('Y-m-d H:i:s') . " - " . $message . "\n", FILE_APPEND);
}

// Log the callback data for debugging
logError("Received data: " . print_r($_POST, true));

// Load the configuration
$config = require 'config.php';

// Unified input parser (POST, GET, JSON)
$input = $_POST;
if (empty($input)) {
    $input = $_GET;
}
if (empty($input)) {
    $raw = file_get_contents('php://input');
    $json = json_decode($raw, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        $input = $json;
    }
}

// Validate required fields
$money = isset($input['amount']) ? $input['amount'] : '';
$order_sn = isset($input['merchantorder']) ? $input['merchantorder'] : '';
$remark = isset($input['proof']) ? $input['proof'] : '';

if (empty($money) || empty($order_sn)) {
    http_response_code(400);
    die("Missing required fields");
}






// Order processing logic
$mchOrderNo = $order_sn;

// Check if the order exists and is not already processed (status = 0)
$checkamt = mysqli_query($conn, "SELECT motta, balakedara FROM thevani WHERE dharavahi = '".$mchOrderNo."' AND sthiti = '0'");

if (!$checkamt) {
    logError("Database query error: " . mysqli_error($conn));
    echo json_encode([
        "message" => "fail(database error)",
        "status" => false,
    ]);
    exit;
}

$checkamtrow = mysqli_num_rows($checkamt);

if ($checkamtrow >= 1) {
    $checkamtar = mysqli_fetch_array($checkamt);
    $motta = $checkamtar['motta'];
    $shonuid = $checkamtar['balakedara'];

    // Update the user's balance
    $nabikarana = "UPDATE shonu_kaichila
                   SET motta = ROUND(motta + '".$motta."', 2)
                   WHERE balakedara = '".$shonuid."'";
    
    if (!$conn->query($nabikarana)) {
        logError("Database update error: " . mysqli_error($conn));
        echo json_encode([
            "message" => "fail(update error)",
            "status" => false,
        ]);
        exit;
    }

    // Update the order status to processed (status = 1)
    $sql2 = mysqli_query($conn, "UPDATE thevani SET sthiti = '1' WHERE dharavahi = '".$mchOrderNo."'");

    if (!$sql2) {
        logError("Database update error: " . mysqli_error($conn));
        echo json_encode([
            "message" => "fail(update error)",
            "status" => false,
        ]);
        exit;
    }
} else {
    echo "ok"; // Response back to the webhook
exit;
}

echo "ok"; // Response back to the webhook
exit;
?>
