<?php
include "pin/header.php";
include "pin/sidenav.php";

$user_id = $_SESSION['user_id'];
$emp_id = $_SESSION['emp_id'];
$user_role = $_SESSION['user_role'];

if (isset($_GET['delete'])) {

    $delete_id = mysqli_real_escape_string($db, base64_decode($_GET['delete']));

    $q = mysqli_query($db, "DELETE FROM `letters_of_intent` WHERE id='$delete_id' ");
    if ($q) {
        echo "<script>alert('Deleted Successfully !');</script>";
    } else {
        echo mysqli_error($db);
    }
    echo "<script>location.href='all_loi';</script>";
}


?>


<!-- ============================================================== -->
<!-- Start Page Content here -->
<!-- ============================================================== -->

<div class="content-page">
    <div class="content">
        <div class="container-fluid">

            <div class="mt-5"></div>

            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body p-4">
                            <div class="d-flex justify-content-between">
                                <h4 class="header-title mt-1 mb-4">
                                    All LOI
                                </h4>
                            </div>


                            <div class="row">
                                <div class="col-12">
                                    <table id="basic-datatable" class="table dt-responsive nowrap">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>LOI Reference Id</th>
                                                <th>Applicant Detail</th>
                                                <th>LOI Subject</th>
                                                <th>Mail Log</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>

                                    </table>
                                </div>
                            </div>

                        </div> <!-- end card body-->
                    </div> <!-- end card -->
                </div><!-- end col-->
            </div>
            <!-- end row-->

        </div>
    </div> <!-- content -->

</div>

<!-- Generate LOI Modal Start -->
 <script src="https://cdn.ckeditor.com/4.21.0/standard/ckeditor.js"></script>
<style>
    @media (min-width: 992px) {
        .modal-lg-LOI {
            max-width: 1500px !important;
        }
    }
</style>

<div class="modal fade" id="generateLoiModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-lg-LOI modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Generate LOI</h5>
                <i data-feather="x" onclick="$('#generateLoiModal').modal('hide');" style="cursor: pointer;"></i>
            </div>
            <div class="modal-body">
                <form id="generateLoiForm">
                    <div class="mb-3">
                        <label for="clientEmailGenerateLoiModal" class="form-label">Enter Email*</label>
                        <input type="text" class="form-control" id="clientEmailGenerateLoiModal" name="LOIEmail" placeholder="Enter Applicant Email" required>
                    </div>
                    <div class="mb-3">
                        <label for="ccEmailsGenerateLoiModal" class="form-label">Enter CC Emails <span class="text-muted">(Optional)</span></label>
                        <input type="text" class="form-control" id="ccEmailsGenerateLoiModal" name="LOICCEmails" placeholder="Enter CC Emails (comma separated)">
                    </div>
                    <div class="mb-3">
                        <label for="clientSubjectGenerateLoiModal" class="form-label">Subject*</label>
                        <input type="text" class="form-control" id="clientSubjectGenerateLoiModal" name="LOISubject" placeholder="Enter Subject" required>
                    </div>
                    <div class="mb-3">
                        <label for="clientMessageGenerateLoiModal" class="form-label">Message*</label>
                        <div id="clientMessageGenerateLoiModal"></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="submit" form="generateLoiForm" class="btn btn-dark">Send LOI</button>
            </div>
        </div>
    </div>
</div>
<!-- Generate LOI Modal End -->

<?php
include "pin/footer.php";
?>

<script>

    // ############################### columns
    let columns = [{
        data: 'id'
    }, {
        data: 'loi_reference_id'
    }, {
        data: 'applicant_name'
    }, {
        data: 'loi_subject'
    }, {
        data: 'mail_log'
    }, {
        data: 'applicant_email'
    }, {
        data: 'applicant_mobile',
        visible: false
    }, {
        data: 'employment_type',
        visible: false
    }];
    // ############################### columns

    function show_hierarchy_data() {

        // ############################### setArray
        // ############################### setArray

        $("#filter_options").html('');
        form_fields.each(function() {
            search_filter(this);
        });

        if (setArray.length > 0) {
            loadTable('#basic-datatable', 'get_from_server/all_loi_get', columns, [0, "asc"], setArray);
        } else {
            loadTable('#basic-datatable', 'get_from_server/all_loi_get', columns, [0, "asc"]);
        }
        // console.log(setArray);
        setArray = [];
        // console.log(setArray);
    }
    
    $(document).ready(function() {
        show_hierarchy_data();
        $("#search_filter").click(show_hierarchy_data);
    });
</script>

