<?php //echo "mode=".$_REQUEST['mode'];

if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
include('../../includes/master/mailer_functions.php');
$d[0] = $_REQUEST['clientnumber'];
$d[1] = 'report';

$email = getMasterDetails('delivery_email');
$subject = 'Your ' . strtoupper($_SESSION['user']) . ' inspection reports';

?>
<style>
.custom-file-button {
    input[type="file"] {
        margin-left: -2px !important;

        &::-webkit-file-upload-button {
            display: none;
        }

        &::file-selector-button {
            display: none;
        }
    }

    &:hover {
        label {
            background-color: #dde0e3;
            cursor: pointer;
        }
    }
}

/* Default: no internal scroll */
#deliveryMailerPane {
    max-height: none;
    overflow: visible;
}

/* Mobile/tablet */
@media (hover:none) and (pointer:coarse),
(max-width: 767.98px) {

    html,
    body {
        height: auto !important;
        overflow: auto !important;
    }

    #deliveryMailerPane {
        height: auto;
        max-height: none;
        min-height: 100dvh;
        /* handles mobile browser bars */
        overflow: visible;
        /* remove inner scroller */
        -webkit-overflow-scrolling: auto;
        overscroll-behavior: auto;
        padding-bottom: 96px;
        /* space for bottom buttons */
    }
}
</style>
<div id="deliveryMailerPane">
    <form id="mailerForm" class="form-horizontal" enctype="multipart/form-data">
        <div class="row">

            <div class="col-12 col-md-3">
                <div class="card mb-5">
                    <div class="card-header">Subject</div>
                    <div class="card-body">
                        <div class="row">
                            <div class="form-group col-12">
                                <input type="text" class="form-control" name="subject" id="subject"
                                    value="<?= getClientName($_REQUEST['clientnumber'], 'name') ?> -  Your examination documentation"
                                    autofocus />
                                <input type="hidden" name="company" value="<?= $xd['clientname'] ?>" readonly>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-12 col-md-9">
                <div class="card mb-5">
                    <div class="card-header">Message</div>
                    <div class="card-body">
                        <div class="row">
                            <div class="form-group col-12">
                                <textarea class="form-control" name="message" id="message"
                                    rows="1"><?= $message ?></textarea>
                            </div>
                        </div>
                    </div>
                </div>
            </div>


        </div>

        <div class="row">
            <div class="col-12 col-md-3">
                <div class="card mb-5">
                    <div id="notifyHeader" class="card-header">Notify HSE</div>
                    <div class="card-body">
                        <div class="col-12 col-md-9">
                            <span>No</span>&nbsp;&nbsp;<span class="form-switch form-input"><input type="checkbox"
                                    id="hseEnable" name="hseEnable"
                                    class="form-check-input" /></span>&nbsp;&nbsp;<span>Yes</span>
                        </div>

                        <div class="row form-group"  data-mdb-select-init data-mdb-filter="true">
                            <select style="width:100%" class="form-control" name="hse" id="hse"
                                data-placeholder="Select HSE" disabled>
                                <option>SELECT HSE</option><?= $hselist ?>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-12 col-md-4">
                <div class="card mb-5">
                    <div class="card-header">Recipients</div>
                    <div class="card-body">
                        <div id="recipientContainer">
                            <!-- existing 5 inputs go here -->
                        </div>

                        <button type="button" class="btn btn-info btn-sm my-2" onclick="addRecipientRow()">
                            <i class="fad fa-plus-circle me-1"></i> Add Recipient Entry
                        </button>
                        <button type="button" class="btn btn-secondary btn-sm float-end my-2" onclick="copyMeIn()">
                            <i class="fad fa-copy"></i> Copy Me In
                        </button>

                        <div class="row">
                            <div class="col-12 my-1 text-center mt-3">
                                <div class="input-group input-group mb-3">
                                    <button id="defaults" type="button"
                                        class="btn btn-light dropdown-toggle ms-auto me-auto" data-mdb-dropdown-init
                                        data-mdb-ripple-init data-mdb-toggle="dropdown" aria-expanded="false">
                                        Load address book recipients
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a class="dropdown-item" href="#" onclick="loadDefaultRecipients('all')">All
                                                Default</a></li>
                                        <hr class="dropdown-divider">
                                        <li><a class="dropdown-item" href="#"
                                                onclick="loadDefaultRecipients('billing')">Billing Only</a></li>
                                        <li><a class="dropdown-item" href="#"
                                                onclick="loadDefaultRecipients('renewal')">Renewal Only</a></li>
                                        <li><a class="dropdown-item" href="#"
                                                onclick="loadDefaultRecipients('delivery')">Delivery Only</a></li>
                                        <?php if ($mode === 'client'): ?>
                                        <li>
                                            <hr class="dropdown-divider">
                                        </li>
                                        <li><a class="dropdown-item" href="#"
                                                onclick="loadDefaultRecipients('client')">Client Only</a></li>
                                        <?php elseif ($mode === 'agent'): ?>
                                        <li>
                                            <hr class="dropdown-divider">
                                        </li>
                                        <li><a class="dropdown-item" href="#"
                                                onclick="loadDefaultRecipients('agent')">Agent Only</a></li>
                                        <?php elseif ($mode === 'broker'): ?>
                                        <li>
                                            <hr class="dropdown-divider">
                                        </li>
                                        <li><a class="dropdown-item" href="#"
                                                onclick="loadDefaultRecipients('broker')">Broker Only</a></li>
                                        <?php endif; ?>
                                    </ul>
                                </div>

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

                </div>
            </div>

            <div class="col-12 col-md-5">
                <div class="card mb-5">
                    <div class="card-header">Attachments
                        <?php if (!empty($_REQUEST['zips']) && $_REQUEST['zipMode'] != "split") { ?><span
                            class="float-end"><a class="btn btn-secondary me-2" onclick="saveFiles()"><i
                                    class="fad fa-cloud-upload"></i> Save for later</a><a id="reset"
                                class="btn btn-warning" onclick="reload()" style="display:none"><i class="fad fa-redo"
                                    style="--fa-secondary-color: black;"></i></a></span><?php } ?></div>
                    <div class="card-body">

                        <?php
                        if (!empty($_REQUEST['attachments'])) { ?>
                        <div id="fileList" class="row d-flex>">
                            <?php
                                $attachments = json_decode($_REQUEST['attachments'], true);
                                $count = count($attachments);
                                $saveArray = array();
                                $cnt = 1;
                                $wnt = 1;
                                $printArray = array();
                                foreach ($attachments as $file) {
                                    if ($count > 0) {
                                        if (empty($file) || $file['file'] == "_undefined.pdf" || $file['file'] == "") {
                                        } else {
                                            if ($file['type'] == "ws") {
                                                $icon = 'class="fad fa-file-word fa-2x" style="--fa-primary-color: black; --fa-secondary-color: white; filter: drop-shadow(0 0 2px #000)"';
                                                $delicon = '<a href="javascript:void(0)" onclick="wsDelete(\'' . $wnt . '\')"><i class="fad fa-window-close" style="cursor:pointer; --fa-primary-color: red;"></i></a>';
                                                $dID = ' id="wsContainer_' . $wnt . '"';
                                                $ident = 'wsreport_' . $wnt;
                                                $src = 'wssource_' . $wnt;
                                                $wnt++;
                                                $title = getWSNoDelivery($file['file']);
                                            }
                                            if ($file['type'] == "rc") {
                                                $icon = 'class="fad fa-file-prescription fa-2x" style="--fa-primary-color: blue; --fa-secondary-color: white; filter: drop-shadow(0 0 2px #000)"';
                                                $dID = '';
                                                $delicon = '';
                                                $ident = 'report_' . $cnt;
                                                $src = 'source_' . $cnt;
                                                $cnt++;
                                                $title = $file['file'];
                                            }
                                            if ($file['type'] == "pdf") {
                                                $icon = 'class="fad fa-file-pdf fa-2x" style="--fa-primary-color: red; --fa-secondary-color: white; filter: drop-shadow(0 0 2px #000)"';
                                                $dID = '';
                                                $delicon = '';
                                                $ident = 'report_' . $cnt;
                                                $src = 'source_' . $cnt;
                                                $cnt++;
                                                $title = $file['file'];
                                            }
                                            if ($file['type'] == "mpdf") {
                                                $icon = 'class="fad fa-file-spreadsheet fa-2x" style="--fa-primary-color: darkblue; --fa-secondary-color: white; filter: drop-shadow(0 0 2px #000)"';
                                                $dID = '';
                                                $delicon = '';
                                                $ident = 'report_' . $cnt;
                                                $src = 'source_' . $cnt;
                                                $cnt++;
                                                $title = $file['file'];
                                            }
                                            if ($file['type'] == "sch") {
                                                $icon = 'class="fad fa-clipboard-list fa-2x" style="--fa-primary-color: darkyellow; --fa-secondary-color: white; filter: drop-shadow(0 0 2px #000)"';
                                                $dID = '';
                                                $delicon = '';
                                                $ident = 'report_' . $cnt;
                                                $src = 'source_' . $cnt;
                                                $cnt++;
                                                $title = $file['file'];
                                            }
                                ?>
                            <div <?= $dID ?> class="col-1 mb-3 text-center rounded"><a
                                    href="<?= $file['source'] ?>/<?= $file['file'] ?>" target="_BLANK"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                    data-html="true" title="<?= $title ?>"><i <?= $icon ?>></i></a>
                                <!--<div class="input-group-prepend btn-info"> <button class="btn btn-md btn-info m-0 px-3" type="button">Reports</button></div>-->
                                <input type="hidden" name="<?= $ident ?>" id="<?= $ident ?>"
                                    value="<?= $file['file'] ?>" readonly>
                                <input type="hidden" name="<?= $src ?>" id="<?= $src ?>" value="<?= $file['source'] ?>"
                                    readonly>
                                <?= $delicon ?>
                            </div>

                            <?php $printArray[] = "../" . $file['source'] . "/" . $file['file'];
                                        }
                                    }
                                } ?>
                        </div>
                        <?php }
                        if (!empty($_REQUEST['zips']) && $_REQUEST['zipMode'] != "split") {
                            $attachments = json_decode($_REQUEST['zips'], true);
                            if ($attachments['type'] == "sch") {
                                $icon = 'class="fad fa-clipboard-list fa-2x" style="--fa-primary-color: darkyellow; --fa-secondary-color: white; filter: drop-shadow(0 0 2px #000)"';
                            }
                            if ($attachments['type'] == "zip") {
                                $icon = 'class="fad fa-file-archive fa-2x" style="--fa-primary-color: white; --fa-secondary-color: orange; filter: drop-shadow(0 0 2px #000)"';
                            }
                            $saveArray[] = $attachments['file'];

                        ?>
                        <div class="row d-flex">
                            <div class="col-1 mb-3 text-center rounded"><a id="link_1"
                                    href="output/reports/<?= $_REQUEST['clientnumber'] ?>/<?= $attachments['file'] ?>"
                                    target="_BLANK" data-mdb-tooltip-init data-mdb-placement="top"
                                    data-mdb-trigger="hover" data-html="true" title="<?= $file['file'] ?>"><i
                                        <?= $icon ?>></i></a>
                                <!--<div class="input-group-prepend btn-info"> <button class="btn btn-md btn-info m-0 px-3" type="button">Reports</button></div>-->
                                <input type="hidden" class="form-control-sm filename is-valid" name="report_1"
                                    id="report_1" value="<?= $attachments['file'] ?>" readonly>
                                <input type="hidden" name="source_1" id="source_1" value="<?= $attachments['source'] ?>"
                                    readonly>
                                <span class="badge badge-pill badge-dark"
                                    onclick="fileRename('report_1','<?= $attachments['file'] ?>')"><i
                                        class="fad fa-file-signature"
                                        style="cursor:pointer; --fa-primary-color: white;"></i></span>
                            </div>

                        </div>

                        <?php $savedMode = "yes";
                        }

                        if (!empty($_REQUEST['zips']) && $_REQUEST['zipMode'] == "split") {
                            $attachments = json_decode($_REQUEST['zips'], true);
                            $cnt = 1; ?>
                        <div class="row d-flex">
                            <?php
                                foreach ($attachments as $file) {
                                    if ($file['type'] == "sch") {
                                        $icon = 'class="fad fa-clipboard-list fa-2x" style="--fa-primary-color: darkyellow; --fa-secondary-color: white; filter: drop-shadow(0 0 2px #000)"';
                                    }
                                    if ($file['type'] == "zip") {
                                        $icon = 'class="fad fa-file-archive fa-2x" style="--fa-primary-color: white; --fa-secondary-color: orange; filter: drop-shadow(0 0 2px #000)"';
                                    }
                                ?>

                            <div class="col-1 mb-3 text-center rounded"><a
                                    href="<?= $file['source'] ?>/<?= $file['file'] ?>" target="_BLANK"
                                    data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
                                    data-html="true" title="<?= $file['file'] ?>"><i <?= $icon ?>></i></a>
                                <!--<div class="input-group-prepend btn-info"> <button class="btn btn-md btn-info m-0 px-3" type="button">Reports</button></div>-->
                                <input type="hidden" class="form-control-sm filename is-valid" name="report_<?= $cnt ?>"
                                    id="report_<?= $cnt ?>" value="<?= $file['file'] ?>" readonly>
                                <input type="hidden" name="source_<?= $cnt ?>" id="source_<?= $cnt ?>"
                                    value="<?= $file['source'] ?>" readonly>

                            </div>

                            <?php $cnt++;
                                } ?>
                        </div>
                        <?php } ?>



                        <div class="input-group mb-3 custom-file-button">
                            <label class="input-group-text" for="attachment_2"><i class="fad fa-paperclip"></i></label>
                            <input type="file" class="form-control" name="attachment_additional"
                                id="attachment_additional" />
                            <input type="hidden" class="form-control" name="source_additional" id="source_additional"
                                readonly>
                        </div>



                    </div>
                </div>

                <?php if ($savedMode == "yes") { ?>

                <div class="card mb-5">
                    <div class="card-header">Saved <span class="float-end">
                            <div class="form-check form-switch">
                                <input type="checkbox" class="form-check-input" id="attachSaved" name="attachSaved"
                                    value="on">
                                <label class="form-check-label" for="attachSaved">Attach Saved files</label>
                            </div>
                        </span></div>
                    <div class="card-body">
                        <?php $files = glob("../../../" . TENANT_URL . "/output/reports/" . $_REQUEST['clientnumber'] . "/saved/*");
                            if (count($files) > 0) {
                                $fcnt = 1;
                                foreach ($files as $myfiles) {
                                    $path_parts = pathinfo($myfiles);
                                    $download = str_replace("../../../" . TENANT_URL . "/", '', $myfiles);
                                    $savedSource = $path_parts['dirname'];
                                    $savedSource = str_replace("../../../" . TENANT_URL . "/", '', $savedSource);
                                    $of .= '<div id="F' . $fcnt . '" class="col-1 mb-3 text-center rounded"><a href="' . $download . '"><i class="fad fa-file-archive fa-2x" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"  data-html="true" title="' . $path_parts['basename'] . '"></i></a><a href="javascript:void(0)"onclick="fileDelete(\'' . $download . '\',\'' . $fcnt . '\',\'' . $path_parts['basename'] . '\')"><i class="fad fa-window-close" style="--fa-primary-color: red;"></a></i><input type="hidden" class="form-control-sm filename is-valid" name="saved_' . $fcnt . '" id="saved_' . $fcnt . '" value="' . $path_parts['basename'] . '" readonly><input type="hidden" name="savedSource_' . $fcnt . '" id="savedSource_' . $fcnt . '" value="' . $savedSource . '" readonly></div>';
                                    $fcnt++;
                                }
                            ?>

                        <?php } ?>
                        <div class="col-12">
                            <div id="filesRow" class="row d-flex"><?= $of ?></div>
                        </div>
                    </div>
                </div>
            </div>
            <?php } ?>
        </div>
