<?php
function enrep_mailer_addressbook_assignment(string $raw, string $fallback): string
{
    $allowed = ['billing', 'delivery', 'renewal'];
    $raw = strtolower(trim($raw));
    $fallback = strtolower(trim($fallback));

    if (in_array($raw, $allowed, true)) {
        return $raw;
    }

    return in_array($fallback, $allowed, true) ? $fallback : 'billing';
}

function enrep_mailer_addressbook_emails(int $clientnumber): array
{
    if ($clientnumber <= 0 || empty($GLOBALS['con'])) {
        return [];
    }

    $emails = [];
    $stmt = $GLOBALS['con']->prepare("SELECT `email` FROM `address_book` WHERE `clientnumber`=?");
    if (!$stmt) {
        return [];
    }

    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $rs = $stmt->get_result();
    $stmt->close();

    while ($row = mysqli_fetch_assoc($rs)) {
        $email = strtolower(trim((string)($row['email'] ?? '')));
        if ($email !== '') {
            $emails[] = $email;
        }
    }

    return array_values(array_unique($emails));
}

function enrep_mailer_addressbook_sites(int $clientnumber): array
{
    if ($clientnumber <= 0 || empty($GLOBALS['con'])) {
        return [];
    }

    $sites = [];
    $stmt = $GLOBALS['con']->prepare("SELECT `locnumber`, `locname` FROM `locations` WHERE `clientnumber`=? ORDER BY `locname` ASC");
    if (!$stmt) {
        return [];
    }

    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $rs = $stmt->get_result();
    $stmt->close();

    while ($row = mysqli_fetch_assoc($rs)) {
        $sites[] = [
            'locnumber' => (int)($row['locnumber'] ?? 0),
            'locname' => (string)($row['locname'] ?? '')
        ];
    }

    return $sites;
}