<script>
    let mail_contentGenerateLoi = CKEDITOR.replace('clientMessageGenerateLoiModal', {
        extraPlugins: 'tabletools',
        // Allow all table-related content
        allowedContent: {
            table: {
                attributes: ['cellspacing', 'cellpadding', 'border', 'width', 'style'],
                styles: '*'
            },
            tr: {
                attributes: ['style'],
                styles: '*'
            },
            td: {
                attributes: ['style', 'width', 'colspan', 'rowspan'],
                styles: '*'
            },
            p: {
                attributes: ['style'],
                styles: '*'
            },
            strong: true,
            a: {
                attributes: ['href', 'style'],
                styles: '*'
            },
            img: {
                attributes: ['src', 'alt', 'style', 'width', 'height'],
                styles: '*'
            },
            br: true
        },

        // Email-specific settings
        enterMode: CKEDITOR.ENTER_BR,
        shiftEnterMode: CKEDITOR.ENTER_P,

        // Preserve inline styles
        config: {
            protectedSource: [/style="[^"]*"/g]
        },
        on: {
            instanceReady: function(evt) {
                console.log('CKEditor instance is ready:', evt.editor);
            }
        }
    });

    function generateLOI(loi_id, template='full_time'){
        try {
            $.ajax({
                url:'fun/manage_loi',
                type: 'POST',
                data: {
                    get_loi_content_id: loi_id,
                    loi_template: template
                },
                success: function(res) {
                    // console.log(res);
                    resData = JSON.parse(res);
                    if (resData.status === 200) {
                        $('#clientEmailGenerateLoiModal').val(resData.applicant_email ?? "");
                        $('#clientSubjectGenerateLoiModal').val(resData.subject ?? "");
                        $('#generateLoiModal button[type=submit]').attr('data-reference-id', resData.loi_reference_id);
                        mail_contentGenerateLoi.setData(resData.content);
                        $('#generateLoiModal').modal('show');
                    } else {
                        failedMessage(resData.message ?? "Failed to generate LOI", 'warning');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error generating LOI:', error);
                }
            });
        } catch (error) {
            console.error('Error generating LOI:', error);
            failedMessage('Something went wrong!', '<?php echo $_SESSION['user_name']; ?>');
        }
    }

    let generateLoiForm = document.querySelector('#generateLoiForm');
    generateLoiForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        let submitBtn = document.querySelector('#generateLoiModal button[type=submit]');
        try {
            let email = document.querySelector('#clientEmailGenerateLoiModal').value;
            let ccEmail = document.querySelector('#ccEmailsGenerateLoiModal').value;
            const validateEmail = (email) => {
                let re = /\S+@\S+\.\S+/;
                return re.test(email);
            }
            if (email != '') {
                let emailArr = email.split(',');
                let emailValid = true;
                emailArr.forEach(em => {
                    if (!validateEmail(em.trim())) {
                        emailValid = false;
                    }
                });

                if (!emailValid) {
                    failedMessage('Please Enter Valid Email Id', '<?php echo $_SESSION['user_name']; ?>');
                    return;
                }
            }

            if (ccEmail != '') {
                let ccEmailArr = ccEmail.split(',');
                let ccEmailValid = true;
                ccEmailArr.forEach(em => {
                    if (!validateEmail(em.trim())) {
                        ccEmailValid = false;
                    }
                });

                if (!ccEmailValid) {
                    failedMessage('Please Enter Valid CC Email Ids', '<?php echo $_SESSION['user_name']; ?>');
                    return;
                }
            }

            let formData = new FormData(e.target);
            formData = Object.fromEntries(formData.entries());

            formData['mailBody'] = mail_contentGenerateLoi.getData();
            formData['reference_id'] = submitBtn.dataset.referenceId;
            // console.log('formData', formData);

            $(submitBtn).prop('disabled', true).text('Sending LOI to Applicant...');

            let result = await $.post('fun/manage_loi', {
                generateLoi_mail_body: JSON.stringify(formData)
            });
            // console.log(result);
            $(submitBtn).prop('disabled', false).text('Send LOI');

            let resData = JSON.parse(result);

            if (resData.status == 200) {
                successMessage("LOI Sent Successfully!", '<?php echo $_SESSION['user_name']; ?>');
                e.target.reset();
                $('#generateLoiModal').modal('hide');
                show_hierarchy_data();
            } else {
                failedMessage("Something Went Wrong!", '<?php echo $_SESSION['user_name']; ?>');
                console.log(resData.error)
            }
        } catch (error) {
            $(submitBtn).prop('disabled', false).text('Send LOI');
            console.error('Error checking button state:', error);
        }
    });
</script>
