<style type="text/css">
    .account_title {
        width: 50px;
        border: 1px solid #ced4da;
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
    }
</style>
<form class="row g-3 auto-width edit_customer" id="edit_customer_form" method="post" enctype='multipart/form-data' action="{!! route('party-account-update', $account->id) !!}">
    @csrf
    @method("POST")
    <div class="col-md-12">
        <div>
            <label for="name" class="form-label">Customer Name <span class="text-danger"><b>*</b></span></label>
        </div>
        <div class="input-group">
            <input type="text" name="name" class="form-control" value="{!! $account->name !!}" placeholder="Account Name">
        </div>
        <span class="text-danger error_name" style="display:none;">This field is required.</span>
    </div>
    <div class="col-md-6">
        <div>
            <label for="account_type_id" class="form-label">Account Type<span class="text-danger"><b>*</b></span></label>
        </div>
        <div class="input-group">
            <select class="account_type_id form-control" name="account_type_id">
                @foreach($account_types as $list)
                <option value="{{ $list->id }}" data-identifier="{!! strtolower($list->type_name) !!}" {!! $account->account_type_id == $list->id ? 'selected' : ($list->is_default == 1 ? 'selected' : '') !!}>{{ $list->type_name }}</option>
                @endforeach
            </select>
        </div>
        @if ($errors->has('account_tyxpe_id'))
            <span class="text-danger">{{ $errors->first('account_type_id') }}</span>
        @endif
        <span class="text-danger error_account_type_id" style="display:none;">This field is required.</span>
    </div>
    <div class="col-md-6">
        <div>
            <label for="accounting_group_id" class="form-label">Accounting Group  <span class="text-danger"><b>*</b></span></label>
        </div>
        <div class="input-group">
            <select class="form-control" name="accounting_group_id">
                <option value=""> -Select -</option>
                @foreach($accounting_groups as $list)
                    <option value="{{ $list->id }}" {!! $account->accounting_group_id == $list->id ? 'selected' : '' !!}>{{ $list->name }}</option>
                @endforeach
            </select>
        </div>
        @if ($errors->has('accounting_group_id'))
            <span class="text-danger">{{ $errors->first('accounting_group_id') }}</span>
        @endif
        <span class="text-danger error_accounting_group_id" style="display:none;">This field is required.</span>
    </div>
    <div class="col-md-6 phone_no_col">
        <div>
            <label class="form-label">Phone no <span class="text-danger"><b>*</b></span></label>
        </div>
        <div class="input-group">
            <input type="tel" class="form-control" placeholder="" id="phone_no" value="{!! $account->account_contact->phone_no ?? '' !!}" />
            <input type="hidden" name="phone_no" value="{!! $account->account_contact->phone_no ?? '' !!}">
        </div>
        <span class="text-danger error_phone" style="display:none;">This field is required.</span>
    </div>

    <div class="col-md-6 whatsapp_no_col">
        <div>
            <label class="form-label">Whatsapp no </label>
        </div>
        <div class="input-group">
            <input type="tel" class="form-control" placeholder="" id="whatsapp_no" value="{!! $account->account_contact->whatsapp_no ?? '' !!}"/>
            <input type="hidden" name="whatsapp_no">
        </div>
    </div>
    <div class="col-md-6">
        <div>
            <label class="form-label">Email </label>
        </div>
        <div class="input-group">
            <input type="email" class="form-control" placeholder="Email" id="email" value="{!! $account->account_contact->email ?? '' !!}" name="email">
        </div>
    </div>
    <div class="col-md-6">
        <label class="form-label">Country</label>
        <select class="single-select form-control" id="country" name="country_id" onchange="changecontry()" required>
            <option value=" "> Select Country</option>
            @foreach($country as $list)
            <option value="{{ $list->id}}" {!! isset($account->first_account_address->country_id) && $account->first_account_address->country_id == $list->id ? 'selected' : '' !!}>{{$list->name}}</option>
            @endforeach
        </select>
    </div>

    <div class="col-md-4">
        <label class="form-label">State</label>
        <input type="hidden" value="{{ $account->first_account_address->state_id ?? '' }}" id="stateid">
        <select class="single-select form-control" name="state_id"  id="states">
        </select>
        <span class="text-danger error_state_id" style="display:none;">This field is required.</span>
    </div>
    <div class="col-md-4">
        <label class="form-label">City</label>
        <input type="hidden" value="{{ $account->first_account_address->city_id ?? '' }}" name="cityid">
        <select class="single-select form-control" name="city_id" id="cities">
        </select>
        <span class="text-danger error_city_id" style="display:none;">This field is required.</span>
    </div>
    <div class="col-md-4">
        <div>
            <label class="form-label">PIN/Postal code </label>
        </div>
        <div class="input-group">

            <input type="text" class="form-control" placeholder="Enter PIN/Postal code" id="postal_code" value="{!! $account->account_contact->postal_code ?? '' !!}" />
        </div>
    </div>
    <div class="col-md-12">
        <label class="form-label">Address </label>
        <textarea name="address" class="form-control" placeholder="Enter Address" >{{$account->account_contact->address ?? ''}}</textarea>
    </div>
    @foreach($license_types as $key => $value)
    @php
        $license_number = '';

        if(isset($account_license[$value->id])) {
            $license_number = $account_license[$value->id]->license_number;
        }
    @endphp
    <div class="col-md-6">
        <label for="license_number" class="form-label">{{ $value->name }} <span class="text-danger"><b>*</b></span></label>
        <input type="text" class="form-control" id="license_number[{{ $value->code }}][license_number]" value="{{$license_number}}" name="license_number[{{ $value->code }}][license_number]" aria-describedby="inputGroupPrepend" value="{{ $existingLicenses[$value->id]->license_number ?? '' }}" required>
        <input type="hidden" name="license_number[{{ $value->code }}][license_type_id]" value="{{ $value->id }}">
    </div>
    @endforeach
