@extends('layouts.app')
@section('title', 'IPD Admission')
@section('pages')

<style type="text/css">
    .breadcrumb-title {
      border-right: none;

    }
    tr td {
     vertical-align: middle !important; 
}
</style>

    <!--breadcrumb-->
    <div class="page-breadcrumb row align-items-center justify-content-between mb-3 px-3 px-md-0">
      <div class="breadcrumb-title col-md-6"> IPD Admission
      </div>
      <div class="col-md-6">
        <nav aria-label="breadcrumb">
          <ol class="breadcrumb justify-content-md-end mb-0">
            <li class="breadcrumb-item"><i class="bi bi-info-circle-fill text-info show-help-support" data-id="93" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
            <li class="breadcrumb-item active" aria-current="page">IPD-In Patient </li>
            <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i> IPD Admission</li>
          </ol>
        </nav>
      </div>
    </div>
    <!--end breadcrumb-->

    <div class="card style_table shadow-none radius-5 min-height">
          <div class="card-header py-3">
            @include('layouts.partials.nav-menu')
            <div class="row gx-2">

              <div class="col-lg-2 col-md-2 col-4 dataTables_length" id="example_length" style="display: none;">
                <i class="bi bi-funnel"></i>
                <select class="form-select" name="patient_type" aria-controls="example">
                    <option value="discharged">Discharged Patient</option>
                </select>
              </div>

                <div class="col-lg-2 col-md-2 col-4 dataTables_length" id="example_length">
                  <i class="bi bi-funnel"></i>
                  <select class="form-select" id="" name="search_type" aria-controls="example">
                      <option value="patient_name">Patient Name</option>
                      <option value="consultant_name">Consultant Name</option>
                      <option value="ipd_admission_no">IPD Admission No</option>
                      <option value="ipd_file_no">IPD File NO</option>
                  </select>
                </div>

              <div class="col-lg-3 col-md-3 col-8">
                  <div class="position-relative">
                      <div class="position-absolute top-50 translate-middle-y search-icon px-3"><i class="bi bi-search"></i></div>
                      <input class="form-control ps-5" type="search" id="search" placeholder="Search" autofocus>
                  </div>
              </div>

              <div class="col-lg-7 col-md-7">
                <div class="ms-auto float-md-end">
                    <div class="btn-group">
                        <a href="{!! route('ipd-admissions-discharged-statements') !!}" class="btn btn-primary">Discharged Statements</a>
                    </div>
                </div>
              </div>
            </div>
          </div>
        <div class="card-body" id="tables">

      @include('ipd-discharged.table')

      <input type="hidden" name="hidden_page" id="hidden_page" value="1" />
      <input type="hidden" name="hidden_column_name" id="hidden_column_name" value="name" />
      <input type="hidden" name="hidden_sort_type" id="hidden_sort_type" value="asc" />
    </div>

