<?php
/**
 * API - Create UPI Payment (Enhanced with QR Code & Deep Links)
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit(0); }

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

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';
require_once '../../includes/UpiVerifier.php';
require_once '../../includes/ApiAuth.php';

// Authenticate
$user = ApiAuth::authenticate();
$userId = $user['id'];

// Get UPI settings
$upiId = getSetting('upi_id', 'merchant@upi');
$merchantName = getSetting('upi_merchant_name', 'Merchant');
$minDeposit = (float)getSetting('upi_min_deposit', 100);
$maxDeposit = (float)getSetting('upi_max_deposit', 100000);
$paymentTimeout = (int)getSetting('upi_payment_timeout', 600);
$upiStatus = getSetting('upi_status', 'active');

if ($upiStatus !== 'active') {
    jsonError('UPI payments are currently disabled');
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input) $input = $_POST;

$amount = (float)($input['amount'] ?? 0);

if ($amount < $minDeposit) {
    jsonError('Minimum deposit is ₹' . number_format($minDeposit));
}
if ($amount > $maxDeposit) {
    jsonError('Maximum deposit is ₹' . number_format($maxDeposit));
}

// Check for existing pending payment
$existing = dbFetch(
    "SELECT * FROM upi_payments WHERE user_id = :uid AND status = 'pending' AND expires_at > NOW()",
    ['uid' => $userId]
);

if ($existing) {
    // Return existing payment with QR and deep links
    $upiLink = UpiVerifier::generateUpiLink($upiId, $merchantName, (float)$existing['amount'], $existing['payment_ref']);
    $qrUrl = UpiVerifier::generateQrCodeDataUrl($upiLink);
    $deepLinks = UpiVerifier::getAppDeepLinks($upiLink);
    
    jsonSuccess('Payment already pending', [
        'payment_ref' => $existing['payment_ref'],
        'payment_id' => $existing['id'],
        'amount' => (float)$existing['amount'],
        'upi_id' => $upiId,
        'upi_link' => $upiLink,
        'qr_code_url' => $qrUrl,
        'deep_links' => $deepLinks,
        'expires_in' => max(0, strtotime($existing['expires_at']) - time())
    ]);
}

// Generate unique payment reference
$paymentRef = 'PAY' . $userId . date('ymdHis') . rand(100, 999);

// Generate UPI link and QR
$upiLink = UpiVerifier::generateUpiLink($upiId, $merchantName, $amount, $paymentRef);
$qrUrl = UpiVerifier::generateQrCodeDataUrl($upiLink);
$deepLinks = UpiVerifier::getAppDeepLinks($upiLink);

$ipAddress = ApiAuth::getClientIp();
$deviceInfo = ApiAuth::getDeviceInfo();

try {
    $paymentId = dbInsert('upi_payments', [
        'payment_ref' => $paymentRef,
        'user_id' => $userId,
        'amount' => $amount,
        'upi_id' => $upiId,
        'status' => 'pending',
        'ip_address' => $ipAddress,
        'device_info' => $deviceInfo,
        'expires_at' => date('Y-m-d H:i:s', time() + $paymentTimeout)
    ]);
    
    if ($paymentId) {
        // Calculate potential bonus
        $bonusPercent = 0;
        $bonusAmount = 0;
        $bonusEnabled = getSetting('deposit_bonus_enabled', '0') === '1';
        if ($bonusEnabled) {
            $bonusTier = dbFetch(
                "SELECT * FROM deposit_bonus_tiers WHERE min_amount <= :amt AND status = 'active' ORDER BY min_amount DESC LIMIT 1",
                ['amt' => $amount]
            );
            if ($bonusTier) {
                $bonusPercent = (float)$bonusTier['bonus_percent'];
                $bonusAmount = $amount * ($bonusPercent / 100);
                $maxBonus = (float)getSetting('deposit_bonus_max_bonus', 0);
                if ($maxBonus > 0 && $bonusAmount > $maxBonus) {
                    $bonusAmount = $maxBonus;
                }
            }
        }
        
        ApiAuth::logApiActivity($userId, 'payment_create', "Amount: ₹{$amount}, Ref: {$paymentRef}");
        
        jsonSuccess('Payment created', [
            'payment_ref' => $paymentRef,
            'payment_id' => $paymentId,
            'amount' => $amount,
            'upi_id' => $upiId,
            'merchant_name' => $merchantName,
            'upi_link' => $upiLink,
            'qr_code_url' => $qrUrl,
            'deep_links' => $deepLinks,
            'expires_in' => $paymentTimeout,
            'bonus_percent' => $bonusPercent,
            'bonus_amount' => $bonusAmount
        ]);
    } else {
        jsonError('Failed to create payment');
    }
} catch (Exception $e) {
    error_log("Payment create error: " . $e->getMessage());
    jsonError('Error creating payment');
}
