<?php
// PUBLIC endpoint - no login required. Powers the demo.php test-payment page.
require_once __DIR__ . '/../includes/functions.php';

$amount = floatval($_POST['amount'] ?? 0);
if ($amount <= 0) {
    jsonResponse(['status' => 'error', 'message' => 'Invalid amount']);
}

$adminSettings = getAdminSettings();
if (empty($adminSettings['upi_id'])) {
    jsonResponse(['status' => 'error', 'message' => 'Demo payments are temporarily unavailable. Please contact support.']);
}

$orderId = generateOrderId('DEMO');
$noteCode = generatePaymentNoteCode();

$order = [
    'order_id' => $orderId,
    'type' => 'demo_test',
    'user_id' => '', // no account involved - public demo
    'amount' => $amount,
    'upi_id' => $adminSettings['upi_id'],
    'note_code' => $noteCode,
    'status' => 'pending',
    'created_at' => nowIST()->format('Y-m-d H:i:s'),
    'created_at_timestamp' => time()
];
saveOrder($order);

$upiString = "upi://pay?pa=" . urlencode($adminSettings['upi_id'])
    . "&pn=" . urlencode('FamAPI Demo')
    . "&tr=" . urlencode($orderId)
    . "&tn=" . urlencode($noteCode)
    . "&am=" . urlencode((string) $amount)
    . "&cu=INR";

$qrUrl = "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=" . urlencode($upiString);

jsonResponse([
    'status' => 'success',
    'data' => [
        'order_id' => $orderId,
        'qr_url' => $qrUrl,
        'amount' => $amount
    ]
]);