</form>

<script>

    $('.details-toggle').hide();
    var toggle = true;

    $("#phone_no").on('input', function() {
        const onlyNumbers = allNumeric($(this).val());
        $("#phone_no").val(onlyNumbers);
    });
    $("#whatsapp_no").on('input', function() {
        const onlyNumbers = allNumeric($(this).val());
        $("#whatsapp_no").val(onlyNumbers);
    });
    $("#alternative_no").on('input', function() {
        const onlyNumbers = allNumeric($(this).val());
        $("#alternative_no").val(onlyNumbers);
    });
    function allNumeric(inputtxt) {
        onlyNumbers = inputtxt.replace(/[^0-9]/g, '');
        if (onlyNumbers.length > 16) {
            onlyNumbers = onlyNumbers.substring(0, 16);
        }
        return onlyNumbers;
    }
    $("[name='year']").on('input', function() {
        var onlyNumbers = allNumeric($(this).val());

        if (onlyNumbers.length > 4) {
            onlyNumbers = onlyNumbers.substring(0, 4);
        }

        $("[name='year']").val(onlyNumbers);
    });

    $("[name='month']").on('input', function() {
        var month = allNumeric($(this).val());

        if (month > 12) {
            month = 12;
        }

        $("[name='month']").val(month);
    });

    $("[name='day']").on('input', function() {
        var day = parseInt($(this).val());
        if (isNaN(day) || day < 1) {
            day = 1;
        }

        if (day > 31) {
            day = 31;
        }

        $("[name='day']").val(day);
    });
    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);
            }
        });
        $.ajax({
            type: "POST",
            url: "{{ url('companies/getcountrycode') }}",
            data: {
                country: country
            },
            success: function (countryCode) {
                var telInput = $('#phone_no, #whatsapp_no, #alternative_no');

                // Destroy the existing instances
                telInput.intlTelInput('destroy');

                // Reinitialize the input fields with the new country code
                telInput.intlTelInput({
                    utilsScript: 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.13/js/utils.js',
                    initialCountry: countryCode, // Set the received country code directly
                    separateDialCode: true
                });
            },
            error: function (data) {
                // Handle error
            }
        });
    }

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

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

        $.ajax({
            type: "POST",
            url: "{{ url('account-type-groups') }}",
            data: {
                selectedType: selectedType
            },
            success: function (data) {
                if (data.success === true) {
                    var content = '';
                    if (data.name == 'GENERAL') {
                        content = '<option value="">-- Select --</option>' + content;
                    }

                    $.each(data.data, function (index, value) {
                        content += '<option value="' + value.id + '">' + value.name + '</option>';
                    });

                    $('[name="accounting_group_id"]').html(content);
                }
            },
            error: function (data) {
                console.log(data);
            }
        });
    });

</script>

@if($country_id)
    <script>
        changecontry();

        $('#states').trigger('change');
    </script>
@endif
