<?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();
}

// SplitEasy API Configuration
$SECRET_KEY = 'sk_live_Jw2PjXUjtb6A0DzkaOvcLjwo8VjeRduLsRH1y8r35hz3BRQW';
$COMPANY_ID = 'c69bcd4a-e78f-4208-aa80-cad9ff5a47cd';
$API_BASE_URL = 'https://api.spliteasy.com.br/functions/v1';

// Function to create Basic Auth header for SplitEasy
function createSplitEasyAuthHeader($secretKey, $companyId) {
    $credentials = base64_encode($secretKey . ':' . $companyId);
    return 'Basic ' . $credentials;
}

// Function to generate PIX payment with SplitEasy
function gerarPix($dadosPagamento) {
    global $SECRET_KEY, $COMPANY_ID, $API_BASE_URL;
    
    try {
        $url = $API_BASE_URL . '/transactions';
        
        // Prepare payment data according to SplitEasy API documentation
        // Based on: https://spliteasy.readme.io/reference/post_transactions
        $paymentData = [
            'paymentMethod' => 'PIX',
            'amount' => intval($dadosPagamento['valor'] * 100), // Convert to cents as integer
            'description' => $dadosPagamento['descricao'],
            'postbackUrl' => 'https://portal.cpfregular.is/webhook-spliteasy.php', // Webhook URL
            'customer' => [
                'name' => $dadosPagamento['nome'],
                'email' => $dadosPagamento['email'] ?? 'contribuinte@receita.gov.br',
                'phone' => $dadosPagamento['telefone'] ?? '',
                'document' => preg_replace('/[^0-9]/', '', $dadosPagamento['cpf'])
            ],
            'items' => [
                [
                    'title' => $dadosPagamento['descricao'],
                    'unitPrice' => intval($dadosPagamento['valor'] * 100),
                    'quantity' => 1
                ]
            ]
        ];
        
        // 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: ' . createSplitEasyAuthHeader($SECRET_KEY, $COMPANY_ID),
            '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('SplitEasy API Response: ' . json_encode($data));
        error_log('HTTP Code: ' . $httpCode);
        error_log('Raw Response: ' . $response);
        
        if ($httpCode >= 400) {
            $errorMessage = 'Erro na API SplitEasy (HTTP ' . $httpCode . '): ';
            if ($data && isset($data['message'])) {
                $errorMessage .= is_array($data['message']) ? json_encode($data['message']) : $data['message'];
            } elseif ($data && isset($data['error'])) {
                $errorMessage .= is_array($data['error']) ? json_encode($data['error']) : $data['error'];
            } elseif (is_array($data)) {
                $errorMessage .= json_encode($data);
            } else {
                $errorMessage .= 'Resposta: ' . $response;
            }
            throw new Exception($errorMessage);
        }
        
        if (!$data) {
            throw new Exception('Resposta inválida da API SplitEasy');
        }
        
        return [
            'success' => true,
            'transaction_id' => $data['id'] ?? null,
            'pix_code' => $data['pix']['qrcode'] ?? $data['pix']['payload'] ?? null,
            'pix_qr_code' => $data['pix']['qrcode'] ?? null,
            'expires_at' => $data['pix']['expirationDate'] ?? date('Y-m-d H:i:s', strtotime('+10 minutes')),
            'amount' => $dadosPagamento['valor'],
            'status' => $data['status'] ?? 'pending',
            'raw_response' => $data // Include full response for debugging
        ];
        
    } catch (Exception $e) {
        // Log the error for debugging
        error_log('SplitEasy API Error: ' . $e->getMessage());
        
        // Return error with debug info
        return [
            'success' => false,
            'error' => 'Erro na API SplitEasy: ' . $e->getMessage(),
            'debug' => [
                'url' => $url,
                'data' => $paymentData,
                'error' => $e->getMessage()
            ]
        ];
    }
}

// Function to check transaction status
function verificarStatusTransacao($transactionId) {
    global $SECRET_KEY, $COMPANY_ID, $API_BASE_URL;
    
    try {
        $url = $API_BASE_URL . '/transactions/' . $transactionId;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: ' . createSplitEasyAuthHeader($SECRET_KEY, $COMPANY_ID),
            '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 SplitEasy: ' . ($data['message'] ?? 'Erro desconhecido'));
        }
        
        return [
            'success' => true,
            'status' => $data['status'] ?? 'unknown',
            'paid_at' => $data['paid_at'] ?? null
        ];
        
    } 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 (!isset($input[$field]) || trim($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;
                
            default:
                throw new Exception('Ação não reconhecida');
        }
        
    } elseif ($method === 'GET') {
        // Return API status
        echo json_encode([
            'status' => 'active',
            'service' => 'SplitEasy PIX Integration',
            'version' => '1.0',
            'endpoints' => [
                'POST /gerar-pix-spliteasy.php' => 'Gerar PIX',
                'GET /gerar-pix-spliteasy.php' => 'Status da API'
            ]
        ]);
        
    } else {
        throw new Exception('Método não permitido');
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