</div>

<div id="printArray" style="display:none"><?= json_encode($printArray) ?></div>
<div id="saverray" style="display:none"><?= json_encode($saveArray) ?></div>
<div id="erm" class="text-center"></div>
<input type="hidden" id="defectList" name="defectListItems" value="0" />
<input type="hidden" id="tenant" name="tenant" value="<?= TENANT_URL ?>" />
<input type="hidden" id="clientnumber" name="clientnumber" value="<?= $_REQUEST['clientnumber'] ?>" />
<input type="hidden" id="company" name="company" value="<?= $_REQUEST['clientnumber'] ?>" />
<div class="text-center"><input id="mailSendButton" type="submit" class="btn btn-info mt-3 mb-4" value="Send Documents">
</div>
</form>


<div id="sending" 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>Sending Documents<br><small>Please
            wait</small>

    </h1>
</div>

<div id="complete" class="col-md-12 text-center" style="display:none">
    <h3 class="alert alert-success">Emails sent successfully</h3>
    <a class="btn btn-secondary me-4"
        href="index.php?t=includes/master&p=delivery.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>">Start Again</a>
    <a class="btn btn-default" href="javascript:void(0)" onClick="printReports()">Print Reports</a>
</div>
<div id="error" class="col-md-12 text-center" style="display:none">
    <h3 class="alert alert-danger">There was a problem</h3>
    <p id="errorMessage"></p>
    <?php if ($delivery == "active") { ?> <a class="btn btn-secondary"
        href="index.php?t=includes/master&p=delivery.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>">Try
        Again</a><?php } ?>
