var cc = '';

function deliveryRunHseZip(selected, errordel, hseFlag, delay) {
    if (hseFlag === '') {
        return;
    }

    setTimeout(function() {
        var defectListElement = document.getElementById('defectList');
        if (defectListElement) {
            console.log("defectList found, calling genHSEZip");
            genHSEZip(selected, errordel);
        } else {
            console.error("defectList not found.");
        }
    }, delay);
}

function deliveryGenerateReportPdfs(varray, selected, errordel, forceGen, outputMode) {
    var reportItems = varray.filter(function(item) {
        return item !== "";
    });
    var remaining = reportItems.length;

    $('#statusCount').text(remaining + ' Items remaining');

    if (remaining <= 0) {
        if (outputMode == "zip") {
            genZip(selected, errordel);
        }
        if (outputMode == "pdf") {
            genPDO(selected, errordel);
        }
        return;
    }

    reportItems.forEach(function(item) {
        var sarray = item.split('-');
        $.post(ROOT_URL + '/functions/generators/checkPDF.php', {
            clientnumber: '<?= $_REQUEST['clientnumber']?>',
            repnumber: sarray[0],
            items: sarray[1],
            form: sarray[2],
            forceGen: forceGen,
            split: "split",
            tenant: TENANT_URL,
            filePath: "regen"
        }, function(ret) {
            remaining -= 1;
            cc = remaining;
            $('#statusCount').html(cc + ' Items remaining<br><i class="fad fa-file-pdf"></i>');
            if (remaining <= 0) {
                if (outputMode == "zip") {
                    genZip(selected, errordel);
                }
                if (outputMode == "pdf") {
                    genPDO(selected, errordel);
                }
            }
        });
    });
}

function genFiles(selected, errordel, forceGen, hse) {
    console.log('merging')

    var outputMode = parent.$("input[name='outputMode']:checked").val();
    $('#deliveryScreen').css('display', 'none');
    var varray = deliveryListFromAny(selected);

    function generateSchedule(next) {
        $('#loading').css('display', 'block')
        $('#statusCount').html('Generating Schedule<br><i class="fad clipboard-list"></i>')
        $.post(ROOT_URL + '/functions/generators/genShed.php', {
            clientnumber: '<?= $_REQUEST['clientnumber']?>',
            site: deliverySelectedSite,
            tenant: TENANT_URL
        }, next);
    }

    function generateCovers(next) {
        $('#statusCount').html('Generating Report Cover<br><i class="fad fa-blanket"></i>')
        $('#loading').css('display', 'block')
        deliveryGenerateCovers(selected, 'single', function() {
            $('#string').val(selected)
            next();
        });
    }

    if (parent.$('#coverOutput').is(":checked")) {
        var coverNext = function() {
            genCvr(selected, errordel);
        };

        if (parent.$('#schAttach').is(":checked")) {
            generateSchedule(function() {
                generateCovers(coverNext);
            });
        } else {
            generateCovers(coverNext);
        }

        deliveryRunHseZip(selected, errordel, hse, 300);
        return;
    }

    var reportNext = function() {
        deliveryGenerateReportPdfs(varray, selected, errordel, forceGen, outputMode);
    };

    if (parent.$('#schAttach').is(":checked")) {
        generateSchedule(function() {
            generateCovers(reportNext);
        });
    } else {
        generateCovers(reportNext);
    }

    deliveryRunHseZip(selected, errordel, hse, 1400);
}
