<!-- Breadcrumb -->
<nav class="hk-breadcrumb" aria-label="breadcrumb">
    <ol class="breadcrumb breadcrumb-light bg-transparent">
        <li class="breadcrumb-item"><a href="<?php echo site_url('dashboard'); ?>"><?php echo $this->lang->line('dashboard'); ?></a></li>
        <li class="breadcrumb-item active" aria-current="page"><?php echo $this->lang->line('report'); ?></li>
    </ol>
</nav>
<!-- /Breadcrumb -->

<!-- Container -->
<div class="container-fluid">
    <!-- Title -->
    <div class="hk-pg-header">
        <h4 class="hk-pg-title">
            <span class="pg-title-icon"><i class="fa fa-arrow-circle-o-down"></i></span>
            <?php echo $this->lang->line('manage'); ?> <?php echo $this->lang->line('report'); ?>
        </h4>
        <div class="d-flex">
            <?php if (has_permission(ADD, 'radiology', 'report')) { ?>
                <a href="<?php echo site_url('radiology/report/create'); ?>" class="btn btn-primary btn-xs mr-10"><i class="fa fa-plus"></i> <?php echo $this->lang->line('create'); ?> <?php echo $this->lang->line('report'); ?></a>
            <?php } ?>

            <?php if (has_permission(VIEW, 'radiology', 'report')) { ?>
                <a href="<?php echo site_url('radiology/report'); ?>" class="btn btn-success btn-xs mr-10"><i class="fa fa-flask"></i> <?php echo $this->lang->line('report'); ?> <?php echo $this->lang->line('list'); ?></a>
            <?php } ?>
        </div>
    </div>
    <!-- /Title -->

    <!-- Row -->
    <div class="row">
        <div class="col-lg-6">
            <div class="card mb-0 mt-0">
                <div class="card-header d-flex justify-content-between">
                    <?php if (has_permission(VIEW, 'radiology', 'report')) { ?>
                        <h6 class="card-header d-flex align-items-center">
                            <i class="fa fa-flask font-30 mr-10"></i>
                            <?php echo $this->lang->line('test'); ?> <?php echo $this->lang->line('list'); ?>
                        </h6>
                    <?php } ?>
                </div>
                <div class="card-body">
                    <div class="table-wrap">
                        <div class="table-responsive">
                            <table class="table table-sm mb-0">
                                <thead>
                                    <tr>
                                        <th><?php echo $this->lang->line('sl_no'); ?></th>
                                        <th><?php echo $this->lang->line('name'); ?></th>
                                        <th><?php echo $this->lang->line('status'); ?></th>
                                        <th><?php echo $this->lang->line('action'); ?></th>
                                    </tr>
                                </thead>
                                <?php echo form_open(site_url('radiology/report/sample_collect'), array('name' => 'sample_collect', 'id' => 'sample_collect', 'class' => 'form-horizontal form-label-left'), ''); ?>
                                <tbody>
                                    <?php $count = 1;
                                    if (isset($tests) && !empty($tests)) { ?>
                                        <?php foreach ($tests as $obj) {
                                            $report = $this->report->get_single('diagnostic_reports', array('patient_id' => $obj->patient_id, 'invoice_id' => $obj->invoice_id, 'investagation_id' => $obj->investagation_id));
                                        ?>
                                            <tr>
                                                <td><?php echo $count++; ?></td>
                                                <td><?php echo $obj->test_name; ?></td>
                                                <td>
                                                    <input class="check_all" type="checkbox" name="sample_collect[]" value="<?php echo $obj->investagation_id; ?>" <?php echo isset($report->sample_collect) && !empty($report->sample_collect) ? 'checked' : ''; ?> />
                                                </td>
                                                <td>
                                                    <?php if (isset($report->sample_collect) && !empty($report->sample_collect)) { ?>
                                                        <?php if (has_permission(EDIT, 'radiology', 'report')) { ?>
                                                            <button class="btn btn-success btn-xs" onclick="getTemplateName('<?php echo $obj->investagation_id; ?>', '<?php echo $report->id; ?>')" type="button" data-toggle="modal" data-target="#generateReportModal">
                                                                <i class="fa fa-pencil"></i>
                                                            </button>
                                                        <?php } ?>
                                                    <?php } ?>
                                                </td>
                                                <input type="hidden" name="patient_id" value="<?php echo $obj->patient_id; ?>">
                                                <input type="hidden" name="invoice_id" value="<?php echo $obj->invoice_id; ?>">
                                                <input type="hidden" name="department_id[<?php echo $obj->investagation_id; ?>]" value="<?php echo $obj->department_id; ?>">
                                                <input type="hidden" name="investagation_id[<?php echo $obj->investagation_id; ?>]" value="<?php echo $obj->investagation_id; ?>">
                                            </tr>
                                        <?php }  ?>
                                    <?php } else { ?>
                                        <tr class="text-center">
                                            <td colspan="4"><?php echo $this->lang->line('no_data_found'); ?></td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="5" align="right">
                                            <button type="button" class="btn btn-gradient-info btn-xs" onclick="check_all();"><?php echo $this->lang->line('check_all'); ?></button>
                                            <button type="button" class="btn btn-gradient-danger btn-xs" onclick="uncheck_all();"><?php echo $this->lang->line('uncheck_all'); ?></button>
                                            <button type="submit" class="btn btn-gradient-primary btn-xs"><?php echo $this->lang->line('generate'); ?></button>
                                        </td>
                                    </tr>
                                </tfoot>
                                <?php echo form_close(); ?>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- / col-lg-7 -->
        <div class="col-lg-6">
            <div class="card mb-0 mt-0">
                <div class="card-header d-flex justify-content-between">
                    <?php if (has_permission(VIEW, 'radiology', 'report')) { ?>
                        <h6 class="card-header d-flex align-items-center">
                            <i class="fa fa-flask font-30 mr-10"></i>
                            <?php echo $this->lang->line('report'); ?> <?php echo $this->lang->line('list'); ?>
                        </h6>
                    <?php } ?>
                </div>
                <div class="card-body">
                    <div class="table-wrap">
                        <div class="table-responsive">
                            <table class="table table-sm mb-0">
                                <thead>
                                    <tr>
                                        <th><?php echo $this->lang->line('report'); ?> <?php echo $this->lang->line('name'); ?></th>
                                        <th><?php echo $this->lang->line('date'); ?></th>
                                        <th><?php echo $this->lang->line('status'); ?></th>
                                        <th width="28%"><?php echo $this->lang->line('action'); ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (isset($reports) && !empty($reports)) { ?>
                                        <?php foreach ($reports as $obj) { ?>
                                            <tr>
                                                <td><?php echo $obj->template_name; ?></td>
                                                <td><?php echo date('Y-d-m, h:i A', strtotime($obj->created_at)); ?></td>
                                                <td><?php echo $obj->template_status ? '<span class="badge badge-success">' . $this->lang->line('complete') . '</span>' : '<span class="badge badge-danger">' . $this->lang->line('pending') . '</span>'; ?></td>
                                                <td>
                                                    <?php if (has_permission(VIEW, 'radiology', 'report')) { ?>
                                                        <?php if ($obj->template_status) { ?>
                                                            <button class="btn btn-orange btn-xs" onclick="getPrint('<?php echo $obj->report_id; ?>')" type="button">
                                                                <i class="fa fa-print"></i>
                                                            </button>
                                                        <?php } ?>
                                                    <?php } ?>
                                                    <?php if (has_permission(VIEW, 'radiology', 'report')) { ?>
                                                        <?php if ($obj->template_id > 0 && $obj->template_status) { ?>
                                                            <a class="btn btn-info btn-xs" href="<?php echo site_url('radiology/report/single/' . $obj->report_id); ?>"><i class="fa fa-eye"></i></a>
                                                        <?php } ?>
                                                    <?php } ?>

                                                    <?php if (has_permission(EDIT, 'radiology', 'report')) { ?>
                                                        <button class="btn btn-success btn-xs" onclick="getTemplateName('<?php echo $obj->investagation_id; ?>', '<?php echo $obj->report_id; ?>')" type="button" data-toggle="modal" data-target="#generateReportModal">
                                                            <i class="fa fa-pencil"></i>
                                                        </button>
                                                    <?php } ?>

                                                    <?php if (has_permission(DELETE, 'radiology', 'report')) { ?>
                                                        <a class="btn btn-danger btn-xs" href="<?php echo site_url('radiology/report/delete/' . $obj->report_id); ?>" onclick="javascript: return confirm('<?php echo $this->lang->line('confirm_alert'); ?>');"> <i class="fa fa-trash"></i></a>
                                                    <?php } ?>
                                                </td>
                                            </tr>
                                        <?php }  ?>
                                    <?php } else { ?>
                                        <tr class="text-center">
                                            <td colspan="4"><?php echo $this->lang->line('no_data_found'); ?></td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- /Container -->

<script>
    function check_all() {
        $('.check_all').prop('checked', true);
    }

    function uncheck_all() {
        $('.check_all').prop('checked', false);;
    }
</script>

<!-- Add OPD Patient Modal -->
<div class="modal fade" id="generateReportModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenter" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <div id="template_"></div>
                <h5 class="modal-title mr-30"><?php echo $this->lang->line('generate') . " " . $this->lang->line('report'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="generateReportForm" accept-charset="utf-8" action="<?php echo base_url('radiology/report/generateReport'); ?>" enctype="multipart/form-data" method="post">
                <div class="modal-body">
                    <div class="form-row">
                        <?php if ($this->session->userdata('role_id') == SUPER_ADMIN || $this->session->userdata('role_id') == ADMIN || $this->session->userdata('role_id') == RADIOLOGIST) { ?>
                            <div class="col-md-6 mb-10">
                                <label for="doctor_id"><?php echo $this->lang->line('doctor'); ?></label>
                                <select class="form-control custom-select doctor_id select2" name="doctor_id" id="doctor_id" required>
                                    <option value="" selected><?php echo $this->lang->line('select'); ?> <?php echo $this->lang->line('doctor'); ?></option>
                                    <?php foreach ($doctors as $obj) { ?>
                                        <option value="<?php echo $obj->user_id; ?>" <?php echo isset($doctor_id) && $doctor_id == $obj->user_id ? 'selected="selected"' : ""; ?>><?php echo $obj->name; ?> [<?php echo $obj->phone; ?>]</option>
                                    <?php } ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-10">
                                <label for="template_id"><?php echo $this->lang->line('template'); ?> <?php echo $this->lang->line('name'); ?></label>
                                <select class="form-control custom-select template_id" name="template_id" id="template_id" required onchange="get_template(this.value)">
                                    <option value="" selected><?php echo $this->lang->line('select'); ?></option>
                                </select>
                            </div>
                        <?php } else { ?>
                            <div class="col-md-6 mb-10">
                                <label for="template_id"><?php echo $this->lang->line('template'); ?> <?php echo $this->lang->line('name'); ?></label>
                                <select class="form-control custom-select template_id" name="template_id" id="template_id" required onchange="get_template(this.value)">
                                    <option value="" selected><?php echo $this->lang->line('select'); ?></option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-10">
                                <label for="note"><?php echo $this->lang->line('remark'); ?></label>
                                <input class="form-control" name="note" id="note" placeholder="<?php echo $this->lang->line('remark'); ?>">
                            </div>
                        <?php } ?>
                        <div class="col-md-12 mt-10 mb-10">
                            <div class="tinymce-wrap">
                                <textarea class="tinymce template" name="template" id="template" placeholder="<?php echo $this->lang->line('template'); ?>"></textarea>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer pt-0">
                    <div class="button-list">
                        <input type="hidden" name="report_id" id="report_id">
                        <button id="saveAndprint" class="btn btn-gradient-success" type="button"><?php echo $this->lang->line('save_and_print'); ?></button>
                        <button id="submit" class="btn btn-gradient-primary" type="submit"><?php echo $this->lang->line('submit'); ?></button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    function getTemplateName(investagation_id, report_id) {
        $('#report_id').val(report_id);
        $.ajax({
            type: "POST",
            url: "<?php echo site_url('ajax/get_investagation_by_radiology_template'); ?>",
            data: {
                investagation_id: investagation_id
            },
            async: false,
            success: function(response) {
                if (response) {
                    $('#template_id').html(response);
                }
            }
        });

        $.ajax({
            type: "POST",
            url: "<?php echo site_url('radiology/report/getReport'); ?>",
            data: {
                report_id: report_id
            },
            dataType: 'json',
            async: false,
            success: function(response) {
                if (response != null) {
                    $('#template_id').val(response.template_id).trigger("change");
                    tinyMCE.activeEditor.setContent(response.template);
                    $('#note').val(response.note);
                } else {
                    tinyMCE.activeEditor.setContent('');
                }
            }
        });
    };

    function get_doctor_template(doctor_id) {
        $.ajax({
            type: "POST",
            url: "<?php echo site_url('ajax/get_doctor_template'); ?>",
            data: {
                doctor_id: doctor_id
            },
            async: false,
            success: function(response) {
                if (response) {
                    $('#template_id').html(response);
                }
            }
        });
    };

    function get_template(template_id) {
        $.ajax({
            type: "POST",
            url: "<?php echo site_url('radiology/report/template'); ?>",
            data: {
                template_id: template_id
            },
            async: false,
            dataType: 'json',
            success: function(response) {
                if (response != null) {
                    tinyMCE.activeEditor.setContent(response.template);
                    // var editor = tinymce.get('template');
                    // editor.execCommand('insertHTML', false, response.template)
                } else {
                    tinyMCE.activeEditor.setContent('');
                }
            }
        });
    };
</script>

<!-- Add Report Form -->
<script>
    $(document).ready(function(e) {
        $("#generateReportForm").on('submit', (function(e) {
            e.preventDefault();
            $.ajax({
                url: '<?php echo base_url('radiology/report/generateReport'); ?>',
                type: "POST",
                data: new FormData(this),
                dataType: 'json',
                contentType: false,
                cache: false,
                processData: false,
                success: function(data) {
                    if (data.status == "failed") {
                        var message = "";
                        $.each(data.error, function(index, value) {
                            message += value;
                        });
                        $.toast({
                            text: message,
                            position: 'top-right',
                            loaderBg: '#7a5449',
                            class: 'jq-toast-danger',
                            hideAfter: 3500,
                            stack: 6,
                            showHideTransition: 'fade'
                        });
                    } else {
                        $.toast({
                            text: data.message,
                            position: 'top-right',
                            loaderBg: '#7a5449',
                            class: 'jq-toast-success',
                            hideAfter: 3500,
                            stack: 6,
                            showHideTransition: 'fade'
                        });
                        window.location.reload(true);
                    }
                }
            });
        }));
    });

    // Save And Print
    $(document).ready(function(e) {
        $("#saveAndprint").on('click', (function(e) {
            $("#submit").attr('disabled', true);
            var form = $(this).parents('form').attr('id');
            var str = $("#" + form).serializeArray();
            var postData = new FormData();
            $.each(str, function(i, val) {
                postData.append(val.name, val.value);
            });
            $.ajax({
                url: '<?php echo base_url('radiology/report/generateReport'); ?>',
                type: "POST",
                data: postData,
                dataType: 'json',
                contentType: false,
                cache: false,
                processData: false,
                success: function(data) {
                    if (data.status == "failed") {
                        var message = "";
                        $.each(data.error, function(index, value) {
                            message += value;
                        });
                        $.toast({
                            text: message,
                            position: 'top-right',
                            loaderBg: '#7a5449',
                            class: 'jq-toast-danger',
                            hideAfter: 3500,
                            stack: 6,
                            showHideTransition: 'fade'
                        });
                    } else {
                        $.toast({
                            text: data.message,
                            position: 'top-right',
                            loaderBg: '#7a5449',
                            class: 'jq-toast-success',
                            hideAfter: 3500,
                            stack: 6,
                            showHideTransition: 'fade'
                        });
                        getPrint(data.report_id);
                    }
                    $("#submit").attr('disabled', false);
                }
            });
        }));
    });
</script>

<script>
    function getPrint(report_id) {
        var base_url = '<?php echo base_url() ?>';
        $.ajax({
            url: base_url + 'radiology/report/print',
            type: 'POST',
            data: {
                report_id: report_id,
            },
            success: function(result) {
                $("#testdata").html(result);
                popup(result);
            }
        });
    }

    function popup(data) {
        var base_url = '<?php echo base_url() ?>';
        var frame1 = $('<iframe />');
        frame1[0].name = "frame1";
        frame1.css({
            "position": "absolute",
            "top": "-1000000px"
        });
        $("body").append(frame1);
        var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
        frameDoc.document.open();
        //Create a new HTML document.
        frameDoc.document.write('<html>');
        frameDoc.document.write('<head>');
        frameDoc.document.write('<title>Report</title>');

        frameDoc.document.write('</head>');
        frameDoc.document.write('<body>');
        frameDoc.document.write(data);
        frameDoc.document.write('</body>');
        frameDoc.document.write('</html>');
        frameDoc.document.close();
        setTimeout(function() {
            window.frames["frame1"].focus();
            window.frames["frame1"].print();
            frame1.remove();
            window.location.reload(true);
        }, 500);
        return true;
    }
</script>

<!-- Tinymce JavaScript -->
<script src="<?php echo VENDOR_URL; ?>tinymce/tinymce.min.js"></script>

<!-- Select2 -->
<link href="<?php echo VENDOR_URL; ?>select2/dist/css/select2.min.css" rel="stylesheet" type="text/css" />
<script src="<?php echo VENDOR_URL; ?>select2/dist/js/select2.full.min.js"></script>

<style>
    .select2-container .select2-selection--single {
        height: calc(2.25rem + 4px) !important;
        width: 100%;
    }

    .select2-container--default .select2-search--dropdown .select2-search__field {
        color: #324148;
        border-width: 2px;
        border-color: #e0e3e4;
        padding: .375rem .75rem;
        height: calc(2.25rem + 4px);
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow b {
        margin-top: 5px;
    }
</style>
<script>
    $(".select2").select2();
    $(function() {
        "use strict";
        tinymce.init({
            selector: '.tinymce',
            height: 300,
            statusbar: false,
            setup: function(editor) {
                editor.on('change', function() {
                    tinymce.triggerSave();
                });
            },
            plugins: [
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table contextmenu paste code'
            ],
            toolbar: 'code || fullscreen || insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent',

        });
    });
</script>