<?php
require "config.php";

// Pega UUID da query string
$uuid = isset($_GET['uuid']) ? $_GET['uuid'] : null;

if (!$uuid) {
    http_response_code(400);
//    echo json_encode(['error' => 'UUID não fornecido']);
	include __DIR__ . '/errordocument/400.php';
    exit;
}

// Busca no banco
$stmt = $pdo->prepare("SELECT status, expire FROM payments WHERE uuid = ?");
$stmt->execute([$uuid]);
$payment = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$payment) {
    http_response_code(404);
//    echo json_encode(['error' => 'Pagamento não encontrado']);
	include __DIR__ . '/errordocument/404.php';
    exit;
}

$statusNumeric = $payment['status'];
$expire = $payment['expire'];

// Ajuste timezone
date_default_timezone_set('America/Sao_Paulo');
$now = new DateTime();
$expireDate = DateTime::createFromFormat('Y-m-d H:i:s', $expire);
$isExpired = $expireDate && $now > $expireDate;

$status = '';
switch ($statusNumeric) {
    case 0: $status = 'pending'; break;
    case 1: $status = 'completed'; break;
    case 2: $status = 'canceled'; break;
    default: $status = 'unknown'; break;
}
if ($isExpired && $status === 'pending') {
    $status = 'expired';
}

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