<?php
// PUBLIC API: GET /api/verify_order.php?api_key=...&order_id=...
// NOTE: stays GET intentionally — this is a documented public endpoint that
// external developers already call as a GET request per docs.php. Changing
// it to POST-only would break every existing integration.
require_once __DIR__ . '/../includes/functions.php';

$apiKey = $_GET['api_key'] ?? '';
$orderId = $_GET['order_id'] ?? '';

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 (!$orderId) {
    jsonResponse(['status' => 'error', 'message' => 'Missing order_id'], 400);
}

$order = getOrderById($orderId);
if (!$order || $order['user_id'] !== $user['id']) {
    jsonResponse(['status' => 'not_found', 'message' => 'Order ID not found'], 404);
}

// If already confirmed previously, just return cached result
if ($order['status'] === 'success') {
    jsonResponse([
        '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'] ?? ''
        ]
    ]);
}

// Check order expiry (5 minute timeout as per docs)
if (isset($order['expires_at_timestamp']) && time() > $order['expires_at_timestamp']) {
    updateOrder($orderId, ['status' => 'expired']);
    jsonResponse(['status' => 'expired', 'message' => 'Order expired (5 min timeout)'], 408);
}

if (!$user['gmail_connected']) {
    jsonResponse(['status' => 'error', 'message' => 'FamPay Gmail not connected'], 500);
}

$appPassword = decryptData($user['fampay_app_password_encrypted']);
$result = checkFamAppInboxForPayment(
    $user['fampay_gmail'],
    $appPassword,
    $order['amount'],
    $order['created_at_timestamp'],
    $order['note_code'] ?? null
);

if ($result['status'] === 'success') {
    $paymentTimeIst = date('d-m-Y H:i:s', $result['payment_timestamp'] ?: time());

    updateOrder($orderId, [
        'status' => 'success',
        'transaction_id' => $result['transaction_id'],
        'utr' => $result['utr'],
        'sender_name' => $result['sender_name'],
        'payment_time_ist' => $paymentTimeIst
    ]);

    // Update user stats
    $user['total_success'] = ($user['total_success'] ?? 0) + 1;
    $user['total_amount_received'] = ($user['total_amount_received'] ?? 0) + $result['amount'];
    saveUser($user);

    jsonResponse([
        'status' => 'success',
        'data' => [
            'order_id' => $order['order_id'],
            'transaction_id' => $result['transaction_id'],
            'amount' => $result['amount'],
            'utr' => $result['utr'],
            'sender_name' => $result['sender_name'],
            'payment_time_ist' => $paymentTimeIst
        ]
    ]);
} elseif ($result['status'] === 'error') {
    jsonResponse(['status' => 'error', 'message' => $result['message']], 500);
} else {
    jsonResponse(['status' => 'pending', 'message' => 'Payment not received yet']);
}
