<?php
/**
 * API - Check Payment Status
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Start session if not started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';

if (!auth()->isUserLoggedIn()) {
    jsonError('Unauthorized', 401);
}

$userId = auth()->getUserId();
$ref = $_GET['ref'] ?? '';

if (empty($ref)) {
    jsonError('Payment reference required');
}

// Get payment record
$payment = dbFetch(
    "SELECT * FROM upi_payments WHERE payment_ref = :ref AND user_id = :uid",
    ['ref' => $ref, 'uid' => $userId]
);

if (!$payment) {
    jsonError('Payment not found');
}

// Get user balance if completed
$newBalance = 0;
if ($payment['status'] === 'completed') {
    $wallet = dbFetch("SELECT balance FROM user_wallets WHERE user_id = :uid", ['uid' => $userId]);
    $newBalance = $wallet['balance'] ?? 0;
}

// Return current status
jsonSuccess('Payment status', [
    'status' => $payment['status'],
    'amount' => $payment['amount'],
    'new_balance' => $newBalance
]);
