@extends('layouts.app')
@section('title','Accounts')
@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"> Accounts
    </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">Accounts</li>
            <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i>  Account 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(auth()->user()->can('accounts-edit'))
                <a href="{{route('accounts.edit',$account->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>
  @php $auth_format = \Session::get('company_data')['date_format'] ?? ''; @endphp
  <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-5">
                      <div class="card">
                          <div class="card-body g-3">
                              <div class="table-responsive">
                                  <div class="d-flex justify-content-between">
                                      <h5 class="mb-0">Account Details</h5>
                                  </div>
                                  <hr class="mb-2">
                                  <table class="table table-bordered align-middle">
                                    <tr>
                                        <td style="text-align:left;">Account Name </td>
                                        <td>{{$account->name}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Account Code </td>
                                        <td>{{$account->code}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Account Type</td>
                                        <td>{{$account->type_name}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Account Category</td>
                                        <td>{{$account->category_name}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Accounting Group</td>
                                        <td>{{$account->group_name}}</td>
                                    </tr>
                                  </table>
                              </div>
                          </div>
                      </div>
                  </div>
                  <div class="col-md-5">
                      <div class="card">
                          <div class="card-body g-3 row">
                              <div class="table-responsive">
                                  <h5 class="mb-0">Additional Details</h5>
                                  <hr class="mb-2">
                                  <table class="table table-bordered align-middle">
                                    <tr>
                                        <td style="text-align:left;">Account Settlement Type</td>
                                        <td>{{$account->settlement_type}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Account Balance Type</td>
                                        <td>{{$account->balance_type}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Opening Balance</td>
                                        <td>{{$account->opening_balance}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Print Name</td>
                                        <td>{{$account->print_name}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;">Referred By</td>
                                        <td>{{$account->credit_limit}}</td>
                                    </tr>
                                  </table>
                              </div>
                          </div>
                      </div>
                  </div>
                  <div class="col-md-2">
                      <div class="card">
                          <div class="card-body g-3 row">
                              <div class="table-responsive" style="margin-bottom: 18px;">
                                  @if($account->image != '')
                                      <img src="{!! getTempUrl($account->image) !!}" height="auto" id="createImage" data-bs-toggle="modal" data-bs-target="#commonModal" style="cursor: pointer;max-width: 120px;width: 120px;">
                                  @else
                                      <img src="{!! asset('admin/images/avtaar.png') !!}" width="100%" height="auto" id="createImage" data-bs-toggle="modal" data-bs-target="#commonModal" style="cursor: pointer;max-width: 120px;width: 120px;">
                                  @endif
                                  <p class="pt-3" style="cursor: pointer;"><strong>Update Profile Image</strong></p>
                              </div>
                          </div>
                      </div>
                  </div>
                  <div class="col-md-12">
                      <div class="card">
                          <div class="card-body g-3 row">
                              <div class="table-responsive">
                                  <h5 class="mb-0">Personal Details</h5>
                                  <hr class="mb-2">
                                  <div>
                                      <strong>Date Of Birth</strong>: {{ date($auth_format, strtotime($account->date_of_birth)) }},
                                      <strong>Marital Status</strong>: {{$account->marital_status}},
                                      <strong>Gender</strong>: {{$account->gender}},
                                      <strong>Blood Group</strong>: {{$account->blood_group}},
                                      @if($account->guardian_name != '')
                                          <strong>Guardian Name</strong>: {{$account->guardian_name}},
                                      @endif
                                      @if($account->anniversary_date != '')
                                          <strong>Anniversary date</strong>: {{ date($auth_format, strtotime($account->anniversary_date)) }},
                                      @endif
                                      <strong>Any Known Allergies</strong>: {{$account->any_known_allergies}},
                                  </div>
                              </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" id="address_tables">
                          </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" id="relatives_tables">
                          </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" id="banks_tables">
                          </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" id="licenses_tables">
                          </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" id="payments_tables">
                          </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" id="attachments_tables">
                          </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('');
            });
          }
        }

        if ($('#commonModal').find('form').hasClass('relatives')) {
            $('.error_name').hide();
            $('.error_code').hide();
            $('.error_priority').hide();

            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) {
                            fetch_ralatives();
                            toastr.success(response.message, 'Success.');

                            // hide modal
                            $('#commonModal').modal('hide');
                        } 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_ralatives();
        fetch_licenses();
        fetch_payments();
        fetch_attachments();
    });
    function fetch_address(){
      $.ajax({
        url:"{!! route('accounts.addresses', $account->id) !!}",
        success:function(data){
            $('#address_tables').html('');
            $('#address_tables').html(data);
            $.switcher('#address_tables .changeAccountStatus');
        }
      })
    }

    function fetch_ralatives(){
      $.ajax({
        url:"{!! route('accounts.relatives', $account->id) !!}",
        success:function(data){
            $('#relatives_tables').html('');
            $('#relatives_tables').html(data);
            $.switcher('#relatives_tables .changeAccountStatus');
        }
      })
    }

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

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

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

    function fetch_attachments(){
      $.ajax({
        url:"{!! route('accounts.attachments', $account->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', $account->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', $account->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', $account->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', $account->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', $account->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', $account->id) !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            changecontry();
          }
        })
    })

    $(document).on('click', '#createRelative', function(){
        $('#commonModalLabel').text('Add New Relative');
        $('.save_button_span').text('Save Relative');
        $.ajax({
          url:"{!! route('accounts.relative.create', $account->id) !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            changecontry();
          }
        })
    })

    $(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);
            changecontry();
            $('#states').trigger('change');
          }
        })
    })

    $(document).on('click', '.editRelative', function(){
        $('#commonModalLabel').text('Edit Relative');
        $('.save_button_span').text('Update Relative');
        var id = $(this).data('id');
        var url = `{!! route('accounts.relative.edit', ':id') !!}`.replace(':id', id);

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

    function changecontry()
    {
        $.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():"{{isset($company_address->state_id) ? $company_address->state_id : ''}}";
        let cityid  = $('input[name="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": "{!! $account->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();
                                fetch_ralatives();
                            }
                            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();
                    fetch_ralatives();
                }
                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": "{!! $account->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();
                            fetch_ralatives();
                        }
                        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
