<?php
require_once __DIR__ . '/../security.php';
require_once __DIR__ . "/../../packages/phpqrcode/qrlib.php";

enrep_require_user();

$data = enrep_request_string('data', '', 2000);
$itemId = preg_replace('/[^A-Za-z0-9_-]/', '', enrep_request_string('item', '', 120));
$tenant = enrep_tenant_segment();

if ($data === '' || $itemId === '' || $tenant === '') {
    enrep_fail(400, 'Invalid QR request');
}

$tenantRoot = realpath(__DIR__ . '/../../../' . $tenant);
if ($tenantRoot === false || !is_dir($tenantRoot)) {
    enrep_fail(400, 'Tenant not found');
}

$imageDir = $tenantRoot . DIRECTORY_SEPARATOR . 'images';
if (!is_dir($imageDir) && !mkdir($imageDir, 0775, true) && !is_dir($imageDir)) {
    enrep_fail(400, 'Unable to create image directory');
}

$filePath = $imageDir . DIRECTORY_SEPARATOR . $itemId . '.png';
QRcode::png($data, $filePath, 'L', 4, 2);
@chmod($filePath, 0644);

echo 's';
