<?php
// PUBLIC API: GET /api/qr.php?api_key=...&upi=...&amount=...
require_once __DIR__ . '/../includes/functions.php';

$apiKey = $_GET['api_key'] ?? '';
$upi = $_GET['upi'] ?? '';
$amount = $_GET['amount'] ?? '';

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);
}

$expiresAt = strtotime($user['plan_expires_at']);
if ($expiresAt < time()) {
    jsonResponse(['status' => 'expired', 'message' => 'Your plan has expired, please renew.'], 402);
}

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

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

$orderId = generateOrderId('FAMPAY');
$noteCode = generatePaymentNoteCode();
$now = nowIST();
$expiresAtOrder = (clone $now)->modify('+5 minutes');

$order = [
    'order_id' => $orderId,
    'type' => 'api_order',
    'user_id' => $user['id'],
    'upi_id' => $upi,
    'amount' => floatval($amount),
    'note_code' => $noteCode,
    'status' => 'pending',
    'created_at' => $now->format('Y-m-d H:i:s'),
    'created_at_timestamp' => time(),
    'expires_at_timestamp' => time() + 300
];
saveOrder($order);

// 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($noteCode)
    . "&am=" . urlencode($amount)
    . "&cu=INR";

// This local endpoint re-renders the QR with the user's avatar stamped in
// the center (falls back to a plain QR automatically if no avatar is set
// or if the GD extension isn't available on this server).
$qrUrl = getBaseUrl() . '/api/qr_image.php?order_id=' . urlencode($orderId);

jsonResponse([
    'status' => 'success',
    'data' => [
        'order_id' => $orderId,
        'qr_url' => $qrUrl,
        'upi_id' => $upi,
        'amount' => (string)$amount,
        'created_at_ist' => $now->format('d-m-Y H:i:s'),
        'expires_at_ist' => $expiresAtOrder->format('d-m-Y H:i:s'),
        'checkout_url' => getBaseUrl() . '/pay.php?api_key=' . urlencode($apiKey) . '&amount=' . urlencode($amount) . '&name=Store+Checkout',
        'open_in_new_tab' => true
    ]
]);
