<?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 `$_GET[table_name]` WHERE id='$delete_id' ");
    if ($q) {
        echo "<script>alert('Deleted Successfully !');</script>";
    } else {
        echo mysqli_error($db);
    }
    echo "<script>location.href='all_letters';</script>";
}


?>


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

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

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

            <div class="row mb-3" id="filter_block">
                <div class="col-md-3">
                    <div class="form-group">
                        <label class="form-label" for="name">Name</label>
                        <input type="text" class="form-control" placeholder="Name" name="name" id="name">
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="form-group">
                        <label class="form-label" for="added_by">Added By</label>
                        <input type="text" class="form-control" placeholder="Added By" name="added_by" id="added_by">
                    </div>
                </div>

                <div class="col-md-2">
                    <div class="d-flex flex-column mb-3">
                        <button type="button" class="btn btn-danger btn-padding mb-1" name="clear_filter" id="clear_filter">Clear</button>
                        <button class="btn btn-success btn-padding" type="button" name="search_filter" id="search_filter">Search</button>
                    </div>
                </div>
                <div class="col-sm-12">
                    <div id="filter_options" class="d-flex align-items-center flex-wrap" style="gap:0.25rem"></div>
                </div>
            </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 Letters
                                </h4>
                            </div>


                            <div class="row">
                                <div class="col-12">
                                    <table id="basic-datatable" class="table dt-responsive nowrap">
                                        <thead>
                                            <tr>
                                                <th>ID</th>
                                                <th>Employee ID</th>
                                                <th>Name</th>
                                                <th>Issue Date</th>
                                                <th>Joining Date</th>
                                                <th>Letter Type</th>
                                                <th>Document Link</th>
                                                <th>Added By</th>
                                                <th>Action</th>
                                                <th>Approvals</th>
                                                <th>Signed Attachment</th>
                                            </tr>
                                        </thead>

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

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

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

</div>


<div class="modal fade" id="letter_request_remark" tabindex="-1" aria-labelledby="letter_request_remarkLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body p-3">
                <div class="d-flex align-items-center justify-content-between mb-4">
                    <h5 class="mb-2">Add Letter Status Remark</h5>
                    <i data-feather="x" onclick="$('#letter_request_remark').modal('hide');"></i>
                </div>
                <div>
                    <form>
                        <div class="row">
                            <div class="col-12">
                                <input type="hidden" name="letter_approve_id" id="letter_approve_id">
                                <input type="hidden" name="letter_approve_id_table" id="letter_approve_id_table">
                                <input type="hidden" name="letter_approve_id_status" id="letter_approve_id_status">
                                <textarea name="letter_approve_id_remark" id="letter_approve_id_remark" required class="form-control" rows="5" placeholder="Enter Remark for letter"></textarea>
                            </div>
                        </div>

                        <div class="row mt-3">
                            <div class="col-12">
                                <div class="w-100 d-flex align-items-center justify-content-end">
                                    <button type="button" name="letter_approve_id_submit" class="btn btn-primary" onclick="approveApi();">Add</button>
                                </div>
                            </div>
                        </div>

                    </form>
                </div>

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

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

