<!-- 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, 'diagnostic', 'report')) { ?>
                <a href="<?php echo site_url('diagnostic/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, 'diagnostic', 'report')) { ?>
                <a href="<?php echo site_url('diagnostic/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-7">
            <div class="card mb-0 mt-0">
                <div class="card-header d-flex justify-content-between">
                    <?php if (has_permission(VIEW, 'diagnostic', '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('group'); ?></th>
                                        <th><?php echo $this->lang->line('name'); ?></th>
                                        <th><?php echo $this->lang->line('sample_collect'); ?></th>
                                        <th><?php echo $this->lang->line('action'); ?></th>
                                        <th><?php echo $this->lang->line('create'); ?></th>
                                        <th><?php echo $this->lang->line('print'); ?></th>
                                    </tr>
                                </thead>
                                <?php echo form_open(site_url('diagnostic/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));
                                            // Check if test result exists for this template
                                            $test_result_exists = $this->report->check_test_result_exists($obj->invoice_id, $obj->investagation_id);
                                            // Debug: Get template ID for this test
                                            $template_id = $this->report->get_template_id_by_test($obj->investagation_id);
                                        ?>
                                            <tr>
                                                <td><?php echo $count++; ?></td>
                                                <td><?php echo $obj->group; ?></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, 'diagnostic', '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>
                                                <td>
                                                    <input class="create_result" type="checkbox" name="investigation_ids[]" value="<?php echo $obj->investagation_id; ?>" <?php echo $test_result_exists ? 'checked' : ''; ?> />
                                                    <!-- Debug: <?php echo "Test ID: {$obj->investagation_id}, Template ID: {$template_id}, Result Exists: " . ($test_result_exists ? 'Yes' : 'No'); ?> -->
                                                </td>
                                                <td>
                                                    <input class="print_result" type="checkbox" name="print_ids[]" value="<?php echo $obj->investagation_id; ?>" />
                                                </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="5"><?php echo $this->lang->line('no_data_found'); ?></td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="7" align="right">
                                            <div class="btn-group mr-2">
                                                <button type="button" class="btn btn-gradient-info btn-xs" onclick="check_all();"><?php echo $this->lang->line('check_all'); ?> <?php echo $this->lang->line('sample_collect'); ?></button>
                                            </div>
                                            <button type="submit" class="btn btn-gradient-primary btn-xs"><?php echo $this->lang->line('generate'); ?></button>
                                            <div class="btn-group mr-2">
                                                <button type="button" class="btn btn-gradient-info btn-xs" onclick="check_all_create();"><?php echo $this->lang->line('check_all'); ?> <?php echo $this->lang->line('create'); ?></button>
                                            </div>
                                            
                                            <button type="button" class="btn btn-gradient-success btn-xs" onclick="submitCreateForm()"><?php echo $this->lang->line('create'); ?></button>
                                            <button type="button" class="btn btn-gradient-warning btn-xs" onclick="submitPrintForm()"><?php echo $this->lang->line('print'); ?></button>
                                        </td>
                                    </tr>
                                </tfoot>
                                <?php echo form_close(); ?>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- / col-lg-7 -->
        <div class="col-lg-5">
            <div class="card mb-0 mt-0">
                <div class="card-header d-flex justify-content-between">
                    <?php if (has_permission(VIEW, 'diagnostic', '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, 'diagnostic', '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, 'diagnostic', 'report')) { ?>
                                                        <?php if ($obj->template_id > 0 && $obj->template_status) { ?>
                                                            <a class="btn btn-info btn-xs" href="<?php echo site_url('diagnostic/report/single/' . $obj->report_id); ?>"><i class="fa fa-eye"></i></a>
                                                        <?php } ?>
                                                    <?php } ?>

                                                    <?php if (has_permission(EDIT, 'diagnostic', '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, 'diagnostic', 'report')) { ?>
                                                        <a class="btn btn-danger btn-xs" href="<?php echo site_url('diagnostic/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);
    }

    function check_all_create() {
        $('.create_result').prop('checked', true);
    }

    function uncheck_all_create() {
        $('.create_result').prop('checked', false);
    }

    function submitCreateForm() {
        var form = document.getElementById('sample_collect');
        form.action = '<?php echo site_url("diagnostic/report/create_new"); ?>';
        
        // Validate if any tests are selected
        var checkedTests = $('.create_result:checked').length;
        if (checkedTests === 0) {
            alert('<?php echo $this->lang->line("please_select_test"); ?>');
            return false;
        }
        
        form.submit();
    }

    function submitPrintForm() {
        // Validate if any tests are selected
        var checkedTests = $('.print_result:checked').length;
        if (checkedTests === 0) {
            alert('<?php echo $this->lang->line("please_select_test"); ?>');
            return false;
        }
        
        // Get selected test IDs
        var printIds = [];
        $('.print_result:checked').each(function() {
            printIds.push($(this).val());
        });
        
        // Get form data
        var formData = new FormData();
        formData.append('invoice_id', $('input[name="invoice_id"]').val());
        formData.append('patient_id', $('input[name="patient_id"]').val());
        printIds.forEach(function(id) {
            formData.append('print_ids[]', id);
        });
        
        // Show loading
        $('#printModal .modal-body').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading...</div>');
        $('#printModal').modal('show');
        
        // Make AJAX request
        $.ajax({
            url: '<?php echo site_url("diagnostic/report/print_selected_ajax"); ?>',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                $('#printModal .modal-body').html(response);
            },
            error: function() {
                $('#printModal .modal-body').html('<div class="text-center text-danger">Error loading print data</div>');
            }
        });
    }

    function printContent() {
        var printWindow = window.open('', '_blank');
        var content = $('#printModal .modal-body').html();
        
        printWindow.document.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>Diagnostic Test Results</title>
                <style>
                    body { font-family: Arial, sans-serif; margin: 20px; font-size: 12px; }
                    .header { text-align: center; margin-bottom: 20px; border-bottom: 2px solid #333; padding-bottom: 10px; }
                    .patient-info { margin-bottom: 20px; }
                    .patient-info table { width: 100%; border-collapse: collapse; }
                    .patient-info td { padding: 5px; border: 1px solid #ddd; }
                    .patient-info td:first-child { font-weight: bold; width: 150px; }
                    .results-table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                    .results-table th, .results-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                    .results-table th { background-color: #f5f5f5; font-weight: bold; }
                    .footer { margin-top: 30px; text-align: center; }
                    @media print { body { margin: 0; padding: 10px; } }
                </style>
            </head>
            <body>
                ${content}
            </body>
            </html>
        `);
        
        printWindow.document.close();
        printWindow.focus();
        printWindow.print();
        printWindow.close();
    }
</script>

<!-- Print Modal -->
<div class="modal fade" id="printModal" tabindex="-1" role="dialog" aria-labelledby="printModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header d-flex justify-content-between align-items-center">
                <h5 class="modal-title" id="printModalLabel"><?php echo $this->lang->line('print'); ?> <?php echo $this->lang->line('report'); ?></h5>
                <div class="d-flex">
                    <button type="button" class="btn btn-secondary btn-sm mr-2" data-dismiss="modal"><?php echo $this->lang->line('cancel'); ?></button>
                    <button type="button" class="btn btn-primary btn-sm mr-2" onclick="printContent()"><?php echo $this->lang->line('print'); ?></button>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            </div>
            <div class="modal-body">
                <!-- Content will be loaded here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo $this->lang->line('cancel'); ?></button>
                <button type="button" class="btn btn-primary" onclick="printContent()"><?php echo $this->lang->line('print'); ?></button>
            </div>
        </div>
    </div>
</div>

<!-- 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('diagnostic/report/generateReport'); ?>" enctype="multipart/form-data" method="post">
                <div class="modal-body">
                    <div class="form-row">
                        <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>
                        <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_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('diagnostic/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_template(template_id) {
        $.ajax({
            type: "POST",
            url: "<?php echo site_url('diagnostic/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('diagnostic/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('diagnostic/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 + 'diagnostic/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>Hasan Masud</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>

<script>
    $(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>