function enrep_render_mailer_addressbook_helper(array $options): void
{
    static $scriptRendered = false;

    $clientnumber = (int)($options['clientnumber'] ?? 0);
    $assignment = enrep_mailer_addressbook_assignment((string)($options['assignment'] ?? ''), (string)($options['fallbackAssignment'] ?? 'billing'));
    $allowSites = !empty($options['allowSites']);
    $contextLabel = (string)($options['contextLabel'] ?? 'mailer');

    $config = [
        'clientnumber' => $clientnumber,
        'assignment' => $assignment,
        'allowSites' => $allowSites,
        'contextLabel' => $contextLabel,
        'knownEmails' => enrep_mailer_addressbook_emails($clientnumber),
        'siteOptions' => $allowSites ? enrep_mailer_addressbook_sites($clientnumber) : [],
        'fcnUrl' => ROOT_URL . '/includes/client/client_addressbook_functions.php'
    ];

    if (!$scriptRendered) {
        $scriptRendered = true;
        ?>
<style>
.mailer-addressbook-add {
    min-width: 34px;
}
</style>
<script>
window.EnrepMailerAddressBook = window.EnrepMailerAddressBook || (function() {
    let cfg = {};
    let pendingInput = null;
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    function norm(value) {
        return String(value || '').trim().toLowerCase();
    }

    function escapeHtml(value) {
        return String(value ?? '').replace(/[&<>"']/g, function(char) {
            return ({
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            })[char];
        });
    }

    function knownSet() {
        return new Set((cfg.knownEmails || []).map(norm).filter(Boolean));
    }

    function isKnown(email) {
        return knownSet().has(norm(email));
    }

    function markKnown(email) {
        const key = norm(email);
        if (!key) return;
        cfg.knownEmails = cfg.knownEmails || [];
        if (!isKnown(key)) cfg.knownEmails.push(key);
    }

    function rowForInput(input) {
        return input ? input.closest('.input-group') : null;
    }

    function removeAddButton(input) {
        const row = rowForInput(input);
        if (!row) return;
        const button = row.querySelector('.mailer-addressbook-add');
        if (button) button.remove();
    }

    function ensureAddButton(input) {
        if (!input || !input.matches('input[id^="recipient_"]')) return;

        const email = String(input.value || '').trim();
        const row = rowForInput(input);
        if (!row) return;

        if (!emailPattern.test(email) || isKnown(email)) {
            removeAddButton(input);
            return;
        }

        let button = row.querySelector('.mailer-addressbook-add');
        if (button) return;

        button = document.createElement('button');
        button.type = 'button';
        button.className = 'btn btn-success mailer-addressbook-add';
        button.title = 'Add to address book';
        button.setAttribute('data-mdb-tooltip-init', '');
        button.innerHTML = '<i class="fad fa-address-book"></i>';
        button.addEventListener('click', function() {
            openModal(input);
        });

        const clearButton = row.querySelector('button.btn-danger,button.btn-danger-dark');
        if (clearButton) {
            row.insertBefore(button, clearButton);
        } else {
            row.appendChild(button);
        }

        if (typeof mdb !== 'undefined' && mdb.Tooltip) {
            try { new mdb.Tooltip(button); } catch (e) {}
        }
    }

    function scanRecipients() {
        document.querySelectorAll('#recipientContainer input[id^="recipient_"]').forEach(ensureAddButton);
    }

    function assignmentLabel() {
        if (cfg.assignment === 'billing') return 'Billing';
        if (cfg.assignment === 'delivery') return 'Delivery';
        if (cfg.assignment === 'renewal') return 'Renewal';
        return 'Billing';
    }

    function assignmentCheckbox(role) {
        const checked = cfg.assignment === role ? ' checked' : '';
        const label = role.charAt(0).toUpperCase() + role.slice(1);
        return '<div class="form-check form-check-inline">' +
            '<input class="form-check-input" type="checkbox" id="MAILER_AB_' + role + '"' + checked + '>' +
            '<label class="form-check-label" for="MAILER_AB_' + role + '">' + label + '</label>' +
        '</div>';
    }

    function sitesHtml() {
        if (!cfg.allowSites) return '';
        const sites = cfg.siteOptions || [];

        if (!sites.length) {
            return '<div class="col-12"><div class="note note-secondary mb-0">No delivery sites are available for this client.</div></div>';
        }

        return '<div class="col-12">' +
            '<label class="control-label" for="MAILER_AB_sites">Delivery sites</label>' +
            '<select id="MAILER_AB_sites" class="form-control" multiple data-mdb-select-init data-mdb-filter="true" data-mdb-container="#addressBookMailerBox">' +
                sites.map(function(site) {
                    return '<option value="' + parseInt(site.locnumber, 10) + '">' + escapeHtml(site.locname) + '</option>';
                }).join('') +
            '</select>' +
            '<div class="form-text">Leave blank for all sites.</div>' +
        '</div>';
    }

    function openModal(input) {
        pendingInput = input;
        const email = String(input.value || '').trim();
        const html =
            '<div class="row g-3">' +
                '<div class="col-12">' +
                    '<div class="note note-secondary mb-0">Add this manually entered recipient to the client address book. It will be saved as auto and marked for ' + assignmentLabel().toLowerCase() + ' emails.</div>' +
                '</div>' +
                '<div class="col-12 col-md-6"><label class="control-label" for="MAILER_AB_firstName">First Name</label><input id="MAILER_AB_firstName" class="form-control" type="text"></div>' +
                '<div class="col-12 col-md-6"><label class="control-label" for="MAILER_AB_lastName">Last Name</label><input id="MAILER_AB_lastName" class="form-control" type="text"></div>' +
                '<div class="col-12 col-md-6"><label class="control-label" for="MAILER_AB_role">Role</label><input id="MAILER_AB_role" class="form-control" type="text" placeholder="Safety officer"></div>' +
                '<div class="col-12 col-md-3"><label class="control-label" for="MAILER_AB_phone1">Phone 1</label><input id="MAILER_AB_phone1" class="form-control" type="text"></div>' +
                '<div class="col-12 col-md-3"><label class="control-label" for="MAILER_AB_phone2">Phone 2</label><input id="MAILER_AB_phone2" class="form-control" type="text"></div>' +
                '<div class="col-12"><label class="control-label" for="MAILER_AB_email">Email</label><input id="MAILER_AB_email" class="form-control" type="email" value="' + escapeHtml(email) + '"></div>' +
                '<div class="col-12"><label class="control-label d-block">Address book options</label>' +
                    '<div class="form-check form-check-inline"><input class="form-check-input" type="checkbox" id="MAILER_AB_auto" checked><label class="form-check-label" for="MAILER_AB_auto">Auto</label></div>' +
                    assignmentCheckbox('billing') +
                    assignmentCheckbox('delivery') +
                    assignmentCheckbox('renewal') +
                '</div>' +
                sitesHtml() +
            '</div>';

        loadModalContent(html, 'addressBookMailerBox', 'modal-lg', 1070, 'true', 'Add address book contact', 'confirm', window.EnrepMailerAddressBook.confirmAdd);

        setTimeout(function() {
            const select = document.getElementById('MAILER_AB_sites');
            if (select && typeof mdb !== 'undefined' && mdb.Select) {
                try { new mdb.Select(select, { filter: true, container: '#addressBookMailerBox' }); } catch (e) {}
            }
        }, 150);
    }

    function selectedSites() {
        const select = document.getElementById('MAILER_AB_sites');
        if (!select) return '';
        const values = Array.from(select.selectedOptions || []).map(function(option) {
            return parseInt(option.value, 10);
        }).filter(function(value) {
            return value > 0;
        });
        return values.length ? JSON.stringify(Array.from(new Set(values))) : 'all';
    }

    function confirmAdd() {
        const email = String(document.getElementById('MAILER_AB_email')?.value || '').trim();
        if (!emailPattern.test(email)) {
            if (typeof showResponse === 'function') showResponse('warning', 'Enter a valid email address');
            return;
        }

        if (isKnown(email)) {
            if (typeof showResponse === 'function') showResponse('warning', 'This email is already in the address book');
            return;
        }

        const assignments = {
            billing: document.getElementById('MAILER_AB_billing')?.checked ? 1 : 0,
            delivery: document.getElementById('MAILER_AB_delivery')?.checked ? 1 : 0,
            renewal: document.getElementById('MAILER_AB_renewal')?.checked ? 1 : 0
        };

        const body = new URLSearchParams({
            fcn: 'addMailer',
            clientnumber: String(cfg.clientnumber || ''),
            firstName: document.getElementById('MAILER_AB_firstName')?.value || '',
            lastName: document.getElementById('MAILER_AB_lastName')?.value || '',
            role: document.getElementById('MAILER_AB_role')?.value || '',
            phone1: document.getElementById('MAILER_AB_phone1')?.value || '',
            phone2: document.getElementById('MAILER_AB_phone2')?.value || '',
            email: email,
            auto: document.getElementById('MAILER_AB_auto')?.checked ? '1' : '0',
            assignments: JSON.stringify(assignments),
            siteNumbers: selectedSites(),
            tenant: TENANT_URL
        });

        fetch(cfg.fcnUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
            body: body.toString()
        })
        .then(function(response) { return response.text(); })
        .then(function(ret) {
            const parts = String(ret || '').trim().split('|');
            if (parts[0] === '1') {
                markKnown(email);
                if (pendingInput) {
                    pendingInput.value = email;
                    removeAddButton(pendingInput);
                }
                if (typeof killModal === 'function') killModal('addressBookMailerBox');
                if (typeof showResponse === 'function') showResponse('success', 'Contact added to address book');
                scanRecipients();
                return;
            }

            const message = parts[0] === 'exists'
                ? 'This email is already in the address book'
                : 'Failed to add contact to address book';
            if (typeof showResponse === 'function') showResponse('danger', message);
        })
        .catch(function(error) {
            console.error('Address book add failed:', error);
            if (typeof showResponse === 'function') showResponse('danger', 'Failed to add contact to address book');
        });
    }

    function init(options) {
        cfg = Object.assign({}, cfg, options || {});
        if (!cfg.clientnumber) return;

        const container = document.getElementById('recipientContainer');
        if (!container) return;

        container.addEventListener('input', function(event) {
            if (event.target && event.target.matches('input[id^="recipient_"]')) {
                ensureAddButton(event.target);
            }
        });

        container.addEventListener('change', function(event) {
            if (event.target && event.target.matches('input[id^="recipient_"]')) {
                ensureAddButton(event.target);
            }
        });

        container.addEventListener('click', function() {
            setTimeout(scanRecipients, 50);
        });

        const observer = new MutationObserver(scanRecipients);
        observer.observe(container, { childList: true, subtree: true });
        setTimeout(scanRecipients, 250);
    }

    return {
        init: init,
        confirmAdd: confirmAdd,
        scan: scanRecipients
    };
})();
</script>
        <?php
    }
    ?>
<script>
window.EnrepMailerAddressBook.init(<?= json_encode($config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?>);
</script>
    <?php
}
?>
