<link rel="stylesheet" href="<?php echo e(asset('public/assets/css/datatables/jquery.dataTables.min.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('public/assets/css/datatables/jquery.datatables.buttons.min.css')); ?>">
<div class="row">
    <div class="col-12">
        <h3 class="">Requested Transcripts</h3><br>
        <div class="card flex-fill">
            <div class="card-header">
                <div class="d-flex align-items-center justify-content-between">
                    <div>
                        <button class="btn btn-primary text-white" onclick="reload()"><i
                                class="fas fa-sync me-1"></i>Reload</button>
                    </div>
                    <div></div>
                </div>
            </div>
            <table id="dataTable-1" class="table table-striped  my-0">
                <thead>
                    <tr>
                        <th>Tracking No</th>
                        <th>Index Number</th>
                        <th class="d-none d-xl-table-cell">Applicant Name</th>
                        <th class="d-none d-xl-table-cell">Contact</th>
                        <th>Email Address</th>
                        <th>Type of Document</th>
                        <th>Delivery Mode</th>
                        <th>Status</th>
                        <th class="d-none d-md-table-cell">Action</th>
                    </tr>
                </thead>
                <tbody id="ordered_documents_table">
                    
                </tbody>
            </table>
        </div>


        <div class="modal fade" id="upload-document" tabindex="-1" role="dialog"
            aria-labelledby="addDesignationModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addDesignationModalLabel">Select Document To Upload</h5>

                        <button type="button" class="btn btn-sm bg-danger text-white" onclick="dismissUploadModal()"
                            class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true" style="color: white;">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="uploadForm" enctype="multipart/form-data">
                            <input type="file" accept="application/pdf" name="pdfFile" id="pdfFile">
                            <button type="button" class="btn btn-sm bg-primary text-white" >Upload PDF</button>
                        </form>
                        <div class="progress">
                            <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0"
                                aria-valuemax="100"></div>
                        </div>
                        <div id="message"></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="preview-document" tabindex="-1" role="dialog"
            aria-labelledby="previewUploadFileLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="previewUploadFileLabel">Preview File</h5>

                        <button type="button" class="btn btn-sm bg-danger text-white" onclick="dismissPreviewModal()"
                            class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true" style="color: white;">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div id="previewPdfContainer">

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


    <script src="<?php echo e(asset('public/assets/js/jquery.min.js')); ?>"></script>
    <script src="<?php echo e(asset('public/assets/js/datatables/jquery.dataTables.min.js')); ?>"></script>

    <script>
    $(document).ready(function() {
        $('#dataTable-1').DataTable({
            dom: 'Bfrtip',
            buttons: [
                // 'copy', 'csv', 'excel', 'pdf', 'print'
                {
                    extend: 'copy',
                    footer: true,
                    exportOptions: {
                        columns: [0, 1, 2, 3, 4]
                    }
                },
                {
                    extend: 'pdf',
                    footer: true,
                    exportOptions: {
                        columns: [0, 1, 2, 3, 4]
                    }
                },
                {
                    extend: 'csv',
                    footer: true,
                    exportOptions: {
                        columns: [0, 1, 2, 3, 4]
                    }
                },
                {
                    extend: 'excel',
                    footer: true,
                    exportOptions: {
                        columns: [0, 1, 2, 3, 4]
                    }
                },
                {
                    extend: 'print',
                    footer: true,
                    exportOptions: {
                        columns: [0, 1, 2, 3, 4]
                    }
                },
            ]
        });

        $(function() {
            $('select').select2();
        });
    });

    function reload() {
        window.location.reload();
    }

    function toggleDocumentStatus(tracking_no) {
        const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;
        let body = {
            tracking_no: tracking_no,
            _token: csrfToken
        }

        Swal.fire({
            title: 'Info',
            text: 'Do you want to save privillages?',
            icon: 'question',
            confirmButtonText: 'Yes',
            showCancelButton: true,
            cancelButtonText: 'No',
            confirmButtonColor: '#1cc88a',
            cancelButtonColor: '#d33',

        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: `<?php echo e(url('/toggle-document-status')); ?>`,
                    method: 'POST',
                    data: body,
                    success: function(result_) {
                        Swal.fire({
                            title: 'Info',
                            text: result_ == 'success' ?
                                'Document status has been toggled successfully!' :
                                'Document status could not be toggled!',
                            icon: result_,
                            confirmButtonText: 'Okay',
                            confirmButtonColor: '#1cc88a'

                        }).then((result) => {
                            window.location.reload();
                        })
                    }
                });

            }
        });
    }

 function getOrderedDocuments() {
        // ordered-documents
        const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;
        $.ajax({
            url: `<?php echo e(url('/ordered-documents')); ?>`,
            method: 'GET',
            success: function(result_) {
                let programs = result_['programs'].map(p => p['value']);
                let ordered_documents = result_['ordered_documents'];
                ordered_documents = ordered_documents.filter(doc => {
                    for (let i = 0; i < programs.length; i++) {
                        let program = programs[i];
                        if (doc.type_of_document.includes(program)) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                    return false;
                });
                drawTable(ordered_documents);
            }
        });
    }

    getOrderedDocuments();

   function drawTable(arr) {
        $('#ordered_documents_table td').parent().remove();
        arr.forEach((ordered_document, ordered_document_index) => {
            console.log(ordered_document);
            let tracking_no = ordered_document['tracking_no'];
            let phone_no = ordered_document['phone_no'];
            let tb = $('#ordered_documents_table');
            let tr = $(`<tr id="${tracking_no}"></tr>`);
            let tracking_no_ = $('<td>' + tracking_no + '</td>');
            let index_no = $('<td>' + ordered_document['index_no'] + '</td>');
            let applicant_name = $('<td>' + ordered_document['applicant_name'] + '</td>');
            let phone_no_ = $('<td>' + ordered_document['phone_no'] + '</td>');
            let emailaddress = $('<td>' + ordered_document['emailaddress'] + '</td>');
            let type_of_document = $('<td>' + ordered_document['type_of_document'] + '</td>');
            let delivery_mode = $('<td>' + ordered_document['delivery_mode'] + '</td>');
            let status = $(
            `<td><span class="badge bg-warning"> ${ordered_document['status']} </span></td>`);
            let action = $(`
            <td> 
                <div class="d-flex align-items-center">
                    <div class="btn-group dropleft">
                        <button class="btn btn-light" type="button" id="dropdownMenuButton"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="fas fa-ellipsis"></i>
                        </button>
                        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                            <button type="button" onclick="viewApplicantDocument('${ordered_document['tracking_no']}')"
                                class="btn btn-light dropdown-item">
                                <i class="fas fa-edit mr-1"></i> View Document
                            </button>
                          
                            <button type="button" class="btn btn-light dropdown-item" title="View complaints"
                                onclick="viewApplicantComplaints('${tracking_no}')">
                                <i class="align-middle" data-feather="message-square"></i>
                                View Complaints
                            </button>
                            <button type="button" class="btn btn-light me-2 dropdown-item"
                                onclick="uploadFile('${tracking_no}', '${phone_no}')"><i
                                    class="fas fa-file-upload me-1"></i>Upload
                                File</button>
                            <button type="button" onclick="previewFile('')"
                                class="btn btn-light me-2 dropdown-item">Preview File</button>
                        </div>

                    </div>
                </div>
            </td>
            `);
            
            tr.append(tracking_no_);
            tr.append(index_no);
            tr.append(applicant_name);
            tr.append(phone_no_);
            tr.append(emailaddress);
            tr.append(type_of_document);
            tr.append(delivery_mode);
            tr.append(status);
            tr.append(action);
            tb.append(tr);
        })
    }


    function viewApplicantDocument(tracking_no) {
        window.location = `<?php echo e(url('/transcript-details/${tracking_no}')); ?>`;
    }
    
    function dismissUploadModal() {
        $('#upload-document').modal('hide');
    }

    function uploadFile() {
        $('#upload-document').modal('show');
    }

    function previewFile(tracking_no) {
        const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;
        let formData = {
            tracking_no: tracking_no,
            _token: csrfToken
        }

        $.ajax({
            url: `<?php echo e(url('/preview-uploaded-document')); ?>`,
            type: 'POST',
            data: formData,
            success: function(data) {
                if (data == "failed") {
                    Swal.fire({
                        title: 'Info',
                        text: 'No document have been uploaded yet!',
                        icon: 'error',
                        confirmButtonText: 'Okay',
                        confirmButtonColor: '#1cc88a'

                    })
                    return;
                }

                previewPdf(`<?php echo e(url('${data}')); ?>`);
            },
            error: function(xhr, status, error) {
                console.log('Error uploading file: ' + error);
            }
        });
    }

    function previewPdf(pdfUrl) {
        var pdfId = document.getElementById("previewPdfContainer");
        pdfId.removeChild(pdfId.childNodes[0]);
        var embed = document.createElement('embed');
        embed.style.width = "100%";
        embed.style.height = "700px";
        embed.setAttribute('src', pdfUrl);
        embed.setAttribute('type', 'application/pdf');
        pdfId.appendChild(embed);
        $('#preview-document').modal('show');
    }

    function dismissPreviewModal() {
        $('#preview-document').modal('hide');
    }
    </script>