<?php //finance_mailer.php

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');

?>

<?php
if (isset($_REQUEST['data'])) {
    $jsonString = urldecode($_REQUEST['data']);
    $data = json_decode($jsonString, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        echo '<pre>JSON Decode Error: ' . json_last_error_msg() . '</pre>';
        exit;
    }

    $clientNumber    = $data['clientNumber'];
    $client          = $data['clientName'];
    $primaryEmail    = $data['primaryEmail'];
    $secondaryEmail  = $data['secondaryEmail'];
    $sub             = $data['subject'];
    $message         = $data['message'];
    $filePath        = $data['filePath'];
    $fileName        = $data['fileName'];
    $invoiceNumber   = $data['invoiceNumber'];
    $mode   = $data['mode'];
} else {
    echo "No data received.";
}


?>

<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;
        }
    }
}
</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-5">
                <div class="card-header">Subject mode</div>
                <div class="card-body">
                    <div class="row">
                        <div class="input-group mb-1 input-group-sm col-12">
                            <input type="text" class="form-control" name="subject" id="subject" value="<?= $sub ?>" />
                        </div>
                    </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-4">
            <div class="card mb-5">
                <div class="card-header">Attachments</div>
                <div class="card-body">

                    <div class="input-group mb-3 custom-file-button input-group-sm">

                        <label class="input-group-text text-info"><i class="fad fa-file-pdf"></i></label>
                        <input type="text" class="form-control filename" name="file_1" id="attachment_1"
                            value="<?= $data['fileName'] ?>" readonly>
                        <input type="hidden" class="form-control" name="source_1" id="source_1"
                            value="<?= $data['filePath'] ?>" readonly>
                        <input type="hidden" class="form-control" name="tenant" id="tenant" value="<?= TENANT_URL ?>"
                            readonly>


                    </div>
                    <?php if (strpos($data['fileName'], '_remind')) {
                        $cl = str_replace('_remind.pdf', '', $data['fileName']);
                        if ($data['mode'] == "agent") {
                            $tp = "_agent.pdf";
                        }
                        if ($data['mode'] == "broker") {
                            $tp = "_broker.zip";
                        }
                        if ($data['mode'] == "client") {
                            $tp = "_invoice.pdf";
                        }
                        if ($data['mode'] == "blank") {
                            $tp = "_invoice.pdf";
                        }
                    ?>
                    <div class="input-group mb-3 custom-file-button input-group-sm">

                        <label class="input-group-text text-info"><i class="fad fa-file-pdf"></i></label>
                        <input type="text" class="form-control filename" name="file_2" id="attachment_2"
                            value="<?= $cl ?><?= $tp ?>" readonly>
                        <input type="hidden" class="form-control" name="source_2" id="source_2" value="<?= $d[5] ?>"
                            readonly>


                    </div>
                    <?php } else { ?>
                    <div class="input-group mb-3 custom-file-button input-group-sm">
                        <label class="input-group-text" for="attachment_2"><i class="fad fa-paperclip"></i></label>
                        <input type="file" class="form-control filename" name="attachment_2" id="attachment_2">
                        <input type="hidden" class="form-control" name="source_2" id="source_2" readonly>

                    </div>
                    <?php } ?>
                    <div class="input-group mb-3 custom-file-button input-group-sm">
                        <label class="input-group-text" for="attachment_3"><i class="fad fa-paperclip"></i></label>
                        <input type="file" class="form-control filename" 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 input-group-sm">
                        <label class="input-group-text" for="attachment_4"><i class="fad fa-paperclip"></i></label>
                        <input type="file" class="form-control filename" 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 col-md-12">
            <div class="card mb-2">
                <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="2"><?= $data['message'] ?></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php if ($delivery == "active") {
        $deltitle = "Send Documents";
    } else {
        $deltitle = "Send Email";
    }
    ?>
    <div id="erm" class="text-center"></div>
    <input type="hidden" id="defectList" name="defectList" />
    <div class="text-center"><input id="mailSendButton" type="submit" class="btn btn-info mt-3 mb-4"
            value="<?= $deltitle ?>"></div>
</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>
    <a class="btn btn-secondary"
        href="index.php?t=includes/master&p=delivery.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>">Start Again</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>
<script>
var D_0 = '<?= $data['clientNumber'] ?>';
var D_2 = '<?= $data['primaryEmail'] ?>';
var D_5 = '<?= $data['filePath'] ?>';
var D_8 = '<?= $data['invoiceNumber'] ?>';
var D_9 = '<?= $data['emailFunction'] ?>';