</div>
</div>
<script>

var mySelect = new mdb.Select(document.getElementById('hse'), {
    filter: true,
    container: "body"
})
var D_0 = '<?= $d[0] ?>';
var D_2 = '<?= $d[2] ?>';
var D_5 = '<?= $d[5] ?>';
var D_8 = '<?= $d[8] ?>';
var D_9 = '<?= $d[9] ?>';

var companyEmail = '<?= getCompanyDetails('email') ?>'

function initializeTooltips() {
    const tooltipElements = document.querySelectorAll('[data-mdb-tooltip-init]');

    tooltipElements.forEach((element) => {
        new mdb.Tooltip(element);
    });
}
document.getElementById('message').textContent = document.getElementById('messageHolder').textContent;
var chainMode = parent.document.querySelector("input[name='chainMode']:checked").value;
var outputMode = parent.document.querySelector("input[name='outputMode']:checked").value;

function wsDelete(i) {
    var wsContainer = document.getElementById('wsContainer_' + i);
    wsContainer.style.transition = 'opacity 0.5s';
    wsContainer.style.opacity = 0;
    setTimeout(function() {
        wsContainer.remove();
    }, 500);
}




function matchCustom(params, data) {
    if (typeof data.value === 'undefined') {
        return null;
    }
}
document.querySelectorAll('[data-mdb-toggle="dropdown"]').forEach((el) => {
    new mdb.Dropdown(el);
});

