<!-- 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-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_billing'); ?>
        </h4>
        <div class="d-flex">
            <a href="<?php echo site_url('billing'); ?>" class="btn btn-primary btn-sm mr-10"><?php echo $this->lang->line('create'); ?> <?php echo $this->lang->line('new'); ?></a>
            <a href="<?php echo site_url('billing/due'); ?>" class="btn btn-danger btn-sm mr-10"><?php echo $this->lang->line('due'); ?> <?php echo $this->lang->line('billing'); ?></a>
            <a href="<?php echo site_url('billing/paid'); ?>" class="btn btn-success btn-sm"><?php echo $this->lang->line('paid'); ?> <?php echo $this->lang->line('billing'); ?></a>
        </div>
    </div>
    <!-- /Title -->

    <!-- Row -->
    <div class="row">
        <!-- col-lg-12 -->
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between">
                    <?php if (has_permission(VIEW, 'billing', 'billing')) { ?>
                        <h6 class="card-header d-flex align-items-center">
                            <i class="fa fa-bold font-30 mr-10"></i>
                            <?php echo $this->lang->line('bill'); ?> <?php echo $this->lang->line('list'); ?>
                        </h6>
                    <?php } ?>
                    <?php echo form_open_multipart(site_url('billing/bill'), array('name' => 'bill', 'id' => 'bill', 'class' => 'needs-validation form-inline', 'novalidate' => 'novalidate', 'method' => 'get'), ''); ?>
                    <div class="form-group mr-2">
                        <div class="input-group input-group-sm">
                            <div class="input-group-append">
                                <button class="btn btn-gradient-primary" type="button"><?php echo $this->lang->line('type'); ?></button>
                            </div>
                            <select class="form-control" name="type" id="type">
                                <option value="0" selected><?php echo $this->lang->line('select'); ?></option>
                                <option value="1" <?php echo isset($type) && $type == 1 ? 'selected="selected"' : ""; ?>><?php echo $this->lang->line('paid'); ?></option>
                                <option value="2" <?php echo isset($type) && $type == 2 ? 'selected="selected"' : ""; ?>><?php echo $this->lang->line('unpaid'); ?></option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group mr-10">
                        <div class="input-group input-group-sm">
                            <input type="text" class="form-control" name="date" id="range" value="<?php echo isset($date) ?  $date : ''; ?>" placeholder="<?php echo $this->lang->line('date'); ?>">
                            <div class="input-group-append">
                                <button class="btn btn-gradient-primary" type="submit"><?php echo $this->lang->line('date'); ?></button>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group input-group-sm">
                            <input type="text" class="form-control" name="search" id="search" value="<?php echo isset($search) ?  $search : ''; ?>" placeholder="<?php echo $this->lang->line('search'); ?>">
                            <div class="input-group-append">
                                <button class="btn btn-gradient-primary" type="submit"><?php echo $this->lang->line('search'); ?></button>
                            </div>
                        </div>
                    </div>
                    <?php echo form_close(); ?>
                </div>
                <div class="card-body">
                    <div class="table-wrap">
                        <div class="table-responsive">
                            <table class="table table-sm mb-0" id="mainTable">
                                <thead>
                                    <tr>
                                        <th><?php echo $this->lang->line('sl_no'); ?></th>
                                        <th><?php echo $this->lang->line('invoice_no'); ?></th>
                                        <th><?php echo $this->lang->line('date'); ?></th>
                                        <th><?php echo $this->lang->line('patient_id'); ?></th>
                                        <th><?php echo $this->lang->line('name'); ?></th>
                                        <th><?php echo $this->lang->line('ref_dr'); ?></th>
                                        <th><?php echo $this->lang->line('reference'); ?></th>
                                        <th><?php echo $this->lang->line('payment'); ?> <?php echo $this->lang->line('status'); ?></th>
                                        <th><?php echo $this->lang->line('net_payable'); ?></th>
                                        <th><?php echo $this->lang->line('discount'); ?></th>
                                        <th><?php echo $this->lang->line('paid'); ?></th>
                                        <th><?php echo $this->lang->line('due'); ?></th>
                                        <th><?php echo $this->lang->line('status'); ?></th>
                                        <th><?php echo $this->lang->line('action'); ?></th>
                                    </tr>
                                </thead>
                                <tbody id="bodyTable">
                                    <?php if (isset($bills) && !empty($bills)) { ?>
                                        <?php foreach ($bills as $obj) { ?>
                                            <tr>
                                                <td><?php echo $sl_count; ?></td>
                                                <td><?php echo $obj->custom_invoice_id; ?></td>
                                                <td><?php echo date('d/m/Y h:ia', strtotime($obj->bill_date)); ?></td>
                                                <td><?php echo $obj->patient_unique_id; ?></td>
                                                <td><?php echo $obj->patient; ?></td>
                                                <td><?php echo $obj->refdr ?? 'Self'; ?></td>
                                                <td><?php echo $obj->commission; ?></td>
                                                <td><?php echo $obj->paid_status == 'paid' ? '<span class="badge badge-success">' . ucfirst($obj->paid_status) . '</span>' : '<span class="badge badge-danger">' . ucfirst($obj->paid_status) . '</span>'; ?></td>
                                                <td><?php echo $obj->net_payable; ?></td>
                                                <td><?php echo $obj->discount; ?></td>
                                                <td><?php echo $obj->advanced; ?></td>
                                                <td><?php echo $obj->due_amount; ?></td>
                                                <td>
                                                    <?php if ($obj->payment_status == 'complete') { ?>
                                                        <span class="badge badge-success"><?php echo $this->lang->line('complete'); ?></span>
                                                    <?php } elseif ($obj->payment_status == 'rejected') { ?>
                                                        <span class="badge badge-danger"><?php echo $this->lang->line('rejected'); ?></span>
                                                    <?php } else { ?>
                                                        <span class="badge badge-warning"><?php echo $this->lang->line('cancel'); ?></span>
                                                    <?php } ?>
                                                </td>
                                                <td>
                                                    <?php if ($obj->commission_payment == 'unpaid') { ?>
                                                        <?php if (has_permission(EDIT, 'billing', 'billing')) { ?>
                                                            <button type="button" title="Add Reference/Commission/Doctor" onclick="getRefId('<?php echo $obj->id; ?>','<?php echo $obj->commission_user_id; ?>')" class="btn btn-xs btn-danger" data-toggle="modal" data-target="#refModal">
                                                                <i class="fa fa-plus"></i>
                                                            </button>
                                                        <?php } ?>
                                                    <?php } ?>
                                                    <?php if ($this->session->userdata('role_id') == SUPER_ADMIN || !empty(custom_permission('add_marketing'))) { ?>
                                                        <?php if (has_permission(EDIT, 'billing', 'billing')) { ?>
                                                            <button type="button" onclick="getInvoiceId('<?php echo $obj->id; ?>')" class="btn btn-xs btn-success" data-toggle="modal" data-target="#marketingModal">
                                                                <?php echo $this->lang->line('marketing'); ?>
                                                            </button>
                                                        <?php } ?>
                                                    <?php } ?>
                                                    <?php if (has_permission(ADD, 'billing', 'billing')) { ?>
                                                        <a href="<?php echo site_url('billing/invoice/' . $obj->id); ?>" class="btn btn-xs btn-primary"><i class="fa fa-eye"></i> <?php echo $this->lang->line('invoice'); ?></a>
                                                    <?php } ?>
                                                    <?php if (has_permission(EDIT, 'billing', 'billing')) { ?>
                                                        <a href="<?php echo site_url('billing/create/' . $obj->patient_id . '?invoice=' . $obj->id); ?>" class="btn btn-xs btn-info"><i class="fa fa-clone"></i></a>
                                                    <?php } ?>
                                                    <?php if (has_permission(EDIT, 'billing', 'billing')) { ?>
                                                        <button type="button" onclick="getInvoiceId('<?php echo $obj->id; ?>')" class="btn btn-xs btn-danger" data-toggle="modal" data-target="#paymentStatusModal">
                                                            <i class="fa fa-pause"></i>
                                                        </button>
                                                    <?php } ?>
                                                    <?php if (has_permission(VIEW, 'billing', 'billing_sms')) { ?>
                                                        <button type="button" onclick="send_sms(<?php echo $obj->id; ?>);" class="btn btn-warning btn-xs">
                                                            <i class="fa fa-envelope-o"></i>
                                                        </button>
                                                    <?php } ?>
                                                    <?php if (has_permission(DELETE, 'billing', 'billing')) { ?>
                                                        <a class="btn btn-xs btn-danger round" href="<?php echo site_url('billing/delete/' . $obj->id); ?>" onclick="javascript: return confirm('<?php echo $this->lang->line('confirm_alert'); ?>');"> <i class="fa fa-trash text-white"></i> </a>
                                                    <?php } ?>
                                                </td>
                                            </tr>
                                        <?php $sl_count++;
                                        } ?>
                                    <?php } else { ?>
                                        <tr class="text-center">
                                            <td colspan="14"><?php echo $this->lang->line('no_data_found'); ?></td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <!-- Card Footer -->
                <?php if ($this->pagination->create_links()) { ?>
                    <div class="card-footer justify-content-end">
                        <?php echo $this->pagination->create_links(); ?>
                    </div>
                <?php } ?>
            </div>
        </div>
    </div>
    <!-- /Row -->
</div>
<!-- /Container -->

<!-- Payment Status Modal -->
<div class="modal fade" id="paymentStatusModal" 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('payment'); ?> <?php echo $this->lang->line('status'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="paymentStatusForm" method="POST" action="<?php echo base_url('billing/payment_status'); ?>">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="payment_status"><?php echo $this->lang->line('status'); ?></label>
                        <select class="form-control" name="payment_status" id="payment_status" required>
                            <option value="" selected><?php echo $this->lang->line('select'); ?></option>
                            <option value="complete"><?php echo $this->lang->line('complete'); ?></option>
                            <option value="rejected"><?php echo $this->lang->line('rejected'); ?></option>
                            <option value="canceled"><?php echo $this->lang->line('cancel'); ?></option>
                        </select>
                    </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>
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="hidden" id="invoice_id" name="invoice_id">
                    <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>

<?php if ($this->session->userdata('role_id') == SUPER_ADMIN || !empty(custom_permission('add_marketing'))) { ?>
    <!-- Marketing Modal -->
    <div class="modal fade" id="marketingModal" 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('marketing'); ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <form id="marketingForm" method="POST" action="<?php echo base_url('billing/add_marketing'); ?>">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="marketing_id"><?php echo $this->lang->line('marketing'); ?> <?php echo $this->lang->line('name'); ?></label>
                                    <select class="form-control" name="marketing_id" id="marketing_id">
                                        <option selected value=""><?php echo $this->lang->line('select'); ?> <?php echo $this->lang->line('employee'); ?></option>
                                        <?php foreach ($marketings as $obj) { ?>
                                            <option value="<?php echo $obj->user_id; ?>"><?php echo $obj->name; ?> [<?php echo $obj->phone; ?>]</option>
                                        <?php } ?>
                                    </select>
                                </div>
                            </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'); ?>" required><?php echo isset($note) ?  $note : ''; ?></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <input type="hidden" class="invoice_id" name="invoice_id">
                        <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>
<?php } ?>

<!-- Ref Modal -->
<div class="modal fade" id="refModal" 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('reference'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="refForm" method="POST" action="<?php echo base_url('billing/add_ref'); ?>">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="form-group">
                                <label for="add_reference_id"><?php echo $this->lang->line('reference'); ?> <?php echo $this->lang->line('name'); ?></label>
                                <select class="form-control select2" name="add_reference_id" id="add_reference_id">
                                    <option selected value=""><?php echo $this->lang->line('select'); ?></option>
                                    <?php foreach ($reference_add as $obj) { ?>
                                        <option value="<?php echo $obj->user_id; ?>"><?php echo $obj->name; ?> [<?php echo $obj->phone; ?>]</option>
                                    <?php } ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <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>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="hidden" id="add_reference_invoice_id" name="add_reference_invoice_id">
                    <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">
    function getInvoiceId(id) {
        $.ajax({
            url: '<?php echo site_url('billing/getInvoiceId/') ?>' + id,
            dataType: 'json',
            success: function(data) {
                $('#invoice_id').val(data.id);
                $('.invoice_id').val(data.id);
                $('#payment_status').val(data.payment_status);
                $('#note').val(data.note);
            }
        });
    }

    function getRefId(id, commission_user_id) {
        if (commission_user_id) {
            $('#add_reference_id').val(commission_user_id);
            $('#add_reference_id').trigger('change');
        }
        $('#add_reference_invoice_id').val(id);
    }
</script>

<script type="text/javascript">
    $(document).ready(function(e) {
        $("#paymentStatusForm").on('submit', (function(e) {
            e.preventDefault();
            $.ajax({
                url: '<?php echo base_url(); ?>billing/payment_status',
                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-primary',
                            hideAfter: 3500,
                            stack: 6,
                            showHideTransition: 'fade'
                        });
                        // location.reload(true);
                        $("#mainTable").load(window.location.href + " #bodyTable");
                        $('#paymentStatusModal').modal('hide');
                    }
                    $('#paymentStatusForm').find('form')[0].reset();
                }
            });
        }));
    });
