<?php
// PUBLIC API: GET /api/qr.php?api_key=...&upi=...&amount=...
header('Content-Type: application/json; charset=utf-8');

try {
    require_once __DIR__ . '/../includes/functions.php';

    $apiKey = $_GET['api_key'] ?? '';
    $amount = $_GET['amount'] ?? '';
    $redirectUrl = trim($_GET['redirect_url'] ?? ''); // Optional: where to send user after payment
    $webhookUrl  = trim($_GET['webhook_url']  ?? ''); // Optional: order-level webhook override

    if ($redirectUrl) {
        if (!preg_match('/^https?:\/\//i', $redirectUrl)) {
            jsonResponse(['status' => 'error', 'message' => 'Invalid redirect_url scheme. Only http and https are allowed.'], 400);
        }
    }

    if ($webhookUrl) {
        if (!preg_match('/^https?:\/\//i', $webhookUrl)) {
            jsonResponse(['status' => 'error', 'message' => 'Invalid webhook_url scheme. Only http and https are allowed.'], 400);
        }
    }

    if (!$apiKey) {
        jsonResponse(['status' => 'unauthorized', 'message' => 'Missing api_key'], 401);
    }

    $user = getUserByApiKey($apiKey);
    if (!$user) {
        jsonResponse(['status' => 'unauthorized', 'message' => 'Invalid api_key'], 401);
    }

    if ($user['status'] === 'banned') {
        jsonResponse(['status' => 'suspended', 'message' => 'Account suspended by admin'], 403);
    }

    if (!$amount || !is_numeric($amount)) {
        jsonResponse(['status' => 'error', 'message' => 'Missing or invalid amount parameter'], 400);
    }

    if (!$user['gmail_connected']) {
        jsonResponse(['status' => 'error', 'message' => 'FamPay Gmail not connected. Connect it in your dashboard first.'], 400);
    }
    $upi = $user['fampay_upi_id'];

    // Rate limit removed to provide unlimited API usage for developers

    $orderId = generateOrderId();
    $now = nowIST();
    $expiresAtOrder = (clone $now)->modify('+5 minutes');
    $baseAmount = floatval($amount);

    $db = getDB();
    if (!$db->inTransaction()) {
        $db->beginTransaction();
    }
    try {
        $stmtLock = $db->prepare("SELECT id FROM users WHERE id = ? FOR UPDATE");
        $stmtLock->execute([$user['id']]);

        $payableAmount = getUniquePayableAmount($baseAmount, $user['id']);

        $order = [
            'order_id' => $orderId,
            'type' => 'api_order',
            'user_id' => $user['id'],
            'upi_id' => $upi,
            'amount' => $baseAmount,
            'payable_amount' => $payableAmount,
            'status' => 'pending',
            'created_at' => $now->format('Y-m-d H:i:s'),
            'created_at_timestamp' => time(),
            'expires_at_timestamp' => time() + 300,
            'redirect_url' => $redirectUrl, // Saved for checkout.php to use
            'webhook_url'  => $webhookUrl   // Order-level webhook override
        ];
        saveOrder($order);
        if ($db->inTransaction()) {
            $db->commit();
        }
    } catch (\Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        jsonResponse(['status' => 'error', 'message' => 'Database error generating order.'], 500);
    }

    // Update usage stats
    $user['total_requests'] = ($user['total_requests'] ?? 0) + 1;
    saveUser($user);

    $upiString = "upi://pay?pa=" . urlencode($upi)
        . "&pn=" . urlencode('FamPay')
        . "&tr=" . urlencode($orderId)
        . "&tn=" . urlencode("Payment for Order " . $orderId)
        . "&am=" . urlencode((string)$payableAmount)
        . "&cu=INR";

    $qrUrl = getBaseUrl() . '/api/qr-image.php?order_id=' . urlencode($orderId);
    $checkoutUrl = getBaseUrl() . '/pay.php?order_id=' . urlencode($orderId);

    jsonResponse([
        'status' => 'success',
        'data' => [
            'order_id' => $orderId,
            'qr_url' => $qrUrl,
            'checkout_url' => $checkoutUrl,
            'upi_id' => $upi,
            'amount' => (string)$baseAmount,
            'payable_amount' => (string)$payableAmount,
            'created_at_ist' => $now->format('d-m-Y H:i:s'),
            'expires_at_ist' => $expiresAtOrder->format('d-m-Y H:i:s')
        ]
    ]);

} catch (\Throwable $e) {
    if (function_exists('jsonResponse')) {
        jsonResponse(['status' => 'error', 'message' => 'Server Error: ' . $e->getMessage()], 500);
    } else {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Server Error: ' . $e->getMessage()]);
        exit;
    }
}