document.getElementById("hseEnable").addEventListener('change', function() {
    if (this.checked) {
        document.getElementById("hse").removeAttribute('disabled');
        loadDefect();
    } else {
        document.getElementById("hse").setAttribute('disabled', 'true');
    }
});

document.querySelectorAll(".select2-results__option").forEach(function(element) {
    element.setAttribute('disabled', 'disabled');
});

function clearField(i) {
    document.getElementById(i).value = '';
}

function getDefaultRecipents(forceType = null) {
    // Use forced type if passed in, otherwise use select value
    const addressType = forceType || document.getElementById('defaultAddressType')?.value || 'delivery';

    switch (addressType) {
        case 'default':
            loadDefaultRecipients('default');
            break;
        case 'all':
        case 'billing':
        case 'renewal':
        case 'delivery':
            loadDefaultRecipients(addressType);
            break;
        default:
            console.warn('Unknown address type:', addressType);
            break;
    }
}

function loadDefaultRecipients(type) {
    const container = document.getElementById('recipientContainer');

    // Clear existing recipients
    while (container.firstChild) {
        container.removeChild(container.firstChild);
    }

    let index = 1;

    // Only inject primary/secondary if type is "default"
    if (type === 'default') {
        if (typeof primaryEmail !== 'undefined' && primaryEmail) {
            container.appendChild(createRecipientRow(index++, primaryEmail));
        }
        if (typeof secondaryEmail !== 'undefined' && secondaryEmail) {
            container.appendChild(createRecipientRow(index++, secondaryEmail));
        }
    }

    // Fetch recipients from backend
    const formData = new FormData();
    formData.append('clientnumber', D_0);
    formData.append('tenant', TENANT_URL);
    formData.append('type', type);

    fetch(ROOT_URL + '/functions/loadEmail.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(ret => {
            if (ret.length === 0 && type !== 'default') {
                const alertRow = document.createElement('div');
                alertRow.className = 'alert alert-warning p-2 mb-2 small text-center';
                alertRow.style.fontSize = '0.8rem';
                alertRow.textContent = `No recipients in the "${type}" group found. Select "All Default"`;
                container.appendChild(alertRow);
                return;
            }

            ret.forEach(item => {
                container.appendChild(createRecipientRow(index++, item.email));
            });
        })
        .catch(error => {
            console.error('Error loading addresses:', error);
        });
}