var primaryEmail = '<?= $data['primaryEmail'] ?>';
var secondaryEmail = '<?= $data['secondaryEmail'] ?>';
var companyEmail = '<?= getCompanyDetails('email') ?>'

document.querySelectorAll('[data-mdb-toggle="dropdown"]').forEach((el) => {
    new mdb.Dropdown(el);
});
document.addEventListener('click', (event) => {
    if (event.target && event.target.id === 'btnCancel') {
        killModal('popupBox')
    }
});

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

    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.`;
                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 || 'all';
    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 handleMailerSubmit(event) {
    event.preventDefault();

    const mailerForm = event.target;

    const recipientInputs = mailerForm.querySelectorAll('input[id^="recipient_"]');
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    let validRecipient = false;
    recipientInputs.forEach(input => {
        if (emailPattern.test(input.value.trim())) {
            validRecipient = true;
        }
    });

    if (!validRecipient) {
        showResponse('warning', 'Please enter at least one valid email address');
        return false;
    }

    const subjectInput = mailerForm.querySelector('#subject');
    const messageInput = mailerForm.querySelector('#message');

    const s = subjectInput?.value.trim() || '';
    const m = messageInput?.value.trim() || '';

    if (s === '' || m === '') {
        showResponse('warning', 'Please complete "subject" and "message" fields');
        return false;
    }

    const sendingElement = document.getElementById('sending');
    const hseNoticeElement = document.getElementById('hseNotice');
    const completeElement = document.getElementById('complete');
    const bypassCheckbox = document.getElementById('bypass');

    if (sendingElement) sendingElement.style.display = 'block';
    if (hseNoticeElement) hseNoticeElement.style.display = 'none';
    if (mailerForm) mailerForm.style.display = 'none';

    const formData = new FormData(mailerForm);

    fetch(ROOT_URL + '/functions/sendmail.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(result => {
            if (sendingElement) sendingElement.style.display = 'none';

            if (result.status === 'success') {
                if (completeElement) completeElement.style.display = 'block';

                if (bypassCheckbox && bypassCheckbox.checked) {
                    showResponse('warning', 'Your email was sent successfully, but date bypass detected');
                } else {
                    const financeFunctionsData = new URLSearchParams();
                    let functionToCall = '';

                    if (D_5 === 'renewals') {
                        functionToCall = 'setRenewalSent';
                    } else if (D_5 === 'statements') {
                        functionToCall = 'setDelivered';
                    }

                    if (functionToCall || D_9 === 'renewalInvoice') {
                        financeFunctionsData.append('FUNCTION', functionToCall);
                        financeFunctionsData.append('tenant', TENANT_URL);
                        financeFunctionsData.append('inv', D_8);
                        alert(functionToCall)
                        fetch(ROOT_URL + '/includes/finance/finance_functions.php', {
                                method: 'POST',
                                body: financeFunctionsData
                            })
                            .then(response => response.text())
                            .then(ret => {
                                showResponse('success', 'Your email was sent successfully' + ret);

                                const emElement = document.getElementById('em' + D_8);
                                if (emElement) {
                                    emElement.innerHTML =
                                        '<span class="badge badge-success m-0" style="font-size:12px; display:block">SENT</span>';
                                }

                                if (D_5 === 'invoices' && typeof confirmSent === 'function') confirmSent(D_8);
                                if (D_5 === 'renewals' && typeof renewButtonSwitch === 'function')
                                    renewButtonSwitch(D_0);
                                if (D_9 === 'renewalInvoice' && typeof renewButtonHide === 'function')
                                    renewButtonHide(D_0);
                            })
                            .catch(error => console.error('Error calling finance_functions.php:', error));
                    }
                }

                showResponse('success', result.message);
                killModal('emailBox');
            } else {
                document.getElementById('error').style.display = 'block';
                document.getElementById('errorMessage').textContent = result.message || 'An error occurred.';
            }
        })
        .catch(error => {
            console.error('Error sending mail:', error);
            showResponse('danger', 'Network error or unable to send email.');
        });

    return false;
}

setTimeout(() => {
    const mailerForm = document.querySelector('#mailerForm');
    if (mailerForm) {
        mailerForm.removeEventListener('submit', handleMailerSubmit); // ensure no duplicate
        mailerForm.addEventListener('submit', handleMailerSubmit, {
            once: true
        }); // once per open
    }
}, 100);

function matchCustom(params, data) {
    if (typeof data.value === 'undefined') {
        return null;
    }
}


function clearField(fieldId) {
    const field = document.getElementById(fieldId);
    if (field) {
        const row = field.closest('.input-group');
        if (row && row.parentNode) {
            row.parentNode.removeChild(row);
        }
    }
}

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