<?php
/* ============================================================
   CONSULTAR STATUS DO PIX via PodPay
   GET api_status.php?id=TRANSACTION_ID
   Devolve { success, paid, status } — compatível com o
   polling do wiinpay-checkout.js e do PixModal.
   ============================================================ */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

require __DIR__ . '/config_pix.php';

$id = isset($_GET['id']) ? preg_replace('/[^A-Za-z0-9_\-]/', '', $_GET['id']) : '';
if ($id === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'paid' => false, 'error' => 'id ausente']);
    exit;
}

// FortPay: GET /transactions/{hash}?api_token=...
// $FORTPAY_ENDPOINT já aponta para .../public/v1/transactions
$url = $FORTPAY_ENDPOINT . '/' . urlencode($id) . '?api_token=' . urlencode($FORTPAY_API_TOKEN);

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING       => "",
    CURLOPT_MAXREDIRS      => 10,
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
    CURLOPT_HTTPHEADER     => [
        "accept: application/json"
    ],
]);

$response = curl_exec($ch);
$err      = curl_error($ch);
curl_close($ch);

if ($err) {
    echo json_encode(['success' => false, 'paid' => false, 'error' => 'cURL Error: ' . $err]);
    exit;
}

$decoded = json_decode($response, true);
if (!is_array($decoded)) {
    echo json_encode(['success' => false, 'paid' => false, 'error' => 'invalid_json', 'raw' => $response]);
    exit;
}

// FortPay retorna formato plano; campo principal é "payment_status"
$d = is_array($decoded['data'] ?? null) ? $decoded['data'] : $decoded;
$status = $d['payment_status'] ?? $d['status'] ?? $decoded['transaction']['status'] ?? $decoded['status'] ?? null;

$paidStatuses = ['paid','approved','confirmed','completed','complete','success','pago','aprovado','aprovada','concluido','concluida'];
$paid = ($status !== null) && in_array(strtolower(trim((string)$status)), $paidStatuses, true);

echo json_encode([
    'success'      => true,
    'paid'         => $paid,
    'status'       => $status,
    'api_response' => $decoded
]);
