<?php require_once(ROOT_URL . '/includes/master/form_functions.php');

switch ($_REQUEST['FUNCTION']) {
    default:
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `clientnumber`='" . $_REQUEST['clientnumber'] . "'") or die(mysqli_error($GLOBALS['con']));
        $stmt->execute();
        $s = $stmt->get_result();
        $stmt->close();
        $xd = mysqli_fetch_array($s);

?>

<script>
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Client List</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>&view=asset"><?= addslashes(getClientName($_REQUEST['clientnumber'])) ?></a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadcrumb-item active">Document Delivery</li>'
</script>


<div id="deliveryScreen" class=" mt-n5 mt-md-0">

    <div id="loadingObject" style="display: none">
        <h1 class="text-center"><i class="fad fa-spinner fa-pulse fa-3x fa-fw"
                style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Loading reports available for
            delivery <br><small>Please wait, this may take a
                while</small></h1>
    </div>

    <div id="initialScreen">
        <div class="row">
            <div class="col-12"><?= checkAuto($_REQUEST['clientnumber']) ?></div>
        </div>


        <section class="dark-grey-text">

            <div class="row">

                <div class="col-12 col-md-4 mb-4">
                    <a href="javascript:void(0)" class="card hoverable">
                        <div class="card-body">
                            <span
                                class="card-img-100 d-inline-flex justify-content-center align-items-center rounded-circle grey lighten-3 me-4">
                                <i class="fad fa-building fa-2x green-text"></i>
                            </span>
                            <span class="dark-grey-text mb-3 fs-4">Site <span
                                    class="text-muted fs-6">(optional)</span></span>
                            <?= getsites2($_REQUEST['clientnumber'], '') ?>
                        </div>
                    </a>
                </div>

                <div class="col-12 col-md-4 mb-4">
                    <a href="javascript:void(0)" class="card hoverable">
                        <div class="card-body date-picker" data-mdb-input-init data-mdb-toggle-button="false"
                            data-mdb-format="dd-mm-yyyy">

                            <span
                                class="card-img-100 d-inline-flex justify-content-center align-items-center rounded-circle grey lighten-3 me-4">
                                <i class="fad fa-calendar-alt fa-2x text-info"></i>
                            </span>

                            <span class="dark-grey-text mb-3 fs-4">Start Date</span>
                            <input data-mdb-toggle="datepicker" class="form-control" type="text" name="date_start"
                                id="date_start" placeholder="Click or tap to begin" />

                        </div>
                    </a>
                </div>

                <div class="col-12 col-md-4 mb-4">
                    <a href="javascript:void(0)" class="card hoverable">
                        <div class="card-body date-picker" data-mdb-input-init data-mdb-toggle-button="false"
                            data-mdb-format="dd-mm-yyyy">

                            <span
                                class="card-img-100 d-inline-flex justify-content-center align-items-center rounded-circle grey lighten-3 me-4">
                                <i class="fad fa-calendar-alt fa-2x  purple-text"></i>
                            </span>

                            <span class="dark-grey-text mb-3 fs-4">End Date</span>
                            <input data-mdb-toggle="datepicker" class="form-control datepicker" type="text"
                                name="date_end" id="date_end" placeholder="END DATE" value="<?= date('d-m-Y') ?>" />

                        </div>
                    </a>
                </div>

            </div>
            <div class="col-md-12 text-center mt-4"><a class="btn btn-info" href="javascript:void(0)"
                    onClick="loadReports()">Load Reports</a></div>
        </section>


        <div class="container pt-5 my-5 z-depth-1">
            <section class="p-md-3 mx-md-5">
                <div class="row d-flex justify-content-between align-items-center">
                    <div class="col-md-6 mb-4">
                        <h2 class="font-weight-bold mb-3">Inspection Certificate Delivery</h2>
                        <p class="text-muted pt-3">The delivery system has been designed to give you the maximum control
                            over your destinations with multiple delivery options.</p>
                    </div>
                    <div class="col-md-6 col-lg-4 d-flex justify-content-center mb-md-0 mb-5">
                        <i class="fad fa-layer-group indigo-text fa-10x"></i>
                    </div>
                </div>

                <div class="row pt-3">
                    <div class="col-lg-3 col-md-6 mb-5">
                        <h5 class="font-weight-bold mb-3"><i class="fad fa-paper-plane indigo-text pr-2"></i> Live
                            Filters</h5>
                        <p class="text-muted mb-lg-0">Filter your available reports based on multiple factors such as
                            dynamic grouping.</p>
                    </div>

                    <div class="col-lg-3 col-md-6 mb-5">
                        <h5 class="font-weight-bold mb-3"><i class="fad fa-pen-alt green-text pr-2"></i> Report Merging
                        </h5>
                        <p class="text-muted mb-lg-0">Combine reports into a single unified document for faster dispatch
                        </p>
                    </div>

                    <div class="col-lg-3 col-md-6 mb-5">
                        <h5 class="font-weight-bold mb-3"><i class="fad fa-user amber-text pr-2"></i> Manual Sorting
                        </h5>
                        <p class="text-muted mb-md-0">Manual sort options to output your preferred layout</p>
                    </div>

                    <div class="col-lg-3 col-md-6 mb-5">
                        <h5 class="font-weight-bold mb-3"><i class="fad fa-rocket blue-text pr-2"></i> Intelligent
                            Detection</h5>
                        <p class="text-muted mb-md-0">EnRep systems dynamically merge, and split inspection reports
                            based on regulations and inspection engineers. Dramatically reducingthe time required to
                            dispatch large numbers of
                            certificates,</p>
                    </div>
                </div>

            </section>
        </div>

    </div>
    <div id="reports"></div>
</div>



<div id="loading" class="col-md-12 text-center" style="display:none; color:#393939">
    <h1>
        <i class="fad fa-spinner fa-pulse fa-3x fa-fw"
            style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Generating
        Documents<br><small>Please wait</small><br>
        <span id="statusCount" class="text-muted" style="font-size: 20px"></span>
    </h1>
</div>

<?php if ($xd['delivery_pref'] == 2) { ?>
<div id="itemList" style="display:none">delivery</div>
<div id="delivery" style="display:none">
    <div id="messageHolder" style="display:none"></div>
    <div id="outputMode" style="display:none"></div>

    <div id="multiList" style="display:none"></div>
    <div id="debug" style="display:none">0</div>
    <div id="defectTemp" style="display:none">0</div>
    <div id="defectList" style="display:none"></div>
    <div class="alert alert-warning">
        <h2 class="text-center">The Customer <strong><?= $xd['clientname'] ?></strong> requests that all certificates
            are delivered in person or by post</h2>

    </div>
    <div id="printReports" style="display:none" class="text-center"><a class="btn btn-default" href="javascript:void(0)"
            onClick="printReports()">Print Reports</a></div>
</div>

<?php } else { ?>
<div id="itemList" style="display:none">delivery</div>
<div id="delivery" class="mt-n5 mt-md-0" style="display:none">

    <span class="badge badge-pill badge-primary mb-4">4</span> SELECT RECIPIENT AND SEND


    <div id="hseNotice" class="col-md-12"></div>
    <div class="clearfix"></div>
    <div id="messageHolder" style="display:none"></div>
    <div id="outputMode" style="display:none"></div>
    <div id="mailerContainer"></div>

    <div id="multiList" style="display:none"></div>
    <div id="debug" style="display:none">0</div>
    <div id="defectTemp" style="display:none">0</div>
    <div id="defectList" style="display:none"></div>
</div>
<?php }
} ?>

