<?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 = 2700;

// 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;
}

$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;
}

// Campo correto retornado pela Mangofy: pix.pix_qrcode_text
$pixCode = $data['pix']['pix_qrcode_text'] ?? null;
$qrCode  = $data['pix']['pix_qrcode_text'] ?? 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);