<?php
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

$items = explode(",", $_REQUEST['items']);
$iCount = count($items);
require_once('../master/form_functions.php');
$repid = "001";
?>
<div id="loadingPNA" style="display:none">
    <h1 class="text-center"><i class="fad fa-flux-capacitor fa-spin fa-3x fa-fw"
            style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Creating PNA <br><small>Please
            wait</small>
    </h1>
</div>
<div id="start" class="row">
    <div class="col-12 alert warning-color-dark text-light p-1 text-center align-middle"><i
            class="fad fa-triangle-exclamation fa-2x" style="--fa-primary-color: white; --fa-secondary-color: red;"></i>
        This will apply to all selected items
        and cannot be undone automatically<br><small>All items will share the same REASON, EXAMINATION DATE, NEXT
            INSPECTION and SURVEYOR, irrespective of original values</small>
    </div>
    <p class="lead">You have chosen to mass PNA the following <b><?= $iCount ?></b> items</p>
    <?php
    foreach ($items as $item) {
        $item = str_replace("C", "", $item);
    ?>
    <div class="col-md-4">
        <div class="card me-2 mb-2 p-2"><?= $item ?> - <?= getItemDetails($item, 'name') ?></div>
    </div>
    <?php } ?>
    <form id="F<?= $repid ?>">
        <?php require_once('../../..' . TENANT_URL . '/forms/items/503.php'); ?>
        <?php require_once('../../..' . TENANT_URL . '/forms/items/base_data_modal.php'); ?>
        <input id="itemList" type="hidden" value="<?= $_REQUEST['items'] ?>">
        <input type="hidden" name="clientnumber" id="clientnumber" value="<?= $_REQUEST['clientnumber'] ?>" />
        <input type="hidden" name="locnumber" id="locnumber" value="<?= $d[1] ?>" />
        <input type="hidden" name="reptype" id="reptype" value="503" />
        <input type="hidden" name="FUNCTION" id="FUNCTION" value="create" />
        <input type="hidden" name="imageMode" id="imageSet" value="<?= $iMode ?>" />
        <input type="hidden" name="pageMode" id="pageSet" value="1" />
        <input type="hidden" id="btn_save" value="save" />
        <input type="hidden" name="tenant" value="<?= TENANT_URL ?>" />
    </form>
</div>
<div id="loader" style="display:none">
    <div class="col-12 text-center text-dark">
        <h1>
            <i class="fad fa-ring fa-spin fa-3x fa-fw"
                style="--fa-primary-color: #0055A6; --fa-secondary-color: grey;"></i><br>Processing
            Request<br><small>Please wait</small>
        </h1>
    </div>
</div>

<script>
var mySelect = new mdb.Select(document.getElementById('surveyor'), {
    filter: true,
    container: '#pnaBoxes'
});

// autofill Function
function autofill(f, s, t) {
    var dest = encodeURI(
        `${ROOT_URL}/includes/master/form_options.php?form=F<?= $repid ?>&source=${s}&type=${t}&tenant=${TENANT_URL}`
        )
    loadModalContent(dest, "popupBox", "modal-xl", 1061, "false", "Select Text", "cancel", );
}

function resetBox(t) {
    document.getElementById(t).value = "None";
    const event = new Event('keyup');
    document.getElementById(t).dispatchEvent(event);
}

function processPna() {
    // Disable all elements with the class 'actionButton'
    document.querySelectorAll('.actionButton').forEach(button => {
        button.disabled = true;
    });

    const pageSet = document.getElementById('pageSet').value;
    const imageSet = document.getElementById('imageSet').value;
    const items = document.getElementById('itemList').value.split(','); // Array of item numbers

    if (document.getElementById('surveyor').value === "NULL") {
        showResponse('danger', 'Please select surveyor before proceeding');
        document.querySelectorAll('.actionButton').forEach(button => {
            button.disabled = false;
        });
        return;
    }

    const formContainer = document.getElementById('formContainer');
    const loadingPNA = document.getElementById('loadingPNA');

    if (formContainer) {
        formContainer.style.opacity = '0.33';
        formContainer.style.transition = 'opacity 0.5s ease';
    }
    if (loadingPNA) {
        loadingPNA.style.display = 'block';
    }

    // Delay helper: returns a Promise that resolves after ms milliseconds.
    const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

    // Retry helper for PDF generation (up to maxRetries).
    const retryFetch = async (url, options, maxRetries = 3, retryDelay = 2000) => {
        let attempts = 0;
        while (attempts < maxRetries) {
            try {
                const response = await fetch(url, options);
                const text = await response.text();
                return text; // Return whatever text we get.
            } catch (error) {
                console.error(`Attempt ${attempts + 1} PDF fetch error:`, error);
            }
            attempts++;
            await delay(retryDelay);
        }
        return null;
    };

    // Main async function to process items sequentially.
    const processItems = async () => {
        for (const item of items) {
            console.log(`Starting processing for item: ${item}`);
            try {
                // Step 1: Get the old inspection date.
                const oldDateResponse = await fetch(`${ROOT_URL}/includes/master/form_functions.php`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        FUNCTION: 'getLastInspection',
                        tenant: TENANT_URL,
                        itemnumber: item
                    })
                });
                const olddate = await oldDateResponse.text();
                //console.log(`Old inspection date for item ${item}: ${olddate}`);

                // Step 2: Create the report (store data) for this item.
                const formData = new FormData(document.getElementById('F001'));
                formData.append('itemnumber', item);
                formData.append('olddate', olddate);

                const formResponse = await fetch(`${ROOT_URL}/includes/master/form_functions.php`, {
                    method: 'POST',
                    body: formData
                });
                const formResult = await formResponse.text();
                //console.log(`Report creation response for item ${item}: ${formResult}`);

                const parts = formResult.trim().split('|');
                if (parts[0] !== "success") {
                    //console.error(`Report creation failed for item ${item}: ${formResult}`);
                    showResponse('danger', `Report creation failed for item ${item}`);
                    continue; // Skip PDF generation for this item.
                }
                const repnumber = parts[1];
                console.log(`Received repnumber ${repnumber} for item ${item}`);

                // Step 3: Generate PDF.
                const expectedSuccess = repnumber + "-0-0" + item;
                const pdfPostData = {
                    orientation: pageSet,
                    imageMode: imageSet,
                    clientnumber: '<?= $_REQUEST['clientnumber'] ?>',
                    repnumber: repnumber,
                    items: item,
                    form: '503',
                    tenant: TENANT_URL
                };
                const pdfParams = new URLSearchParams(pdfPostData);
                const pdfOptions = {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: pdfParams.toString()
                };

                const pdfResult = await retryFetch(`${ROOT_URL}/functions/generators/genPDF2.php`, pdfOptions);
                if (!pdfResult || pdfResult.trim() !== expectedSuccess) {
                    //console.error(`PDF generation failed for item ${item}. Expected "${expectedSuccess}", got "${pdfResult}"`);
                    showResponse('danger', `PDF generation failed for item ${item}`);
                    // Optionally, you can decide to retry further or stop processing.
                } else {
                    //console.log(`PDF generation succeeded for item ${item}: ${pdfResult}`);
                }

                // Optional delay before processing the next item.
                await delay(1500);
            } catch (error) {
                console.error(`Error processing item ${item}:`, error);
                showResponse('danger', `Error processing item ${item}`);
            }
        }

        // All items processed.
        showResponse('success', 'Your data has been saved successfully');
        window.location.href = '<?= $_SESSION['returnLanding'] ?>';
    };

    // Invoke processItems after it's been defined.
    processItems();
}
</script>