@extends('layouts.app')
@section('title','Receipt Vouchers')
@section('pages')
<style type="text/css">
    .clear{
    clear:both;
    margin-top: 20px;
}

.autocomplete{
    position: relative;
}
.autocomplete .searchResult{
    list-style: none;
    padding: 0px;
    width: 78%;
    position: absolute;
    margin: 0;
    margin-top: 40px;
    background: white;
    z-index: 5;
}

.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_reference i {
    height: 20px;
    width: 20px;
    background: #0d6efd25;
    color: #0d6efd;
    text-align: center;
    border-radius: 50px;
    line-height: 20px;
}

.add_btn {
    height: 40px;
    width: 40px;
    font-size:16px;
    border-radius: 0 3.5px 3.5px 0;
    padding: 0;
}
    .custom_grid {
        padding-left:1rem;
        padding-right:1rem;
    }
    .custom_grid .input-group {
        position:relative;
    }
    .custom_grid .input-group .form-label {
        position:absolute;
        top:-10px;
        left:5px;
        font-size:12px;
        padding:0px 8px;
        background-color:#f7f8fa;
        z-index:5;
    }
    .custom_grid .input-group .form-control.br-0 {
        border-radius:0;
    }
    .custom_grid .btn {
        font-size:22px;
        padding: 0.15rem 0.75rem;
        border-top-left-radius:0px;
        border-bottom-left-radius:0px;
    }
    .select2-container--bootstrap4 .select2-selection {
        border-top-right-radius:0px;
        border-bottom-right-radius:0px;
    }
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">

<!--breadcrumb-->
<div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
    <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> Receipt Vouchers</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">

                <li class="breadcrumb-item active" aria-current="page">New Receipt Voucher Entry</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="javascript:history.back()" class="btn btn-info"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
        </div>
    </div>
</div>
<!--end breadcrumb-->

<div class="row auto">
    <div class="col-xl-12 mx-auto">


                    <form class="auto-width create_billing" id="create_receipt_voucher_form" action="{{ route('add-receipt-vouchers')}}" method="post" enctype='multipart/form-data'>
                        <!-- For validation comment on -->
                        <!-- <form class="row g-3 was-validated"> -->
                        @csrf

                            <div class="card style_table">
                                <div class="card-body pt-2 ps-3" style="border-radius:0px;">
                                    <div class="row align-items-center">
                                    <div class="col-md-4">
                                        <div>
                                            <label class="form-label">Receipt Date <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group autocomplete">
                                            <input type="date" name="receipt_date" id="receipt_date" class="doctor-select form-control" placeholder="Date" value="{{ date('Y-m-d') }}">
                                        </div>
                                        <span class="text-danger error_receipt_date" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-4">
                                        <div>
                                            <label class="form-label">#Receipt No</label>
                                        </div>
                                        <div class="input-group autocomplete">
                                            <input type="text" name="receipt_no" id="receipt_no" class="patient-select form-control" placeholder="Search Voucher No">
                                            <ul class="searchResult"></ul>
                                        </div>
                                        <span class="text-danger error_receipt_no" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-4">
                                        <div>
                                            <label class="form-label">Receipt At<span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group autocomplete">
                                            <input type="text" name="receipt_at" id="receipt_at_id" class="receipt-at-select form-control" placeholder="Search Cash/Bank account">
                                            <ul class="searchResult"></ul>
                                            <input type="hidden" name="receipt_at_id" value="">
                                        </div>
                                        <span class="text-danger error_receipt_at_id" style="display:none;">This field is required.</span>
                                    </div>
                                </div>
                                </div>
                                    <div class="row custom_grid align-items-end gx-0 mt-4 mb-3">
                                        <div class="col-md-3">
                                            <div>
                                            <label class="form-label">Accounts <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group autocomplete">
                                            <input type="text" name="account_name" id="account_id" class="accounts-select form-control" placeholder="Search Account">
                                            <ul class="searchResult"></ul>
                                            <input type="hidden" name="account_id" value="">
                                        </div>
                                        <span class="text-danger error_account_id" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="input-group">
                                            <label for="amount" class="form-label">Amount</label>
                                            <input type="number" name="amount" class="form-control br-0 amount" value="" placeholder="Enter Amount">
                                        </div>
                                    </div>
                                    <div class="col-md-2">
                                          <button class="btn btn-primary add_to_cart w-100" type="button"><i class="bx bx-plus"></i></button>
                                    <span class="text-danger error_duplicate_receipt_no" style="display:none;">This Item is Already Added to Cart.</span>
                                    </div>
                              </div>
                          </div>
                    </form>
                            <div class="cart_products">
                            </div>

                            <div class="card style_table">
                              <div class="row custom_grid align-items-end gx-0 mt-4 mb-3">
                                        <div class="col-md-12">
                                            <div>
                                            <label class="form-label">Note / Description <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <textarea class="form-textarea" name="remarks" id="remarks" rows="3"></textarea>
                                        </div>
                                        <span class="text-danger error_remarks" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-12 mt-4" align="center">
                                        <div class="d-grid gap-2 w-50">
                                          <button class="btn btn-md btn-primary save_button" type="button"><i class="bx bx-save"></i> Save Receipt Vouchers</button>
                                      </div>
                                    </div>
                              </div>
                          </div>

                </div>
            </div>
