@extends('layouts.app')
@section('title','Contra Voucher')
@section('pages')

<style type="text/css">
    .breadcrumb-title {
      border-right: none;
    }
    .dataTables_filter{
        margin-bottom: 6px;
    }
</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"> Contra Voucher
    </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="42" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
          <li class="breadcrumb-item" aria-current="page">Contra Voucher</li>
            <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i>  Contra Voucher Details </li>
        </ol>
      </nav>
    </div>
  </div>
  <!--end breadcrumb-->
  <div class="card style_table shadow-none radius-5 min-height my-auto">
    <div class="card-header py-3">
      @include('layouts.partials.nav-menu')
      <div class="row gx-2">
        <div class="col-lg-12 col-md-12">
          <div class="ms-auto float-md-end">

            <div class="btn-group">
                <a href="javascript:history.back()" class="btn btn-outline-secondary me-1"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
            </div>

            <div class="btn-group">
              @if(in_array('contra-voucher-edit', $authRolePermissions))
                <a href="{{route('contra-vouchers.edit',$accountJournal->id)}}" class="btn btn-warning" data-bs-toggle="tooltip" data-bs-placement="bottom" title="Edit">
                  <i class="bi bi-pencil-square text-white"></i>
                </a>
              @endif
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="row auto">
      <div class="col-xl-12 mx-auto">
          <div class="shadow-none radius-5 min-height">
              <div class="row">
                  <div class="col-md-6">
                      <div class="card">
                          <div class="card-body g-3">
                              <div class="table-responsive">
                                  <div class="d-flex justify-content-between">
                                      <h5 class="mb-0">Contra Voucher</h5>
                                  </div>
                                  <hr class="mb-2">
                                  <table class="table table-bordered align-middle">
                                    <tr>
                                        <td style="text-align:left;">Contra Voucher No </td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Contra Voucher Transaction Date </td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Contra Voucher Reference</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Contra Voucher Financial Year</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Contra Vouchering Description</td>
                                    </tr>
                                  </table>
                              </div>
                          </div>
                      </div>
                  </div>
                  <div class="col-md-6">
                      <div class="card">
                          <div class="card-body g-3">
                              <div class="table-responsive">
                                  <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">&nbsp;</h5>
                                  </div>
                                  <hr class="mb-2">
                                  <table class="table table-bordered align-middle">
                                    <tr>
                                        <td>{{$accountJournal->voucher_no}}</td>
                                    </tr>
                                    <tr>
                                        <td>{{$accountJournal->transaction_date}}</td>
                                    </tr>
                                    <tr>
                                        <td>{{isset($accountJournal->reference)? $accountJournal->reference : ''}}</td>
                                    </tr>
                                    <tr>
                                        <td>{{$accountJournal->financialYear->financial_year_name}}</td>
                                    </tr>
                                    <tr>
                                        <td>{{$accountJournal->description}}</td>
                                    </tr>
                                  </table>
                              </div>
                          </div>
                      </div>
                  </div>
              </div>
          </div>
      </div>
      <div class="col-xl-12 mx-auto">
          <div class="shadow-none radius-5 min-height">
              <div class="row">
                  <div class="col-md-12">
                      <div class="card">
                          <div class="card-body g-3">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Contra Voucher Details <i class="bi bi-info-circle-fill text-info show-help-support" data-id="39"></i></h5>
                                        </div>
                                <hr class="mb-2">
                                <table id="example" class="table table-bordered align-middle" style="width:100%">
                                    <thead class="table-light">
                                        <tr>
                                            <th class="thbutton">Date</th>
                                            <th>Account</th>
                                            <th class="thbutton">Debit</th>
                                            <th class="thbutton">Credit</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    @if(isset($accountJournal->contraVoucherTransaction)&&count($accountJournal->contraVoucherTransaction)>0)
                                      @foreach($accountJournal->contraVoucherTransaction as $key => $transactions)
                                    <tr>
                                      <td>{{$transactions->transaction_date}}</td>
                                      <td>{!! isset($transactions->transaction_type)&&$transactions->transaction_type=='CREDIT' ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" : "" !!} {{$transactions->account->name}}</td>
                                      <td>{{isset($transactions->transaction_type)&&$transactions->transaction_type=='DEBIT' ? convertDecimelPoint($transactions->amount) : "" }}</td>
                                      <td>{{isset($transactions->transaction_type)&&$transactions->transaction_type=='CREDIT' ? convertDecimelPoint($transactions->amount) : "" }}</td>
                                    </tr>
                                      @endforeach
                                    @endif
                                    </tbody>
                                </table>
                            </div>
                          </div>
                      </div>
                  </div>
              </div>
          </div>
      </div>
  </div>

    <!--end row-->
@endsection
@section('js')
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
<script type="text/javascript">
    $(document).on('click', '.save_button', function(event){
        event.preventDefault();
        var error = 0;

        if ($('#commonModal').find('form').hasClass('address')) {
            $('.error_address_line1').hide();
            $('.error_district_name').hide();
            $('.error_taluka_name').hide();
            $('.error_pin_code').hide();
            $('.error_priority').hide();
            $('.error_address_type_id').hide();

            if ($('#commonModal').find('form').find('[name="address_line1"]').val().trim() == '') {
              $('.error_address_line1').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="country_id"]').val() == '') {
              $('.error_country_id').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="state_id"]').val() == '') {
              $('.error_state_id').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="city_id"]').val() == '') {
              $('.error_city_id').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="pin_code"]').val() == '') {
              $('.error_pin_code').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('input[name="priority"]').val().trim() == '') {
              $('.error_priority').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="address_type_id"]').val() == '') {
              $('.error_address_type_id').show();
              error = 1;
            }
            var account_id = $('#commonModal').find('form').find('input[name="account_id"]').data('id');
            $('#commonModal').find('form').find('input[name="account_id"]').val(account_id);

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

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

                          // hide modal
                          $('#commonModal').modal('hide');
                          fetch_address();
                        } 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!');

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

        if ($('#commonModal').find('form').hasClass('bank')) {
            $('.account_name').hide();
            $('.bank_name').hide();
            $('.account_no').hide();
            $('.branch_name').hide();
            $('.error_priority').hide();

            if ($('#commonModal').find('form').find('[name="account_name"]').val().trim() == '') {
              $('.error_account_name').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="bank_name"]').val() == '') {
              $('.error_bank_name').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="branch_name"]').val() == '') {
              $('.error_branch_name').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="account_no"]').val() == '') {
              $('.error_account_no').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="priority"]').val() == '') {
              $('.error_priority').show();
              error = 1;
            }

            var account_id = $('#commonModal').find('form').find('input[name="account_id"]').data('id');
            $('#commonModal').find('form').find('input[name="account_id"]').val(account_id);


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

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

                          // hide modal
                          $('#commonModal').modal('hide');
                          fetch_banks();
                        } 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!');

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

        if ($('#commonModal').find('form').hasClass('license')) {
            $('.error_license_type_id').hide();
            $('.error_license_number').hide();
            $('.error_valid_from').hide();
            $('.error_valid_upto').hide();

            if ($('#commonModal').find('form').find('select[name="license_type_id"]') == '' || $('#commonModal').find('form').find('select[name="license_type_id"]').val() == undefined)
            {
                $('.error_license_type_id').show();
                error = 1;
            }
            if ($('#commonModal').find('form').find('[name="license_number"]').val().trim() == '') {
              $('.error_license_number').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="valid_from"]').val().trim() == '') {
              $('.error_valid_from').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="valid_upto"]').val().trim() == '') {
              $('.error_valid_upto').show();
              error = 1;
            }

            var account_id = $('#commonModal').find('form').find('input[name="account_id"]').data('id');
            $('#commonModal').find('form').find('input[name="account_id"]').val(account_id);

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

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

                          // hide modal
                          $('#commonModal').modal('hide');
                          fetch_licenses();
                        } 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!');

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

        if ($('#commonModal').find('form').hasClass('payment')) {
            $('.error_payment_mode_id').hide();
            $('.error_priority').hide();

            if ($('#commonModal').find('form').find('[name="payment_mode_id"]').val().trim() == '') {
              $('.error_payment_mode_id').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="priority"]').val().trim() == '') {
              $('.error_priority').show();
              error = 1;
            }

            var account_id = $('#commonModal').find('form').find('input[name="account_id"]').data('id');
            $('#commonModal').find('form').find('input[name="account_id"]').val(account_id);

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

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

                          // hide modal
                          $('#commonModal').modal('hide');
                          fetch_payments();
                        } 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!');

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

        if ($('#commonModal').find('form').hasClass('attachment')) {
            $('.error_file').hide();
            $('.error_title').hide();
            $('.error_details').hide();

            if ($('#commonModal').find('form').find('[name="file"]').val().trim() == ''
              && !$('#commonModal').find('form').hasClass('edit')) {
              $('.error_file').show();
              error = 1;
            }
            if ($('#commonModal').find('form').find('[name="title"]').val().trim() == '') {
              $('.error_title').show();
              error = 1;
            }

            var account_id = $('#commonModal').find('form').find('input[name="account_id"]').data('id');
            $('#commonModal').find('form').find('input[name="account_id"]').val(account_id);


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

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

                          // hide modal
                          $('#commonModal').modal('hide');
                          fetch_attachments();
                        } 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!');

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

        if ($('#commonModal').find('form').hasClass('image')) {
            $('.error_file').hide();
            $('.error_title').hide();

            if ($('#commonModal').find('form').find('[name="file"]').val().trim() == '') {
              $('.error_file').show();
              error = 1;
            }

            var account_id = $('#commonModal').find('form').find('input[name="account_id"]').data('id');
            $('#commonModal').find('form').find('input[name="account_id"]').val(account_id);

            if (error == 0) {
              $('#commonModal').find('form').submit();
            }
        }

        if ($('#commonModal').find('form').hasClass('license-types')) {
          $('.error_name').hide();
          $('.error_code').hide();
          $('.error_priority').hide();
          var error = 0;

          if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
            $('.error_name').show();
            error = 1;
          }
          if ($('#commonModal').find('form').find('input[name="code"]').val().trim() == '') {
            $('.error_code').show();
            error = 1;
          }
          if ($('#commonModal').find('form').find('input[name="priority"]').val().trim() == '') {
            $('.error_priority').show();
            error = 1;
          }

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

            $.ajax({
                url: "{!! route('license-types.store') !!}",
                data: formdata,
                processData: false,
                contentType: false,
                type: 'POST',
                success: function (response) {
                    if (response.success === true) {
                      toastr.success(response.message, 'Success.');

                      // hide modal
                      $('#commonModal').modal('hide');

                      setTimeout(function() {
                          clickBTN();
                      }, 1000);
                    } 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!');

                // hide modal
                $('#commonModal').modal('hide');
                $('#commonModal').find('.modal-body').html('');
            });
          }
        }
        error = 1;
    })
    $( function() {
        $('.datepicker').datepicker({
            "dateFormat" : "dd-mm-yy",
            "maxDate": '0',
            "changeMonth": true,
            "changeYear": true
        }).datepicker("setDate",'now')
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });
    function clickBTN() {
      $('#createLicenses').trigger('click');
    }
    $(document).ready(function(){
        fetch_banks();
        fetch_address();
        fetch_licenses();
        fetch_payments();
        fetch_attachments();
    });
    function fetch_address(){
      $.ajax({
        url:"{!! route('accounts.addresses', $accountJournal->id) !!}",
        success:function(data){
            $('#address_tables').html('');
            $('#address_tables').html(data);
            $.switcher('#address_tables .changeAccountStatus');
        }
      })
    }

    function fetch_banks(){
      $.ajax({
        url:"{!! route('accounts.banks', $accountJournal->id) !!}",
        success:function(data){
            $('#banks_tables').html('');
            $('#banks_tables').html(data);
            $.switcher('#banks_tables .changeAccountStatus');
        }
      })
    }

    function fetch_licenses(){
      $.ajax({
        url:"{!! route('accounts.licenses', $accountJournal->id) !!}",
        success:function(data){
            $('#licenses_tables').html('');
            $('#licenses_tables').html(data);
            $.switcher('#licenses_tables .changeAccountStatus');
        }
      })
    }

    function fetch_payments(){
      $.ajax({
        url:"{!! route('accounts.payments', $accountJournal->id) !!}",
        success:function(data){
            $('#payments_tables').html('');
            $('#payments_tables').html(data);
            $.switcher('#payments_tables .changeAccountStatus');
        }
      })
    }

    function fetch_attachments(){
      $.ajax({
        url:"{!! route('accounts.attachments', $accountJournal->id) !!}",
        success:function(data){
            $('#attachments_tables').html('');
            $('#attachments_tables').html(data);
            $.switcher('#attachments_tables .changeAccountStatus');
        }
      })
    }

    $(document).on('click', '#createImage', function(){
        $('#commonModalLabel').text('Upload New Image');
        $('.save_button_span').text('Upload Image');
        $.ajax({
          url:"{!! route('account-images.create_images', $accountJournal->id) !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

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

    $(document).on('click', '#createAttachment', function(){
        $('#commonModalLabel').text('Add New Attachment');
        $('.save_button_span').text('Save Attachment');
        $.ajax({
          url:"{!! route('account-attachments.create_attachments', $accountJournal->id) !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $('.datepicker').datepicker("destroy");

            // Re-initialize the datepicker
            $('.datepicker').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', '.editAttachment', function(){
        $('#commonModalLabel').text('Edit Attachment');
        $('.save_button_span').text('Update Attachment');
        var id = $(this).data('id');
        var url = `{!! route('account-attachments.edit', ':id') !!}`.replace(':id', id);

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

            // Re-initialize the datepicker
            $('.datepicker').datepicker({
                "dateFormat" : "dd-mm-yy",
                "changeMonth": true,
                "changeYear": true
            })
            .on('changeDate', function (ev) {
                 $(this).datepicker('hide');
            })
            .on('focusout', function (ev) {
                 $(this).datepicker('hide');
            });
          }
        })
    })

    $(document).on('click', '#createPayment', function(){
        $('#commonModalLabel').text('Add New Payment');
        $('.save_button_span').text('Save Payment');
        $.ajax({
          url:"{!! route('account-payments.create_payment', $accountJournal->id) !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

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

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

    $(document).on('click', '#createLicenses', function(){
        $('#commonModalLabel').text('Add New License');
        $('.save_button_span').text('Save License');
        $.ajax({
          url:"{!! route('account-licenses.create_license', $accountJournal->id) !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);

            // $('.datepicker').datepicker("destroy");

            // Re-initialize the datepicker
            $( function() {
                $('#valid_from').datepicker();
            });
            $( function() {
                $('#valid_from').datepicker();
            });
            $( function() {
                $('#valid_upto').datepicker();
            });
            }
        })
    })

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

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

            // Re-initialize the datepicker
            $('.datepicker').datepicker({
                "dateFormat" : "dd-mm-yy",
                "maxDate": '0',
                "changeMonth": true,
                "changeYear": true
            })
            .on('changeDate', function (ev) {
                 $(this).datepicker('hide');
            })
            .on('focusout', function (ev) {
                 $(this).datepicker('hide');
            });
          }
        })
    })

    $(document).on('click', '#createBank', function(){
        $('#commonModalLabel').text('Add New Bank');
        $('.save_button_span').text('Save Bank');
        $.ajax({
          url:"{!! route('account-banks.create_bank', $accountJournal->id) !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

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

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

    $(document).on('click', '#createAddress', function(){
        $('#commonModalLabel').text('Add New Address');
        $('.save_button_span').text('Save Address');
        $.ajax({
          url:"{!! route('account-addresses.create_address', $accountJournal->id) !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
          }
        })
    })

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

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

    function changecontry()
    {
        let country = $('#country').val();

        $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            type: "POST",
            url: "{{ url('companies/getstate') }}",
            data: {
                country:country
            },
            success: function (data) {
                $('#states').html(data);
            },
            error: function (data) {
                //console.log(data);
            }
        });

        // GET COUNTRY CODE OF SELECTED COUNTRY
        $.ajax({
            type: "POST",
            url: "{{ url('companies/getcountrycode') }}",
            data: {
                country:country
            },
            success: function (countryCode) {
            }
        });
    }

    function getcity()
    {
        let states_id=$('#states').val();

        $.ajax({
            type: "POST",
            url: "{{ url('companies/getcity') }}",
            data: {states_id:states_id},
            success: function (data) {
                $('#cities').html(data);
            },
        });
    }

    function changecountry()
    {
        $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        let country=$('#country').val();
        let stateid=$('#stateid').val();

        $.ajax({
            type: "POST",
            url: "{{ url('companies/getstate') }}",
            data: {country:country,stateid:stateid},
            success: function (data) {
                $('#states').html(data);
                $('#states').trigger('change');
            },
            error: function (data) {
                console.log(data);
            }
        });
    }

    $(document).on('change', '#states', function () {
        let states_id=$('#states').val()?$('#states').val():"";
        let cityid=$('#cityid').val();

        $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            type: "POST",
            url: "{{ url('companies/getcity') }}",
            data: {states_id:states_id,cityid:cityid},
            success: function (data) {
                $('#cities').html(data);
            },
            error: function (data) {
                console.log(data);
            }
        });
    })

    /*********change status**********/
    $("body").on("click",'.changeAccountStatus', function(event){
        dataString       = {"id":$(this).data('id'),"status":$(this).data('status'),"account": "{!! $accountJournal->id !!}"};
        var UrlValue     = $(this).data('url');
        var status       = $(this).data('status');
        var changeStatus = $(this);

        Swal.fire({
            title: 'Are you sure you want to change status?',
            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    :dataString,
                    headers:
                    {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    beforeSend: function( xhr ) {
                        // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },
                    success : function(response){
                        if(response.success){
                            var ErroMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('success',ErroMsg);

                            if($(this).hasClass('address')){
                                fetch_address();
                            }
                            else if ($(this).hasClass('bank')) {
                                fetch_banks();
                            }
                            else if ($(this).hasClass('licenses')) {
                                fetch_licenses();
                            }
                            else if ($(this).hasClass('payments')) {
                                fetch_payments();
                            } else if ($(this).hasClass('attachments')) {
                                fetch_attachments();
                            }

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

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

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

                if($(this).hasClass('address')){
                    fetch_address();
                }
                else if ($(this).hasClass('bank')) {
                    fetch_banks();
                }
                else if ($(this).hasClass('licenses')) {
                    fetch_licenses();
                }
                else if ($(this).hasClass('payments')) {
                    fetch_payments();
                } else if ($(this).hasClass('attachments')) {
                    fetch_attachments();
                }
            }
            //return false;
        });
    //return false;
    });

    /*********delete data**********/
    $("body").on("click",'.deleteAccountData', function(event){
        dataString    = {"id":$(this).data('id')};
        var UrlValue  = $(this).data('url');
        var btn = $(this);
        //alert(dataValue);
        console.log($('meta[name="csrf-token"]').attr('content'));
        console.log(dataString);

        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'),
                        "account": "{!! $accountJournal->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){
                    console.log(response.data);
                    if(response.success){
                        var ErroMsg = $(this).printErrorMsg(response.message);

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

                        if(btn.hasClass('address')){
                            fetch_address();
                        }
                        else if (btn.hasClass('bank')) {
                            fetch_banks();
                        }
                        else if (btn.hasClass('licenses')) {
                            fetch_licenses();
                        }
                        else if (btn.hasClass('payments')) {
                            fetch_payments();
                        } else if (btn.hasClass('attachments')) {
                            fetch_attachments();
                        }
                        console.log('s');
                    }else{
                        var ErroMsg = $(this).printErrorMsg(response.message);
                        $(this).Toastshow('error',ErroMsg);
                    }
                },
                error: function (data) {
                  console.log("error ",data);
                }
            });
            }
        });
    });
</script>
@endsection
