@extends('layouts.app')
@section('title','Company')
@section('pages')
<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" />
<style type="text/css">
    .select2-container {
        z-index: 1062;
    }
    table tr td {
        white-space: normal;
    }
</style>
<!--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> Companies</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">

                <li class="breadcrumb-item active" aria-current="page">Comapany Details</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('companies.index')}}" class="btn btn-info"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
        </div>
        <div class="btn-group">
            <a href="{{ route('companies.edit',$company_basic->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>
        </div>

    </div>
</div>
<!--end breadcrumb-->

<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">
                                <h5 class="mb-0">Company Basic Details</h5>
                                <hr class="mb-2">
                                <table class="table table-bordered align-left">
                                    <tr>
                                        <td style="text-align: left;"><strong>Company Name</strong></td>
                                        <td>{{$company_basic->name}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Office Type</strong></td>
                                        <td>
                                            {!! $company_basic->office_type=="head_office" ? 'Head Office' : $company_basic->office_type !!}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Email</strong></td>
                                        <td>{{$company_basic->email}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong> Phone</strong></td>
                                        <td>{{$company_basic->phone_number}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong> Mobile</strong></td>
                                        <td>{{$company_basic->mobile_number}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Whatsapp</strong></td>
                                        <td>{{$company_basic->whatsapp_no}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Branch</strong></td>
                                        <td>{{$company_basic->branch_name}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Branch Code</strong></td>
                                        <td>{{$company_basic->branch_code}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Website</strong></td>
                                        <td>{{$company_basic->website}}</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">Company Aditional Details</h5>
                                <hr class="mb-2">
                                <table class="table table-bordered align-left">
                                    <tr>
                                        <td style="text-align: left;"><strong>Tag Line</strong></td>
                                        <td>{{$company_basic->tag_line}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Letter Head</strong></td>
                                        <td>
                                            {!! $company_basic->letter_head=="head_office" ? 'Head Office' : 'Self' !!}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Deal's in </strong></td>
                                        <td>{{$company_basic->deals_in}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Date Format </strong></td>
                                        <td>{{$company_basic->date_format}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Time Format </strong></td>
                                        <td>{{$company_basic->time_format}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Time Zone </strong></td>
                                        <td>{{$company_basic->getZone->name}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Language </strong></td>
                                        <td>{{ $company_basic->language->name ?? '' }}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align: left;"><strong>Currency </strong></td>
                                        <td>{{ $company_basic->currency->currency ?? '' }}</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 text-center" style="margin-bottom: 18px;">
                                @if($company_basic->logo != '')
                                    <img src="{!! getTempUrl($company_basic->logo) !!}" height="auto" id="createImage" data-bs-toggle="modal" data-bs-target="#commonModal" style="cursor: pointer;max-width: 120px;width: 120px;">
                                @else
                                    <img src="{!! 'https://metaminthealth.s3.ap-south-1.amazonaws.com/metamintassets/images/meta_mint_white_logo.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>
                                <p class="text-primary text-center">Max Logo Size:<br>Width:640px,Height:136px</p>
                            </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="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="documents_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="company_images">
                        </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).ready(function(){
            fetch_banks();
            fetch_address();
            fetch_documents();
            company_images();
        });

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

        function fetch_address(){
          $.ajax({
            url:"{!! route('companies.addresses', $company_basic->id) !!}",
            success:function(data){
                $('#address_tables').html('');
                $('#address_tables').html(data);
                $.switcher('#address_tables .changeAccountStatus');
            }
          })
        }

        function fetch_documents(){
          $.ajax({
            url:"{!! route('companies.documents', $company_basic->id) !!}",
            success:function(data){
                $('#documents_tables').html('');
                $('#documents_tables').html(data);
                $.switcher('#documents_tables .changeAccountStatus');
            }
          })
        }

        function company_images(){
          $.ajax({
            url:"{!! route('companies.images', $company_basic->id) !!}",
            success:function(data){
                $('#company_images').html('');
                $('#company_images').html(data);
                $.switcher('#company_images .changeAccountStatus');
            }
          })
        }

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

        $(document).on('click', '#createBank', function(){
            $('#commonModalLabel').text('Add New Bank');
            $('.save_button_span').text('Save Bank');
            $.ajax({
              url:"{!! route('company-banks.create_bank', $company_basic->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('company-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('companies-addresses.create_address', $company_basic->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('companies-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', '#createCompanyImages', function(){
            $('#commonModalLabel').text('Add New Company Image');
            $('.save_button_span').text('Save Images');
            $.ajax({
              url:"{!! route('companies-images.create_images', $company_basic->id) !!}",
              success:function(data){
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
                changecontry();
              }
            })
        })

        $(document).on('click', '.editCompanyImages', function(){
            $('#commonModalLabel').text('Edit Company Image');
            $('.save_button_span').text('Update Company Image');
            var id = $(this).data('id');
            var url = `{!! route('companies-images.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', '#createLicenses', function(){
            $('#commonModalLabel').text('Add New Document');
            $('.save_button_span').text('Save Document');
            $.ajax({
              url:"{!! route('company-documents.create_document', $company_basic->id) !!}",
              success:function(data){
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);

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

                // Re-initialize the datepicker

                // $('#date_to').datepicker({
                //     format: 'Y-m-d'
                // });
                // var currentDate = new Date();
                // var formattedDate = currentDate.getDate().toString().padStart(2, '0') + '/' + (currentDate.getMonth() + 1).toString().padStart(2, '0') + '/' + currentDate.getFullYear();
                // $('#date_to').val(formattedDate);

                // $('#date_from').datepicker({
                // format: 'Y-m-d'
                // });
                // var currentDate = new Date();
                // var formattedDate = currentDate.getDate().toString().padStart(2, '0') + '/' + (currentDate.getMonth() + 1).toString().padStart(2, '0') + '/' + currentDate.getFullYear();
                // $('#date_from').val(formattedDate);
                function formatDate(date) {
                    const options = { day: 'numeric', month: 'numeric', year: 'numeric' };
                    return new Date(date).toLocaleDateString(undefined, options);
                }

                var currentDate = new Date().toISOString().split('T')[0];
                $('#date_from').datepicker().val(formatDate(currentDate));

                function formatDate(date) {
                    const options = { day: 'numeric', month: 'numeric', year: 'numeric' };
                    return new Date(date).toLocaleDateString(undefined, options);
                }

                var currentDate = new Date().toISOString().split('T')[0];
                $('#date_to').datepicker().val(formatDate(currentDate));

              }
            })
        })

        $(document).on('click', '.editLicenses', function(){
            $('#commonModalLabel').text('Edit Document');
            $('.save_button_span').text('Update Document');
            var id = $(this).data('id');
            var url = `{!! route('company-documents.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
                $('#valid_from').datepicker({ format: 'mm/dd/yy' }).on('changeDate', function (ev) {
                     $(this).datepicker('hide');
                })
                .on('focusout', function (ev) {
                     $(this).datepicker('hide');
                });

                $('#valid_upto').datepicker({ format: 'mm/dd/yy' })
                .on('changeDate', function (ev) {
                     $(this).datepicker('hide');
                })
                .on('focusout', function (ev) {
                     $(this).datepicker('hide');
                });
              }
            })
        })


        $(document).on('click', '.save_button', function(event){
            event.preventDefault();
            var error = 0;

            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 company_id = $('#commonModal').find('form').find('input[name="company_id"]').data('id');
                $('#commonModal').find('form').find('input[name="company_id"]').val(company_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');
                              location.reload();
                            } 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('company_images')) {
                $('.error_image_url').hide();
                $('.error_image_type').hide();
                $('.error_height').hide();
                $('.error_width').hide();
                $('.error_priority').hide();
                $('.error_alignment').hide();
                    
                if (!$('#commonModal').find('form').hasClass('company_image_update')) {
                    if ($('#commonModal').find('form').find('[name="image_url"]').val().trim() == '') {
                      $('.error_image_url').show();
                      error = 1;
                      setTimeout(function () {
                        $('.error_image_url').hide();
                        }, 3000);
                    }
                }

                if ($('#commonModal').find('form').find('[name="image_type"]').val() == '') {
                    $('.error_image_type').show();
                    error = 1;
                    setTimeout(function () {
                        $('.error_image_type').hide();
                        }, 3000);
                }
                if ($('#commonModal').find('form').find('input[name="height"]').val().trim() == '') {
                    $('.error_height').show();
                    error = 1;
                    setTimeout(function () {
                    $('.error_height').hide();
                    }, 3000);
                }
                if ($('#commonModal').find('form').find('input[name="width"]').val().trim() == '') {
                    $('.error_width').show();
                    error = 1;
                    setTimeout(function () {
                    $('.error_width').hide();
                    }, 3000);
                }
                if ($('#commonModal').find('form').find('[name="alignment"]').val() == '') {
                    $('.error_alignment').show();
                    error = 1;
                     setTimeout(function () {
                        $('.error_alignment').hide();
                        }, 3000);
                }
                if ($('#commonModal').find('form').find('input[name="priority"]').val().trim() == '') {
                    $('.error_priority').show();
                    error = 1;
                    setTimeout(function () {
                    $('.error_priority').hide();
                    }, 3000);
                }


                var company_id = $('#commonModal').find('form').find('input[name="company_id"]').data('id');
                $('#commonModal').find('form').find('input[name="company_id"]').val(company_id);
                console.log(error);
                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');
                              location.reload();
                            } 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')) {
                $('.error_account_holder_name').hide();
                $('.error_bank_name').hide();
                $('.error_account_number').hide();
                $('.error_bank_branch').hide();
                $('.error_priority').hide();

                if ($('#commonModal').find('form').find('[name="account_holder_name"]').val().trim() == '') {
                  $('.error_account_holder_name').show();
                  error = 1;
                  setTimeout(function () {
                    $('.error_account_holder_name').hide();
                    }, 3000);
                }
                if ($('#commonModal').find('form').find('[name="ifsc_code"]').val().trim() == '') {
                  $('.error_ifsc_code').show();
                  error = 1;
                  setTimeout(function () {
                    $('.error_ifsc_code').hide();
                    }, 3000);
                }
                if ($('#commonModal').find('form').find('[name="bank_name"]').val().trim() == '') {
                  $('.error_bank_name').show();
                  error = 1;

                  setTimeout(function () {
                    $('.error_bank_name').hide();
                    }, 3000);
                }
                if ($('#commonModal').find('form').find('[name="account_number"]').val() == '') {
                  $('.error_account_number').show();
                  error = 1;

                  setTimeout(function () {
                    $('.error_account_number').hide();
                    }, 3000);
                }
                if ($('#commonModal').find('form').find('[name="priority"]').val() == '') {
                  $('.error_priority').show();
                  error = 1;

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

                var company_id = $('#commonModal').find('form').find('input[name="company_id"]').data('id');
                $('#commonModal').find('form').find('input[name="company_id"]').val(company_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('address')) {
                $('.error_address_1').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_1"]').val().trim() == '') {
                  $('.error_address_1').show();
                  error = 1;
                  setTimeout(function () {
                    $('.error_address_1').hide();
                    }, 3000);
                }
                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().trim() == '') {
                  $('.error_pin_code').show();
                  error = 1;

                  setTimeout(function () {
                    $('.error_pin_code').hide();
                    }, 3000);
                }
                if ($('#commonModal').find('form').find('input[name="priority"]').val().trim() == '') {
                  $('.error_priority').show();
                  error = 1;

                  setTimeout(function () {
                    $('.error_priority').hide();
                    }, 3000);
                }
                if ($('#commonModal').find('form').find('[name="address_type_id"]').val() == '') {
                  $('.error_address_type_id').show();
                  error = 1;
                }
                var company_id = $('#commonModal').find('form').find('input[name="company_id"]').data('id');
                $('#commonModal').find('form').find('input[name="company_id"]').val(company_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('license')) {
                $('.error_license_type_id').hide();
                $('.error_license_number').hide();
                $('.error_valid_from').hide();
                $('.error_valid_upto').hide();

                if ($('#commonModal').find('form').find('[select="license_type_id"]').val()) {
                  $('.error_license_type_id').show();
                  error = 1;

                  setTimeout(function () {
                    $('.error_license_type_id').hide();
                    }, 3000);
                }
                if ($('#commonModal').find('form').find('[name="license_number"]').val().trim() == '') {
                  $('.error_license_number').show();
                  error = 1;

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

                var company_id = $('#commonModal').find('form').find('input[name="company_id"]').data('id');
                $('#commonModal').find('form').find('input[name="company_id"]').val(company_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_documents();
                            } 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('document-types')) {
                  $('.error_country_id').hide();
                  $('.error_license_code').hide();
                  $('.error_license_type_name').hide();

                  var country_id        = $('#commonModal').find('form').find('select[name="country_id"]').val();
                  var license_code      = $('#commonModal').find('form').find('input[name="license_code"]').val();
                  var license_type_name = $('#commonModal').find('form').find('input[name="license_type_name"]').val();

                  if (country_id == '') {
                    $('.error_country_id').show();
                    error = 1;
                  }
                  if (license_type_name == '') {
                    $('.error_license_type_name').show();
                    error = 1;
                  }
                  if (license_code == '') {
                    $('.error_license_code').show();
                    error = 1;
                  }

                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');
                              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 clickBTN() {
          $('#createLicenses').trigger('click');
        }
        $(document).on('click', '.create_license_types', function(){
          $('#commonModalLabel').text('Add New Documents Type');
          $('.save_button_span').text('Save Documents Type');
          $.ajax({
            url:"{!! route('document-types.create') !!}",
            success:function(data){
              $('#commonModal').find('.modal-body').html('');
              $('#commonModal').find('.modal-body').html(data);

              $('.single-select').select2({
                  theme: 'bootstrap4',
                  width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
                  placeholder: $(this).data('placeholder'),
                  allowClear: Boolean($(this).data('allow-clear')),
              });
            }
          })
        })

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

            Swal.fire({
                title: 'Are you sure you want to change status?',
                icon: 'warning',
                showDenyButton: true,
                showCancelButton: false,
                confirmButtonText: 'Yes',
                denyButtonText: 'No',
            }).then((result) => {
                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(btn.hasClass('address')){
                                    fetch_address();
                                }
                                else if (btn.hasClass('bank')) {
                                    fetch_banks();
                                }
                                else if (btn.hasClass('licenses')) {
                                    fetch_documents();
                                }
                                else if (btn.hasClass('payments')) {
                                    fetch_payments();
                                } else if (btn.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_documents();
                    }
                    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'),
                            "company": "{!! $company_basic->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){
                            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_documents();
                            }
                            else if (btn.hasClass('payments')) {
                                fetch_payments();
                            } else if (btn.hasClass('attachments')) {
                                fetch_attachments();
                            }
                        }else{
                            var ErroMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('error',ErroMsg);
                        }
                    },
                    error: function (data) {
                      console.log("error ",data);
                    }
                });
                }
            });
        });

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

    </script>
@endsection

