<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/bootstrap.php';

require_login($conn);

$canPreviewQr = can_access($conn, 'quick_service') || can_access($conn, 'services') || can_access($conn, 'queue') || can_access($conn, 'booking');

$amountRaw = str_replace(',', '', trim((string) ($_GET['amount'] ?? '')));
$amount = is_numeric($amountRaw) ? max(0.0, (float) $amountRaw) : 0.0;
$downloadRequested = isset($_GET['download']) && (string) $_GET['download'] !== '0';
$scopeKey = trim((string) ($_GET['scope'] ?? 'quick_service'));
$branchName = trim((string) ($_GET['branch'] ?? ''));

if ($canPreviewQr) {
    $preview = quick_service_qr_preview($amount, $branchName, $scopeKey);

    if (($preview['type'] ?? 'none') !== 'none' && trim((string) ($preview['src'] ?? '')) !== '') {
        if ($downloadRequested && (string) ($preview['type'] ?? '') === 'image') {
            $localPath = storage_upload_absolute_path_from_public((string) ($preview['src'] ?? ''), 'quick_service');

            if ($localPath && is_file($localPath)) {
                $extension = strtolower((string) pathinfo($localPath, PATHINFO_EXTENSION));
                $mimeType = match ($extension) {
                    'jpg', 'jpeg' => 'image/jpeg',
                    'gif' => 'image/gif',
                    'webp' => 'image/webp',
                    'svg' => 'image/svg+xml',
                    default => 'image/png',
                };

                header('Content-Type: ' . $mimeType);
                header('Content-Length: ' . (string) filesize($localPath));
                header('Content-Disposition: attachment; filename="quick-service-qr.' . ($extension !== '' ? $extension : 'png') . '"');
                readfile($localPath);
                exit();
            }
        }

        redirect((string) $preview['src']);
    }
}

header('Content-Type: image/svg+xml; charset=UTF-8');

$message = !$canPreviewQr
    ? 'QR preview access denied'
    : (quick_service_qr_available($branchName, $scopeKey) ? 'QR preview unavailable' : 'QR not configured');

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<svg xmlns="http://www.w3.org/2000/svg" width="280" height="280" viewBox="0 0 280 280" role="img" aria-label="<?= e($message) ?>">
    <rect width="280" height="280" rx="24" fill="#f6fbff"/>
    <rect x="18" y="18" width="244" height="244" rx="20" fill="#ffffff" stroke="#c9d7e7" stroke-width="2"/>
    <text x="140" y="122" text-anchor="middle" font-family="Arial, sans-serif" font-size="20" font-weight="700" fill="#06213f">QR</text>
    <text x="140" y="154" text-anchor="middle" font-family="Arial, sans-serif" font-size="14" fill="#4f6b8a"><?= e($message) ?></text>
</svg>
