@extends('layouts.app')

@section('title', 'Death Register')

@section('pages')

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

    tr td {
        vertical-align: middle !important; 
    }
     .autocomplete{
        position: relative;
    }
    .autocomplete .searchResult{
        list-style: none;
        padding: 0px;
        width: 78%;
        position: absolute;
        margin: 0;
        margin-top: 40px;
        background: white;
        z-index: 15005;
    }

    .autocomplete .searchResult li{
        background: #F2F3F4;
        padding: 10px;
        margin-bottom: 1px;
        white-space: break-spaces;
    }

    .autocomplete .searchResult li:nth-child(even){
        background: #E5E7E9;
        color: black;
    }

    .autocomplete .searchResult li:hover{
        cursor: pointer;
        background: #CACFD2;
    }

    .add_btn {
        height: 40px;
        width: 40px;
        font-size:16px;
        border-radius: 0 3.5px 3.5px 0;
        padding: 0;
    }
    .select2-selection {
        height: 40px !important;
    }

    .flatpickr-calendar {
        width: 308px !important;
        font-size: 12px !important;
    }

    .ui-widget.ui-widget-content{
      z-index: 5000;
    }
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">
<!-- Include Flatpickr CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link rel="stylesheet" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css') }}" rel="stylesheet" />



<!-- 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">Death Register</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 Death Register</li>
                <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i> Death Register</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-5 col-md-5">
                <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">
                         <button class="btn btn-primary" id="create_death_register" type="button" data-bs-toggle="modal" data-bs-target="#commonModal">+ Add New Death Register</button>
                    </div>
                    <div class="btn-group">
                      <a href="{{route('death-registers-statement')}}" class="btn btn-secondary"><i class="bi bi-receipt"></i> Death Register Statement</a>
                    </div>
                </div>
            </div>

            
        </div>
    </div>
    <div class="card-body" id="tables">
        @include('death-registers.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>
</div>

@endsection
@section('js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js') }}"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>




