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

?>
<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>
<?php

// Function to check if a string is base64 encoded
function isBase64Encoded($string)
{
    // Base64 strings should be divisible by 4 and match the Base64 pattern
    return (strlen($string) % 4 === 0) && preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string);
}


// Parse query string properly
parse_str($_SERVER['QUERY_STRING'], $queryParams);
$input = isset($_REQUEST['string']) ? $_REQUEST['string'] : (isset($_REQUEST['data']) ? $_REQUEST['data'] : null);

if ($input !== null) {
    // URL-decode the input
    $decoded_input = urldecode($input);

    // Function to check if a string is valid Base64
    function isBase64($str)
    {
        $decoded = base64_decode($str, true);
        return $decoded !== false;
    }

    // Check if the input is Base64-encoded JSON
    if (isBase64($decoded_input)) {
        // Decode Base64
        $json_string = base64_decode($decoded_input);

        // Debug: Print the full decoded Base64 string BEFORE JSON decoding
        //echo "🔍 Debugging: Full Base64 Decoded String:\n";
        //echo $json_string . "\n\n";

        // Decode JSON into an associative array
        $d = json_decode($json_string, true);

        if (json_last_error() === JSON_ERROR_NONE) {
            // echo "✅ Successfully decoded Base64 and JSON.\n";
            //print_r($d);
        } else {
            echo "❌ JSON decoding failed after Base64 decoding.";
            echo "\nJSON Error: " . json_last_error_msg();
            echo "\nRaw decoded JSON string:\n" . $json_string;
        }
    } else {
        echo "⚠️ Input is not Base64 encoded.\n";
    }
} else {
    echo $d[0] = $_REQUEST['clientnumber'];;
}





//////////////////////////////
//	MAILER OPTIONS d[]		//
//							//
//		[0] client			//
//		[1] type			//
//		[2] recipient		//
//		[3] subject			//
//		[4] message			//
//		[5] attachment		//
//		[6] source		//
//							//
//////////////////////////////

?>

<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</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-12">
                            <input type="text" class="form-control" name="subject" id="subject" value="<?= $d[3] ?>"
                                autofocus />
                        </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 class="input-group mb-3">
                        <input type="text" class="form-control" name="recipient_1" id="recipient_1"
                            placeholder="Add Recipient" value="<?= $d[2] ?>" />
                        <button type="button" class="btn btn-danger m-0 px-3 py-2"
                            onclick="clearField('recipient_1')"><i class="fad fa-ban"></i></button>
                    </div>
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" name="recipient_2" id="recipient_2"
                            placeholder="Add Recipient" />
                        <button type="button" class="btn btn-danger m-0 px-3 py-2"
                            onclick="clearField('recipient_2')"><i class="fad fa-ban"></i></button>
                    </div>
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" name="recipient_3" id="recipient_3"
                            placeholder="Add Recipient" />
                        <button type="button" class="btn btn-danger m-0 px-3 py-2"
                            onclick="clearField('recipient_3')"><i class="fad fa-ban"></i></button>
                    </div>
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" name="recipient_4" id="recipient_4"
                            placeholder="Add Recipient" />
                        <button type="button" class="btn btn-danger m-0 px-3 py-2"
                            onclick="clearField('recipient_4')"><i class="fad fa-ban"></i></button>
                    </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 custom-file-button mb-3">
                        <?php if ($d[5] != "") { ?>
                        <span class="input-group-text secondary active">File</span>
                        <input type="text" class="form-control filename" name="file_1" id="attachment_1"
                            value="<?= $d[6] ?>" readonly>
                        <input type="hidden" class="form-control" name="source_1" id="source_1" value="<?= $d[5] ?>"
                            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 col-md-12">
            <div class="card mb-5">
                <div class="card-header">Message</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-12">
                            <textarea class="form-control" name="message" id="message" rows="6"><?= $d[4] ?></textarea>
                        </div>
                    </div>
                </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>
</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>
    <?php if ($delivery == "active") { ?> <a class="btn btn-secondary"
        href="index.php?t=includes/master&p=delivery.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>">Start
        Again</a><?php } ?>
</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>
// Function to update modal content
function updateModalContent() {
    //alert("Function updateModalContent called"); // Test alert to ensure the function is called
    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><?= $d['1'] ?></strong><br /></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 } ?>
}

// Call the function to update the modal content
updateModalContent();


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

    event.preventDefault(); // Prevent the form from submitting the default way

    var recipient1 = document.getElementById('recipient_1').value;
    var recipient2 = document.getElementById('recipient_2').value;
    var recipient3 = document.getElementById('recipient_3').value;
    var recipient4 = document.getElementById('recipient_4').value;

    if (!recipient1 && !recipient2 && !recipient3 && !recipient4) {
        showResponse('warning', 'Please add at least one recipient');
        return false;
    }

    var d = '<?= $d['0'] ?>';
    var e = '<?= $d['2'] ?>';
    var subject = document.getElementById('subject').value.trim();
    var message = document.getElementById('message').value.trim();

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

    var formData = new FormData(this);

    fetch(ROOT_URL + '/functions/sendmail.php', {
            method: 'POST',
            body: formData,
        })
        .then(response => response.json()) // Parse the JSON response
        .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); // Display the success message from the server

                var popupClose = document.getElementById('modalBtnCancel');
                popupClose.click();
            }
            if (result.status === "error") {
                // Handle error
                document.getElementById('sending').style.display = 'none';
                document.getElementById('error').style.display = 'block';
                document.getElementById('errorMessage').textContent = result.message ||
                'An error occurred.';
            }
        })


    return false;
});



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



<?php if ($delivery == "active") { ?>
// HSE Enable change event
document.getElementById('hseEnable').addEventListener('change', function() {
    var hseElement = document.getElementById('hse');
    if (this.checked) {
        hseElement.removeAttribute('disabled');
    } else {
        hseElement.setAttribute('disabled', 'true');
    }
});

// Disabling select options
document.querySelectorAll('.select2-results__option').forEach(function(option) {
    if (option.hasAttribute('disabled')) {
        // Custom logic if needed
    }
});
<?php } ?>

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

// Load default address function
function loadDefaultAddress() {
    var clientNumber = '<?= $d[0] ?>';
    fetch('functions/loadEmail.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                clientnumber: clientNumber
            })
        })
        .then(response => response.json())
        .then(data => {
            data.forEach((item, index) => {
                var recipientField = document.getElementById('recipient_' + (index + 1));
                if (recipientField) {
                    recipientField.value = item.email;
                }
            });
        })
        .catch(error => {
            console.error('Error:', error);
        });
}
</script>