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

$jsonInput = json_decode(file_get_contents('php://input'), true);
if (is_array($jsonInput)) {
    foreach ($jsonInput as $key => $value) {
        $_REQUEST[$key] = is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
    }
}

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');
include_once(__DIR__ . '/../client/client_addressbook_mailer_helper.php');
$d[0] = $_REQUEST['clientnumber'];
$d[1] = 'report';

$email = getMasterDetails('delivery_email');
$clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
$clientName = getClientName($clientnumber, 'name');
$locationName = trim((string)($_REQUEST['locationName'] ?? ''));
$dateStart = trim((string)($_REQUEST['dateStart'] ?? $_REQUEST['start'] ?? ''));
$dateEnd = trim((string)($_REQUEST['dateEnd'] ?? $_REQUEST['end'] ?? ''));
$dateRange = '';
$subject = $clientName . ' -  Your examination documentation';
$message = '';
$useDefaultReportMessage = false;
$attachmentTotalBytes = 0;
$printArray = [];
$saveArray = [];
$savedMode = "no";
$deliveryWarnings = [];

if (!empty($_REQUEST['deliveryWarnings'])) {
    $decodedWarnings = is_array($_REQUEST['deliveryWarnings'])
        ? $_REQUEST['deliveryWarnings']
        : json_decode((string)$_REQUEST['deliveryWarnings'], true);
    if (is_array($decodedWarnings)) {
        $deliveryWarnings = array_values(array_unique(array_filter(array_map('strval', $decodedWarnings))));
    }
}

function deliveryMailerAttachmentBytes($source, $file)
{
    $source = trim((string)$source, "/\\");
    $file = basename((string)$file);

    if ($source === '' || $file === '') {
        return 0;
    }

    $path = "../../../" . TENANT_URL . "/" . $source . "/" . $file;
    return file_exists($path) ? filesize($path) : 0;
}

function deliveryMailerPrintPath($source, $file)
{
    $source = trim((string)$source, "/\\");
    $file = basename((string)$file);

    if ($source === '' || $file === '' || strtolower(pathinfo($file, PATHINFO_EXTENSION)) !== 'pdf') {
        return '';
    }

    return "../" . $source . "/" . $file;
}

function deliveryMailerAddPrintFile(array &$printArray, $source, $file)
{
    $path = deliveryMailerPrintPath($source, $file);
    if ($path !== '' && !in_array($path, $printArray, true)) {
        $printArray[] = $path;
    }
}

function deliveryMailerAddPrintContents(array &$printArray, $contents)
{
    if (!is_array($contents)) {
        return;
    }

    foreach ($contents as $file) {
        if (!is_array($file)) {
            continue;
        }
        deliveryMailerAddPrintFile($printArray, $file['source'] ?? '', $file['file'] ?? '');
    }
}

$site = (int)($_REQUEST['site'] ?? 0);
if ($locationName === '' && $site > 0) {
    $stmtLocation = $GLOBALS['con']->prepare("SELECT `locname` FROM `locations` WHERE `locnumber`=? AND `clientnumber`=? LIMIT 1");
    if ($stmtLocation) {
        $stmtLocation->bind_param('ii', $site, $clientnumber);
        $stmtLocation->execute();
        $locationRow = $stmtLocation->get_result()->fetch_assoc();
        $stmtLocation->close();
        $locationName = trim((string)($locationRow['locname'] ?? ''));
    }
}

if ($dateStart !== '' && $dateEnd !== '') {
    $dateRange = $dateStart . ' - ' . $dateEnd;
} elseif ($dateStart !== '') {
    $dateRange = 'From ' . $dateStart;
} elseif ($dateEnd !== '') {
    $dateRange = 'To ' . $dateEnd;
}