<script>

    $(document).on('click', '#bodyVitals', function(){
        if ($('#bodyVitals').hasClass('hiddenVitals')) {
            $('.body_vitals_details').show();
            $('#bodyVitals').html('<i class="bx bx-minus"></i> Hide Vitals');
            $('#bodyVitals').removeClass('hiddenVitals');
        } else {
            $('.body_vitals_details').hide();
            $('#bodyVitals').html('<i class="bx bx-plus"></i> Add Vitals');
            $('#bodyVitals').addClass('hiddenVitals');
        }
    });

    function reinitializeTelInput(countryCode) {
        if ($('#relation_phone').length > 0) {
            var telInput = $('#commonModal').find('#phone_no , #whatsapp_no , #alternative_no, #relation_phone');
        } else {
            var telInput = $('#commonModal').find('#phone_no , #whatsapp_no , #alternative_no');
        }

        telInput.intlTelInput('destroy'); // Destroy the existing instances

        telInput.intlTelInput({
            utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/utils.js",
            initialCountry: countryCode || '{!! $countryCode ?? '' !!}',
            separateDialCode: true
        });
    }

    /*********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('patient_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){
                          $(this).Toastshow('success',response.message);

                       // Refreshing data after deletion
                          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 {
                          // Handle failure case
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error', ErroMsg);
                      }
                  },
                  error: function (data) {
                    console.log("error ",data);
                  }
              });
              }
          });
    });

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

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

    function fetch_data(page, sort_type, sort_by, query, account_type, accounting_groups){
    var search_type = $('[name="search_type"]').val();

    $.ajax({
      url:"?page="+page+"&sortby="+sort_by+"&sorttype="+sort_type+"&query="+query+"&accounting_groups="+accounting_groups+"&account_type="+account_type+"&search_type="+search_type,
      success:function(data){
        $('#tables').html('');
        $('#tables').html(data);
        $(document).ready(function(){$.switcher();});
      }
    });
    }

    /******** 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];
        var account_type      = $('#account_type').val();
        var accounting_groups = $('#accounting_groups').val();

        fetch_data(page, sort_type, column_name, query,account_type,accounting_groups);
    }, 700));

    $('body').on('change', '.sorting', function(){

      var column_name = $(this).val();
      console.log('perpage',column_name);
      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():'';
      var account_type      = $('#account_type').val();
      var accounting_groups = $('#accounting_groups').val();
      fetch_data(page, reverse_order, column_name, query,account_type,accounting_groups);
    });

    $('body').on('change', '.accounting_groups', function(){

      var column_name = $('.sorting').val();
      console.log('perpage',column_name);
      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():'';
      var account_type      = $('#account_type').val();
      var accounting_groups = $('#accounting_groups').val();
      fetch_data(page, reverse_order, column_name, query,account_type,accounting_groups);
    });

    $('body').on('change', '.account_type', function(){

      var column_name = $('.sorting').val();
      console.log('perpage',column_name);
      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():'';
      var account_type      = $('#account_type').val();
      var accounting_groups = $('#accounting_groups').val();
      fetch_data(page, reverse_order, column_name, query,account_type,accounting_groups);
    });

    $('body').on('click', '.pager a', function(event){
      event.preventDefault();
      console.log('url', $(this).attr('href'));
      var page = $(this).attr('href').split('page=')[1];
      $('#hidden_page').val(page);
      var column_name       = $('.sorting').val()?$('.sorting').val():'';
      var sort_type         = $('#hidden_sort_type').val();
      var query             = $('#search').val()?$('#search').val():'';
      var account_type      = $('#account_type').val();
      var accounting_groups = $('#accounting_groups').val();
      $('li').removeClass('active');
      $(this).parent().addClass('active');
      fetch_data(page, sort_type, column_name, query,account_type,accounting_groups);
    });

    // Create Death Register
    $(document).on('click', '#create_death_register', function() {
    $('#commonModalLabel').text('New Death Register');
    $('.save_button_span').text('Save Death Register');
    $.ajax({
        url: "{{ route('death-registers-account-create') }}",
        success: function(data) {
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
        }
    })
    });


  //Create Death Register
  $(document).on('click','.save_button', function(e) {
  e.preventDefault();

  var error = 0;

  if ($('#commonModal').find('form').hasClass('create_death_register')) {
      if (error == 0) {
          let formdata = new FormData($('#create_death_register_form')[0]);
          $.ajax({
              url: $('#create_death_register_form').attr('action'),
              data: formdata,
              processData: false,
              contentType: false,
              type: 'POST',
              success: function (response) {
                  if (response.success === true) {
                      toastr.success(response.message, 'Success.');
                      // append new category to selection
                      $('[name="death_registers_id"]').val(response.data.id);
                      $('#death_registers_id').val(response.data.name);

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

                       // Refreshing data after deletion
                          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 {
                          // Handle failure case
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error', ErroMsg);
                      }

              }
          })
          .fail(function(jqXHR, textStatus, errorThrown) {
              console.log('AJAX request failed:', textStatus, errorThrown);
              toastr.error('An error occurred during the request.', 'Error!');
          });
      }
  }

  if ($('#commonModal').find('form').hasClass('edit_death_register')) {
      if (error == 0) {
          $.ajax({
              url: $('#edit_death_register_form').attr('action'),
              data: $('#edit_death_register_form').serialize(),
              // processData: false,
              // contentType: false,
              type: 'POST',
              success: function (response) {
                  if (response.success === true) {
                      toastr.success(response.message, 'Success.');
                      $('[name="death_registers_id"]').val(response.data.id);
                      $('#commonModal').modal('hide');
                      $('#commonModal').find('.modal-body').html('');
                      // Refreshing data after deletion
                          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 {
                          // Handle failure case
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error', ErroMsg);
                      }
              }
          })
          .fail(function(jqXHR, textStatus, errorThrown) {
              console.log('AJAX request failed:', textStatus, errorThrown);
              toastr.error('An error occurred during the request.', 'Error!');
          });
      }
  }
  })


  // Edit Death Register Modal 
  $(document).on('click', '#edit_death_register', function() {
    var id = $(this).data('id');
     $('#commonModalLabel').text('Edit Death Register');
        $('.save_button_span').text('Update Death Register');
        var url = `{!! route('death-registers.edit', ':id') !!}`.replace(':id', id);

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




    
</script>

@endsection