<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
include('config.php'); // Include database connection
require_once('lib/Config_RechPay.php');
require_once('lib/RechPayChecksum.php');

$Server = $_SERVER['SERVER_NAME'];
// Example output: localhost ya domain name

//$logFile = 'payment_log.txt';

// Logging Function
function logMessage($message) {
    global $logFile;
    $timestamp = date("Y-m-d H:i:s");
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND | LOCK_EX);
}

//logMessage("Payment processing started");

$secret = 'z00O2QH3aC'; // Your secret key.
$key = 'd61d49-db8c01-d54fab-ad282b-0df7fb'; // API key or token

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $status = $_POST['status'] ?? '';
    $hash = $_POST['hash'] ?? '';

    if ($status === 'SUCCESS') {
        // logMessage("Received SUCCESS status");

        try {
            $encoded = hash_decrypt($hash, $secret);
            $pdata = json_decode($encoded, true);

            // logMessage("Decoded payment data: " . json_encode($pdata, JSON_PRETTY_PRINT));

            $txnStatus = $pdata['txnStatus'] ?? '';
            $payeeVpa = $pdata['payee_vpa'] ?? '';
            $amt = $pdata['txnAmount'] ?? 0;
            $userid = $pdata['sender_note'] ?? '';
            $txn_id = $pdata['txnId'] ?? '';
            $utr_number = $pdata['utr'] ?? '';
            $orderId = $pdata['orderId'] ?? '';

            $sql = "SELECT * FROM users WHERE id = $userid";
            $result = $connection->query($sql);
            $row = $result->fetch_assoc();  // Fetch the row correctly
           

            if ($txnStatus === "TXN_SUCCESS" && $payeeVpa) {
                // logMessage("Transaction successful for user ID: $userid, amount: $amt");

                // Get the updated balance
                $stmt = $connection->prepare("SELECT balance FROM users WHERE id = ?");
                $stmt->bind_param("d", $userid);
                $stmt->execute();
                $stmt->bind_result($wallet_balance);
                $stmt->fetch();
                $stmt->close();

                $new_balance = $wallet_balance + $amt;

                // Update the reports table with the new balance (Use prepared statement)
                $stmt = $connection->prepare("UPDATE wallethistory 
                                              SET txn_id = ?, 
                                                  ref_id = ?, 
                                                  balance = ?, 
                                                  new_balance=?,
                                                  status = '1' 
                                              WHERE orderid = ?");
                $stmt->bind_param("ssdss", $txn_id, $utr_number, $new_balance, $wallet_balance,$orderId);

                if ($stmt->execute()) {
                    // logMessage("Record updated successfully for order ID: $orderId");
                } else {
                    // logMessage("Error updating record for order ID: $orderId: " . $stmt->error);
                }

                // Update wallet balance (Use prepared statement)
                $stmt = $connection->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                $stmt->bind_param("ds", $amt, $userid);

                if ($stmt->execute()) {
                    // logMessage("Wallet updated successfully for user ID: $userid");

                    // Redirect to success page
                    header("Location: https://www.hargharrojgar.in/new/addmoney.php?txn_status=TXN_Success");
                    exit;
                } else {
                    // logMessage("Failed to update wallet for user ID: $userid: " . $stmt->error);
                    header("Location: https://www.hargharrojgar.in/new/addmoney.php?txn_status=TXN_FAILED");
                    exit;
                }

                $stmt->close();
            } else {
                // logMessage("Transaction failed or invalid UPI ID");
                header("Location: https://www.hargharrojgar.in/new/addmoney.php?txn_status=TXN_FAILED");
                exit;
            }
        } catch (Exception $e) {
            // logMessage("Error processing payment: " . $e->getMessage());
            header("Location: https://www.hargharrojgar.in/new/addmoney.php?txn_status=ERROR");
            exit;
        }
    } else {
        // logMessage("Invalid status received: $status");
        header("Location: https://www.hargharrojgar.in/new/addmoney.php?txn_status=INVALID_STATUS");
        exit;
    }
} else {
    // logMessage("Invalid request method");
    http_response_code(405); // Method Not Allowed
    exit;
}
?>
