<?php
/**
 * ============================================
 * 🔍 API - Verificar Status de Pagamento
 * ============================================
 * Endpoint: GET /api/check-payment.php?id=TRANSACTION_ID
 * 
 * Retorna: { "status": "paid", "paid": true }
 */

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

// Configuração do Gateway
define('GATEWAY_API_URL', 'https://api.allowpay.online/functions/v1'); // Mude para seu gateway
define('GATEWAY_API_KEY', 'sua_api_key_aqui'); // Sua API Key

// Recebe ID da transação
$transactionId = $_GET['id'] ?? null;

if (!$transactionId) {
    echo json_encode([
        'error' => true,
        'message' => 'ID da transação não informado'
    ]);
    exit;
}

// Sanitiza ID
$transactionId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $transactionId);

// ========================================
// 1️⃣ VERIFICA NO BANCO DE DADOS LOCAL
// ========================================
$localStatus = verificarStatusLocal($transactionId);

if ($localStatus) {
    echo json_encode([
        'transaction_id' => $transactionId,
        'status' => $localStatus,
        'paid' => in_array(strtolower($localStatus), ['paid', 'pago', 'approved', 'confirmed']),
        'source' => 'database'
    ]);
    exit;
}

// ========================================
// 2️⃣ VERIFICA NO GATEWAY (API)
// ========================================
$gatewayStatus = verificarStatusGateway($transactionId);

if ($gatewayStatus) {
    // Salva no banco local para cache
    salvarStatusLocal($transactionId, $gatewayStatus['status']);
    
    echo json_encode([
        'transaction_id' => $transactionId,
        'status' => $gatewayStatus['status'],
        'paid' => in_array(strtolower($gatewayStatus['status']), ['paid', 'pago', 'approved', 'confirmed']),
        'source' => 'gateway',
        'paidAt' => $gatewayStatus['paidAt'] ?? null
    ]);
    exit;
}

// ========================================
// 3️⃣ NÃO ENCONTROU
// ========================================
echo json_encode([
    'transaction_id' => $transactionId,
    'status' => 'unknown',
    'paid' => false,
    'message' => 'Transação não encontrada'
]);

// ========================================
// FUNÇÕES
// ========================================

/**
 * Verifica status no banco de dados local (JSON ou MySQL)
 */
function verificarStatusLocal($transactionId) {
    // Opção 1: Arquivo JSON
    $statusFile = __DIR__ . '/../data/transactions.json';
    
    if (file_exists($statusFile)) {
        $transactions = json_decode(file_get_contents($statusFile), true) ?: [];
        
        foreach ($transactions as $tx) {
            if (($tx['transaction_id'] ?? $tx['id'] ?? '') === $transactionId) {
                return $tx['status'] ?? null;
            }
        }
    }
    
    // Opção 2: MySQL (descomente se usar banco)
    /*
    try {
        $pdo = new PDO('mysql:host=localhost;dbname=seu_banco', 'usuario', 'senha');
        $stmt = $pdo->prepare("SELECT status FROM transactions WHERE transaction_id = ?");
        $stmt->execute([$transactionId]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result) {
            return $result['status'];
        }
    } catch (Exception $e) {
        error_log("Erro DB: " . $e->getMessage());
    }
    */
    
    return null;
}

/**
 * Verifica status no gateway via API
 */
function verificarStatusGateway($transactionId) {
    $url = GATEWAY_API_URL . '/transactions/' . $transactionId;
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_HTTPHEADER => [
            'Accept: application/json',
            'Authorization: Bearer ' . GATEWAY_API_KEY
        ]
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200 || !$response) {
        return null;
    }
    
    $data = json_decode($response, true);
    
    if (!$data) {
        return null;
    }
    
    // Adapte conforme a estrutura do seu gateway
    return [
        'status' => $data['data']['status'] ?? $data['status'] ?? null,
        'paidAt' => $data['data']['paidAt'] ?? $data['paidAt'] ?? null
    ];
}

/**
 * Salva status no banco local para cache
 */
function salvarStatusLocal($transactionId, $status) {
    $statusFile = __DIR__ . '/../data/transactions.json';
    $dataDir = dirname($statusFile);
    
    if (!is_dir($dataDir)) {
        @mkdir($dataDir, 0755, true);
    }
    
    $transactions = [];
    if (file_exists($statusFile)) {
        $transactions = json_decode(file_get_contents($statusFile), true) ?: [];
    }
    
    // Atualiza ou adiciona
    $found = false;
    foreach ($transactions as &$tx) {
        if (($tx['transaction_id'] ?? $tx['id'] ?? '') === $transactionId) {
            $tx['status'] = $status;
            $tx['updated_at'] = date('Y-m-d H:i:s');
            $found = true;
            break;
        }
    }
    
    if (!$found) {
        $transactions[] = [
            'transaction_id' => $transactionId,
            'status' => $status,
            'created_at' => date('Y-m-d H:i:s')
        ];
    }
    
    @file_put_contents($statusFile, json_encode($transactions, JSON_PRETTY_PRINT));
}