<!--end row-->

@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>
    $(document).ready(function(){
        fetch_cart();
    });

    function fetch_cart(){
         ;
      $.ajax({
        url:"{!! route('receipt-voucher-entries') !!}",
        success:function(data){
            $('.cart_products').html('');
            $('.cart_products').html(data);
        }
      })
    }



    $(document).on('click','.save_button', function(e) {

        e.preventDefault();

                 ;
            $('.error_receipt_at_id').hide();
            $('.error_receipt_date').hide();
            var error = 0;
                 ;

            if ($('[name="receipt_at_id"]').val().trim() == '') {
              $('.error_receipt_at_id').show();
              error = 1;
            }
            if ($('input[name="receipt_date"]').val().trim() == '') {
              $('.error_receipt_date').show();
              error = 1;
            }
             ;

            if (error == 0) {

                ;

                let formdata = new FormData();
                formdata.append( 'receipt_date', $('#receipt_date').val());
                formdata.append( 'receipt_no', $('#receipt_no').val());
                formdata.append( 'remarks', $('#remarks').val());
                formdata.append( 'account_id', $('input[name="receipt_at_id"]').val());
                formdata.append( 'total_amount', parseInt($('#totalAmount').text().trim().replace ( /[^\d.]/g, '' )));
                $.ajax({
                    url: "{!! route('receipt-voucher-submit') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                             ;
                            $('#receipt_date').val('');
                            $('#receipt_no').val('');
                            $('#remarks').val('');
                            $('#receipt_at_id').val('');
                            $('input[name="receipt_at_id"]').val('');

                             ;

                            setTimeout(function() {
                                window.location.href = "{!! route('receipt-voucher.index') !!}";
                            }, 1000);


                            return false;
                        } 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!');
                });
            }
        });


    $(document).on('click','.add_to_cart', function(e) {
        e.preventDefault();

        //$('.error_receipt_no').hide();
        $('.error_receipt_date').hide();
        $('.error_account_id').hide();
        //$('.error_remarks').hide();
        //$('.error_details_narration').hide();
        $('.error_duplicate_receipt_no').hide();
        var error = 0;
        /*
        if ($('input[name="receipt_no"]').val().trim() == '') {
          $('.error_receipt_no').show();
          error = 1;
        }
        */
        if ($('[name="receipt_date"]').val().trim() == '' || $('[name="receipt_date"]').val() == undefined) {
          $('.error_receipt_date').show();
          error = 1;
        }
        if ($('[name="account_id"]').val() == '' || $('[name="account_id"]').val() == undefined) {
          $('.error_account_id').show();
          error = 1;
        }
        /*
        if ($('#remarks').val() == '' || $('#remarks').val() == undefined) {
          $('.error_remarks').show();
          error = 1;
        }
        */
        /*if ($('[name="details_narration"]').val() == '' || $('[name="details_narration"]').val() == undefined) {
          $('.error_details_narration').show();
          error = 1;
        }*/
        /*var productIds = $('.cart-products').map(function() {
            return $(this).data('receipt_no').toString();
        }).get();
        */
        if (error == 0) {
            let formdata = new FormData($('.create_billing')[0]);

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

                        $('#details_narration').val('');
                        $('#account_id').val('');
                        $('[name="amount"]').val('');
                        $('[name="credit"]').val('');
                        $('[name="account_id"]').val('');

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

        error = 1;
    })

    $(document).ready(function(){

        $('.receipt-at-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="receipt_at_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('receipt-voucher-search-accounts') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'get_accounts_for_receipt_voucher',
                        search_text: request.term
                    },
                    success: function(json) {
                         ;
                        if (json.error) {
                            $('[name="receipt_at_id"]').val('');
                            return false;
                        }
                         ;
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                 ;
                event.preventDefault();
                $(this).val(ui.item.name + "");
                $('[name="receipt_at_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
             ;
            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };

        $('.accounts-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="account_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('receipt-voucher-search-accounts') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'get_accounts_for_receipt_voucher',
                        search_text: request.term
                    },
                    success: function(json) {
                         ;
                        if (json.error) {
                            $('[name="account_id"]').val('');
                            return false;
                        }
                         ;
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                 ;
                event.preventDefault();
                $(this).val(ui.item.name + "");
                $('[name="account_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
             ;
            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };

    });

    const patientSelect = document.querySelector(".accounts-select");
    const ReceiptAtSelect = document.querySelector(".receipt-at-select");
    const querySelector = document.querySelector(".searchResult");

    document.addEventListener("click", (event) => {
        if (event.target !== patientSelect && event.target !== querySelector) {
            $(".searchResult").empty();
        }
    });

    $(document).on('click', '#create_patient', function(){
        $('#commonModalLabel').text('Add New Patient');
        $('.save_button_span').text('Save Patient');
        $.ajax({
          url:"{!! route('patient-account-create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            reinitializeTelInput();
            $('[name="date_of_birth"]').datepicker('destroy');

            $('[name="date_of_birth"]').datepicker({
                "dateFormat" : "dd-mm-yy",
                "maxDate": '0',
                "changeMonth": true,
                "changeYear": true
            }).datepicker("setDate",'now')
            .on('changeDate', function (ev) {
                 $(this).datepicker('hide');
            })
            .on('focusout', function (ev) {
                 $(this).datepicker('hide');
            });
          }
        })
    })

    $(document).on('click', '#create_doctor', function(){
        $('#commonModalLabel').text('Add New Doctor');
        $('.save_button_span').text('Save Doctor');
        $.ajax({
          url:"{!! route('doctor-account-create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            reinitializeTelInput();
            $('[name="date_of_birth"]').datepicker('destroy');

            $('[name="date_of_birth"]').datepicker({
                "dateFormat" : "dd-mm-yy",
                "maxDate": '0',
                "changeMonth": true,
                "changeYear": true
            }).datepicker("setDate",'now')
            .on('changeDate', function (ev) {
                 $(this).datepicker('hide');
            })
            .on('focusout', function (ev) {
                 $(this).datepicker('hide');
            });
          }
        })
    })



    function reinitializeTelInput(countryCode) {
        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
        });
    }



    $(document).on('click change', '#account_id', function(){
        $('[name="search_product"]').val('');
        $('.create_billing [name="product_price"]').val('');
        $('#search_product').val('');
    })

    $(document).on('focusout', '[name="product_details"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('receipt_no'),
                "product_details": $(this).val(),
            },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    $(document).on('focusout', '[name="vial_code"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('receipt_no'),
                "vial_code": $(this).val(),
          },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    $(document).on('focusout', '.cart_products [name="product_price"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('receipt_no'),
                "product_price": $(this).val(),
          },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    $(document).on('focusout', '.cart_products [name="per_discount"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('receipt_no'),
                "per_discount": $(this).val(),
          },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    $(document).on('focusout', '.cart_products [name="flat_discount"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('receipt_no'),
                "flat_discount": $(this).val(),
          },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    $(document).on('focusout', '.cart_products [name="per_discount"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('receipt_no'),
                "per_discount": $(this).val(),
          },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    /*********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){
                         toastr.success(response.message, 'Success.');
                          fetch_cart();
                           ;
                      }else{
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error',ErroMsg);
                      }
                  },
                  error: function (data) {
                    console.log("error ",data);
                  }
              });
              }
          });
    });
    function getAge(birthdate) {
        if (birthdate != '' && birthdate != null && birthdate != undefined) {
            var birthdateObj = new Date(birthdate);
            var now = new Date();
            var age = now.getFullYear() - birthdateObj.getFullYear();

            // Adjust age if birthday hasn't occurred this year yet
            if (now.getMonth() < birthdateObj.getMonth() || (now.getMonth() === birthdateObj.getMonth() && now.getDate() < birthdateObj.getDate())) {
                age--;
            }
            return age;
        }
    };
</script>
@endsection
