<?php
/**
 * Bank UPI Payment Handler
 * This file handles payments using the UPI pool system
 * Integrated into payment.php
 */

require_once('../database/config.php');
require_once('../database/UpiPoolManager.php');

$upiManager = new UpiPoolManager($conn);
$settings = $upiManager->getGatewaySettings();

// Check which gateway to use
$use_bank_upi = false;

if ($settings['default_gateway'] == 'bank_upi') {
    $use_bank_upi = true;
} elseif ($settings['default_gateway'] == 'auto') {
    // Smart selection logic - use bank UPI for smaller amounts
    if ($amount < 5000) {
        $use_bank_upi = true;
    }
}

if ($use_bank_upi) {
    // Use Bank UPI System
    $upi_data = $upiManager->getNextUPI();
    
    if ($upi_data) {
        // Log UPI assignment
        $upiManager->logUPIAssignment($upi_data['upi_id'], $orderid, $amount);
        
        // Calculate commission
        $commission_percent = $settings['bank_upi_commission'];
        $fixed_fee = $settings['bank_upi_fixed'];
        $commission = ($amount * $commission_percent / 100) + $fixed_fee;
        
        // Generate UPI payment URL
        $upi_url = 'upi://pay?pa=' . urlencode($upi_data['upi_id']) .
                   '&pn=' . urlencode($customer_name) .
                   '&am=' . urlencode($amount) .
                   '&tid=' . urlencode($orderid) .
                   '&tr=' . urlencode($orderid) .
                   '&tn=' . urlencode('Payment for ' . $orderid) .
                   '&cu=INR';
        
        // Generate QR code
        $qr_code_url = 'https://qr-generator.developer-dhanyainfotech.workers.dev/?upi_id=' . 
                       urlencode($upi_data['upi_id']) . 
                       '&customer_name=' . urlencode($customer_name) . 
                       '&amount=' . urlencode($amount) . 
                       '&orderid=' . urlencode($orderid);
        
        $res = [
            "status" => "SUCCESS",
            "message" => "Payment link generated",
            "orderid" => $orderid,
            "amount" => $amount,
            "customer_name" => $customer_name,
            "merchant_name" => "Bank UPI",
            "upi_id" => $upi_data['upi_id'],
            "upi_name" => $upi_data['upi_name'],
            "payment_link" => $upi_url,
            "qr_code" => $qr_code_url,
            "expiration_time" => date('Y-m-d H:i:s', $token_data['expiration_time']),
            "gateway" => "bank_upi",
            "commission" => $commission,
            "is_hdfc" => false
        ];
        
        // Update order with UPI details
        $stmt = $conn->prepare("UPDATE create_orders SET upi_id = ?, merchant_name = 'Bank UPI' WHERE orderid = ?");
        $stmt->execute([$upi_data['upi_id'], $orderid]);
        
    } else {
        // No UPI available, fallback to RSPay
        $res = [
            "status" => "FAILED",
            "message" => "No UPI available at the moment. Please try again later.",
            "expiration_time" => date('Y-m-d H:i:s', $token_data['expiration_time'])
        ];
    }
} else {
    // Use RSPay (existing code continues here)
    // This is handled in the main payment.php file
}
?>