<script>

     /***************** Global Delay Fucntion ***************/
     function delay(callback, ms) {
        var timer = 0;
        return function() {
            var context = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function() {
                callback.apply(context, args);
            }, ms || 0);
        };
    }

    $(document).ready(function(){
      function clear_icon(){
        $('#id_icon').html('');
        $('#post_title_icon').html('');
      }

      function fetch_data(page, sort_type, sort_by, query){
        var search_type = $('[name="search_type"]').val();
        var patient_type = $('[name="patient_type"]').val();
        $.ajax({
          url:"?page="+page+"&sortby="+sort_by+"&sorttype="+sort_type+"&query="+query+"&search_type="+search_type+"&patient_type="+patient_type,
          success:function(data){
            $('#tables').html('');
            $('#tables').html(data);
            $(document).ready(function(){$.switcher();});
          }
        })
      }

      $(document).on('click', '#create', function(){
        $('#commonModalLabel').text('Add New Bed');
        $('.save_button_span').text('Save Bed');
        $.ajax({
          url:"{!! route('beds.create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
      })

      $(document).on('click', '.edit', function(){
        $('#commonModalLabel').text('Edit Beds');
        $('.save_button_span').text('Update Beds');
        var id = $(this).data('id');
        var url = `{!! route('beds.edit', ':id') !!}`.replace(':id', id);

        $.ajax({
          url:url,
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
      })

        
       /******** searching ********/
        $(document).on('keyup', '#search', delay(function() {
            var query = $('#search').val();

            if (query.length < 2 && query.length != 0) {
                return;
            }

            var column_name = $('.sorting').val();
            var sort_type   = $('#hidden_sort_type').val();
            var page        = 1 ? 1 : (this).attr('href').split('page=')[1];
            fetch_data(page, sort_type, column_name, query);
        }, 700));

        $('body').on('change', '.sorting', function() {
            var column_name = $(this).val();
            var order_type = $(this).data('sorting_type');
            var reverse_order = '';
            var page = 1 ? 1 : (this).attr('href').split('page=')[1];
            var query = $('#search').val() ? $('#search').val() : '';
            fetch_data(page, reverse_order, column_name, query);
        });
        $('body').on('click', '.pager a', function(event) {
            event.preventDefault();
            $('#hidden_page').val(page);
            var page = $(this).attr('href').split('page=')[1];
            var column_name = $('.sorting').val() ? $('.sorting').val() : '';
            var sort_type = $('#hidden_sort_type').val();
            var query = $('#search').val() ? $('#search').val() : '';
            $('li').removeClass('active');
            $(this).parent().addClass('active');
            fetch_data(page, sort_type, column_name, query);
        });
        /*********change status**********/
        $("body").on("click", '.changeStatusCustom', function(event) {
            dataString = {
                "id": $(this).data('id'),
                "status": $(this).data('status')
            };
            var UrlValue = $(this).data('url');
            var status = $(this).data('status');
            var changeStatus = $(this);
            var btn = $(this);

            Swal.fire({
                title: 'Are you sure you want to change status?',
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: false,
                confirmButtonText: 'Yes',
                denyButtonText: 'No',
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: UrlValue,
                        method: 'post',
                        data: dataString,
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        beforeSend: function(xhr) {
                            // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                        },
                        success: function(response) {
                            if (response.success) {
                                var ErroMsg = $(this).printErrorMsg(response
                                    .message);
                                $(this).Toastshow('success', ErroMsg);

                                var page = $('.pager').find('.active a').attr(
                                    'href') == undefined ? 1 : $('.pager').find(
                                    '.active a').attr('href').split('page=')[1];
                                var column_name = $('.sorting').val() ? $(
                                    '.sorting').val() : '';
                                var sort_type = $('#hidden_sort_type').val();
                                var query = $('#search').val() ? $('#search')
                                .val() : '';

                                fetch_data(page, sort_type, column_name, query);
                            } else {
                                var ErroMsg = $(this).printErrorMsg(response
                                    .message);
                                if (ErroMsg === '') {
                                    ErroMsg = "Something went wrong!";
                                }
                                $(this).Toastshow('error', ErroMsg);

                                if (status == 1) {
                                    changeStatus.parent().find('.ui-switcher').attr(
                                        'aria-checked', false);
                                } else {
                                    changeStatus.parent().find('.ui-switcher').attr(
                                        'aria-checked', true);
                                }
                            }
                        },
                        error: function(data) {
                            console.log("error ", data);

                            if (status == 1) {
                                changeStatus.parent().find('.ui-switcher').attr(
                                    'aria-checked', false);
                            } else {
                                changeStatus.parent().find('.ui-switcher').attr(
                                    'aria-checked', true);
                            }
                        }
                    });
                } else if (result.isDenied) {

                var page = $('.pager').find('.active a').attr(
                    'href') == undefined ? 1 : $('.pager').find(
                    '.active a').attr('href').split('page=')[1];
                var column_name = $('.sorting').val() ? $(
                    '.sorting').val() : '';
                var sort_type = $('#hidden_sort_type').val();
                var query = $('#search').val() ? $('#search')
                .val() : '';

                fetch_data(page, sort_type, column_name, query);
                }
                //return false;
            });
            //return false;
        });
        /*********delete data**********/
        $("body").on("click", '.deleteDataCustom', function(event) {
            dataString = {
                "id": $(this).data('id')
            };
            var UrlValue = $(this).data('url');
            var btn = $(this);

            Swal.fire({
                title: 'Are you sure you want to delete this?',
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: false,
                confirmButtonText: 'Yes',
                denyButtonText: 'No',
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.isConfirmed) {
                    $.ajax({
                        url: UrlValue,
                        method: 'post',
                        data: {
                            "_token": $('meta[name="csrf-token"]').attr('content'),
                            "id": $(this).data('id')
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        beforeSend: function(xhr) {
                            // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                        },
                        success: function(response) {
                            if (response.success) {
                                var ErroMsg = $(this).printErrorMsg(response
                                    .message);

                                $(this).Toastshow('success', ErroMsg);

                                var page = $('.pager').find('.active a').attr(
                                    'href') == undefined ? 1 : $('.pager').find(
                                    '.active a').attr('href').split('page=')[1];
                                var column_name = $('.sorting').val() ? $(
                                    '.sorting').val() : '';
                                var sort_type = $('#hidden_sort_type').val();
                                var query = $('#search').val() ? $('#search')
                                .val() : '';

                                fetch_data(page, sort_type, column_name, query);
                            } else {
                                var ErroMsg = $(this).printErrorMsg(response
                                    .message);
                                $(this).Toastshow('error', ErroMsg);
                            }
                        },
                        error: function(data) {
                            console.log("error ", data);
                        }
                    });
                }
            });
        });

        $(document).on('change', '[name="patient_type"]', function() {
            var query       = $('#search').val();
            var column_name = $('.sorting').val();
            var sort_type   = $('#hidden_sort_type').val();
            var page        = 1 ? 1 : (this).attr('href').split('page=')[1];
            fetch_data(page, sort_type, column_name, query);
        });
    });


    $(document).on('click', '#createBed', function(){
        var admissionNo     = $(this).data('admission-no');
        var patientDetails  = $(this).data('patient-details');
    $('#commonModalLabel').text('Bed for ' +patientDetails +'  ('+admissionNo+')');
    // $('.save_button').html('<i class="bi bi-check-circle"></i> Confirm Bed');
    $('.save_button').hide();
        var id = $(this).data('id');
        var url = `{!! route('ipd-admissions-beds.create', ':id') !!}`.replace(':id', id);
    $.ajax({
      url:url,
      success:function(data){
        $('#commonModal').find('.modal-body').html('');
        $('#commonModal').find('.modal-body').html(data);
        $('#check_in_date_time').datetimepicker({
          format:'d/m/Y H:i A',
        });
        $('#check_out_date_time').datetimepicker({
          format:'d/m/Y H:i A',
        });
      }
    });
  });


 

</script>


<script>
    $(document).ready(function() {
        $(document).on('click', '.select-bed', function() {
            var old_selected = $('.select-bed');
            old_selected.removeClass('text-white');
            old_selected.addClass('btn-outline-success');
            old_selected.removeClass('btn-success');

            $('.save_and_confirm').removeClass('disabled');

            var bedName = $(this).data('bed-name');

            $('#bed_name').html(bedName);

            var bed = $(this).data('id');
            $('[name="bed_id"]').val(bed);
            $(this).addClass('btn-success');
            $(this).addClass('text-white');
            $(this).removeClass('btn-outline-success');
        });
    });


    $(document).on('click', '.save_and_confirm', function(event) {
        var error = 0;
        if ($('#commonModal').find('form').hasClass('bed')) {
            $('.error_bed_no_id').hide();

            if ($('[name="bed_id"]').val() == '') {
                toastr.error('Please select a bed first!', 'Error!');
                error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('#commonModal').find('form')[0]);

                var url = "{!! route('ipd-admissions-beds.create-step-2', ':id') !!}";
                var id  = $('#commonModal').find('form').data('id');
                url     = url.replace(':id',id);

                $.ajax({
                        url: url,
                        data: formdata,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            $('.save_button').show();
                            $('#commonModalLabel').text('Assign Bed');
                            $('.save_button').html('<i class="bx bx-save"></i> <span class="save_button_span">Save Bed</span>');
                            $('#commonModal').find('.modal-body').html('');
                            $('#commonModal').find('.modal-body').html(response);
                            $('#check_in_date_time').datetimepicker({
                                format: 'd/m/Y H:i A',
                            });
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
            }
        }
    })


    $(document).on('click', '.save_button', function(event) {
        event.preventDefault();

        var error = 0;

        if ($('#commonModal').find('form').hasClass('bed')) {
            $('.error_bed_no_id').hide();

            if ($('[name="bed_id"]').val() == '') {
                toastr.error('Please select a bed first!', 'Error!');
                error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('#commonModal').find('form')[0]);

                var url = "{!! route('ipd-admissions-beds.create-step-2', ':id') !!}";
                var id  = $('#commonModal').find('form').data('id');
                url     = url.replace(':id',id);

                $.ajax({
                    url: url,
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function(response) {
                        $('#commonModalLabel').text('Assign Bed');
                        $('.save_button').html('<i class="bx bx-save"></i> <span class="save_button_span">Save Bed</span>');
                        $('#commonModal').find('.modal-body').html('');
                        $('#commonModal').find('.modal-body').html(response);
                        $('#check_in_date_time').datetimepicker({
                            format: 'd/m/Y H:i A',
                        });
                    }
                })
                .fail(function(jqXHR, textStatus, errorThrown) {
                    console.log('AJAX request failed:', textStatus, errorThrown);
                    toastr.error('An error occurred during the request.', 'Error!');
                });
            }
        } else if ($('#commonModal').find('form').hasClass('store-bed')) {
            if ($('[name="bed_no_id"]').val() == '') {
                toastr.error('Please select a bed first!', 'Error!');
                error = 1;
            }

            if (error == 0) {
                let formdata = new FormData($('#add_bed')[0]);

                $.ajax({
                        url: $('#add_bed').attr('action'),
                        data: formdata,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            if (response.success === true) {
                                toastr.success(response.message, 'Success.');

                                // hide modal
                                $('#commonModal').modal('hide');
                                $('#commonModal').find('.modal-body').html('');

                                window.location.reload();
                            } else {
                                toastr.error(response.message, 'Error!');
                            }
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
            }
        }
    })
</script>

<script>
    $(document).ready(function() {
        $('tr[data-bs-toggle="collapse"]').click(function() {
            var target = $(this).data('bs-target');
            var icon = $(this).find('i.bi');
            
            $(target).on('shown.bs.collapse', function () {
                icon.removeClass('bi-arrow-down-short').addClass('bi-arrow-up-short');
            });

            $(target).on('hidden.bs.collapse', function () {
                icon.removeClass('bi-arrow-up-short').addClass('bi-arrow-down-short');
            });
        });
    });
</script>
@endsection