<script>
var namesElement = document.getElementById('names');
if (namesElement) {
    namesElement.addEventListener('change', function() {
        var recipientElement = document.getElementById('recipient');
        if (recipientElement) {
            recipientElement.value = namesElement.value;
        }
    });
}

function loadReports() {
    var xsite = document.getElementById('siteList').value;
    var xstart = document.getElementById('date_start').value;
    var xend = document.getElementById('date_end').value;

    if (xstart === '' || xend === '') {
        showResponse('danger', 'Please set START date and END date before proceeding');
    } else {
        document.getElementById('initialScreen').style.display = 'none';
        document.getElementById('loadingObject').style.display = 'block';

        var params = 'site=' + encodeURIComponent(xsite) +
            '&clientnumber=' + encodeURIComponent('<?= $_REQUEST['clientnumber'] ?>') +
            '&start=' + encodeURIComponent(xstart) +
            '&end=' + encodeURIComponent(xend) +
            '&tenant=' + TENANT_URL;

        // Use the loadContentAndExecuteScripts function to load the content
        loadContentAndExecuteScripts(ROOT_URL + '/functions/generators/genReports.php', 'reports', params, function() {
            // Hide the loading object when the reports are loaded
            document.getElementById('loadingObject').style.display = 'none';
            document.getElementById('messageHolder').textContent =
                'Please find attached your inspection reports for the period ' + xstart + ' - ' + xend + '.';
        });
    }
}


function loadDefect() {
    var list = document.getElementById('defectTemp').textContent;
    document.getElementById('defectList').value = list;
}

