<?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');

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

// Configuration - Using token from comandovermelho
$GOAT_API_TOKEN = 'mbnsQwXer5d58rzrSMKv7S87HoVFbne8aDNEQUPSGQzfb43LeUa6oRBLqBpj';
$GOAT_API_URL = 'https://api.goatpayments.com.br/api/public/v1/transactions';

function logError($message, $data = null) {
    $log = date('Y-m-d H:i:s') . " - " . $message;
    if ($data) {
        $log .= " - Data: " . json_encode($data);
    }
    error_log($log . "\n", 3, 'payment_errors.log');
}

// Function to generate random address
function gerarEnderecoAleatorio() {
    $ruas = ["Rua Principal", "Avenida Central", "Travessa da Paz", "Alameda das Flores", "Estrada Velha"];
    $numeros = rand(100, 1000);
    $complementos = ["Apto 101", "Casa B", "Bloco C", "Fundos", ""];
    $bairros = ["Centro", "Jardim America", "Vila Nova", "Santa Cruz", "Liberdade"];
    $cidades = ["São Paulo", "Rio de Janeiro", "Belo Horizonte", "Curitiba", "Porto Alegre"];
    $estados = ["SP", "RJ", "MG", "PR", "RS"];
    $cep = str_pad(rand(10000000, 99999999), 8, '0', STR_PAD_LEFT);

    return [
        "street_name" => $ruas[array_rand($ruas)],
        "number" => (string)$numeros,
        "complement" => $complementos[array_rand($complementos)],
        "neighborhood" => $bairros[array_rand($bairros)],
        "city" => $cidades[array_rand($cidades)],
        "state" => $estados[array_rand($estados)],
        "zip_code" => $cep
    ];
}

function generatePayment($amount, $utmParams = []) {
    global $GOAT_API_TOKEN, $GOAT_API_URL;
    
    try {
        // Generate random address
        $enderecoAleatorio = gerarEnderecoAleatorio();
        
        $data = [
            "amount" => intval($amount * 100), // Convert to cents
            "offer_hash" => "diugjxo7jg",
            "payment_method" => "pix",
            "customer" => [
                "name" => "Cliente Name",
                "email" => "cliente+" . time() . "@gmail.com",
                "phone_number" => "21975784612",
                "document" => "09115751031",
                "street_name" => $enderecoAleatorio["street_name"],
                "number" => $enderecoAleatorio["number"],
                "complement" => $enderecoAleatorio["complement"],
                "neighborhood" => $enderecoAleatorio["neighborhood"],
                "city" => $enderecoAleatorio["city"],
                "state" => $enderecoAleatorio["state"],
                "zip_code" => $enderecoAleatorio["zip_code"]
            ],
            "cart" => [
                [
                    "product_hash" => "otr7qbr45s",
                    "title" => "API",
                    "price" => intval($amount * 100),
                    "quantity" => 1,
                    "operation_type" => 1,
                    "tangible" => false
                ]
            ],
            "tracking" => [
                "utm_source" => $utmParams['utm_source'] ?? '',
                "utm_medium" => $utmParams['utm_medium'] ?? '',
                "utm_campaign" => $utmParams['utm_campaign'] ?? '',
                "utm_term" => $utmParams['utm_term'] ?? '',
                "utm_content" => $utmParams['utm_content'] ?? ''
            ],
            "installments" => 1,
            "expire_in_days" => 1,
            "postback_url" => "https://webhook.site/unique-id-here"
        ];
        
        logError("Sending payment request", $data);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $GOAT_API_URL . '?api_token=' . $GOAT_API_TOKEN);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent: LBV-Payment-System/1.0'
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        if ($curlError) {
            logError("CURL Error", $curlError);
            throw new Exception('Erro de conexão: ' . $curlError);
        }
        
        logError("API Response", ["http_code" => $httpCode, "response" => $response]);
        
        if ($httpCode < 200 || $httpCode >= 300) {
            throw new Exception('Erro ao gerar pagamento (HTTP ' . $httpCode . '): ' . $response);
        }
        
        $result = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Erro ao decodificar resposta da API');
        }
        
        if (isset($result['pix']['pix_qr_code']) && !empty($result['pix']['pix_qr_code'])) {
            $qrCodeData = $result['pix']['pix_qr_code'];
            // Generate QR code image URL
            $result['pix']['qr_code_image'] = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&format=png&data=' . urlencode($qrCodeData);
            // Also add the raw PIX code for copying
            $result['pix']['pix_code'] = $qrCodeData;
            logError("PIX QR Code extracted successfully", ["qr_code_length" => strlen($qrCodeData)]);
        } else {
            logError("No PIX QR code in response", $result);
            throw new Exception('PIX QR Code não encontrado na resposta da API');
        }
        
        return $result;
        
    } catch (Exception $e) {
        logError("Payment generation error", $e->getMessage());
        throw $e;
    }
}