$stmt = $GLOBALS['con']->prepare("SELECT `default_email_report_subject`, `default_email_report_message` FROM `system` WHERE `id`='1' LIMIT 1");
if ($stmt) {
    $stmt->execute();
    $systemDefaults = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $tokenValues = [
        '[CLIENT_NAME]' => $clientName,
        '[LOCATION_NAME]' => $locationName,
        '[DATE_RANGE]' => $dateRange,
        '{client}' => $clientName,
        '{company}' => $_SESSION['company'] ?? '',
        '{user}' => $_SESSION['user'] ?? '',
        '[CLIENT]' => $clientName,
        '[COMPANY]' => $_SESSION['company'] ?? '',
        '[USER]' => $_SESSION['user'] ?? ''
    ];

    $defaultSubject = trim((string)($systemDefaults['default_email_report_subject'] ?? ''));
    if ($defaultSubject !== '') {
        $subject = strtr($defaultSubject, $tokenValues);
    }

    $defaultMessage = (string)($systemDefaults['default_email_report_message'] ?? '');
    if ($defaultMessage !== '') {
        $defaultMessageSettings = json_decode($defaultMessage, true);
        if (is_array($defaultMessageSettings)) {
            $useDefaultReportMessage = !empty($defaultMessageSettings['enabled']);
            if ($useDefaultReportMessage && !empty($defaultMessageSettings['message'])) {
                $message = strtr((string)$defaultMessageSettings['message'], $tokenValues);
            }
        }
    }
}
?>
<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: 1024px) {

    html,
    body,
    body.delivery-mailer-active,
    body.delivery-mailer-active .container.body,
    body.delivery-mailer-active .right_col,
    body.delivery-mailer-active #delivery,
    body.delivery-mailer-active #mailerContainer {
        height: auto !important;
        max-height: none !important;
        min-height: 100% !important;
        overflow: visible !important;
        overflow-y: visible !important;
    }

    body.delivery-mailer-active {
        overflow-y: auto !important;
    }

    #deliveryMailerPane {
        height: auto;
        max-height: none !important;
        min-height: 100dvh;
        /* handles mobile browser bars */
        overflow: visible !important;
        /* 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="<?= htmlspecialchars($subject, ENT_QUOTES, 'UTF-8') ?>"
                                       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="4"><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></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($deliveryWarnings)) { ?>
                        <div class="alert alert-warning py-2 mb-3">
                            <strong>Written Scheme attachment skipped</strong>
                            <ul class="mb-0 ps-3">
                                <?php foreach ($deliveryWarnings as $warning) { ?>
                                <li><?= htmlspecialchars($warning, ENT_QUOTES, 'UTF-8') ?></li>
                                <?php } ?>
                            </ul>
                        </div>
                        <?php } ?>

                        <?php
                        if (!empty($_REQUEST['attachments'])) { ?>
                        <div id="fileList" class="row d-flex>">
                            <?php
                                $attachments = json_decode($_REQUEST['attachments'], true);
                                $count = count($attachments);
                                $cnt = 1;
                                $wnt = 1;
                                foreach ($attachments as $file) {
                                    if ($count > 0) {
                                        if (empty($file) || $file['file'] == "_undefined.pdf" || $file['file'] == "") {
                                        } else {
                                            $metaIdent = '';
                                            if ($file['type'] == "ws") {
                                                $icon = 'class="fad fa-file-word fa-2x" style="--fa-primary-color: black; --fa-secondary-color: grey;"';
                                                $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: grey;"';
                                                $dID = '';
                                                $delicon = '';
                                                $ident = 'report_' . $cnt;
                                                $src = 'source_' . $cnt;
                                                $metaIdent = 'logmeta_' . $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: grey;"';
                                                $dID = '';
                                                $delicon = '';
                                                $ident = 'report_' . $cnt;
                                                $src = 'source_' . $cnt;
                                                $metaIdent = 'logmeta_' . $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: grey;"';
                                                $dID = '';
                                                $delicon = '';
                                                $ident = 'report_' . $cnt;
                                                $src = 'source_' . $cnt;
                                                $metaIdent = 'logmeta_' . $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: grey;"';
                                                $dID = '';
                                                $delicon = '';
                                                $ident = 'report_' . $cnt;
                                                $src = 'source_' . $cnt;
                                                $metaIdent = 'logmeta_' . $cnt;
                                                $cnt++;
                                                $title = $file['file'];
                                            }
                                            $attachmentTotalBytes += deliveryMailerAttachmentBytes($file['source'] ?? '', $file['file'] ?? '');
                                            deliveryMailerAddPrintFile($printArray, $file['source'] ?? '', $file['file'] ?? '');
                                ?>
                            <div <?= $dID ?> class="col-1 mb-3 text-center"><a class=" "
                                   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>
                                <?php if ($metaIdent !== '') { ?>
                                <input type="hidden" name="<?= $metaIdent ?>" id="<?= $metaIdent ?>"
                                       value="<?= htmlspecialchars(json_encode($file, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') ?>" readonly>
                                <?php } ?>
                                <?= $delicon ?>
                            </div>

                            <?php
                                        }
                                    }
                                } ?>
                        </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: grey;"';
                            }
                            if ($attachments['type'] == "zip") {
                                $icon = 'class="fad fa-file-archive fa-2x" style="--fa-primary-color: grey; --fa-secondary-color: orange;"';
                            }
                            $saveArray[] = $attachments['file'];
                            if (($attachments['type'] ?? '') === 'zip') {
                                deliveryMailerAddPrintContents($printArray, $attachments['contents'] ?? []);
                            } else {
                                deliveryMailerAddPrintFile($printArray, $attachments['source'] ?? '', $attachments['file'] ?? '');
                            }
                       
                        
                        // Resolve path + size for main report_1
                        $reportPath = "../../../" . TENANT_URL . "/output/reports/" . $_REQUEST['clientnumber'] . "/" . $attachments['file'];
                        $reportSizeLabel = 'Size N/A';

                        if (file_exists($reportPath)) {
                            $reportSizeBytes = filesize($reportPath);
                            $attachmentTotalBytes += $reportSizeBytes;
                            $reportSizeLabel = number_format($reportSizeBytes / 1048576, 2) . ' MB'; // 1024*1024
                        }
                        ?>

                        <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="<?= $attachments['file'] ?>">
                                    <i <?= $icon ?>></i>
                                </a>

                                <div class="small text-muted mt-1">
                                    <?= $reportSizeLabel ?>
                                </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>
                                <input type="hidden" name="logmeta_1" id="logmeta_1"
                                       value="<?= htmlspecialchars(json_encode($attachments, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') ?>" 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: grey;"';
                                    }
                                    if ($file['type'] == "zip") {
                                        $icon = 'class="fad fa-file-archive fa-2x" style="--fa-primary-color: white; --fa-secondary-color: orange;"';
                                    }
                                    $attachmentTotalBytes += deliveryMailerAttachmentBytes($file['source'] ?? '', $file['file'] ?? '');
                                    if (($file['type'] ?? '') === 'zip') {
                                        deliveryMailerAddPrintContents($printArray, $file['contents'] ?? []);
                                    } else {
                                        deliveryMailerAddPrintFile($printArray, $file['source'] ?? '', $file['file'] ?? '');
                                    }
                                ?>

                            <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>
                                <input type="hidden" name="logmeta_<?= $cnt ?>" id="logmeta_<?= $cnt ?>"
                                       value="<?= htmlspecialchars(json_encode($file, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') ?>" 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>

                        <?php
                        if (!isset($attachmentTotalBytes)) {
                            $attachmentTotalBytes = 0;
                        }

                        if ($attachmentTotalBytes > 0) {
                            $attachmentTotalMb = $attachmentTotalBytes / 1048576;
                            $attachmentTotalLabel = number_format($attachmentTotalMb, 2) . ' MB';
                            $overLimit = ($attachmentTotalMb > 25);
                            ?>
                        <div class="alert alert-<?= $overLimit ? 'danger' : 'info' ?> mt-1">
                            <i class="fad fa-paperclip me-2"></i>
                            Total attachment size: <strong><?= $attachmentTotalLabel ?></strong>
                            <?php if ($overLimit): ?>
                            <br>
                            <small>
                                Combined attachment size exceeds 25 MB.
                                Many email providers may reject messages over this limit.
                                Consider removing or splitting attachments.
                            </small>
                            <?php endif; ?>
                        </div>
                        <?php
                        }
                        ?>



                    </div>
                </div>

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

                <div class="card">
                    <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
            $of = '';
            $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);

                    // Size per saved file
                    $fileSizeLabel = 'Size N/A';
                    if (file_exists($myfiles)) {
                        $fileSizeBytes = filesize($myfiles);
                        $attachmentTotalBytes += $fileSizeBytes;
                        $fileSizeLabel = number_format($fileSizeBytes / 1048576, 2) . ' MB';
                    }

                    $of .= '<div id="F' . $fcnt . '" class="col-1 mb-3 text-center rounded">';
                    $of .= '  <a href="' . $download . '" target="_blank">';
                    $of .= '      <i class="fad fa-file-archive fa-2x"'
                         . ' data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"'
                         . ' data-html="true" title="' . htmlspecialchars($path_parts['basename'], ENT_QUOTES) . '"></i>';
                    $of .= '  </a>';

                    // Per-file size display
                    $of .= '  <div class="small text-muted mt-1">' . $fileSizeLabel . '</div>';

                    // Delete icon
                    $of .= '  <a href="javascript:void(0)"'
                         . '     onclick="fileDelete(\'' . $download . '\',\'' . $fcnt . '\',\'' . $path_parts['basename'] . '\')">';
                    $of .= '      <i class="fad fa-window-close" style="--fa-primary-color: red;"></i>';
                    $of .= '  </a>';

                    // Hidden fields
                    $of .= '  <input type="hidden" class="form-control-sm filename is-valid"'
                         . '         name="saved_' . $fcnt . '" id="saved_' . $fcnt . '"'
                         . '         value="' . htmlspecialchars($path_parts['basename'], ENT_QUOTES) . '" readonly>';
                    $of .= '  <input type="hidden"'
                         . '         name="savedSource_' . $fcnt . '" id="savedSource_' . $fcnt . '"'
                         . '         value="' . htmlspecialchars($savedSource, ENT_QUOTES) . '" readonly>';
                    $of .= '</div>';

                    $fcnt++;
                }
            }
            ?>

                        <div class="col-12">
                            <div id="filesRow" class="row d-flex"><?= $of ?></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'] ?>" />
        <input type="hidden" id="defaultAddressType" value="delivery" />
        <div class="text-center"><input id="mailSendButton" type="submit" class="btn btn-info mt-3 mb-4 hidden" 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" style="display:none">
        <div class="alert alert-success">
            <h3 class="mb-2"><i class="fad fa-check-circle me-2"></i>Email delivery complete</h3>
            <p id="deliverySuccessMessage" class="mb-0">Emails sent successfully.</p>
        </div>
        <div class="card mb-4">
            <div class="card-header">Delivery Summary</div>
            <div class="card-body">
                <div class="row">
                    <div class="col-12 col-md-6 mb-3">
                        <h6 class="text-muted text-uppercase mb-2">Recipients</h6>
                        <ul id="deliverySuccessRecipients" class="mb-0 ps-3"></ul>
                    </div>
                    <div class="col-12 col-md-6 mb-3">
                        <h6 class="text-muted text-uppercase mb-2">Attachments</h6>
                        <ul id="deliverySuccessAttachments" class="mb-0 ps-3"></ul>
                    </div>
                    <div class="col-12">
                        <h6 class="text-muted text-uppercase mb-2">Subject</h6>
                        <p id="deliverySuccessSubject" class="mb-0"></p>
                    </div>
                </div>
            </div>
        </div>
        <div class="text-center">
            <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 Sent Pack</a>
        </div>
    </div>
    <div id="error" class="col-md-12" style="display:none">
        <div class="alert alert-danger">
            <h3 class="mb-2"><i class="fad fa-exclamation-triangle me-2"></i>Email delivery failed</h3>
            <p class="mb-0">The email was not sent. Review the message below, then try again.</p>
        </div>
        <div class="card mb-4">
            <div class="card-header">Error Details</div>
            <div class="card-body">
                <pre id="errorMessage" class="mb-0 text-danger" style="white-space: pre-wrap; font-family: inherit;"></pre>
            </div>
        </div>
        <div class="text-center">
            <?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>
</div>
<?php
enrep_render_mailer_addressbook_helper([
    'clientnumber' => (int)($_REQUEST['clientnumber'] ?? 0),
    'assignment' => 'delivery',
    'fallbackAssignment' => 'delivery',
    'allowSites' => true,
    'contextLabel' => 'delivery'
]);
?>
<script>
document.getElementById('footerControls').innerHTML =
    '<button class="btn btn-secondary" onclick="triggerAction(\'mailSendButton\')">SEND DOCUMENTS</button>';
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 deliverySite = '<?= (int)$site ?>';

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

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

    tooltipElements.forEach((element) => {
        new mdb.Tooltip(element);
    });
}
var useDefaultReportMessage = <?= $useDefaultReportMessage ? 'true' : 'false' ?>;
var messageHolder = document.getElementById('messageHolder');
if (!useDefaultReportMessage && messageHolder) {
    document.getElementById('message').textContent = messageHolder.textContent;
}
var chainModeElement = document.querySelector("input[name='chainMode']:checked") || parent.document.querySelector("input[name='chainMode']:checked");
var outputModeElement = document.querySelector("input[name='outputMode']:checked") || parent.document.querySelector("input[name='outputMode']:checked");
var chainMode = chainModeElement ? chainModeElement.value : 'merge';
var outputMode = outputModeElement ? outputModeElement.value : 'zip';

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;
    const seenEmails = new Set();

    function appendRecipient(email) {
        const value = String(email || '').trim();
        const key = value.toLowerCase();
        if (!value || seenEmails.has(key)) return;

        seenEmails.add(key);
        container.appendChild(createRecipientRow(index++, value));
    }

    // Only inject primary/secondary if type is "default"
    if (type === 'default') {
        if (typeof primaryEmail !== 'undefined' && primaryEmail) {
            appendRecipient(primaryEmail);
        }
        if (typeof secondaryEmail !== 'undefined' && secondaryEmail) {
            appendRecipient(secondaryEmail);
        }
    }

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

    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 => {
                appendRecipient(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 deliveryMailerListFromSelector(selector, labelCallback) {
    return Array.from(document.querySelectorAll(selector))
        .map(function(field) {
            return labelCallback(field);
        })
        .filter(function(value) {
            return value !== '';
        });
}

function deliveryMailerRenderList(elementId, values, emptyText) {
    const element = document.getElementById(elementId);
    if (!element) return;

    element.innerHTML = '';
    const list = values.length ? values : [emptyText];

    list.forEach(function(value) {
        const item = document.createElement('li');
        item.textContent = value;
        element.appendChild(item);
    });
}

function deliveryMailerCollectSummary() {
    const recipients = deliveryMailerListFromSelector('input[id^="recipient_"]', function(field) {
        return field.value.trim();
    });

    const bcc = document.getElementById('BCCrecipient')?.value.trim() || '';
    if (bcc !== '') {
        recipients.push(bcc + ' (copy)');
    }

    const attachments = [];
    deliveryMailerListFromSelector('input[id^="report_"]', function(field) {
        return field.value.trim();
    }).forEach(function(file) {
        attachments.push(file);
    });
    deliveryMailerListFromSelector('input[id^="wsreport_"]', function(field) {
        return field.value.trim();
    }).forEach(function(file) {
        attachments.push(file);
    });

    if (document.getElementById('attachSaved')?.checked) {
        deliveryMailerListFromSelector('input[id^="saved_"]', function(field) {
            return field.value.trim();
        }).forEach(function(file) {
            attachments.push(file);
        });
    }

    const additional = document.getElementById('attachment_additional')?.files?.[0]?.name || '';
    if (additional !== '') {
        attachments.push(additional);
    }

    return {
        subject: document.getElementById('subject')?.value.trim() || '',
        recipients: Array.from(new Set(recipients)),
        attachments: Array.from(new Set(attachments))
    };
}

function deliveryMailerRenderSuccess(result) {
    const summary = deliveryMailerCollectSummary();
    const response = typeof result === 'object' && result !== null ? result : {
        message: result
    };
    const responseRecipients = Array.isArray(response.recipients) ? response.recipients : [];
    const responseAttachments = Array.isArray(response.attachments) ? response.attachments.map(function(file) {
        return file && file.file ? file.file : '';
    }).filter(function(file) {
        return file !== '';
    }) : [];
    const messageElement = document.getElementById('deliverySuccessMessage');
    const subjectElement = document.getElementById('deliverySuccessSubject');

    if (messageElement) {
        messageElement.textContent = response.message || 'Emails sent successfully.';
    }
    if (subjectElement) {
        subjectElement.textContent = summary.subject || 'No subject recorded';
    }

    deliveryMailerRenderList('deliverySuccessRecipients', responseRecipients.length ? responseRecipients : summary.recipients, 'No recipients recorded');
    deliveryMailerRenderList('deliverySuccessAttachments', responseAttachments.length ? Array.from(new Set(responseAttachments)) : summary.attachments, 'No attachments recorded');
}

function deliveryMailerRenderError(message) {
    const errorElement = document.getElementById('errorMessage');
    if (errorElement) {
        errorElement.textContent = message || 'An unexpected error occurred. Please try again later.';
    }
}

function printReports() {
    const printArrayElement = document.getElementById('printArray');
    const printFiles = printArrayElement ? JSON.parse(printArrayElement.textContent || '[]') : [];

    if (!printFiles.length) {
        showResponse('warning', 'No printable PDF attachments were found for this delivery.');
        return;
    }

    var xhr = new XMLHttpRequest();
    xhr.open('POST', ROOT_URL + '/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();
            if (ret === "s") {
                var pdfUrl = `output/reports/<?= $_REQUEST['clientnumber'] ?>/reports.pdf?ts=${Date.now()}`;
                var win = window.open(pdfUrl, '_blank');
                if (win) {
                    win.focus();
                    win.print();
                } else {
                    showResponse('warning', "Please allow popups for this website to print the sent pack.");
                }
            } else {
                showResponse('danger', 'Unable to prepare the printable sent pack.');
            }
        }
    };
    xhr.send('files=' + encodeURIComponent(JSON.stringify(printFiles)) +
        '&client=' + encodeURIComponent('<?= $_REQUEST['clientnumber'] ?>') +
        '&tenant=' + encodeURIComponent(TENANT_URL));
}

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('delivery');
initializeTooltips();
</script>
