@extends('backend.layouts.app')

@section('content')
<div class="row page-titles">
   <div class="col-md-5 align-self-center">
      <h4 class="text-themecolor">Edit Service Provider</h4>
   </div>
   <div class="col-md-7 align-self-center text-right">
      <div class="d-flex justify-content-end align-items-center">
         <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
            <li class="breadcrumb-item"><a href="{{ route('serviceProvider') }}">Service Provider</a></li>
            <li class="breadcrumb-item active">Edit Service Provider</li>
         </ol>
      </div>
   </div>
</div>

<div class="container-fluid">
    <div class="content-wrapper">
        <section class="content">
            <div class="row">
                <div class="col-md-12">
                    <div class="card card-primary">
                        <div class="card-body">
                            <form id="form" action="{{ route('serviceProvider.updates', $user->id) }}" method="POST">
                                @csrf
                                @method('PUT')
                                <div class="row">
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="first_name">First Name<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                            <input type="text" id="first_name" name="first_name" class="form-control" placeholder="Enter first name" value="{{ old('first_name', $user->first_name) }}">
                                        </div>
                                    </div>

                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="last_name">Last Name<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                            <input type="text" id="last_name" name="last_name" class="form-control" placeholder="Enter last name" value="{{ old('last_name', $user->last_name) }}">
                                        </div>
                                    </div>

                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="email">Email<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                            <input type="email" readOnly id="email" name="email" class="form-control" placeholder="Enter email address" value="{{ old('email', $user->email) }}">
                                        </div>
                                        @if (isset($errors) && $errors->has('email'))
                                        <p style="color:red;">{{ $errors->first('email') }}</p>
                                    @endif
                                    </div>




                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="mobile_country_id">Mobile Country Code<span style="color: red;font-size:18px;"><b>*</b></span></label>


                                            <select id="mobile_country_id" name="mobile_country_id" class="form-control">
                                                <option value="">Select Country</option>
                                                @foreach($countries as $country)
                                                    <option value="{{ $country->id }}" {{ old('mobile_country_id', $user->mobile_country_id) == $country->id ? 'selected' : '' }}>{{ $country->phone_code }}  ({{ $country->name }})</option>
                                                @endforeach
                                            </select>

                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="phone">Mobile Number<span style="color: red;font-size:18px;"><b>*</b></span></label>
                                            <input type="text" id="phone" name="phone" oninput="this.value = this.value.replace(/[^0-9]/g, '');" class="form-control" placeholder="Enter mobile number" value="{{ old('phone', $user->mobile) }}">
                                        </div>
                                    </div>


                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="address">Address</label>
                                            <input type="text" id="address" name="address" class="form-control" placeholder="Enter address" value="{{ old('address', optional($user->userInformations)->address) }}">
                                        </div>
                                    </div>

                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="country_id">Country</label>
                                            <select id="country_id" name="country_id" class="form-control">
                                                <option value="">Select Country</option>
                                                @foreach($countries as $country)
                                                    <option value="{{ $country->id }}" {{ old('country_id', optional($user->userInformations)->country_id) == $country->id ? 'selected' : '' }}>{{ $country->name }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="state_id">State</label>
                                            <select id="state_id" name="state_id" class="form-control">
                                                <option value="">Select State</option>
                                                @if(isset($user->userInformations) && $user->userInformations->state)
                                                    <option selected value="{{ $user->userInformations->state->id }}">
                                                        {{ $user->userInformations->state->name }}
                                                    </option>
                                                @endif
                                            </select>
                                        </div>
                                    </div>


                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="city_id">City</label>
                                            <select id="city_id" name="city_id" class="form-control">
                                                <option value="">Select City</option>
                                                @if( isset($user->userInformations)&&  $user->userInformations->city)
                                                <option selected value="{{ $user->userInformations->city->id }}">
                                                    {{ $user->userInformations->city->name }}
                                                </option>
                                                @endif
                                            </select>
                                        </div>
                                    </div>


                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="post_code">Post Code</label>
                                            <input type="text" id="post_code" name="post_code" class="form-control" placeholder="Enter post code" value="{{ old('post_code', optional($user->userInformations)->post_code) }}">
                                        </div>
                                    </div>

                                    <div class="col-sm-6">
                                        <div class="form-group">
                                            <label for="dob">Date of Birth</label>
                                            <input type="date" id="dob" name="dob" class="form-control" value="{{ old('dob', optional($user->userInformations)->dob) }}" min="{{ \Carbon\Carbon::now()->subYears(100)->format('Y-m-d') }}" max="{{ \Carbon\Carbon::now()->subYears(14)->format('Y-m-d') }}">
                                        </div>
                                    </div>

                                            <div class="col-sm-12">
                                        <div class="form-group">
                                            <div class="custom-control custom-checkbox mr-sm-2 m-b-15">
                                                <input type="checkbox" class="custom-control-input" name="status" id="checkbox0" value="1" {{ old('status', $user->status) ? 'checked' : '' }}>
                                                <label class="custom-control-label" for="checkbox0">Is Active</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-12">
                                        <button type="submit" class="btn btn-primary">Update</button>
                                        <a href="{{ route('serviceProvider') }}"
                                        class="btn btn-secondary">Back</a>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>


<script>
    document.addEventListener('DOMContentLoaded', function() {

    $(document).ready(function() {
        $.validator.addMethod("regex", function(value, element, regexp) {
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        }, "Please enter a valid email address.");

        $.validator.addMethod("strongPassword", function(value, element) {
            return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/.test(value);
        }, "Password must contain at least one uppercase letter, one lowercase letter, one numeric digit, one special character, and be at least 8 characters long.");

        $.validator.addMethod("noOnlySpaces", function(value, element) {
            return $.trim(value).length !== 0;
        }, "Please enter a value other than spaces.");

        $.validator.addMethod("minAge", function(value, element, minAge) {
                var today = new Date();
                var birthDate = new Date(value);
                var age = today.getFullYear() - birthDate.getFullYear();
                var m = today.getMonth() - birthDate.getMonth();
                if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
                    age--;
                }
                return this.optional(element) || age >= minAge;
            }, "You must be at least 14 years old.");

        $('#form').validate({
            rules: {
                first_name: {
                    required: true,
                    maxlength: 50,
                    noOnlySpaces: true
                },
                last_name: {
                    required: true,
                    maxlength: 50,
                    noOnlySpaces: true
                },
                email: {
                    required: true,
                    noOnlySpaces: true,
                email: true,
                remote: {
                    url: "{{ route('serviceProvider.checkEmail') }}",
                    type: "get",
                    data: {
                        email: function() {
                            return $("#email").val();
                        },
                        id: "{{ $user->id }}"
                    }
                }
                },
                phone: {
                    required: true,
                    minlength: 7,
                    maxlength: 15,
                    noOnlySpaces: true,
                    number: true
                },
                address: {
                    // required: true,
                    maxlength: 255,
                    // noOnlySpaces: true
                },
                // city_id: {
                //     required: true
                // },
                // state_id: {
                //     required: true
                // },
                // country_id: {
                //     required: true
                // },
                post_code: {
                    // required: true,
                    maxlength: 10,
                    // noOnlySpaces: true,
                    number: true
                },
                dob: {
                    // required: true,
                    date: true,
                    minAge: 14
                },
                password: {
                    required: true,
                    maxlength: 100,
                    noOnlySpaces: true,
                    strongPassword: true
                },
                password_confirmation: {
                    required: true,
                    noOnlySpaces: true,
                    maxlength: 100,
                    equalTo: "#password"
                },
                mobile_country_id: {
                    required: true,
                    noOnlySpaces: true
                },
                is_email_verified: {
                    required: true,
                    noOnlySpaces: true
                }
            },
            messages: {
                email: {
                    required: "Email is required",
                    email: "Please enter a valid email address",
                    remote: "Email already exists"
                },
        password_confirmation:{
            equalTo:"Passwords do not match."
        },
        post_code:{
            maxlength: "Please enter no more than 10 digits.",
            number:'Please enter a valid post code'
        },
        phone: {
            required: "Mobile number is required.",
            minlength: "Mobile number must be at least 7 digits long.",
            maxlength: "Mobile number cannot exceed 15 digits.",
            number: "Please enter a valid mobile number (digits only)."
        },
            },
            highlight: function(element) {
                $(element).addClass('is-invalid').removeClass('is-valid');
            },
            unhighlight: function(element) {
                $(element).removeClass('is-invalid').addClass('is-valid');
            },
            submitHandler: function(form) {
                // Disable the submit button to prevent multiple submissions
                $(form).find('button[type="submit"]').attr("disabled", true);

                // Submit the form
                form.submit();
            }
        });

        $('.toggle-password').click(function() {
            var passwordInput = $(this).closest('.form-group').find('.password-toggle');
            var passwordIcon = $(this).find('i');

            if (passwordInput.attr('type') === 'password') {
                passwordInput.attr('type', 'text');
                passwordIcon.removeClass('fa-eye').addClass('fa-eye-slash');
            } else {
                passwordInput.attr('type', 'password');
                passwordIcon.removeClass('fa-eye-slash').addClass('fa-eye');
            }
            var today = new Date();
            var minDate = new Date(today.getFullYear() - 100, today.getMonth(), today.getDate());
            var maxDate = new Date(today.getFullYear() - 14, today.getMonth(), today.getDate());

            $('#dob').attr('min', minDate.toISOString().split('T')[0]);
            $('#dob').attr('max', maxDate.toISOString().split('T')[0]);
        });

        $(document).on('change', '#country_id', function() {
            $('#state_id').empty().append('<option value="">Select State</option>');
            $('#city_id').empty().append('<option value="">Select City</option>');
            var countryId = $(this).val();
            $.ajax({
                url: '{{ route('serviceProvider.stateList') }}', // Named route
                type: 'GET',
                data: { country_id: countryId }, // Replace with the actual country ID
                success: function(response) {
                    if (response.status === 'success') {
                        var stateSelect = $('#state_id');
                        stateSelect.empty(); // Clear the existing options
                        stateSelect.append('<option value="">Select State</option>'); // Add the default option

                        $.each(response.data, function(index, state) {
                            stateSelect.append('<option value="' + state.id + '">' + state.name + '</option>');
                        });
                    } else {
                        alert('No states found for the selected country.');
                    }
                },
                error: function(xhr) {
                    console.error('Request failed:', xhr);
                }
            });
        });

        $(document).on('change', '#state_id', function() {
             $('#city_id').empty().append('<option value="">Select City</option>');
            var stateId = $(this).val();
            $.ajax({
                url: '{{ route('serviceProvider.cityList') }}', // Named route
                type: 'GET',
                data: { state_id: stateId }, // Replace with the actual country ID
                success: function(response) {
                    if (response.status === 'success') {
                        var citySelect = $('#city_id');
                        citySelect.empty(); // Clear the existing options
                        citySelect.append('<option value="">Select City</option>'); // Add the default option

                        $.each(response.data, function(index, city) {
                            citySelect.append('<option value="' + city.id + '">' + city.name + '</option>');
                        });
                    } else {
                        alert('No city found for the selected country.');
                    }
                },
                error: function(xhr) {
                    console.error('Request failed:', xhr);
                }
            });
        });
    });
});
</script>

@endsection