function createRecipientRow(index, value = '') {
    const row = document.createElement('div');
    row.className = 'input-group input-group-sm mb-2';
    row.id = 'recipient_row_' + index;

    row.innerHTML = `
        <input type="text" class="form-control form-control-sm" name="recipient_${index}" id="recipient_${index}" value="${value}" placeholder="Add Recipient" />
        <button type="button" class="btn btn-danger" onclick="clearField('recipient_${index}')"><i class="fad fa-ban"></i></button>
    `;

    return row;
}

function loadDefaultAddress() {
    var selectedType = document.getElementById('defaultAddressType')?.value || 'delivery';
    loadDefaultRecipients(selectedType);
}


function addRecipientRow() {
    const container = document.getElementById('recipientContainer');
    const lastIndex = [...container.querySelectorAll('input[id^="recipient_"]')]
        .map(el => parseInt(el.id.split('_')[1]))
        .reduce((a, b) => Math.max(a, b), 0);

    const n = lastIndex + 1;
    const row = document.createElement('div');
    row.className = 'input-group input-group-sm mb-2';
    row.id = 'recipient_row_' + n;

    row.innerHTML = `
        <input type="text" class="form-control form-control-sm" name="recipient_${n}" id="recipient_${n}" placeholder="Add Recipient" />
        <button type="button" class="btn btn-danger" onclick="clearField('recipient_${n}')"><i class="fad fa-ban"></i></button>
    `;

    container.appendChild(row);
}

