<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/qrcode.php';

// Compatibilidade com o APP:
// Se o app chamar /qrcode.php na raiz sem sessão de admin, ele recebe o QR diretamente.
// Se chamar ?json=1, recebe os links em JSON.
if (!gpc_logged_in()) {
    $publicQrUrl = gpc_qrcode_configured_url();
    if (isset($_GET['json']) || isset($_GET['link']) || isset($_GET['info'])) {
        gpc_qrcode_json_out($publicQrUrl);
    }
    gpc_qrcode_stream_or_redirect($publicQrUrl, 300);
}

$pageTitle = 'QR Code de Suporte';
$self = basename((string) ($_SERVER['PHP_SELF'] ?? 'qrcode.php')) ?: 'qrcode.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!gpc_csrf_check($_POST['csrf'] ?? null)) {
        gpc_flash('bad', 'Sessão expirada. Tente novamente.');
        header('Location: ' . $self);
        exit;
    }

    $qrUrl = isset($_POST['qr_url']) && is_string($_POST['qr_url']) ? trim($_POST['qr_url']) : '';

    if ($qrUrl !== '' && !filter_var($qrUrl, FILTER_VALIDATE_URL)) {
        gpc_flash('bad', 'Link inválido. Use um link completo, começando com http:// ou https://');
        header('Location: ' . $self);
        exit;
    }

    gpc_setting_save('qr_url', $qrUrl);
    // Remove configurações antigas de imagem/cache para evitar conflito.
    gpc_setting_save('qr_code_path', '');
    gpc_setting_save('qr_logo_path', '');

    gpc_flash('ok', $qrUrl !== '' ? 'Link do QR Code salvo com sucesso.' : 'QR Code desativado com sucesso.');
    header('Location: ' . $self);
    exit;
}

$csrf = gpc_csrf_token();
$qrUrl = gpc_qrcode_configured_url();
$qrImageUrl = $qrUrl !== '' ? gpc_qrcode_remote_url($qrUrl, 300) : '';
$rootEndpoint = gpc_public_url('qrcode.php');
$apiEndpoint = gpc_public_url('api/support_qr.php');

require_once __DIR__ . '/includes/header.php';
?>

<div class="card">
    <div class="card-body">
        <h2 style="margin-top:0">QR Code de Suporte</h2>
        <p style="color:#666;margin-top:4px">
            Configure apenas o link de suporte. O QR Code será gerado automaticamente por link, sem depender de upload de foto ou arquivo salvo.
        </p>

        <form method="post">
            <input type="hidden" name="csrf" value="<?= gpc_h((string) $csrf) ?>">

            <div class="field">
                <label for="qr_url">Link do suporte</label>
                <input id="qr_url" type="url" name="qr_url" value="<?= gpc_h($qrUrl) ?>"
                       placeholder="https://wa.me/5527996242049" style="width:100%;">
                <small style="display:block;color:#666;margin-top:6px">
                    Exemplo: link do WhatsApp, Telegram, site de suporte ou painel do cliente.
                </small>
            </div>

            <div class="form-actions" style="margin-top:16px">
                <button type="submit" class="btn"><i data-lucide="save"></i> Salvar Link</button>
                <?php if ($qrUrl !== ''): ?>
                    <a class="btn btn-ghost" href="<?= gpc_h($rootEndpoint) ?>" target="_blank"><i data-lucide="external-link"></i> Testar QR</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
</div>

<?php if ($qrUrl !== ''): ?>
<div class="card" style="margin-top:18px">
    <div class="card-body">
        <h3 style="margin-top:0">Prévia</h3>
        <div style="display:flex;gap:22px;align-items:flex-start;flex-wrap:wrap">
            <div style="background:#fff;border:1px solid #ddd;border-radius:12px;padding:12px;max-width:324px">
                <img src="<?= gpc_h($qrImageUrl) ?>" alt="QR Code de suporte" style="width:300px;max-width:100%;display:block">
            </div>
            <div style="min-width:260px;flex:1">
                <p><strong>Link configurado:</strong><br><?= gpc_h($qrUrl) ?></p>
                <p><strong>Endpoint raiz para o APP:</strong><br><code><?= gpc_h($rootEndpoint) ?></code></p>
                <p><strong>Endpoint correto do APP:</strong><br><code><?= gpc_h($apiEndpoint) ?></code></p>
                <p style="color:#666">Endpoint correto para configurar no APP: <code>/api/support_qr.php</code>. Também aceita <code>?json=1</code> caso precise receber em JSON ou <code>?url=1</code> para texto puro.</p>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
