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

$payload = [];
$input = isset($_REQUEST['string']) ? $_REQUEST['string'] : (isset($_REQUEST['data']) ? $_REQUEST['data'] : null);

if ($input !== null) {
    $decoded_input = urldecode((string)$input);
    $json_string = base64_decode($decoded_input, true);
    if ($json_string !== false) {
        $tmp = json_decode($json_string, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($tmp)) {
            $payload = $tmp;
        }
    }
}

$clientNumber = (string)($payload['clientNumber'] ?? ($_REQUEST['clientnumber'] ?? ''));
$clientName   = (string)($payload['clientName'] ?? '');
$primaryEmail = (string)($payload['primaryEmail'] ?? '');
$secondaryEmail = (string)($payload['secondaryEmail'] ?? '');
$subject      = (string)($payload['subject'] ?? '');
$message      = (string)($payload['message'] ?? '');
$filePath     = (string)($payload['filePath'] ?? '');
$fileName     = (string)($payload['fileName'] ?? '');
$addrMode     = (string)($payload['mode'] ?? ($payload['addressMode'] ?? ''));
$sentCallbackUrl = (string)($payload['sentCallbackUrl'] ?? '');
$messageHasHtml = $message !== strip_tags($message);

?>
<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; } }
}

.mailer-html-editor {
    min-height: 160px;
    padding: 1rem;
    border: 1px solid #ced4da;
    border-radius: .25rem;
    background: #fff;
    color: #212529;
    line-height: 1.5;
    outline: none;
}

.mailer-html-editor:focus {
    border-color: #3b71ca;
    box-shadow: 0 0 0 .2rem rgba(59, 113, 202, .15);
}

.mailer-html-editor p:last-child {
    margin-bottom: 0;
}
</style>

