<?php

$text = trim((string) ($_GET['text'] ?? ''));
$size = max(80, min(1000, intval($_GET['size'] ?? 200)));
if ($text === '' || strlen($text) > 2048) {
    http_response_code(400);
    exit('Invalid text parameter');
}

$cacheDir = dirname(__DIR__) . '/data/cache/qrcode';
if (!is_dir($cacheDir)) @mkdir($cacheDir, 0700, true);
$cacheFile = $cacheDir . '/' . hash('sha256', $size . '|' . $text) . '.png';
if (is_file($cacheFile) && filemtime($cacheFile) > time() - 86400) {
    header('Content-Type: image/png');
    header('Cache-Control: public, max-age=86400');
    readfile($cacheFile);
    exit;
}

$rateFile = $cacheDir . '/rate_' . hash('sha256', (string) ($_SERVER['REMOTE_ADDR'] ?? '')) . '.json';
$rate = is_file($rateFile) ? json_decode((string) @file_get_contents($rateFile), true) : [];
if (!is_array($rate) || intval($rate['window'] ?? 0) < time() - 60) $rate = ['window' => time(), 'count' => 0];
$rate['count']++;
@file_put_contents($rateFile, json_encode($rate), LOCK_EX);
if ($rate['count'] > 30) {
    http_response_code(429);
    exit('Too Many Requests');
}

$apiUrl = 'https://api.qrserver.com/v1/create-qr-code/?format=png&size=' . $size . 'x' . $size . '&data=' . rawurlencode($text);
$context = stream_context_create([
    'http' => ['timeout' => 8, 'user_agent' => 'EnterpriseCMS/1.1'],
    'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
]);
$imageData = @file_get_contents($apiUrl, false, $context);
if ($imageData === false || strlen($imageData) > 5 * 1024 * 1024 || @getimagesizefromstring($imageData) === false) {
    http_response_code(502);
    exit('QR service unavailable');
}
@file_put_contents($cacheFile, $imageData, LOCK_EX);
header('Content-Type: image/png');
header('Cache-Control: public, max-age=86400');
echo $imageData;
