<?php
require_once __DIR__ . '/../security.php';

$tenant = "alanboswell.enrep.co.uk";

foreach ([
    __DIR__ . '/../../../' . $tenant . '/config.php',
    __DIR__ . '/../../../config.php',
    '/config.php',
] as $configPath) {
    if (!defined('CONFIG_LOADED') && is_file($configPath)) {
        require_once $configPath;
    }
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}
enrep_require_user();

$clientnumber = enrep_request_int('clientnumber');
$repnumber = enrep_request_int('repnumber');
$items = enrep_request_int('items');
$form = enrep_request_int('form');
$forceGen = enrep_request_enum('forceGen', ['yes', ''], '');

if ($clientnumber < 1 || $repnumber < 1 || $items < 1) {
    enrep_fail(400, 'Invalid report');
}

$_REQUEST['tenant'] = $tenant;
$_REQUEST['clientnumber'] = (string)$clientnumber;
$_REQUEST['repnumber'] = (string)$repnumber;
$_REQUEST['items'] = (string)$items;
if ($form > 0) {
    $_REQUEST['form'] = (string)$form;
}
$_REQUEST['forceGen'] = $forceGen;

$tenantOutputBase = defined('TENANT_DEFER')
    ? rtrim((string)TENANT_DEFER, '/')
    : rtrim('../../../' . $tenant, '/');
$reportPath = $tenantOutputBase . '/output/reports/' . $clientnumber . '/' . $repnumber . '_' . $items . '.pdf';
if (file_exists($reportPath) && $forceGen !== 'yes') {
    echo '1';
    exit;
}

require_once __DIR__ . '/genPDF2.php';