function saveFiles() {
    var files = document.getElementById('saverray').textContent;
    var obj = JSON.parse(files);
    var name = obj[0].replace('.zip', '');
    var dest = '';
    dest +=
        '<p class="text-center lead">If you wish to rename the file for ease of use, enter the name in the box below</p>';
    dest +=
        '<div class="col-12"><input type="text" class="form-control" placeholder="New file name" id="name" value="' +
        name + '" /></div>';

    loadModalContent(dest, "saveBox", "modal-sm", 1060, "true", "Save files", "confirm", saveConfirm);
}

function saveConfirm() {
    var files = document.getElementById('saverray').textContent;
    var name = document.getElementById("name").value;
    killModal('saveBox')
    document.getElementById("name").value = '';
    var reps = document.getElementById('itemList').textContent;
    fetch(ROOT_URL + '/functions/deliveryModules/saveFiles.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `FCN=save&client=<?= $_REQUEST['clientnumber'] ?>&files=${encodeURIComponent(files)}&name=${encodeURIComponent(name)}&reps=${encodeURIComponent(reps)}&tenant=${TENANT_URL}`
        }).then(response => response.text())
        .then(ret => {
            var d = ret.trim().split('|');
            if (d[0] === "saved") {
                showResponse('success', 'Archive saved successfully');
                var nfile = '';
                var n = Math.floor(Math.random() * (100 - 70 + 1) + 70);

                nfile += '<div id="F' + n + '" class="col-1 mb-3 text-center rounded"><a href="' + d[2] +
                    '"><i class="fad fa-file-archive fa-2x" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"  data-html="true" title="' +
                    d[
                        1] + '"></i></a><a href="javascript:void(0)" onclick="fileDelete(\'' + d[2] + '\',\'' + n +
                    '\',\'' + d[1] +
                    '\')"><i class="fad fa-window-close" style="--fa-primary-color: red;"></i></a><input type="hidden" class="form-control-sm filename is-valid" name="saved_' +
                    n + '" id="saved_' + n + '" value="' + d[1] +
                    '" readonly><input type="hidden" name="savedSource_' + n + '" id="savedSource_' +
                    n + '" value="' + d[3] + '" readonly></div>';
                document.getElementById('filesRow').innerHTML += nfile;
                document.getElementById('reset').style.display = 'inline-block';
            }
        });
}

