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

$payload = delivery_json_input();
$tenant = delivery_load_tenant();
$manifest = delivery_manifest($payload);

require_once __DIR__ . '/../../includes/master/form_functions.php';

$clientnumber = (int)$manifest['clientnumber'];
$coverTemplate = trim((string)($manifest['options']['coverTemplate'] ?? 'default'));
if ($coverTemplate === '') {
    $coverTemplate = 'default';
}
$dateStart = trim((string)($manifest['options']['dateStart'] ?? ''));
$dateEnd = trim((string)($manifest['options']['dateEnd'] ?? ''));
$dateRangeTitle = '';
if ($dateStart !== '' && $dateEnd !== '') {
    $dateRangeTitle = $dateStart . ' - ' . $dateEnd;
} elseif ($dateStart !== '') {
    $dateRangeTitle = 'From ' . $dateStart;
} elseif ($dateEnd !== '') {
    $dateRangeTitle = 'To ' . $dateEnd;
}

function delivery_cover_chain_from_linked($linkedRaw): array
{
    $linkedRaw = trim((string)$linkedRaw);
    if ($linkedRaw === '' || $linkedRaw === '[]' || !preg_match('/^\s*(\d+)\s*:/', $linkedRaw, $match)) {
        return ['', ''];
    }

    $chainId = 'C' . (string)$match[1];
    $chainTitle = $chainId;
    $posLastColon = strrpos($linkedRaw, ':');
    if ($posLastColon !== false) {
        $tail = trim(substr($linkedRaw, $posLastColon + 1));
        if ($tail !== '' && $tail !== $linkedRaw) {
            $chainTitle = $tail;
        }
    }

    return [$chainId, $chainTitle];
}

function delivery_cover_report_chain(array $report): array
{
    $chainId = trim((string)($report['chainId'] ?? ''));
    $chainTitle = trim((string)($report['chainTitle'] ?? ''));
    if ($chainId !== '') {
        return [$chainId, $chainTitle];
    }

    $itemnumber = (int)($report['itemnumber'] ?? 0);
    if ($itemnumber < 1) {
        return ['', ''];
    }

    $stmt = $GLOBALS['con']->prepare("SELECT `linked` FROM `itemdetails` WHERE `itemnumber` = ? LIMIT 1");
    if (!$stmt) {
        return ['', ''];
    }
    $stmt->bind_param('i', $itemnumber);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    return delivery_cover_chain_from_linked($row['linked'] ?? '');
}

$groups = [];

foreach ($manifest['coverReports'] as $report) {
    [$chainId, $chainTitle] = delivery_cover_report_chain($report);
    $key = trim((string)$chainId);
    if ($key === '') {
        $key = 'unchained';
    }
    if (!isset($groups[$key])) {
        $groups[$key] = [
            'key' => $key,
            'title' => $key === 'unchained' ? 'Unchained' : ($chainTitle !== '' ? $chainTitle : $key),
            'reports' => [],
        ];
    }
    $report['chainId'] = $key === 'unchained' ? '' : $key;
    $report['chainTitle'] = $groups[$key]['title'];
    $groups[$key]['reports'][] = $report;
}

$split = !empty($manifest['options']['chainCovers']) && count($groups) > 1;
if (!$split) {
    $groups = [[
        'key' => 'all',
        'title' => '',
        'reports' => $manifest['coverReports'],
    ]];
}

$stamp = time() . '_' . random_int(1000, 9999);
$files = [];

foreach ($groups as $group) {
    if (empty($group['reports'])) {
        continue;
    }

    $suffix = preg_replace('/[^A-Za-z0-9_-]/', '_', (string)$group['key']);
    if ($suffix === '') {
        $suffix = 'cover';
    }
    $coverFile = 'report_cover_' . $clientnumber . '_' . $stamp . '_' . $suffix . '.pdf';

    $_REQUEST['tenant'] = $tenant;
    $_REQUEST['clientnumber'] = (string)$clientnumber;
    $_REQUEST['site'] = (string)$manifest['site'];
    $_REQUEST['mode'] = 'split';
    $_REQUEST['items'] = array_map('delivery_report_token', $group['reports']);
    $_REQUEST['cover_file'] = $coverFile;
    $coverTitle = trim((string)$group['title']);
    $_REQUEST['cover_title'] = $coverTitle;
    $_REQUEST['cover_template'] = $coverTemplate;
    $_REQUEST['cover_dateRange'] = $dateRangeTitle;
    $_POST['cover_file'] = $coverFile;
    $_POST['cover_title'] = $coverTitle;
    $_POST['cover_template'] = $coverTemplate;
    $_POST['cover_dateRange'] = $dateRangeTitle;

    delivery_generator_include('genCover.php');
    $files[] = delivery_file_entry($clientnumber, $coverFile, 'rc');
}

delivery_response([
    'ok' => true,
    'files' => $files,
]);