<form id="mailerForm" class="form-horizontal" enctype="multipart/form-data">
    <div class="row">
        <div class="col-12 col-md-4">
            <div class="card mb-4">
                <div class="card-header">Subject</div>
                <div class="card-body">
                    <input type="text" class="form-control" name="subject" id="subject" value="<?= htmlspecialchars($subject) ?>" autofocus />
                </div>
            </div>
        </div>

        <div class="col-12 col-md-4">
            <div class="card mb-4">
                <div class="card-header">Recipients</div>
                <div class="card-body">
                    <div id="recipientContainer"></div>

                    <?php if ($addrMode === 'delivery') { ?>
                        <div class="mt-2">
                            <button type="button" class="btn btn-info btn-sm my-1" 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-1" onclick="copyMeIn()">
                                <i class="fad fa-copy"></i> Copy Me In
                            </button>
                        </div>
                    <?php } else { ?>
                        <div class="mt-2">
                            <button type="button" class="btn btn-info btn-sm my-1" onclick="addRecipientRow()">
                                <i class="fad fa-plus-circle me-1"></i> Add Recipient Entry
                            </button>
                        </div>
                    <?php } ?>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-4">
            <div class="card mb-4">
                <div class="card-header">Attachments</div>
                <div class="card-body">
                    <div class="input-group custom-file-button mb-3">
                        <?php if ($filePath !== "" || $fileName !== "") { ?>
                            <span class="input-group-text secondary active">File</span>
                            <input type="text" class="form-control filename" name="file_1" id="attachment_1"
                                   value="<?= htmlspecialchars($fileName) ?>" readonly>
                            <input type="hidden" class="form-control" name="source_1" id="source_1"
                                   value="<?= htmlspecialchars($filePath) ?>" readonly>
                        <?php } else { ?>
                            <label class="input-group-text" for="attachment_1"><i class="fad fa-paperclip"></i></label>
                            <input type="file" class="form-control" name="attachment_1" id="attachment_1" />
                            <input type="hidden" class="form-control" name="source_1" id="source_1" readonly>
                        <?php } ?>
                    </div>

                    <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_2" id="attachment_2" />
                        <input type="hidden" class="form-control" name="source_2" id="source_2" readonly>
                    </div>

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

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

    <div class="row">
        <div class="col-12">
            <div class="card mb-4">
                <div class="card-header">Message</div>
                <div class="card-body">
                    <?php if ($messageHasHtml) { ?>
                        <textarea class="d-none" name="message" id="message"><?= htmlspecialchars($message) ?></textarea>
                        <div id="messageHtmlEditor" class="mailer-html-editor" contenteditable="true"></div>
                    <?php } else { ?>
                        <textarea class="form-control" name="message" id="message" rows="6"><?= htmlspecialchars($message) ?></textarea>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>

    <div id="erm" class="text-center"></div>
    <div class="text-center">
        <input id="mailSendButton" type="submit" class="btn btn-success mt-1 mb-1" value="Send Email">
    </div>

    <input type="hidden" class="form-control" name="tenant" id="tenant" value="<?= TENANT_URL ?>" readonly>
    <input type="hidden" class="form-control" name="clientnumber" id="clientnumber" value="<?= htmlspecialchars($clientNumber) ?>" readonly>
</form>

<div id="sending" class="col-md-12 text-center" style="display:none; color:#393939">
    <h1>
        <i class="fad fa-mail-bulk fa-spin 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>
</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>
</div>

<script>
function updateModalContent() {
    var modalHeader = document.querySelector('#popupBox .modal-header');
    if (modalHeader) {
        modalHeader.innerHTML = `
            <div class="col-6"><a href="javascript:void(0)" class="sa">Direct Mailer</a></div>
            <div class="col-6"><span class="float-end"><strong>Emailing:</strong> <strong><?= addslashes($clientName) ?></strong></span></div>
        `;
    }

    <?php if (($_REQUEST['mode'] ?? '') === "popup") { ?>
    var modalFooter = document.querySelector('#popupBox .modal-footer');
    if (modalFooter) {
        modalFooter.innerHTML = `
            <a id="modalBtnCancel" href="javascript:void(0)" class="btn btn-danger" data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover" title="Close">Cancel</a>
        `;
    }
    <?php } ?>
}
updateModalContent();

function sanitizeMailerHtml(html) {
    const template = document.createElement('template');
    template.innerHTML = html || '';

    const allowedTags = new Set([
        'A', 'B', 'BR', 'DIV', 'EM', 'H1', 'H2', 'H3', 'H4', 'HR', 'I',
        'LI', 'OL', 'P', 'SMALL', 'SPAN', 'STRONG', 'TABLE', 'TBODY',
        'TD', 'TH', 'THEAD', 'TR', 'U', 'UL'
    ]);
    const blockedTags = new Set([
        'BASE', 'BUTTON', 'EMBED', 'FORM', 'IFRAME', 'INPUT', 'LINK',
        'META', 'OBJECT', 'SCRIPT', 'SELECT', 'STYLE', 'TEXTAREA'
    ]);

    const nodes = [];
    const walker = document.createTreeWalker(template.content, NodeFilter.SHOW_ELEMENT);
    while (walker.nextNode()) {
        nodes.push(walker.currentNode);
    }

    nodes.forEach((node) => {
        const tag = node.tagName;

        if (blockedTags.has(tag)) {
            node.remove();
            return;
        }

        if (!allowedTags.has(tag)) {
            node.replaceWith(...Array.from(node.childNodes));
            return;
        }

        Array.from(node.attributes).forEach((attribute) => {
            const name = attribute.name.toLowerCase();
            const value = attribute.value || '';
            const isTableSpan = (tag === 'TD' || tag === 'TH') && (name === 'colspan' || name === 'rowspan');

            if (name.startsWith('on') || name === 'style' || name.startsWith('data-')) {
                node.removeAttribute(attribute.name);
                return;
            }

            if (tag === 'A' && name === 'href') {
                if (!/^(https?:|mailto:|tel:|\/|#)/i.test(value)) {
                    node.removeAttribute(attribute.name);
                }
                return;
            }

            if (tag === 'A' && (name === 'target' || name === 'rel')) {
                return;
            }

            if (isTableSpan) {
                return;
            }

            node.removeAttribute(attribute.name);
        });

        if (tag === 'A' && node.hasAttribute('href')) {
            node.setAttribute('target', '_blank');
            node.setAttribute('rel', 'noopener');
        }
    });

    return template.innerHTML;
}

function syncMailerMessageEditor() {
    const editor = document.getElementById('messageHtmlEditor');
    const message = document.getElementById('message');

    if (!editor || !message) {
        return;
    }

    const cleanHtml = sanitizeMailerHtml(editor.innerHTML).trim();
    if (editor.innerHTML !== cleanHtml) {
        editor.innerHTML = cleanHtml;
    }
    message.value = cleanHtml;
}

(function initMailerMessageEditor() {
    const editor = document.getElementById('messageHtmlEditor');
    const message = document.getElementById('message');

    if (!editor || !message) {
        return;
    }

    editor.innerHTML = sanitizeMailerHtml(message.value);
    editor.addEventListener('input', syncMailerMessageEditor);
})();

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

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 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 = (isFinite(lastIndex) ? lastIndex : 0) + 1;
    container.appendChild(createRecipientRow(n, ''));
}

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

    let index = 1;

    if (type === 'default') {
        const pe = "<?= addslashes($primaryEmail) ?>";
        const se = "<?= addslashes($secondaryEmail) ?>";
        if (pe) container.appendChild(createRecipientRow(index++, pe));
        if (se) container.appendChild(createRecipientRow(index++, se));
    }

    const formData = new FormData();
    formData.append('clientnumber', "<?= addslashes($clientNumber) ?>");
    formData.append('tenant', TENANT_URL);
    formData.append('type', type);

    fetch(ROOT_URL + '/functions/loadEmail.php', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(ret => {
            ret.forEach(item => container.appendChild(createRecipientRow(index++, item.email)));
            if (container.querySelectorAll('input[id^="recipient_"]').length === 0) {
                container.appendChild(createRecipientRow(1, "<?= addslashes($primaryEmail) ?>"));
                container.appendChild(createRecipientRow(2, "<?= addslashes($secondaryEmail) ?>"));
            }
        })
        .catch(() => {
            container.appendChild(createRecipientRow(1, "<?= addslashes($primaryEmail) ?>"));
            container.appendChild(createRecipientRow(2, "<?= addslashes($secondaryEmail) ?>"));
        });
}

function getDefaultRecipents(forceType = null) {
    const addressType = forceType || 'delivery';
    switch (addressType) {
        case 'all':
        case 'billing':
        case 'renewal':
        case 'delivery':
        case 'default':
            loadDefaultRecipients(addressType);
            break;
    }
}

function copyMeIn() {
    const me = "<?= addslashes($_SESSION['email'] ?? '') ?>";
    if (!me) return;

    const container = document.getElementById('recipientContainer');
    const inputs = [...container.querySelectorAll('input[id^="recipient_"]')];

    for (const inp of inputs) {
        if (!inp.value) { inp.value = me; return; }
    }
    addRecipientRow();
    const last = container.querySelector('input[id^="recipient_"]:last-of-type');
    if (last) last.value = me;
}

(function initRecipients() {
    const container = document.getElementById('recipientContainer');
    container.appendChild(createRecipientRow(1, "<?= addslashes($primaryEmail) ?>"));
    container.appendChild(createRecipientRow(2, "<?= addslashes($secondaryEmail) ?>"));

    <?php if ($addrMode === 'delivery') { ?>
        getDefaultRecipents('delivery');
    <?php } ?>
})();

document.getElementById('mailerForm').addEventListener('submit', function(event) {
    event.preventDefault();

    syncMailerMessageEditor();

    const subject = document.getElementById('subject').value.trim();
    const message = document.getElementById('message').value.trim();

    const recips = [...document.querySelectorAll('input[id^="recipient_"]')].map(i => i.value.trim()).filter(Boolean);
    if (recips.length === 0) {
        showResponse('warning', 'Please add at least one recipient');
        return false;
    }
    if (!subject || !message) {
        showResponse('warning', 'Please complete "subject" and "message" fields');
        return false;
    }

    document.getElementById('sending').style.display = 'block';
    document.getElementById('mailerForm').style.display = 'none';

    const formData = new FormData(this);
    const sentCallbackUrl = "<?= addslashes($sentCallbackUrl) ?>";

    fetch(ROOT_URL + '/functions/sendmail.php', { method: 'POST', body: formData })
        .then(r => r.json())
        .then(result => {
            if (result.status === "success") {
                document.getElementById('sending').style.display = 'none';
                document.getElementById('error').style.display = 'none';
                document.getElementById('complete').style.display = 'block';
                showResponse('success', result.message);

                const closeMailer = function() {
                    const popupClose = document.getElementById('modalBtnCancel');
                    if (popupClose) popupClose.click();
                };

                if (sentCallbackUrl) {
                    const callbackData = new FormData();
                    callbackData.append('email_to', recips.join(', '));
                    fetch(sentCallbackUrl, { method: 'POST', body: callbackData }).finally(function() {
                        if (typeof plantChangeReload === 'function') {
                            plantChangeReload();
                        }
                        closeMailer();
                    });
                } else {
                    closeMailer();
                }
            } else {
                document.getElementById('sending').style.display = 'none';
                document.getElementById('error').style.display = 'block';
                document.getElementById('errorMessage').textContent = result.message || 'An error occurred.';
            }
        });

    return false;
});
</script>
