@extends('layouts.app')
@section('title','Journal 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">
<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 d-flex align-items-center mb-3 px-3 px-md-0">
    <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> Journal 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 Journal Entry</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('journal-voucher.index')}}" 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_journal_voucher_form" action="{{ route('add-journal-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">Date <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group autocomplete">
                                            <input type="" name="transaction_date" id="transaction_date" class="doctor-select form-control" id="transaction_date" readonly style="cursor: pointer"  placeholder="Date" value="">
                                        </div>
                                        <span class="text-danger error_transaction_date" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-4">
                                        <div>
                                            <label class="form-label">#Voucher No / Reference No</label>
                                        </div>
                                        <div class="input-group autocomplete">
                                            <input type="text" name="voucher_no" id="voucher_no" class="patient-select form-control" placeholder="Search Voucher No">
                                            <ul class="searchResult"></ul>
                                        </div>
                                        <span class="text-danger error_voucher_no" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-4">
                                        <div>
                                            <label class="form-label">Financial Year<span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group autocomplete">
                                            <select class="form-control br-0" id="financial_year_id" name="financial_year_id" required>
                                                @foreach($financialYears as $list)
                                                <option value="{{ $list->financialyearid}}" {!! $list->is_default == 1 ? 'selected' : '' !!} title="{{$list->financial_year_name}}">{{$list->financial_year_name}}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <span class="text-danger error_financial_year_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 class="input-group-append" style="margin: auto 10px auto 0;">
                                        <button class="btn btn-secondary add_btn" id="create_account" type="button" data-bs-toggle="modal" data-bs-target="#commonModal">+</button>
                                        <button class="btn btn-primary edit_btn" style="height: 40px;" id="edit_customer" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"><i class="bi bi-pencil-square"></i></button>
                                    </div>

                                </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="input-group">
                                        <label for="debit" class="form-label">Debit Amount</label>
                                        <input type="number" name="debit" class="form-control br-0 amount" value="" placeholder="Enter Debit Amount">
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="input-group">
                                        <label for="credit" class="form-label">Credit Amount</label>
                                        <input type="number" name="credit" class="form-control br-0 amount" value="" placeholder="Enter Credit Amount">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="input-group autocomplete">
                                        <label class="form-label">Narration</label>
                                        <input type="text" name="details_narration" id="details_narration" class="form-control" placeholder="Write Narration">
                                    </div>
                                    <span class="text-danger error_details_narration" style="display:none;">This field is required.</span>
                                </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>
                                </div>
                                    <span class="text-danger error_duplicate_voucher_no" style="display:none;">This Item is Already Added to Cart.</span>
                                    <span class="text-danger error_account_id" style="display:none;">This field is required.</span>
                                    <span class="text-danger error_credit" style="display:none;">Please enter Debit or credit amount. Both inputs can not be empty.</span>
                            </div>
                      </div>
                    </form>
                            <div class="cart_products">
                            </div>

                            <div class="card style_table">
                              <div class="row align-items-end gx-0 mt-4 mb-3">
                                        <div class="col-md-12 px-3">
                                            <div>
                                            <label class="form-label">Note / Description </label>
                                        </div>
                                        <div class="input-group">
                                            <textarea class="form-textarea" name="description" id="description" rows="3"></textarea>
                                        </div>
                                        <span class="text-danger error_description" style="display:none;">This field is required.</span>
                                    </div>
                                    <div class="col-12 mt-4" align="center">
                                        <div class="d-grid gap-2" style="width: 20%">
                                          <button class="btn btn-md btn-primary save_button" type="button"><i class="bx bx-save"></i> Save Journal 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 type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>

