@extends('layouts.app')
@section('title', ($statement_by == 'patient' ? 'Patient' : 'Item').' wise Referral Statement')
@section('pages')
<style type="text/css">
    .breadcrumb-title {
      border-right: none;
    }
</style>
<link rel="stylesheet/less" 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"> {!! $statement_by == 'patient' ? 'Patient' : 'Item' !!} Wise Referral Statement @if(!empty($agent) && isset( $agent->name )) OF Agent {!! !empty($agent) && isset( $agent->name ) ? $agent->name : '' !!} @endif
  </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="11" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
        <li class="breadcrumb-item" aria-current="page">Settings</li>
        <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i> Agent Referral list</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 align-items-end gx-0 mt-2 mb-2">
      @if(!empty($id))
        <div class="col-lg-7 col-md-7 col-7 custom_grid">
          <h5>Collection Agent {!! $agent->name !!} </h5>
          <input type="hidden" name="month_year" class="month_year" value="{!! $month !!}">
          <input type="hidden" name="agent" class="agent" value="{!! $id !!}">
        </div>
      @else
        <div class="col-lg-2 col-md-2 col-2 custom_grid">
          <div class="input-group">
            <label class="form-label">Collection Agent <span class="text-danger"><b></b></span></label>
            <select class="form-control br-0 agent" id="agent" name="agent" required>
              <option value="">Select Agent</option>
              @foreach($agent as $key => $value)
                <option value="{!! $value->id !!}">{!! $value->name !!}</option>
              @endforeach
            </select>
          </div>
        </div>
        <div class="col-lg-2 col-md-2 col-2 custom_grid">
          <div class="input-group">
            <label class="form-label">Month-Year <span class="text-danger"><b></b></span></label>
            <input type="month" name="month_year" class="month_year form-control " style="cursor: pointer;" placeholder="Month">
          </div>
        </div>
        <div class="col-lg-3 col-md-3 col-3">
            <button class="btn btn-success btn-lg search-filters w-100" type="button">Search</button>
        </div>
      @endif

      <div class="col-lg-5 col-md-5">
        <div class="ms-auto float-md-end">

          <div class="btn-group">
              <a href="{!! route('agent-referral-list') !!}" class="btn btn-outline-secondary me-1"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
          </div>
        </div>
      </div>
    </div>
  </div>

   <div class="card-body" id="print_div">
      <div id="tables">
        @include('referral-vouchers.print.agent-table')
      </div>
    <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 class="row btns">
    <div class="col-md-6" style="text-align: right;">
        <button id="btn_print" type="button" class="btn btn-primary btn-lg"><i class="bi bi-printer text-white"></i> Print Statement </button>
    </div>
    <div class="col-md-6" style="text-align: left;">
        <button id="export" type="button" class="btn btn-primary btn-lg"><i class="bi bi-download text-white"></i> Export </button>
    </div>
  </div>
@endsection
@section('js')
  <script>
    $(document).ready(function() {
        $(document).on('click', '#btn_print', function(event) {
            event.preventDefault();
            $('#btn_back').hide();
            printInvoice();
            return;
        });
        $(document).on('click', '#export', function(event) {
            event.preventDefault();
            var month_year = $('.month_year').val();
            var agent     = $('.agent').val();

            if(month_year != '') {
              var url = "{!! route('export-referral-agent-statement') !!}?month_year="+ month_year + "&agent="+agent + "&statement_by={!! $statement_by !!}";
              window.location.href = url;
            } else {
              toastr.error('Month and Year fields are required!');
            }
        });
        $(document).on('change', '#statement_by', function(event) {
            event.preventDefault();
            $('#typeForm').submit();
            return;
        });

    });

    function printInvoice() {
        let printDiv = $('#print_div').html();
        let content = window.open('', '', 'height=750px,width=960px');
        let doc = content.document;
        let head = doc.head;
        let body = doc.body;

        @if(!empty($id))
          $(head).append('<Title>Agent. {!! $agent->name !!} {!! $month !!}</Title>');
        @else
          $(head).append('<Title>Agent Referral Voucher</Title>');
        @endif

        $(head).append('<link rel="stylesheet" href="{{ asset('admin/css/bootstrap.min.css') }}" type="text/css">');
        $(head).append('<link rel="stylesheet" href="{{ asset('admin/css/print.css') }}" type="text/css">');
        $(head).append('<style>@page {size: auto;}</style>');
        $(body).append(printDiv);

        setTimeout(function() {
            content.print();
        }, 500);
    }

  </script>
  <script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
  <script>
      $( function() {
        $('.datepickers').datepicker();
      });
     /***************** 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 month_year = $('.month_year').val();
          var collection = $('.collection').val();
          var agent     = $('.agent').val();

          if (month_year != '') {
            $.ajax({
              url:"?page="+page+"&sortby="+sort_by+"&sorttype="+sort_type+"&query="+query+"&month_year="+month_year+"&collection="+collection+"&agent="+agent,
              success:function(data){
                $('#tables').html('');
                $('#tables').html(data);
                $(document).ready(function(){$.switcher();});
              }
            })
          } else {
            toastr.error('Month and Year field are required!');
          }
        }

          /******** Change Like below ********/
        $(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();
          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():'';
          fetch_data(page, reverse_order, column_name, query);
        });
        $('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():'';
          $('li').removeClass('active');
          $(this).parent().addClass('active');
          fetch_data(page, sort_type, column_name, query);
        });

        $('body').on('click', '.search-filters', function(event){

          var month_year = $('.month_year').val();
          var collection   = $('.collection').val();

          if(month_year != '') {
            var page        = $('#hidden_page').val();
            var column_name = $('.sorting').val();
            var sort_type   = $('#hidden_sort_type').val();
            var query       = $('#search').val()?$('#search').val():'';

            fetch_data(page, sort_type, column_name, query);
          } else {
            toastr.error('Month and Year field are required!');
          }
        });
        $(document).on('click', '.store-incentive', function(event){

          var month_year = $('.month_year').val();
          var division   = $('[name="division"]').val();
          var agent   = $('.agent').val();

          if(month_year == '') {
            toastr.error('Month and Year field are required!');
          } else {
            $.ajax({
              url: '{{ route("referral-vouchers.store") }}',
                type: 'POST',
                dataType: 'JSON',
                data: {
                    "_token"     : $('meta[name="csrf-token"]').attr('content'),
                    "month_year" : month_year,
                    "division"   : division,
                    "agent"     : agent
                },
                success: function(json) {
                    toastr.success('Referral Voucher generated successfully.');
                }
            });
          }
        });
      });
  </script>
@endsection