</script>
<script type="text/javascript">
    $(document).ready(function(e) {
        $("#refForm").on('submit', (function(e) {
            e.preventDefault();
            $.ajax({
                url: '<?php echo base_url(); ?>billing/add_ref',
                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-primary',
                            hideAfter: 3500,
                            stack: 6,
                            showHideTransition: 'fade'
                        });
                        // location.reload(true);
                        $("#mainTable").load(window.location.href + " #bodyTable");
                        $('#refModal').modal('hide');
                    }
                    $('#refForm').find('form')[0].reset();
                }
            });
        }));
    });
</script>

<script type="text/javascript">
    $(document).ready(function(e) {
        $("#marketingForm").on('submit', (function(e) {
            $('button[type=submit]').attr('disabled', true);
            e.preventDefault();
            $.ajax({
                url: '<?php echo base_url(); ?>billing/add_marketing',
                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-primary',
                            hideAfter: 3500,
                            stack: 6,
                            showHideTransition: 'fade'
                        });
                        $("#marketingModal").hide();
                    }
                },
                complete: function() {
                    window.location.reload(true);
                }
            });
        }));
    });
</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>

<!-- 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;
    }

    .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();
    $('#range').daterangepicker({
        startDate: new Date(),
        endDate: moment(),
        showDropdowns: true,
        minYear: 1901,
        locale: {
            format: 'YYYY/MM/DD',
        },
        ranges: {
            'Today': [moment(), moment()],
            'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            'Tomorrow': [moment().subtract(-1, 'days'), moment().subtract(-1, 'days')],
            'Last 7 Days': [moment().subtract(6, 'days'), moment()],
            'Last 30 Days': [moment().subtract(29, 'days'), moment()],
            'This Month': [moment().startOf('month'), moment().endOf('month')],
            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
            'This Year': [moment().startOf('year'), moment().endOf('year')],
            'Last Year': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')]
        }
    });

    function send_sms(id) {
        $.confirm({
            title: 'Send SMS!',
            content: 'Are you sure to send SMS?',
            type: 'red',
            typeAnimated: true,
            buttons: {
                tryAgain: {
                    text: 'Yes',
                    btnClass: 'btn-red',
                    action: function() {
                        $.ajax({
                            url: "<?php echo site_url('billing/billing_sms'); ?>/" + id,
                            method: 'get'
                        });
                        $.alert('SMS Sent Successfully!');
                    }
                },
                close: function() {}
            }
        });
    }
</script>