<script>
    $(document).ready(function(){
        // Disable the edit_customer button initially
        $('#edit_customer').prop('disabled', true);

        // Add input event listener to check the input field and enable/disable the button
        $('#account_id').on('input', function() {
            var customerName = $(this).val();
            var editCustomerBtn = $('#edit_customer');

            if (customerName.trim() === "") {
                // If the input is empty, disable the button
                editCustomerBtn.prop('disabled', true);
            } else {
                // If the input is not empty, enable the button
                editCustomerBtn.prop('disabled', false);
            }
        });

        fetch_cart();
    });

    $('#transaction_date').datepicker({
        format: "{!! $companyDateFormate??'dd-mm-yyyy' !!}",
        autoclose: true,
        //startDate: financialYearDates.fromDate,//optional
        //endDate: financialYearDates.toDate//optional
        }).datepicker("setDate", new Date());

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

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

        e.preventDefault();
        if ($('#commonModal').find('form').hasClass('create_customer')) {
            if ($('#phone_no').val().trim() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }

            if ($('#whatsapp_no').val().trim() != '') {
                var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
            }

            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_phone').hide();
            $('.error_country_id').hide();
            var error = 0;

            if ($('input[name="name"]').val().trim() == '' || $('[name="account_title_id"]').val() == '') {
              $('.error_name').show();
              error = 1;
              setTimeout(function () {
                $('.error_name').hide();
                }, 3000);

            }

            if ($('[name="country_id"]').val().trim() == '') {
              $('.error_country_id').show();
              error = 1;
              setTimeout(function () {
                $('.error_country_id').hide();
                }, 3000);

            }

            if ($('input[name="phone_no"]').val().trim() == '') {
              $('.error_phone').show();
              error = 1;
              setTimeout(function () {
                $('.error_phone').hide();
                }, 3000);

            }

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

                $.ajax({
                    url: $('#create_customer_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="account_id"]').val(response.data.id);
                            $('#account_id').val(response.data.name);

                            $('#edit_customer').prop('disabled', false);

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } 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!');
                });
            }
        } else if ($('#commonModal').find('form').hasClass('edit_customer')) {
            if ($('#phone_no').val().trim() != '') {
                var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
            }

            if ($('#whatsapp_no').val().trim() != '') {
                var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
                var dailcode_array = dailcode_title.split("+");
                $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
            }

            $('.error_name').hide();
            $('.error_email').hide();
            $('.error_phone').hide();
            $('.error_country_id').hide();
            $('.error_date_of_birth').hide();
            var error = 0;

            if ($('input[name="name"]').val().trim() == '' || $('[name="account_title_id"]').val() == '') {
              $('.error_name').show();
              error = 1;
              setTimeout(function () {
                $('.error_name').hide();
                }, 3000);

            }

            if ($('[name="country_id"]').val().trim() == '') {
              $('.error_country_id').show();
              error = 1;
              setTimeout(function () {
                $('.error_country_id').hide();
                }, 3000);

            }

            if ($('input[name="phone_no"]').val().trim() == '') {
              $('.error_phone').show();
              error = 1;
              setTimeout(function () {
                $('.error_phone').hide();
                }, 3000);

            }

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

                $.ajax({
                    url: $('#edit_customer_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="account_id"]').val(response.data.id);
                            $('#account_id').val(response.data.name);
                            $('#edit_customer').prop('disabled', false);

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        } 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!');
                });
            }
        } else {
                //  ;
            $('.error_financial_year_id').hide();
            $('.error_transaction_date').hide();
            var error = 0;
                //  ;

            if ($('[name="financial_year_id"]').val() == null || $('[name="financial_year_id"]').val() == '') {
              $('.error_financial_year_id').show();
              error = 1;
            } else if (validateDate()) {
              toastr.error('Selected date must be in between Financial Years!', 'Error.');
              error = 1;
            }

            if ($('input[name="transaction_date"]').val().trim() == '') {
                $('.error_transaction_date').show();
                error = 1;
                setTimeout(function () {
                    $('.error_transaction_date').hide();
                }, 3000);
            }
            if (parseInt($('#totalDebit').text().trim().replace ( /[^\d.]/g, '' )) != parseInt($('#totalCredit').text().trim().replace ( /[^\d.]/g, '' ))) {
                toastr.error('Total debit and credit column amount must be equal. And can not be zero', 'Error.');
                error = 1;
            }

            if (validateDate()) {
              toastr.error('Selected date must be in between Financial Years!', 'Error.');
              error = 1;
            }
               //  ;

            if (error == 0) {

               //  ;

                let formdata = new FormData();
                formdata.append( 'transaction_date', $('#transaction_date').val());
                formdata.append( 'voucher_no', $('#voucher_no').val());
                formdata.append( 'description', $('#description').val());
                formdata.append( 'financial_year_id', $('#financial_year_id').val());
                $.ajax({
                    url: "{!! route('journal-voucher-submit') !!}",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function (response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            //  ;
                            $('#transaction_date').val('');
                            $('#voucher_no').val('');
                            $('#description').val('');
                            $('#financial_year_id').val('');

                            //  ;

                            setTimeout(function() {
                                window.location.href = "{!! route('journal-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_voucher_no').hide();
        $('.error_transaction_date').hide();
        $('.error_account_id').hide();
        //$('.error_description').hide();
        //$('.error_details_narration').hide();
        $('.error_duplicate_voucher_no').hide();
        $('.error_credit').hide();
        var error = 0;

        /*
        if ($('input[name="voucher_no"]').val().trim() == '') {
          $('.error_voucher_no').show();
          error = 1;
        }
        */

        if (($('[name="debit"]').val() == '' || $('[name="debit"]').val() < 1) && ($('[name="credit"]').val() == '' || $('[name="credit"]').val() < 1)) {
          $('.error_credit').show();
          error = 1;
          setTimeout(function () {
            $('.error_credit').hide();
            }, 3000);
        }

        if ($('[name="transaction_date"]').val().trim() == '' || $('[name="transaction_date"]').val() == undefined) {
          $('.error_transaction_date').show();
          error = 1;
          setTimeout(function () {
            $('.error_transaction_date').hide();
            }, 3000);
        }
        if ($('[name="account_id"]').val() == '' || $('[name="account_id"]').val() == undefined) {
          $('.error_account_id').show();
          error = 1;
          setTimeout(function () {
            $('.error_account_id').hide();
            }, 3000);
        }
        /*
        if ($('#description').val() == '' || $('#description').val() == undefined) {
          $('.error_description').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('voucher_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="debit"]').val('');
                        $('[name="credit"]').val('');
                        $('[name="account_id"]').val('');
                        $('[name="debit"]').attr('disabled',false);
                        $('[name="credit"]').attr('disabled',false);
                        $('#account_id').focus();
                    } 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;
    })

    var telInput = $('#phone_no , #whatsapp_no , #alternative_no');
    telInput.intlTelInput({
        utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js', // Update the URL to the correct one
        initialCountry: '{!! $countryCode  !!}', // Set the new country code
        separateDialCode: true
    });

    $(document).on('input','.amount', function(e) {
        e.preventDefault();
        if(e.target.name=='debit'){
            $('[name="debit"]').val($.trim(this.value));
            $('[name="credit"]').val();
        }else{
            $('[name="credit"]').val($.trim(this.value));
            $('[name="debit"]').val();
        }
    });

    $(document).on('input','[name="debit"]', function(e) {
        e.preventDefault();
        if($.trim(this.value) > 0){
            $('[name="credit"]').val('0');
        }else{
            $('[name="debit"]').val('0');
            $('[name="credit"]').val('0');
        }

        if($.trim(this.value) < 0) {
            $('[name="credit"]').val('0');
        }
    });

    $(document).on('input','[name="credit"]', function(e) {
        e.preventDefault();
        if($.trim(this.value) > 0){
            $('[name="debit"]').val('0');
        } else {
            $('[name="debit"]').val('0');
            $('[name="debit"]').val('0');
        }

        if($.trim(this.value) < 0) {
            $('[name="credit"]').val('0');
        }
    });

    $(document).ready(function(){

        $('.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('journal-voucher-search-accounts') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'get_accounts_for_journal_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 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('voucher_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('voucher_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('voucher_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('change', '.voucher-entries [name="details_narration[]"]', function(){
        var id = $(this).data('id');

        $.ajax({
          url     : '{!! route("journal-voucher-entry-update") !!}',
          method  : 'post',
          data    : {
                "_token"            : $('meta[name ="csrf-token"]').attr('content'),
                "id"                : id,
                "details_narration" : $(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('change', '.voucher-entries [name="debit[]"]', function(){
        var id = $(this).data('id');

        $.ajax({
          url     : '{!! route("journal-voucher-entry-update") !!}',
          method  : 'post',
          data    : {
                "_token" : $('meta[name ="csrf-token"]').attr('content'),
                "id"     : id,
                "debit"  : $(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('change', '.voucher-entries [name="credit[]"]', function(){
        var id = $(this).data('id');

        $.ajax({
          url     : '{!! route("journal-voucher-entry-update") !!}',
          method  : 'post',
          data    : {
                "_token" : $('meta[name ="csrf-token"]').attr('content'),
                "id"     : id,
                "credit" : $(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;
        }
    };


    function validateDate() {
        //debugger;
        // Your date input field ID
        var dateInput = $("#transaction_date").val();
       
        var selectedDate = parseDateString(dateInput);
       
        var selectedOption = $("#financial_year_id option:selected");

        // Get the title attribute of the selected option
        var selectedTitle = selectedOption.attr("title");
        var dateParts = selectedTitle.split('-');

        // Extract individual values
        var startYear = dateParts[0];
        var endYear = dateParts[1];

        // Get the selected date from the input field
       //var selectedDate = new Date(dateInput.val());

        if (selectedDate >= new Date(startYear, 0, 1) && selectedDate <= new Date(endYear, 11, 31)) {
            return false;
        } else {
            return true;
        }
    };

    function parseDateString(dateString) {
    const formats = [
        'MM/DD/YYYY',
        'MM-DD-YYYY',
        'YYYY/MM/DD',
        'YYYY-MM-DD',
        'DD/MM/YYYY',
        'DD-MM-YYYY',
        'dd/mm/YYYY'
        // Add more formats as needed
    ];

    for (const fmt of formats) {
        const date = moment(dateString, fmt, true); // The `true` flag is for strict parsing
        if (date.isValid()) {
            return date.toDate(); // Convert moment object to JavaScript Date object
        }
    }

    console.error("Invalid date format");
    return null;
}

    /*************** Create Customer **************/
    $(document).on('click', '#create_account', function(){
        $('#commonModalLabel').text('New Party');
        $('.save_button_span').text('Save Party');
        $.ajax({
          url:"{!! route('party-account-create') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);

          }
        })
    })

    // Click event for the disabled edit_customer button
    $('#edit_customer').on('click', function() {
        var customerName = $('[name="account_id"]').val();

        if (customerName.trim() === "") {
            $('.error_account_id').show();

            setTimeout(function () {
                $('.error_account_id').hide();
            }, 3000);
        } else {
            $('.error_account_id').hide();

            $('#commonModalLabel').text('Edit Party');
            $('.save_button_span').text('Update Party');
            var id = $('[name="account_id"]').val();
            var url = `{!! route('party-account-edit', ':id') !!}`.replace(':id', id);

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

    var telInput = $('#phone_no , #whatsapp_no , #alternative_no');
    telInput.intlTelInput({
        utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js', // Update the URL to the correct one
        initialCountry: '{!! $countryCode  !!}', // Set the new country code
        separateDialCode: true
    });
</script>
@endsection
