<?php
// Porte fiel de api/pix/create.php (mesma lógica da rota /api/public/pix/create)
require_once __DIR__ . '/../config.php';

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    json_out(['success' => false, 'error' => 'Método não permitido'], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
if (!is_array($input)) {
    json_out(['success' => false, 'error' => 'Dados inválidos'], 400);
}

$get = function ($k) use ($input) { return trim((string) ($input[$k] ?? '')); };

$name = $get('customer_name');
$email = $get('customer_email');
$doc = only_digits($get('customer_document'));
$phone = only_digits($get('customer_phone'));

if (mb_strlen($name) < 2) json_out(['success' => false, 'error' => 'Informe seu nome completo.'], 400);
if (!preg_match('/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/', $email)) json_out(['success' => false, 'error' => 'Informe um e-mail válido.'], 400);
if (strlen($doc) !== 11) json_out(['success' => false, 'error' => 'Informe um CPF válido.'], 400);
if (strlen($phone) < 10) json_out(['success' => false, 'error' => 'Informe um telefone válido.'], 400);

$kitId = $get('kit');
$kitTitle = $get('kit_title') ?: 'Kit FitS36';

$amount = (int) round((float) str_replace(',', '.', $get('amount')));
if ($amount < 100 || $amount > 100000) json_out(['success' => false, 'error' => 'Valor do pedido inválido.'], 400);

$shipCents = (int) round((float) str_replace(',', '.', $get('shipping_fee')));
if ($shipCents < 0 || $shipCents >= $amount) $shipCents = 0;
$shipLabel = $get('shipping_label') ?: 'Frete Grátis';

$payload = [
    'amount' => $amount,
    'payment_method' => 'pix',
    'customer' => [
        'name' => $name,
        'email' => $email,
        'document' => ['number' => $doc, 'type' => 'cpf'],
        'phone' => $phone,
    ],
    'items' => [[
        'title' => $kitTitle,
        'unit_price' => max(0, $amount - $shipCents),
        'quantity' => 1,
        'tangible' => true,
        'external_ref' => 'kit-' . $kitId,
    ]],
    'shipping' => [
        'fee' => $shipCents,
        'address' => [
            'street' => $get('customer_address'),
            'street_number' => 'S/N',
            'complement' => '',
            'zip_code' => only_digits($get('customer_postal_code')),
            'neighborhood' => $get('customer_neighborhood'),
            'city' => $get('customer_city'),
            'state' => $get('customer_state'),
            'country' => 'BR',
        ],
    ],
    'pix' => ['expires_in_days' => 1],
    'installments' => 1,
    'metadata' => ['kit' => $kitId],
];

$res = vennox_request('/v1/payment-transaction/create', 'POST', $payload);
$status = $res['status'];

if ($status < 200 || $status >= 300) {
    error_log("Vennox create falhou [$status]: " . $res['raw']);
    $msg = $res['json']['message'] ?? "Erro no gateway de pagamento ($status)";
    json_out(['success' => false, 'error' => $msg], 400);
}

$created = vennox_unwrap($res['json']);
$pix = $created['pix'] ?? [];
if (is_array($pix) && array_keys($pix) === range(0, max(0, count($pix) - 1)) && isset($pix[0])) {
    $pix = $pix[0];
}

$copy = $pix['qr_code'] ?? ($pix['url'] ?? '');
if (!$copy) {
    error_log('Vennox não retornou o código Pix: ' . $res['raw']);
    json_out(['success' => false, 'error' => 'O gateway não retornou o código Pix.'], 400);
}

$qrImage = 'https://api.qrserver.com/v1/create-qr-code/?size=320x320&margin=0&data=' . rawurlencode($copy);

json_out([
    'success' => true,
    'transaction_id' => $created['id'] ?? '',
    'amount' => $amount / 100,
    'pix_copy_paste' => $copy,
    'pix_qrcode_image' => $qrImage,
    // Janela de urgência exibida no checkout (o Pix em si vale 24h)
    'expires_at' => gmdate('c', time() + 15 * 60),
]);
