<?php
// PUBLIC endpoint - no login required. Polled from demo.php.
require_once __DIR__ . '/../includes/functions.php';

function demoSuccessData($order) {
    return [
        'status' => 'success',
        'data' => [
            'order_id' => $order['order_id'],
            'transaction_id' => $order['transaction_id'] ?? '',
            'amount' => $order['amount'],
            'utr' => $order['utr'] ?? '',
            'sender_name' => $order['sender_name'] ?? '',
            'payment_time_ist' => $order['payment_time_ist'] ?? ''
        ]
    ];
}

$orderId = $_POST['order_id'] ?? '';
$order = getOrderById($orderId);

if (!$order || ($order['type'] ?? '') !== 'demo_test') {
    jsonResponse(['status' => 'error', 'message' => 'Order not found']);
}

if ($order['status'] === 'success') {
    jsonResponse(demoSuccessData($order));
}

$adminSettings = getAdminSettings();
if (empty($adminSettings['gmail_id'])) {
    jsonResponse(['status' => 'error', 'message' => 'Admin Gmail not configured. Contact support.']);
}

$appPassword = decryptData($adminSettings['app_password_encrypted']);
$result = checkFamAppInboxForPayment(
    $adminSettings['gmail_id'],
    $appPassword,
    $order['amount'],
    $order['created_at_timestamp'],
    $order['note_code'] ?? null
);

if ($result['status'] === 'success') {
    updateOrder($orderId, [
        'status' => 'success',
        'transaction_id' => $result['transaction_id'] ?? '',
        'utr' => $result['utr'] ?? '',
        'sender_name' => $result['sender_name'] ?? '',
        'payment_time_ist' => date('d-m-Y H:i:s', $result['payment_timestamp'] ?: time())
    ]);
    $order['transaction_id'] = $result['transaction_id'] ?? '';
    $order['utr'] = $result['utr'] ?? '';
    $order['sender_name'] = $result['sender_name'] ?? '';
    $order['payment_time_ist'] = date('d-m-Y H:i:s', $result['payment_timestamp'] ?: time());
    jsonResponse(demoSuccessData($order));
} elseif ($result['status'] === 'error') {
    jsonResponse(['status' => 'error', 'message' => $result['message']]);
} else {
    jsonResponse(['status' => 'pending', 'message' => 'Payment not received yet']);
}