<?php
header('Content-Type: application/json; charset=utf-8');

$apiKey = '25b4dd0505fd7d180e909d04d47e4c16ab86hav0aslebm7fmdsqidsn7mxe5qb';
$storeCode = 'f47ecfc81404da9938b38742b8028917';

// Recebe dados da URL
$nome = isset($_GET['nome']) ? trim($_GET['nome']) : '';
$cpf  = isset($_GET['cpf']) ? preg_replace('/\D/', '', $_GET['cpf']) : '';

// Dados mínimos
if (!$nome || strlen($cpf) < 11) {
    http_response_code(400);
    echo json_encode([
        'error' => 'Nome ou CPF inválido'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// Dados obrigatórios da API
$email = 'cliente@exemplo.com';
$phone = '11999999999';
$ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';

// Valor em centavos
$paymentAmount = 500;

// Identificador interno
$externalCode = 'PEDIDO_' . time();

$payload = [
    'store_code' => $storeCode,
    'external_code' => $externalCode,
    'payment_method' => 'pix',
    'payment_format' => 'regular',
    'installments' => 1,
    'payment_amount' => $paymentAmount,
    'shipping_amount' => 0,
    'postback_url' => 'https://seudominio.com.br/seguro/webhook_pix.php',
    'items' => [
        [
            'title' => 'Pagamento via PIX',
            'quantity' => 1,
            'unit_price' => $paymentAmount,
            'tangible' => false
        ]
    ],
    'customer' => [
        'email' => $email,
        'name' => $nome,
        'document' => $cpf,
        'phone' => $phone,
        'ip' => $ip
    ],
    'pix' => [
        'expires_in_days' => 1
    ],
    'extra' => [
        'userAgent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        'url_referer' => $_SERVER['HTTP_REFERER'] ?? '',
        'url_full' => 'https://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . ($_SERVER['REQUEST_URI'] ?? '')
    ]
];

$ch = curl_init('https://checkout.mangofy.com.br/api/v1/payment');

curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: ' . $apiKey,
        'Store-Code: ' . $storeCode,
        'Content-Type: application/json',
        'Accept: application/json'
    ],
    CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
    CURLOPT_TIMEOUT => 30,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);

curl_close($ch);

if ($curlError) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Erro no cURL',
        'details' => $curlError
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// ============================================================
// DEBUG TEMPORÁRIO — mostra resposta bruta da Mangofy
// Cole no servidor, tente gerar um PIX, veja o que aparece
// no Network > Response do DevTools, e me mande o resultado.
// Depois remove esse bloco.
// ============================================================
echo json_encode([
    'debug_raw' => json_decode($response, true) ?: $response,
    'http_code' => $httpCode
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
exit;
// ============================================================

$data = json_decode($response, true);

if ($httpCode < 200 || $httpCode >= 300) {
    http_response_code($httpCode);
    echo json_encode([
        'error' => 'Erro ao criar pagamento',
        'http_code' => $httpCode,
        'response' => $data ?: $response
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

/*
 * Mapeamento flexível dos possíveis campos do PIX
 */
$pixCode = null;
$qrCode = null;

if (isset($data['pix']) && is_array($data['pix'])) {
    $pixCode = $data['pix']['copy_paste']
        ?? $data['pix']['code']
        ?? $data['pix']['payload']
        ?? $data['pix']['emv']
        ?? null;

    $qrCode = $data['pix']['qr_code']
        ?? $data['pix']['qrcode']
        ?? $data['pix']['qrCode']
        ?? null;
}

if (!$pixCode) {
    $pixCode = $data['pix_code']
        ?? $data['copy_paste']
        ?? $data['qr_copy_paste']
        ?? $data['payload']
        ?? $data['emv']
        ?? null;
}

if (!$qrCode) {
    $qrCode = $data['qr_code']
        ?? $data['qrcode']
        ?? $data['qrCode']
        ?? null;
}

echo json_encode([
    'id'          => $data['payment_code'] ?? null,
    'paymentCode' => $data['payment_code'] ?? null,
    'external_id' => $data['external_code'] ?? $externalCode,
    'status'      => $data['payment_status'] ?? 'pending',
    'pix'         => $pixCode,
    'qr_code'     => $qrCode,
], JSON_UNESCAPED_UNICODE);