function getChecksMulti() {
    console.log('multi mode')
    var splitMode = parent.$("input[name='chainMode']:checked").val();
    if (splitMode == "split") {
        splitter('multi')
        return;
    }

    var selectedItems = [];
    var errorItems = [];
    var hseItems = [];
    selected = '';
    errordel = '';
    hse = '';

    $('input[type=checkbox]').each(function() {
        if ($(this).is(":checked") && $(this).attr('name') != null) {
            selectedItems.push($(this).attr('name'));
            if ($(this).data('status') === "URGENT") {
                var y = $(this).attr('name').split("-");
                hseItems.push('../output/reports/<?= $_REQUEST['clientnumber']?>/' + y[0] + '_' + y[1] + '.pdf');
                errorItems.push($(this).attr('name'));
            }
        }
    });

    selected = deliveryListToJson(selectedItems);
    errordel = deliveryListToJson(errorItems);
    hse = hseItems.join(',');
    deliveryStoreList('itemList', selectedItems);

    if (selectedItems.length === 0) {
        showResponse('warning', 'No Items Selected')
        return;
    }

    loadModalContent(
        '<p>Do you wish to manually sort the reports?</p>',
        "multiBox",
        "modal-xl",
        1060,
        "true",
        'Manual Sort',
        'sortReports',
        'genPack(' + deliveryJsArg(selected) + ',' + deliveryJsArg(errordel) + ',' + deliveryJsArg(hse) + ')',
        'manualSort(' + deliveryJsArg(selected) + ',' + deliveryJsArg(errordel) + ',' + deliveryJsArg(hse) + ')'
    );
}

////////////////////////////////////////////////////////////////////////////////

function deliveryPostPromise(url, data) {
    return new Promise(function(resolve, reject) {
        $.post(url, data, function(ret) {
            resolve(ret);
        }).fail(function(xhr) {
            reject(xhr);
        });
    });
}

function deliveryGenerateCoversPromise(selected, mode) {
    return new Promise(function(resolve) {
        deliveryGenerateCovers(selected, mode, resolve);
    });
}

function deliveryMultiCapableForms() {
    return ['500', '502', '503', '504', '506', '900'];
}

function deliveryMultiGroupByForm(items) {
    var grouped = {};
    items.forEach(function(token) {
        var parts = deliveryTokenParts(token);
        var form = parts.reptype || '';
        if (!grouped[form]) {
            grouped[form] = [];
        }
        grouped[form].push(token);
    });
    return grouped;
}

function deliveryCompareReportGroups(group) {
    return deliveryPostPromise(ROOT_URL + '/functions/compare_reports.php', {
        data: group,
        tenant: TENANT_URL
    }).then(function(ret) {
        try {
            var parsed = $.parseJSON($.trim(ret));
            return Array.isArray(parsed) && parsed.length ? parsed : group.map(function(item) {
                return [item];
            });
        } catch (error) {
            return group.map(function(item) {
                return [item];
            });
        }
    });
}

function deliveryGenerateMultiPdf(array, form) {
    $('#statusCount').html('Generating Multi ' + form + ' Report<br><i class="fad fa-file-spreadsheet"></i>')
    return deliveryPostPromise(ROOT_URL + '/functions/generators/genMultiPDF.php', {
        clientnumber: '<?= $_REQUEST['clientnumber']?>',
        items: array,
        form: form,
        tenant: TENANT_URL
    }).then(function(data) {
        data = String(data || '').trim();
        if (data !== '') {
            deliveryStoreAppend('multiList', data);
        }
        return data;
    });
}

function deliveryGenerateSinglePdf(token) {
    var y = String(token).split("-");
    $('#statusCount').html('Generating Report ' + (y[0] || '') + '<br><i class="fad fa-file-pdf"></i>')
    return deliveryPostPromise(ROOT_URL + '/functions/generators/checkPDF.php', {
        clientnumber: '<?= $_REQUEST['clientnumber']?>',
        repnumber: y[0],
        items: y[1],
        form: y[2],
        forceGen: document.getElementById('forceGen')?.checked ? 'force' : '',
        tenant: TENANT_URL
    }).then(function() {
        deliveryStoreAppend('multiList', token);
        return token;
    });
}

function deliveryProcessMultiFormGroup(form, group) {
    if (deliveryMultiCapableForms().indexOf(String(form)) === -1 || group.length <= 1) {
        return Promise.all(group.map(deliveryGenerateSinglePdf));
    }

    return deliveryCompareReportGroups(group).then(function(groups) {
        var jobs = [];
        groups.forEach(function(itemGroup) {
            if (!Array.isArray(itemGroup)) {
                itemGroup = [itemGroup];
            }
            itemGroup = itemGroup.filter(Boolean);
            if (itemGroup.length > 1) {
                jobs.push(deliveryGenerateMultiPdf(itemGroup, form));
            } else if (itemGroup.length === 1) {
                jobs.push(deliveryGenerateSinglePdf(itemGroup[0]));
            }
        });
        return Promise.all(jobs);
    });
}

function deliveryGenerateMultiOutputs(items) {
    var grouped = deliveryMultiGroupByForm(items);
    var jobs = Object.keys(grouped).map(function(form) {
        return deliveryProcessMultiFormGroup(form, grouped[form]);
    });

    if (!jobs.length) {
        return Promise.resolve([]);
    }

    return Promise.all(jobs);
}

function genPack(selected, errordel, hse) {
    console.log('genpack multi')
    $('#multiBox').modal('hide');
    $('#deliveryScreen').css('display', 'none');
    $('#loading').css('display', 'block')

    var varray = deliveryListFromAny(selected);
    var outputMode = parent.$("input[name='outputMode']:checked").val();

    deliveryStoreList('itemList', varray);
    deliveryStoreList('multiList', []);

    var scheduleJob = Promise.resolve();
    if (parent.$('#schAttach').is(":checked")) {
        $('#statusCount').html('Generating Schedule<br><i class="fad clipboard-list"></i>')
        scheduleJob = deliveryPostPromise(ROOT_URL + '/functions/generators/genShed.php', {
            clientnumber: '<?= $_REQUEST['clientnumber']?>',
            site: deliverySelectedSite,
            tenant: TENANT_URL
        });
    }

    scheduleJob
        .then(function() {
            $('#statusCount').html('Generating Report Covers<br><i class="fad fa-blanket"></i>')
            return deliveryGenerateCoversPromise(selected, 'multi');
        })
        .then(function() {
            return deliveryGenerateMultiOutputs(varray);
        })
        .then(function() {
            if (outputMode == "zip") {
                genZips(hse);
            }
            if (outputMode == "pdf") {
                genMPDO(hse);
            }
        })
        .catch(function(error) {
            console.error(error);
            $('#loading').css('display', 'none');
            showResponse('danger', 'Unable to generate all selected reports');
        });
}

// EOF GENPACK
////////////////////////////////////////////////////////////////////////////////
