<?php
declare(strict_types=1);

session_start();
require_once '../config.php';
$conn = getDBConnection();

header('Content-Type: application/json');
ini_set('display_errors', '0');
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'failed', 'receipt_number' => '']);
    exit;
}

$paymentId = isset($_POST['payment_id']) && ctype_digit((string) $_POST['payment_id']) ? (int) $_POST['payment_id'] : 0;
if ($paymentId <= 0) {
    echo json_encode(['status' => 'failed', 'receipt_number' => '']);
    exit;
}

if (!$conn) {
    echo json_encode(['status' => 'failed', 'receipt_number' => '']);
    exit;
}

$stmt = $conn->prepare("SELECT status, receipt_number FROM online_payments WHERE id = ? LIMIT 1");
$stmt->bind_param('i', $paymentId);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$stmt->close();

if (!$row) {
    echo json_encode(['status' => 'failed', 'receipt_number' => '']);
    exit;
}

echo json_encode([
    'status' => $row['status'],
    'receipt_number' => $row['receipt_number'] ?? ''
]);
