<?php
declare(strict_types=1);

/**
 * QR Code por link remoto, sem depender de arquivo/cache local.
 * Isso evita erro de permissão em /media ou /uploads e funciona melhor no app.
 */
function gpc_qrcode_remote_url(string $url, int $size = 300): string
{
    $url = trim($url);
    $size = max(120, min(1000, $size));
    return 'https://api.qrserver.com/v1/create-qr-code/?size=' . $size . 'x' . $size . '&margin=10&data=' . rawurlencode($url);
}

function gpc_qrcode_configured_url(): string
{
    return trim((string) gpc_setting('qr_url', ''));
}

function gpc_qrcode_json_out(string $url): void
{
    $qrImage = $url !== '' ? gpc_qrcode_remote_url($url, 300) : '';
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-cache, no-store, must-revalidate');
    echo json_encode([
        'ok' => $url !== '',
        'url' => $url,
        'link' => $url,
        'support_url' => $url,
        'qr_url' => $url,
        'image' => $qrImage,
        'qrcode' => $qrImage,
        'qr_code' => $qrImage,
        'qr_image' => $qrImage,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function gpc_qrcode_stream_or_redirect(string $url, int $size = 300): void
{
    $url = trim($url);
    if ($url === '') {
        http_response_code(404);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['ok' => false, 'error' => 'QR Code sem link configurado'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    $remote = gpc_qrcode_remote_url($url, $size);

    // Tenta entregar PNG direto pelo servidor. Se a hospedagem bloquear saída externa,
    // faz redirect para o link do QR, sem depender de arquivo salvo.
    $imageData = false;
    $httpCode = 0;

    if (function_exists('curl_init')) {
        $ch = curl_init($remote);
        if ($ch !== false) {
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 12);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            $imageData = curl_exec($ch);
            $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
        }
    }

    if (!is_string($imageData) || $imageData === '' || $httpCode < 200 || $httpCode >= 300) {
        $ctx = stream_context_create(['http' => ['timeout' => 12, 'follow_location' => 1]]);
        $imageData = @file_get_contents($remote, false, $ctx);
    }

    if (is_string($imageData) && $imageData !== '') {
        header('Content-Type: image/png');
        header('Content-Length: ' . strlen($imageData));
        header('X-Content-Type-Options: nosniff');
        header('Cache-Control: no-cache, no-store, must-revalidate');
        echo $imageData;
        exit;
    }

    header('Location: ' . $remote, true, 302);
    exit;
}
?>
