<!-- 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('billing'); ?></li>
    </ol>
</nav>
<!-- /Breadcrumb -->

<!-- Container -->
<div class="container">
    <!-- 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_invoice'); ?>
        </h4>
        <div class="align-items-center">
            <?php if (has_permission(VIEW, 'billing', 'billing')) { ?>
                <button class="btn btn-sm btn-outline-light btn-wth-icon icon-wthot-bg mr-15" onclick="printOfficeBill(<?php echo $this->uri->segment(3, 0); ?>);">
                    <span class="icon-label"><i class="fa fa-print"></i> </span>
                    <span class="btn-text">Print1 </span>
                </button>
            <?php } ?>

            <?php if (has_permission(VIEW, 'billing', 'billing')) { ?>
                <button class="btn btn-sm btn-outline-light btn-wth-icon icon-wthot-bg mr-15" onclick="printBill(<?php echo $this->uri->segment(3, 0); ?>);">
                    <span class="icon-label"><i class="fa fa-print"></i> </span>
                    <span class="btn-text">Print3</span>
                </button>
            <?php } ?>
            <?php if (has_permission(VIEW, 'billing', 'billing')) { ?>
                <a href="<?php echo site_url('billing'); ?>" class="btn btn-primary btn-sm mr-15"><?php echo $this->lang->line('create'); ?> <?php echo $this->lang->line('new'); ?></a>
            <?php } ?>

            <?php if (has_permission(VIEW, 'billing', 'billing')) { ?>
                <a href="<?php echo site_url('billing/bill'); ?>" class="btn btn-success btn-sm mr-15"><?php echo $this->lang->line('billing'); ?> <?php echo $this->lang->line('list'); ?></a>
            <?php } ?>

            <?php if (has_permission(VIEW, 'billing', 'billing')) { ?>
                <a href="<?php echo site_url('billing/history/' . $this->uri->segment(3, 0)); ?>" class="btn btn-violet btn-sm mr-15"><?php echo $this->lang->line('payment'); ?> <?php echo $this->lang->line('history'); ?></a>
            <?php } ?>

            <?php if (has_permission(VIEW, 'billing', 'billing')) { ?>
                <?php if ($invoice->paid_status == 'unpaid') { ?>
                    <button onclick="GetPaymentData(<?php echo $this->uri->segment(3, 0); ?>)" type="button" class="btn btn-teal btn-sm" data-toggle="modal" data-target="#addPaymentModal"><?php echo $this->lang->line('add'); ?> <?php echo $this->lang->line('payment'); ?></button>
                <?php } ?>
            <?php } ?>
        </div>
    </div>
    <!-- /Title -->

    <!-- Row -->
    <div class="row">
        <div class="col-xl-12">
            <section class="hk-sec-wrapper hk-invoice-wrap pa-35">
                <div class="invoice-to-wrap pb-0">
                    <div class="row">
                        <div class="col-md-8 mb-30">
                            <span class="d-block text-uppercase mb-5 font-13">billing to</span>
                            <h6 class="mb-5 text-uppercase"><?php echo $patient->patient ? $patient->patient : ''; ?> [<?php echo $patient->patient_unique_id; ?>]</h6>
                            <address>
                                <span class="d-block">Sex & Age : <?php echo $this->lang->line($patient->gender); ?> / <?php echo get_age($patient->dob); ?></span>
                                <span class="d-block">Mobile No : <?php echo $patient->phone; ?></span>
                                <span class="d-block">Address : <?php echo $patient->address; ?></span>
                                <span class="d-block"><span class="text-red">Ref By :</span>
                                    <?php
                                    if ($patient->ref_dr_name) {
                                        echo $patient->ref_dr_name;
                                    } elseif ($patient->self) {
                                        echo 'Self';
                                    } else {
                                        echo $patient->refdr . ', ' . $patient->specialist;
                                    } ?>
                                </span>
                                <span class="d-block"><span class="text-red">Commission :</span> <?php echo $patient->commission; ?> <?php echo $patient->commission_phone ? '[' . $patient->commission_phone . ']' : ''; ?></span>
                                <span class="d-block">Prepared By : <?php echo $patient->created_by; ?></span>
                                <?php if ($this->session->userdata('role_id') == SUPER_ADMIN || !empty(custom_permission('modified_by'))) { ?>
                                    <span class="d-block">Modified By : <?php echo $patient->modified_by; ?></span>
                                    <span class="d-block">Date : <?php echo $patient->modified_by ? date('d F, Y h:i A', strtotime($patient->modified_at)) : ''; ?></span>
                                <?php } ?>
                            </address>
                        </div>
                        <div class="col-md-4 mb-30">
                            <span class="d-block text-uppercase mb-5 font-13">billing from</span>
                            <h6 class="mb-5 text-uppercase"><?php echo $this->global_setting->brand_title; ?></h6>
                            <address>
                                <span class="d-block"><?php echo $this->global_setting->address; ?></span>
                                <span class="d-block">Phone: <?php echo $this->global_setting->phone; ?></span>
                                <span class="d-block">Email: <?php echo $this->global_setting->email; ?></span>
                                <span class="d-block text-red font-weight-bold">Invoice#: <?php echo $invoice->custom_invoice_id; ?></span>
                                <?php if ($invoice->prev_invoice_id > 0  && $invoice->prev_invoice_id != null) { ?>
                                    <span class="d-block text-mute font-11">
                                        Prev Invoice#:
                                        <?php
                                        $prev =  $this->billing->get_single('invoices', array('id' => $invoice->prev_invoice_id));
                                        echo isset($prev->custom_invoice_id) ? $prev->custom_invoice_id : '';
                                        ?>
                                    </span>
                                <?php } ?>
                                <span class="d-block">Bill Date: <?php echo date('d/m/Y, h:i A', strtotime($invoice->bill_date)); ?></span>
                                <?php if ($invoice->paid_status == 'unpaid' && $invoice->due_amount > 0) { ?>
                                    <span class="d-block text-uppercase text-red font-weight-bold">Due: <?php echo $invoice->due_amount; ?></span>
                                <?php } ?>
                            </address>
                        </div>
                    </div>
                </div>
                <?php if (isset($tests) & !empty($tests)) { ?>
                    <div class="invoice-details">
                        <div class="table-wrap">
                            <div class="table-responsive">
                                <table class="table table-sm table-border mb-0">
                                    <thead class="text-center bg-gradient-sunset">
                                        <tr>
                                            <th class="text-white font-weight-700 text-center w-15"><?php echo $this->lang->line('sl_no'); ?></th>
                                            <th class="text-white font-weight-700 text-left w-20"><?php echo $this->lang->line('department'); ?></th>
                                            <th class="text-white font-weight-700 text-left w-35"><?php echo $this->lang->line('test'); ?> <?php echo $this->lang->line('name'); ?></th>
                                            <th class="text-white font-weight-700 text-center w-10"><?php echo $this->lang->line('quantity'); ?></th>
                                            <th class="text-white font-weight-700 text-center w-10"><?php echo $this->lang->line('rate'); ?></th>
                                            <th class="text-white font-weight-700 text-center w-10"><?php echo $this->lang->line('total'); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php $count = 1; ?>
                                        <?php foreach ($tests as $obj) { ?>
                                            <tr>
                                                <td class="text-center"><?php echo $count++; ?></td>
                                                <td class="text-left"><?php echo $obj->department; ?></td>
                                                <td class="text-left"><?php echo $obj->test_name; ?></td>
                                                <td class="text-center"><?php echo $obj->unit; ?></td>
                                                <td class="text-right"><?php echo $obj->rate; ?></td>
                                                <td class="text-right"><?php echo $obj->total_rate; ?></td>
                                            </tr>
                                        <?php } ?>
                                        <?php foreach ($tubes as $obj) { ?>
                                            <tr>
                                                <td class="text-center"><?php echo $count++; ?></td>
                                                <td class="text-left"><?php echo $obj->department; ?></td>
                                                <td class="text-left"><?php echo $obj->tube; ?></td>
                                                <td class="text-center"><?php echo $obj->quantity; ?></td>
                                                <td class="text-right"><?php echo $obj->rate; ?></td>
                                                <td class="text-right"><?php echo $obj->total_rate; ?></td>
                                            </tr>
                                        <?php } ?>
                                        <tr class="bg-transparent">
                                            <td colspan="5" class="text-right text-light">Total</td>
                                            <td class="text-right"><?php echo $invoice->total_bill; ?></td>
                                        </tr>
                                        <tr class="bg-transparent">
                                            <td colspan="5" class="text-right text-light border-top-0">Discount</td>
                                            <td class="text-right border-top-0"><?php echo $invoice->discount; ?></td>
                                        </tr>
                                        <tr class="bg-transparent">
                                            <td colspan="5" class="text-right text-light border-top-0">Net Payable</td>
                                            <td class="text-right border-top-0"><?php echo $invoice->net_payable; ?></td>
                                        </tr>
                                        <tr class="bg-transparent">
                                            <td colspan="5" class="text-right text-light border-top-0">Advanced Amount</td>
                                            <td class="text-right border-top-0"><?php echo $invoice->advanced; ?></td>
                                        </tr>
                                        <?php if ($invoice->commission_user_id > 0) { ?>
                                            <tr class="bg-transparent">
                                                <td colspan="5" class="text-right text-light border-top-0">Total Commission</td>
                                                <td class="text-right border-top-0"><?php echo $invoice->commission_user_id > 0 ? $invoice->commission_amount : '0.00'; ?></td>
                                            </tr>
                                            <tr class="bg-transparent">
                                                <td colspan="5" class="text-right text-light border-top-0">Payable Commission</td>
                                                <td class="text-right border-top-0"><?php echo $invoice->commission_user_id > 0 ? number_format($invoice->payable_commission - $invoice->discount, 2) : '0.00'; ?></td>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                    <tfoot class="border-bottom border-1">
                                        <tr>
                                            <th colspan="5" class="text-right font-weight-600">Due Amount</th>
                                            <th class="text-right font-weight-600 text-red"><?php echo $invoice->due_amount; ?></th>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php } ?>
            </section>
        </div>
    </div>
    <!-- /Row -->
</div>
<!-- /Container -->

<!-- Add Payment Modal -->
<div class="modal fade" id="addPaymentModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalForms" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo $this->lang->line('add'); ?> <?php echo $this->lang->line('payment'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="addPaymentForm" method="POST" action="<?php echo base_url('billing/add_payment'); ?>"  autocomplete="off">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="authorized_person"><?php echo $this->lang->line('authorized'); ?> <?php echo $this->lang->line('person'); ?></label>
                        <select class="form-control" name="authorized_person" id="authorized_person">
                            <option selected value="0"><?php echo $this->lang->line('select'); ?> <?php echo $this->lang->line('authorized'); ?></option>
                            <?php foreach ($authorized_persons as $obj) { ?>
                                <option value="<?php echo $obj->user_id; ?>" <?php echo isset($authorized_person) && $authorized_person == $obj->user_id ? 'selected="selected"' : ""; ?>><?php echo $obj->name; ?> - <?php echo $obj->designation; ?></option>
                            <?php } ?>
                        </select>
                        <div class="valid-feedback">
                            <?php echo $this->lang->line('looks_good'); ?>
                        </div>
                        <div class="invalid-feedback">
                            <?php echo $this->lang->line('required_field'); ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="date"><?php echo $this->lang->line('payment'); ?> <?php echo $this->lang->line('date'); ?></label>
                        <input type="text" class="form-control" name="date" id="date" value="<?php echo isset($date) ?  $date : ''; ?>" placeholder="<?php echo $this->lang->line('payment'); ?> <?php echo $this->lang->line('date'); ?>" required>
                        <div class="valid-feedback">
                            <?php echo $this->lang->line('looks_good'); ?>
                        </div>
                        <div class="invalid-feedback">
                            <?php echo $this->lang->line('required_field'); ?>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="due"><span class=" text-red"><?php echo $this->lang->line('due'); ?> <?php echo $this->lang->line('amount'); ?></span></label>
                                <input type="text" readonly class="form-control" id="due_amount" placeholder="<?php echo $this->lang->line('due'); ?> <?php echo $this->lang->line('amount'); ?>">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="second_less"><?php echo $this->lang->line('second_less'); ?></label>
                                <input type="text" class="form-control" name="second_less" id="second_less" value="<?php echo isset($second_less) ?  $second_less : ''; ?>" placeholder="<?php echo $this->lang->line('second_less'); ?>">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="amount"><?php echo $this->lang->line('payment'); ?> <?php echo $this->lang->line('amount'); ?></label>
                        <input type="text" class="form-control" name="amount" id="amount" value="<?php echo isset($amount) ?  $amount : ''; ?>" placeholder="<?php echo $this->lang->line('payment'); ?> <?php echo $this->lang->line('amount'); ?>" required>
                        <div class="invalid-feedback">
                            <?php echo $this->lang->line('required_field'); ?>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><?php echo $this->lang->line('remark'); ?></span>
                            </div>
                            <textarea class="form-control" name="note" id="note" aria-label="<?php echo $this->lang->line('remark'); ?>"><?php echo isset($note) ?  $note : ''; ?></textarea>
                            <div class="valid-feedback">
                                <?php echo $this->lang->line('looks_good'); ?>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="hidden" id="invoice_id" name="invoice_id" value="<?php echo $this->uri->segment(3, 0); ?>">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo $this->lang->line('cancel'); ?></button>
                    <button id="submit" type="submit" class="btn btn-primary"><?php echo $this->lang->line('submit'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script type="text/javascript">
    $("#amount").on("keyup", function() {
        var val = +this.value || 0;
        var cal = ($("#due_amount").val() - val);
        $("#second_less").val(Math.round(cal));
    });
</script>

<!-- Daterangepicker -->
<link href="<?php echo VENDOR_URL; ?>daterangepicker/daterangepicker.css" rel="stylesheet" type="text/css" />
<script src="<?php echo VENDOR_URL; ?>moment/min/moment.min.js"></script>
<script src="<?php echo VENDOR_URL; ?>daterangepicker/daterangepicker.js"></script>


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>


<script>
    $("#date").daterangepicker({
        singleDatePicker: true,
        startDate: new Date(),
        showDropdowns: true,
        minYear: 1901,
        timePicker: true,
        timePicker24Hour: true,
        timePickerIncrement: 1,
        timePickerSeconds: false,
        autoUpdateInput: true,
        locale: {
            format: 'YYYY-MM-DD HH:mm',
        }
    });
</script>

<script type="text/javascript">
    function GetPaymentData(id) {
        $.ajax({
            url: '<?php echo site_url('billing/get_payment_data/') ?>' + id,
            dataType: 'json',
            success: function(data) {
                $('#due_amount').val(data.amount);
                $('#amount').val(data.amount);
            }
        });
    }
    $(document).ready(function(e) {
        $("#addPaymentForm").on('submit', (function(e) {
            e.preventDefault();
            $.ajax({
                url: '<?php echo base_url('billing/add_payment'); ?>',
                type: "POST",
                data: new FormData(this),
                dataType: 'json',
                contentType: false,
                cache: false,
                processData: false,
                success: function(data) {
                    if (data.status == "failed") {
                        $('#addPaymentModal').hide();
                        $.toast({
                            text: data.error,
                            position: 'top-right',
                            loaderBg: '#7a5449',
                            class: 'jq-toast-danger',
                            hideAfter: 3500,
                            stack: 6,
                            showHideTransition: 'fade'
                        });

                        $.confirm({
                            title: 'Warning! Attention Please!!!',
                            content: data.error,
                            type: 'red',
                            typeAnimated: true,
                            buttons: {
                                close: function() {
                                    $('#addPaymentModal').show();
                                }
                            }
                        });
                    } else {
                        $.toast({
                            text: data.message,
                            position: 'top-right',
                            loaderBg: '#7a5449',
                            class: 'jq-toast-primary',
                            hideAfter: 3500,
                            stack: 6,
                            showHideTransition: 'fade'
                        });
                        $('#addPaymentModal').hide();
                        window.location.replace('<?php echo base_url('billing/history/'); ?><?php echo $this->uri->segment(3, 0); ?>');
                    }
                }
            });
        }));
    });
</script>

<script>
    function printBill(id) {
        $.ajax({
            url: '<?php echo site_url('billing/print'); ?>',
            type: 'POST',
            data: {
                id: id,
            },
            success: function(result) {
                $("#testdata").html(result);
                popup(result);
            }
        });
    }
    
    function printOfficeBill(id) {
        $.ajax({
            url: '<?php echo site_url('billing/printOffice'); ?>',
            type: 'POST',
            data: {
                id: id,
            },
            success: function(result) {
                $("#testdata").html(result);
                popup(result);
            }
        });
    }

    function popup(data) {
        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>Print Invoice</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>