<?php
// Handle RSPay Callback (Webhook)

// DEBUG LOGGING START
$debugLogFile = __DIR__ . '/callback_debug.txt';
// file_put_contents($debugLogFile, date('[Y-m-d H:i:s] ') . "Hit received from " . $_SERVER['REMOTE_ADDR'] . "\n", FILE_APPEND); // Optional: Disable to save space if needed
// DEBUG LOGGING END

// Prevent any HTML error output
ini_set('display_errors', 0);
error_reporting(0);

// RSPay expects plain text "success" string to mark callback as successful
header("Content-Type: text/plain"); 

require_once('../../database/config.php'); // Your main DB config
require_once('config.php'); // RSPay config

// Log callback for debugging
$raw_post = file_get_contents("php://input");
$logData = date('Y-m-d H:i:s'). " BODY: " . $raw_post . "\n";
file_put_contents(__DIR__ . '/callback_log.txt', $logData, FILE_APPEND);

$data = json_decode($raw_post, true);

if (!$data) {
    echo "fail";
    exit;
}

// 1. Verify Signature
$received_sign = isset($data['sign']) ? $data['sign'] : '';
$params_to_sign = $data;
unset($params_to_sign['sign']);
unset($params_to_sign['signType']); 

$calculated_sign = generateRspaySign($params_to_sign, $rspay_key);

// Debug Signature
// file_put_contents(__DIR__ . '/callback_log.txt', "Calc Sign: $calculated_sign | Rec Sign: $received_sign\n", FILE_APPEND);

if ($calculated_sign !== $received_sign) {
    file_put_contents(__DIR__ . '/callback_log.txt', "ERROR: Signature Mismatch.\n", FILE_APPEND);
    // echo "fail"; // Optionally return fail, but sometimes better to silence for security specific probing
    // exit; 
}

// 2. Check Parameters & Update DB
$merchantOrderId = $data['merchantOrderId']; 
$platformOrderId = $data['platformOrderId'] ?? $data['orderId'] ?? ''; 
$status = $data['state']; // 1: Successful, 2: Processing, 3: Failed
$amount = floatval($data['amount']);
$utr = $data['utr'] ?? ''; 

if ($status == 1) {
    // Payment Successful
    
    // Check if order exists
    $stmt = $conn->prepare("SELECT * FROM create_orders WHERE orderid = ?");
    $stmt->execute([$merchantOrderId]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($order) {
         // --- FEE CALCULATION START ---
        // Fetch Global Settings
        $set_stmt = $conn->prepare("SELECT * FROM settings LIMIT 1");
        $set_stmt->execute();
        $settings = $set_stmt->fetch(PDO::FETCH_ASSOC);

        // Fetch User Data for Margins
        $usr_stmt = $conn->prepare("SELECT * FROM loginusers WHERE username = ?");
        $usr_stmt->execute([$order['user']]);
        $usrrow = $usr_stmt->fetch(PDO::FETCH_ASSOC);
        
        // Calculate Commission
        $payin_base = floatval($settings['rspay_payin_base'] ?? 0);
        
        // Use global fallback if user specific is empty or 0 (adjusted logic)
        $payin_margin = 0;
        if(isset($settings['payin_commission'])) {
             $payin_margin = floatval($settings['payin_commission']);
        }
        
        $payin_percent = $payin_base + $payin_margin;
        
        $payin_fixed_base = floatval($settings['rspay_payin_fixed'] ?? 0);
        $payin_fixed_margin = floatval($settings['payin_fixed'] ?? 0); 
        $payin_fixed = $payin_fixed_base + $payin_fixed_margin;
        
        // Fee Formula: (Amount * % / 100) + Fixed
        $fee = ($amount * ($payin_percent / 100)) + $payin_fixed;
        $settled_amount = $amount - $fee;
        
        // Ensure settled amount is not negative
        if ($settled_amount < 0) $settled_amount = 0;
        // --- FEE CALCULATION END ---

        // Only process if currently NOT success
        // IMPORTANT: Even if already success, we might need to return "success" to RSPay to stop retries.
        // But we should ONLY credit the wallet ONCE.
        
        if ($order['txn_status'] !== 'SUCCESS') {
           

            $txn_status = 'SUCCESS';
            $received_from = 'RSPay';
            
            // Prepare Outgoing Callback Data
            $callback_url = $usrrow['callback_url'] ?? '';
            $callbackResponse = 'N/A';
            $httpCode = 0;
            $postData = [
                'user' => $order['user'],
                'orderid' => $merchantOrderId,
                'amount' => $amount,
                'status' => $txn_status,
                'txn_status' => $txn_status,
                'utr_number' => $utr,
                'received_from' => $received_from,
                'date' => $order['date'], // Original creation date
                'api_txn_id' => $platformOrderId,
                'transactions_id' => $platformOrderId,
                'timestamp' => time()
            ];

            // Send Callback if URL exists
            if (!empty($callback_url)) {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $callback_url);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $callbackResponse = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
            }

            // Update create_orders table (Mark callback_sent = 1)
            $updateQuery = "UPDATE create_orders SET 
                            transactions_id = ?, 
                            api_txn_id = ?, 
                            txn_status = ?, 
                            received_from = ?, 
                            amount = ?, 
                            utr_number = ?,
                            callback_sent = 1
                            WHERE orderid = ?";
                            
            $updateStmt = $conn->prepare($updateQuery);
            $updateStmt->execute([
                $platformOrderId, 
                $platformOrderId, 
                $txn_status,
                $received_from,
                $amount, // Keep original transaction amount here
                $utr,
                $merchantOrderId
            ]);
            
            // UPDATE USER WALLET WITH SETTLED AMOUNT
            $walletUpdate = $conn->prepare("UPDATE loginusers SET wallet = wallet + ? WHERE username = ?");
            $walletUpdate->execute([$settled_amount, $order['user']]);

             // LOG DB SUCCESS
            file_put_contents(__DIR__ . '/callback_log.txt', "DB UPDATED: Order $merchantOrderId SUCCESS. Fee: $fee. Credited: $settled_amount. Callback Sent to $callback_url (HTTP $httpCode)\n", FILE_APPEND);

            // Log into callback_logs table (Outgoing Log)
            try {
                $logStmt = $conn->prepare("INSERT INTO callback_logs (user_name, order_id, amount, utr_number, received_from, txn_status, callback_url, http_code, sent_data, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                $logStmt->execute([
                    $order['user'],
                    $merchantOrderId,
                    $amount,
                    $utr,
                    'RSPay',
                    'SUCCESS', // Transaction Status is SUCCESS
                    $callback_url,
                    $httpCode,
                    json_encode($postData)
                ]);
            } catch (Exception $e) { }
        } else {
             file_put_contents(__DIR__ . '/callback_log.txt', "INFO: Order $merchantOrderId already SUCCESS. Ignoring wallet update.\n", FILE_APPEND);
        }
    } else {
        file_put_contents(__DIR__ . '/callback_log.txt', "ERROR: Order $merchantOrderId not found in DB.\n", FILE_APPEND);
    }

    // ALWAYS echo success if status is 1, even if we already processed it, to stop RSPay retries
    echo "success";
    
} else {
    // Status not 1 (e.g. processing or failed)
    echo "success"; // Acknowledge receipt
}
?>