<script>
    function deleteData(id, table) {
        if (confirm('Do you want to Delete ?')) {
            location.href = `?table_name=${table}&delete=${id}`;
        }
    }

    function sendForApproval(letter_approval_request_id, table) {
        if (confirm('Do you want to Send for Approval?')) {
            $.ajax({
                url: 'fun/function',
                type: 'POST',
                data: {
                    letter_approval_request_id,
                    table
                },
                dataType: 'json',
                success: function(res) {
                    // console.log(res);
                    if (res.status === 200) {
                        successMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                        setTimeout(() => {
                            location.href = 'all_letters';
                        }, 2000);
                    } else {
                        failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                    }
                }
            });
        }
    }


    function approveApi() {

        let letter_approve_id = $('#letter_approve_id').val();
        let letter_table = $('#letter_approve_id_table').val();
        let letter_status = $('#letter_approve_id_status').val();
        let letter_remark = $('#letter_approve_id_remark').val();

        // console.log(letter_approve_id, letter_table, letter_status, letter_remark);
        if (letter_status == 2 && letter_remark.trim() == '') {
            failedMessage('Please, Fill the remark.', '<?php echo $_SESSION['user_name']; ?>');
            return false;
        }

        if (confirm('Do you want to Approve this letter?')) {
            $.ajax({
                url: 'fun/function',
                type: 'POST',
                data: {
                    letter_approve_id,
                    letter_table,
                    letter_status,
                    letter_remark
                },
                dataType: 'json',
                success: function(res) {
                    // console.log(res);
                    if (res.status === 200) {
                        successMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                        setTimeout(() => {
                            location.href = 'all_letters';
                        }, 2000);
                    } else {
                        failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                    }
                }
            })
        }

    }

    function approveLetter(letter_approve_id, table, status) {

        $('#letter_approve_id').val(letter_approve_id);
        $('#letter_approve_id_table').val(table);
        $('#letter_approve_id_status').val(status);

        if (status == 2) {
            $('#letter_request_remark').modal('show');
        } else {
            approveApi();
        }
    }


    $(document).on('click', '.approvers-info-details', function(e) {
        let data = $(this).next().val();
        let status_list = ['Pending', 'Approved', 'Reject'];
        let status_list_color = ['text-warning', 'text-success', 'text-danger'];
        let d = JSON.parse(data);

        let text = '';
        d.forEach((record, index) => {
            text += `<h4>Approve Request ${index + 1}</h4>`;
            text += `
                <table border="1" cellspacing="0" cellpadding="5" class="table table-striped">
                    <thead>
                        <tr>
                            <th>Employee</th>
                            <th>Status</th>
                            <th>Message</th>
                            <th>Request Time</th>
                            <th>Status Update</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            for (const [emp_id, values] of Object.entries(record)) {
                text += `
                    <tr>
                        <td><strong>${emp_id}</strong></td>
                        <td class="${status_list_color[values.status]}">${status_list[values.status]}</td>
                        <td>${values.message || '-'}</td>
                        <td>${values.time}</td>
                        <td>${values.update_time}</td>
                    </tr>
                `;
            }
            text += `</tbody></table><br>`; // Separate tables for multiple records
        });

        $('#right_sidebar_title').html('Approvers Details');
        $('#right_sidebar_details').html(text);
        show_hide_right_bar();
    });



    function sendLetter(id, table, file_name) {
        if (confirm('Do you want to send this letter?')) {
            $("#addTickSend" + atob(id)).removeClass('uil-envelope-share').text('Sending...');
            $.ajax({
                url: `fun/letters_download`,
                type: 'POST',
                data: {
                    letter_id: id,
                    letter_file_name: file_name,
                    letter_table: table
                },
                // dataType: 'json',
                success: function(res) {
                    console.log(res);
                    res = JSON.parse(res);
                    console.log(res);
                    if (res.status === 200) {
                        $("#addTickSend" + atob(id)).text('Mail Send');
                        successMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                    } else {
                        failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                        $("#addTickSend" + atob(id)).addClass('uil-envelope-share').text('');
                    }
                }
            });
        }

    }


    async function uploadSignedAttachment(id, table, letter_file) {
        let file = document.getElementById(`signed_attachment_${table}_${atob(id)}`).files[0];

        if (!file) {
            failedMessage('Please select a file to upload.', '<?php echo $_SESSION['user_name']; ?>');
            return false;
        }
        // check is pdf
        if (file && file.type !== 'application/pdf') {
            failedMessage('Please upload a PDF file.', '<?php echo $_SESSION['user_name']; ?>');
            return false;
        }
        if (file.size > 5 * 1024 * 1024) { // 5 MB limit
            failedMessage('File size exceeds 5 MB limit.', '<?php echo $_SESSION['user_name']; ?>');
            return false;
        }

        if (confirm('Do you want to upload signed attachment?')) {

            let formData = new FormData();
            formData.append('letter_id', id);
            formData.append('letter_table', table);
            formData.append('signed_attachment', file);
            formData.append('signed_attachment_id', 1);

            $(`#signed_attachment_button_${table}_${atob(id)}`).text('Uploading...').prop('disabled', true);
            await $.ajax({
                url: 'fun/letters_download',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function(res) {
                    console.log(res);
                    res = JSON.parse(res);
                    console.log(res);
                    if (res.status === 200) {
                        successMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');

                        setTimeout(() => {
                            location.href = 'all_letters';
                        }, 2000);

                        // let text = `<a href="${res.signed_attachment_path}" target="_blank" class="btn btn-success btn-sm">Signed Attachment</a>
                        // <a href="javascript:;" onclick="sendSignedLetter('${id}','${table}', '${letter_file}');" title="Send Mail with Signed Letter" class="text-secondary"><i class="uil uil-envelope-share" id="addTickSendSigned${atob(id)}"></i></a>`;

                        // $(`#signed_attachment_${table}_${atob(id)}`).parent().removeClass('input-group');
                        // $(`#signed_attachment_${table}_${atob(id)}`).parent().html(text);
                    } else {
                        failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                    }
                }
            });
            $(`#signed_attachment_button_${table}_${atob(id)}`).text('Upload').prop('disabled', false);
        }
    }

    async function sendSignedLetter(id, table, letter_file) {
        if (confirm('Do you want to send this signed letter?')) {
            $("#addTickSendSigned" + atob(id)).removeClass('uil-envelope-share').text('Sending...');
            await $.ajax({
                url: `fun/letters_download`,
                type: 'POST',
                data: {
                    signed_letter_id: id,
                    signed_letter_file_name: letter_file,
                    signed_letter_table: table
                },
                // dataType: 'json',
                success: function(res) {
                    console.log(res);
                    res = JSON.parse(res);
                    console.log(res);
                    if (res.status === 200) {
                        $("#addTickSendSigned" + atob(id)).text('Mail Send');
                        successMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                    } else {
                        failedMessage(res.message, '<?php echo $_SESSION['user_name']; ?>');
                        $("#addTickSendSigned" + atob(id)).addClass('uil-envelope-share').text('');
                    }
                }
            });
        }
    }           

    $(document).ready(function() {

        // ############################### columns
        let columns = [{
            data: 'row_num'
        }, {
            data: 'employee_id'
        }, {
            data: 'name'
        }, {
            data: 'issue_date'
        }, {
            data: 'joining_date'
        }, {
            data: 'letter_type'
        }, {
            data: 'document'
        }, {
            data: 'added_by_name'
        }, {
            data: 'id'
        }, {
            data: 'approved_by'
        }, {
            data: 'signed_attachment'
        }, {
            data: 'signed_mail_send',
            visible: false
        }, {
            data: 'mail_send',
            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_letters_get', columns, [0, "asc"], setArray);
            } else {
                loadTable('#basic-datatable', 'get_from_server/all_letters_get', columns, [0, "asc"]);
            }
            // console.log(setArray);
            setArray = [];
            // console.log(setArray);
        }

        show_hierarchy_data();
        $("#search_filter").click(show_hierarchy_data);
    });
</script>