<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Include PayFort configuration
require_once '../payfort-config.php';

// Validate configuration
try {
    validatePayFortConfig();
} catch (Exception $e) {
    error_log('PayFort Configuration Error: ' . $e->getMessage());
}

// Function to generate PIX payment using PayFort API
function gerarPix($dadosPagamento) {
    try {
        // Validate configuration
        validatePayFortConfig();
        
        $url = getPayFortCashInUrl() . '/transaction/qrcode/cashin';
        
        // Prepare payment data according to PayFort API documentation
        // Based on: https://docs.payfortbr.com/docs/Cash-In
        $paymentData = [
            'payerName' => $dadosPagamento['nome'],
            'payerDocument' => preg_replace('/[^0-9]/', '', $dadosPagamento['cpf']),
            'payerEmail' => $dadosPagamento['email'] ?? 'contato@receita.gov.br',
            'payerPhone' => $dadosPagamento['telefone'] ?? '',
            'productName' => $dadosPagamento['descricao'] ?? 'Regularização Fiscal - Imposto de Renda',
            'productDescription' => 'Pagamento de multa e regularização fiscal',
            'value' => intval($dadosPagamento['valor'] * 100), // Convert to cents as integer
            'postbackUrl' => getPayFortWebhookUrl(), // Webhook URL
            'orderId' => 'CPF_' . time() . '_' . substr($dadosPagamento['cpf'], -4) // Generate unique order ID
        ];
        
        // Initialize cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paymentData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: ' . createPayFortAuthHeader(),
            'User-Agent: Portal-CPF-Regular/1.0'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            throw new Exception('Erro cURL: ' . $error);
        }
        
        $data = json_decode($response, true);
        
        // Log the response for debugging
        error_log('PayFort API Response: ' . json_encode($data));
        error_log('HTTP Code: ' . $httpCode);
        error_log('Raw Response: ' . $response);
        
        if ($httpCode >= 400) {
            $errorMessage = 'Erro na API PayFort (HTTP ' . $httpCode . '): ';
            if ($data && isset($data['message'])) {
                $errorMessage .= $data['message'];
            } else {
                $errorMessage .= 'Resposta: ' . $response;
            }
            throw new Exception($errorMessage);
        }
        
        if (!$data) {
            throw new Exception('Resposta inválida da API PayFort');
        }
        
        // Check if API key is not configured
        if (!isPayFortConfigured()) {
            throw new Exception('API Key do PayFort não configurada. Configure as credenciais no arquivo payfort-config.php');
        }
        
        return [
            'success' => true,
            'transaction_id' => $data['transactionId'] ?? null,
            'external_id' => $data['externalId'] ?? null,
            'order_id' => $data['orderId'] ?? null,
            'pix_code' => $data['qrCode'] ?? null,
            'pix_qr_code' => $data['qrCodeBase64'] ?? null,
            'expires_at' => date('Y-m-d H:i:s', strtotime('+30 minutes')), // PayFort doesn't specify expiration, using 30 minutes
            'amount' => $dadosPagamento['valor'],
            'status' => 'created', // PayFort returns 'created' status initially
            'raw_response' => $data // Include full response for debugging
        ];
        
    } catch (Exception $e) {
        // Log the error for debugging
        error_log('PayFort API Error: ' . $e->getMessage());
        
        // Return error with debug info
        return [
            'success' => false,
            'error' => 'Erro na API PayFort: ' . $e->getMessage(),
            'debug' => [
                'url' => $url,
                'data' => $paymentData,
                'error' => $e->getMessage()
            ]
        ];
    }
}

// Function to check transaction status using PayFort API
function verificarStatusTransacao($transactionId) {
    try {
        validatePayFortConfig();
        
        $url = getPayFortCashInUrl() . '/transaction/get/by/id/' . $transactionId;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: ' . createPayFortAuthHeader(),
            'User-Agent: Portal-CPF-Regular/1.0'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            throw new Exception('Erro cURL: ' . $error);
        }
        
        $data = json_decode($response, true);
        
        if ($httpCode >= 400) {
            throw new Exception('Erro na API PayFort: ' . ($data['message'] ?? 'Erro desconhecido'));
        }
        
        return [
            'success' => true,
            'status' => $data['status'] ?? 'unknown',
            'paid_at' => $data['processedAt'] ?? null,
            'end_to_end_id' => $data['endToEndId'] ?? null,
            'raw_response' => $data
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// Function to check transaction status by order ID using PayFort API
function verificarStatusTransacaoPorOrderId($orderId) {
    try {
        validatePayFortConfig();
        
        $url = getPayFortCashInUrl() . '/transaction/get/by/orderId/' . $orderId;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: ' . createPayFortAuthHeader(),
            'User-Agent: Portal-CPF-Regular/1.0'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            throw new Exception('Erro cURL: ' . $error);
        }
        
        $data = json_decode($response, true);
        
        if ($httpCode >= 400) {
            throw new Exception('Erro na API PayFort: ' . ($data['message'] ?? 'Erro desconhecido'));
        }
        
        return [
            'success' => true,
            'status' => $data['status'] ?? 'unknown',
            'paid_at' => $data['processedAt'] ?? null,
            'end_to_end_id' => $data['endToEndId'] ?? null,
            'raw_response' => $data
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

try {
    $method = $_SERVER['REQUEST_METHOD'];
    
    if ($method === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            $input = $_POST;
        }
        
        $action = $input['action'] ?? 'gerar_pix';
        
        switch ($action) {
            case 'gerar_pix':
                // Validate required fields
                $requiredFields = ['nome', 'cpf', 'valor'];
                foreach ($requiredFields as $field) {
                    if (empty($input[$field])) {
                        throw new Exception("Campo obrigatório: $field");
                    }
                }
                
                $dadosPagamento = [
                    'nome' => $input['nome'],
                    'cpf' => $input['cpf'],
                    'valor' => floatval($input['valor']),
                    'descricao' => $input['descricao'] ?? 'Regularização Fiscal - Imposto de Renda',
                    'email' => $input['email'] ?? '',
                    'telefone' => $input['telefone'] ?? ''
                ];
                
                $resultado = gerarPix($dadosPagamento);
                echo json_encode($resultado);
                break;
                
            case 'verificar_status':
                $transactionId = $input['transaction_id'] ?? '';
                if (empty($transactionId)) {
                    throw new Exception('ID da transação é obrigatório');
                }
                
                $resultado = verificarStatusTransacao($transactionId);
                echo json_encode($resultado);
                break;
                
            case 'verificar_status_order':
                $orderId = $input['order_id'] ?? '';
                if (empty($orderId)) {
                    throw new Exception('Order ID é obrigatório');
                }
                
                $resultado = verificarStatusTransacaoPorOrderId($orderId);
                echo json_encode($resultado);
                break;
                
            default:
                throw new Exception('Ação não reconhecida');
        }
        
    } elseif ($method === 'GET') {
        // Return API status
        echo json_encode([
            'status' => 'active',
            'service' => 'PayFort PIX Integration - Funil',
            'version' => '2.0',
            'provider' => 'PayFort',
            'endpoints' => [
                'POST /gerar-pix-payfort.php' => 'Gerar PIX',
                'GET /gerar-pix-payfort.php' => 'Status da API'
            ],
            'actions' => [
                'gerar_pix' => 'Gerar novo PIX',
                'verificar_status' => 'Verificar status por transaction ID',
                'verificar_status_order' => 'Verificar status por order ID'
            ]
        ]);
        
    } else {
        throw new Exception('Método não permitido');
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