function printReports() {
    var reps = document.getElementById('printArray').textContent;

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'functions/printMerge.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var ret = xhr.responseText.trim();
            //alert(ret);
            if (ret === "s") {
                printJS('output/reports/<?= $_REQUEST['clientnumber'] ?>/reports.pdf');
            }
        }
    };
    xhr.send('files=' + encodeURIComponent(reps) +
        '&client=' + encodeURIComponent('<?= $_REQUEST['clientnumber'] ?>'));
}

<?php if ($_REQUEST['items'] != "") { ?>
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('initialScreen').style.display = 'none';

    var params = 'clientnumber=' + encodeURIComponent('<?= $_REQUEST["clientnumber"] ?>') +
        '&tenant=' + TENANT_URL +
        '&items=' + encodeURIComponent('<?= $_REQUEST["clientnumber"] ?>');

    loadContentAndExecuteScripts(ROOT_URL + '/functions/generators/genReports.php', 'reports', params,
    function() {
        // Hide the loading object when the reports are loaded
        document.getElementById('messageHolder').textContent =
            'Please find attached your inspection reports.';
    });
});



<?php } ?>
// Global, resilient submit handler for dynamically injected #mailerForm
function handleMailerSubmit() {
    event.preventDefault();

    // recipients check
    if (
        !document.getElementById("recipient_1").value &&
        !document.getElementById("recipient_2").value &&
        !document.getElementById("recipient_3").value &&
        !document.getElementById("recipient_4").value
    ) {
        showResponse('warning', 'Please add at least one recipient');
        return;
    }

    const s = document.getElementById("subject").value.trim();
    const m = document.getElementById("message").value.trim();
    if (!s || !m) {
        showResponse('warning', 'Please complete "subject" and "message" fields');
        return;
    }
    const defectList = document.getElementById('defectList');
    const defectListValue = defectList.value;
    const sending = document.getElementById('sending');
    const hseNotice = document.getElementById('hseNotice');
    const mailerForm = document.getElementById('mailerForm');
    const mailSendButton = document.getElementById('mailSendButton');
    if (sending) sending.style.display = 'block';
    if (hseNotice) hseNotice.style.display = 'none';
    if (mailerForm) mailerForm.style.display = 'none';
    if (mailSendButton) mailSendButton.style.display = 'none';
    const formData = new FormData(event.target);
    formData.set('tenant', TENANT_URL);
     formData.set('defectListItems', defectListValue);
    fetch(ROOT_URL + '/functions/sendDeliveryMail.php', {
            method: 'POST',
            body: formData
        })
        .then(r => r.json())
        .then(result => {
            if (sending) sending.style.display = 'none';
            if (result.status === 'success') {
                document.getElementById('error')?.style && (document.getElementById('error').style.display =
                'none');
                document.getElementById('complete')?.style && (document.getElementById('complete').style.display =
                    'block');

                if (document.getElementById('bypass')?.checked) {
                    showResponse('warning', 'Your email was sent successfully, but date bypass detected');
                } else {
                    showResponse('success', result.message);
                    if (typeof genMasterPDF === 'function') genMasterPDF();
                }

                const items = document.getElementById('itemList')?.textContent || '';
                const multi = document.getElementById('multiList')?.textContent || '';
                const mode = multi ? 'multi' : '';
                if (!document.getElementById('bypass')?.checked) {
                    fetch(ROOT_URL + '/includes/master/report_functions.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: `FUNCTION=setDelivered&string=${encodeURIComponent(items)}&mode=${mode}&tenant=${TENANT_URL}`
                    });
                }
            } else {
                document.getElementById('error')?.style && (document.getElementById('error').style.display =
                    'block');
                const em = document.getElementById('errorMessage');
                if (em) em.textContent = result.message || 'An error occurred.';
            }
        })
        .catch(() => {
            if (sending) sending.style.display = 'none';
            document.getElementById('error')?.style && (document.getElementById('error').style.display = 'block');
            const em = document.getElementById('errorMessage');
            if (em) em.textContent = 'An unexpected error occurred. Please try again later.';
        });
}

// Capture-phase delegation so it works for dynamically injected content
document.addEventListener('submit', function(e) {
    if (e.target && e.target.id === 'mailerForm') {
        handleMailerSubmit(e);
    }
}, true);

// Optional: ensure button click triggers submit even if native submit is blocked
document.addEventListener('click', function(e) {
    if (e.target && e.target.id === 'mailSendButton') {
        e.preventDefault();
        const form = document.getElementById('mailerForm');
        if (form) {
            if (typeof form.requestSubmit === 'function') form.requestSubmit();
            else form.dispatchEvent(new Event('submit', {
                cancelable: true,
                bubbles: true
            }));
        }
    }
}, true);
</script>