<?php
// Enforce temporary error trapping to catch hidden query crashes
error_reporting(E_ALL);
ini_set('display_errors', 1); 

ob_start();
if (session_status() === PHP_SESSION_NONE) { 
    session_start(); 
}

// Incorporate parent Titan framework system rules
require_once('../../titancore/titanconfig.php');
require_once('lib/Config_RechPay.php');
require_once('lib/RechPayChecksum.php');

// Simple file logging function to trace what data arrives
function writeGatewayLog($msg) {
    $logFile = __DIR__ . '/gateway_debug.log';
    $timestamp = date("Y-m-d H:i:s");
    file_put_contents($logFile, "[$timestamp] $msg\n", FILE_APPEND | LOCK_EX);
}

// Capture incoming raw requests to ensure the gateway is actually hitting this page
writeGatewayLog("Callback URL accessed via method: " . $_SERVER['REQUEST_METHOD']);

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$baseUrl = $protocol . $_SERVER['SERVER_NAME'];

$secret = 'Xft2ConEj6'; 
$key = 'ae91cf-4da9be-8d9126-52175c-53bc98'; 

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

    writeGatewayLog("Initial Payload - Status received: '$status', Hash empty? " . (empty($hash) ? 'YES' : 'NO'));

    if (strtoupper($status) === 'SUCCESS') {
        try {
            $encoded = hash_decrypt($hash, $secret);
            $pdata = json_decode($encoded, true);

            if (!$pdata) {
                writeGatewayLog("CRITICAL ERROR: Failed to decrypt hash or decode payload JSON string.");
                die("Decryption Failure.");
            }

            // Extract values directly from decrypted data array
            $txnStatus  = $pdata['txnStatus'] ?? '';
            $payeeVpa   = $pdata['payee_vpa'] ?? '';
            $amt        = floatval($pdata['txnAmount'] ?? 0);
            $userid     = trim($pdata['sender_note'] ?? ''); // Contains numeric primary user id (e.g., 5)
            $txn_id     = trim($pdata['txnId'] ?? '');
            $utr_number = trim($pdata['utr'] ?? '');
            $orderId    = trim($pdata['orderId'] ?? '');

            writeGatewayLog("Decoded Payload Content: Order ID: $orderId, Txn Status: $txnStatus, Amount: $amt, Target User ID: $userid");

            if ($txnStatus === "TXN_SUCCESS") {
                
                // Clean input variables strictly before processing SQL execution
                $userid_clean  = $conn->real_escape_string($userid);
                $txn_id_clean  = $conn->real_escape_string($txn_id);
                $utr_clean     = $conn->real_escape_string($utr_number);
                $orderId_clean = $conn->real_escape_string($orderId);

                // Check profile context matching directly against user ID
                $user_q = $conn->query("SELECT wallet FROM users WHERE id = '$userid_clean' LIMIT 1");
                
                if ($user_q && $user_q->num_rows > 0) {
                    $u_row = $user_q->fetch_assoc();
                    $wallet_balance = floatval($u_row['wallet']);
                    $new_balance = $wallet_balance + $amt;

                    writeGatewayLog("User account matched. Existing balance: $wallet_balance. Calculated target new balance: $new_balance");

                    // 1. UPDATE TRANSACTION LEDGER STATUS (Change status from '0' to '1')
                    // Note: Removed user matching conditions here to bypass potential mobile/ID string column mismatches. 
                    // Matching strictly against the unique orderid ensures it updates accurately.
                    $upd_history = $conn->query("UPDATE `wallethistory` 
                                                 SET `txn_id` = '$txn_id_clean', 
                                                     `ref_id` = '$utr_clean', 
                                                     `balance` = '$wallet_balance', 
                                                     `new_balance` = '$new_balance', 
                                                     `status` = '1' 
                                                 WHERE `orderid` = '$orderId_clean'");
                    
                    $history_affected = $conn->affected_rows;
                    writeGatewayLog("Wallet history status execution status: " . ($upd_history ? "SUCCESS" : "FAILED") . " | Rows affected: $history_affected");

                    // 2. INJECT LIQUIDITY CREDITS INTO USER'S MAIN WALLET BALANCE
                    $upd_wallet = $conn->query("UPDATE `users` SET `wallet` = `wallet` + $amt WHERE `id` = '$userid_clean'");
                    $wallet_affected = $conn->affected_rows;
                    writeGatewayLog("User main wallet update status: " . ($upd_wallet ? "SUCCESS" : "FAILED") . " | Rows affected: $wallet_affected");

                    if ($upd_history && $upd_wallet) {
                        writeGatewayLog("All changes updated successfully. Triggering dashboard redirect.");
                        header("Location: " . $baseUrl . "/dashboard/add.php?txn_status=TXN_Success");
                        exit;
                    } else {
                        writeGatewayLog("SQL Execution Error Info: " . $conn->error);
                        header("Location: " . $baseUrl . "/dashboard/add.php?txn_status=TXN_FAILED");
                        exit;
                    }
                } else {
                    writeGatewayLog("DATABASE MISMATCH: No user accounts found matching user ID '$userid_clean'. Check your primary key values.");
                    header("Location: " . $baseUrl . "/dashboard/add.php?txn_status=USER_NOT_FOUND");
                    exit;
                }
            } else {
                writeGatewayLog("TRANSACTION FAILURE: Gateway payload returned status: '$txnStatus'");
                header("Location: " . $baseUrl . "/dashboard/add.php?txn_status=TXN_FAILED");
                exit;
            }
        } catch (Exception $e) {
            writeGatewayLog("SYSTEM CRASH TRAPPED: " . $e->getMessage());
            header("Location: " . $baseUrl . "/dashboard/add.php?txn_status=ERROR");
            exit;
        }
    } else {
        writeGatewayLog("INVALID STATUS CALLBACK RECEIVED: status factor was '$status'");
        header("Location: " . $baseUrl . "/dashboard/add.php?txn_status=INVALID_STATUS");
        exit;
    }
} else {
    writeGatewayLog("METHOD REJECTED: Request did not drop via expected POST conditions.");
    http_response_code(405);
    exit;
}
?>