function fileDelete(f, t, n) {
    dest = '<p>Are you sure you wish to remove the saved archive <strong>' + n + '</strong>?</p>'
    loadModalContent(dest, "deleteBox", "modal-sm", 1060, "true", "Delete File", "confirm", "deleteConfirm('" + f +
        "','" + t + "')");

}

function deleteConfirm(f, t) {
    var reps = document.getElementById('itemList').textContent;
    killModal('deleteBox')
    fetch(ROOT_URL + '/functions/deliveryModules/saveFiles.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `FCN=delete&client=<?= $_REQUEST['clientnumber'] ?>&files=${encodeURIComponent(f)}&reps=${encodeURIComponent(reps)}&tenant=${TENANT_URL}`
        }).then(response => response.text())
        .then(ret => {
            if (ret.trim() === "removed") {
                document.getElementById('F' + t).remove();
                showResponse('success', 'Archive removed successfully');
            }
        });
}

function fileRename(t, f) {
    var name = f.replace('.zip', '');
    dest = "<p>Do you want to rename the file?</p><p>New Name: <input id='newName' class='form-control'></p>"
    loadModalContent(dest, "fileBox", "modal-sm", 1060, "true", "Rename File", "confirm", "renameConfirm('" + t +
        "','" + f + "')");
}

function renameConfirm(t, f) {
    var newname = document.getElementById("newName").value;
    killModal('fileBox')
    document.getElementById("newName").value = '';
    fetch(ROOT_URL + '/functions/deliveryModules/saveFiles.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `FCN=rename&client=<?= $_REQUEST['clientnumber'] ?>&file=${encodeURIComponent(f)}&newName=${encodeURIComponent(newname)}&tenant=${TENANT_URL}`
        }).then(response => response.text())
        .then(ret => {
            var d = ret.trim().split('|');
            if (d[0] === "renamed") {
                showResponse('success', 'Archive renamed successfully');
                var nname = [d[1] + '.zip'];

                document.getElementById("saverray").textContent = JSON.stringify(nname);
                document.getElementById("link_1").setAttribute('href', d[2] + '.zip');
                document.getElementById(t).value = d[1] + '.zip';
            }
        });
}

function reload() {
    location.reload();
}

function printReports() {
    // Path to the reports.pdf file
    var pdfUrl = `output/reports/<?= $_REQUEST['clientnumber'] ?>/report.pdf`;

    // Open the PDF in a new tab and trigger print dialog
    var win = window.open(pdfUrl, '_blank');
    if (win) {
        win.focus();
        win.print();
    } else {
        showResponse('warning', "Please allow popups for this website to print the reports.");

    }
}

function copyMeIn() {

    if (document.getElementById('BCCrecipient')) return;

    const container = document.getElementById('recipientContainer');
    const lastIndex = [...container.querySelectorAll('input[id^="recipient_"]')]
        .map(el => parseInt(el.id.split('_')[1]) || 0)
        .reduce((a, b) => Math.max(a, b), 0);

    const n = lastIndex + 1;
    const email = companyEmail || '';

    const row = document.createElement('div');
    row.className = 'input-group input-group-sm mb-2';
    row.id = 'recipient_row_bcc';

    row.innerHTML = `
        <input type="text" 
               class="form-control form-control-sm bg-light text-muted" 
               name="BCCrecipient" 
               id="BCCrecipient" 
               value="${email}" 
               placeholder="BCC to Self" 
               readonly />
        <button type="button" class="btn btn-danger-dark" onclick="clearField('BCCrecipient')">
            <i class="fad fa-ban"></i>
        </button>
    `;

    container.appendChild(row);
}


getDefaultRecipents('default');
initializeTooltips();
getDefaultRecipents();
</script>