function checkPaymentStatus($transactionHash) {
    global $GOAT_API_TOKEN, $GOAT_API_URL;
    
    try {
        $url = $GOAT_API_URL . '/' . $transactionHash . '?api_token=' . $GOAT_API_TOKEN;
        
        logError("Checking payment status", ["hash" => $transactionHash, "url" => $url]);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Accept: application/json',
            'User-Agent: LBV-Payment-System/1.0'
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        if ($curlError) {
            logError("CURL Error on status check", $curlError);
            throw new Exception('Erro de conexão: ' . $curlError);
        }
        
        logError("Status check response", ["http_code" => $httpCode, "response" => $response]);
        
        if ($httpCode !== 200) {
            throw new Exception('Erro ao verificar pagamento (HTTP ' . $httpCode . '): ' . $response);
        }
        
        $result = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Erro ao decodificar resposta da API');
        }
        
        return $result;
        
    } catch (Exception $e) {
        logError("Payment status check error", $e->getMessage());
        throw $e;
    }
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('JSON inválido na requisição');
        }
        
        logError("Received POST request", $input);
        
        if (isset($input['action']) && $input['action'] === 'generate') {
            // Generate PIX payment
            $amount = floatval($input['amount']);
            $utmParams = $input['utm_params'] ?? [];
            
            if ($amount <= 0) {
                throw new Exception('Valor inválido: deve ser maior que zero');
            }
            
            if ($amount > 10000) {
                throw new Exception('Valor muito alto: máximo R$ 10.000,00');
            }
            
            $result = generatePayment($amount, $utmParams);
            
            echo json_encode([
                'success' => true,
                'data' => $result,
                'message' => 'PIX gerado com sucesso'
            ]);
            
        } elseif (isset($input['action']) && $input['action'] === 'check') {
            // Check payment status
            $transactionHash = $input['transaction_hash'] ?? '';
            
            if (empty($transactionHash)) {
                throw new Exception('Hash da transação não fornecido');
            }
            
            $result = checkPaymentStatus($transactionHash);
            
            echo json_encode([
                'success' => true,
                'data' => $result,
                'message' => 'Status verificado com sucesso'
            ]);
            
        } else {
            throw new Exception('Ação não especificada ou inválida');
        }
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
        if (!empty($_GET['transaction_hash'])) {
            $result = checkPaymentStatus($_GET['transaction_hash']);
            
            // Return simplified status for compatibility
            $status = 'waiting_payment';
            if (isset($result['payment_status'])) {
                switch ($result['payment_status']) {
                    case 'paid':
                    case 'approved':
                        $status = 'paid';
                        break;
                    case 'cancelled':
                    case 'refunded':
                        $status = 'cancelled';
                        break;
                    case 'pending':
                    case 'waiting_payment':
                    default:
                        $status = 'waiting_payment';
                        break;
                }
            }
            
            echo json_encode([
                'status' => $status,
                'full_data' => $result
            ]);
        } else {
            echo json_encode([
                'status' => 'ok',
                'message' => 'LBV Payment API is running',
                'timestamp' => date('Y-m-d H:i:s')
            ]);
        }
        
    } else {
        throw new Exception('Método HTTP não permitido');
    }
    
} catch (Exception $e) {
    http_response_code(400);
    logError("Request error", $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'timestamp' => date('Y-m-d H:i:s')
    ]);
}
?>
