@extends('frontend.layouts.app')

@section('content')
@php
    $breadCrump2 = 'Service Listing';
@endphp

<!--Job listing start -->
<div class="wrapper-inner">
    <div class="job-listing">
      <div class="container">
        <h3 class="mb-md-4 mb-xl-5 job-title">Recommended Services</h3>
        <div class="villalistcarduper d-flex align-items-center justify-content-between">
          <div class="villalistcarduperlt d-flex align-items-center">
            <a href="javascript:void(0)">  <img src="{{asset('frontend/images/sorticon.png')}}" alt="sorticon"></a>

            <div class="sortbyebx d-flex align-items-center">
                <span class="sorttxt">Sort by: </span>
                <select id="sortFilter">
                    <option value="relevance">Relevance</option>
                    <option value="date_latest" {{(request('sorting')=="date_latest")? 'selected':''}}>Date Latest</option> <!-- This can mean the most recently posted jobs -->
                    <option value="date_oldest" {{(request('sorting')=="date_oldest")? 'selected':''}}>Date Oldest</option> <!-- Added this for clarity -->
                    <option value="rate_high_to_low" {{(request('sorting')=="rate_high_to_low")? 'selected':''}}>Rate: High to Low</option> <!-- Clarified sorting order -->
                    <option value="rate_low_to_high" {{(request('sorting')=="rate_low_to_high")? 'selected':''}}>Rate: Low to High</option> <!-- Added this option for flexibility -->
                </select>
            </div>

               <div class="filter-dropdown">
                <form action="{{ route('employer.service.list') }}">
                    <div class="filter-head">
                        <div class="filter-title"> Filter By</div>
                    </div>
                    <div class="keyword-box">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group topbrsearch">
                                    <label>Keywords </label>
                                    <input type="text" class="form-control" name="keywords"
                                        placeholder="Service Title" value="{{ request('keywords') }}">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>Service Category</label>
                                    <select class="form-control" name="category_id">
                                        <option value="">Select</option>
                                        @foreach ($categories as $cat => $category)
                                            <option value="{{ $cat }}"
                                                {{ request('category_id') == $cat ? 'selected' : '' }}>
                                                {{ $category }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <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 }}"
                                                {{ request('country_id') == $country->id ? 'selected' : '' }}>
                                                {{ $country->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <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>
                                        <!-- Populate states based on selected country (if applicable) -->
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <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>
                                        <!-- Populate cities based on selected state (if applicable) -->
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex align-items-center justify-content-between">
                        <button class="btn-custom">Apply Now</button>
                        <a href="{{ route('employer.service.list') }}" class="btn-custom">Reset Filter</a>
                    </div>
                </form>

            </div>
          </div>
          <a href="javascript:void(0)" class="filter-btn"> <i><img src="{{asset('frontend/images/filter-icon.png')}}" alt="filter-icon"></i>Filter By</a>
        </div>
         <div class="row">

            @foreach ($services as $service)
          <div class="col-lg-4 col-sm-6">
            <div class="recent-card">
              <div class="recent-img">
                <div class="recent-tp-tag">
                  <span class="businessTag">{{$service->category?->title}}</span>
                  {{-- <span class="availTag"></span> --}}
                </div>

                @if($service->category?->image)
                <img src="{{asset('backend/category/'.$service->category?->image)}}" alt="recent-img01">
                @else
                <img src="{{ asset('frontend/images/recent-img04.jpg') }}" alt="recent-img01">

                @endif

              </div>
              <div class="recent-info">
                <h4 class="mb-2"> <a href="{{route('employer.service.detail',$service->id)}}">{{$service->title}}</a> </h4>
                <div class="location-text mb-2"> <i><img src="{{asset('frontend/images/recent-location.png')}}" alt="recent-location"></i>
                  {{$service->city?->name.', '.$service->state?->name.', '.$service->country?->name}}</div>
                <p>{!! strlen($service->description) > 200 ? substr($service->description, 0, 200) . '...' : $service->description !!}</p>
                <div class="d-flex justify-content-between align-items-center">
                  <div class="recentprice">
                    <span> Per Hour Rate </span>
                    @if(floatval($service->discounted_amount==0))
                    <strong> ${{$service->pricing}}</strong>
                    @else
                    <strong> <del>${{$service->pricing}}</del> ${{$service->discounted_amount}}</strong>
                    @endif
                  </div>
                  @if(auth()->guard('employer')->check())
                  <a href="{{route('employer.service.book',$service->id)}}" class="btn-custom"> Book Now</a>
                    @elseif(!auth()->guard('employer')->check())
                    @else
                    <a href="{{ route('users.login').'?serviceid='.$service->id }}" class="btn-custom">Book Now</a>
                    @endif
                </div>
              </div>
            </div>
          </div>
          @endforeach


         </div>
         <div class="d-flex justify-content-center">
            <ul class="pagination">
                {{-- Previous Page Link --}}
                @if ($services->onFirstPage())
                    <li class="page-item disabled">
                        <span class="page-link"><i class="arrow left"></i> Prev</span>
                    </li>
                @else
                    <li class="page-item">
                        <a class="page-link" href="{{ $services->previousPageUrl() }}"><i class="arrow left"></i>
                            Prev</a>
                    </li>
                @endif

                {{-- Pagination Elements --}}
                @for ($i = 1; $i <= $services->lastPage(); $i++)
                    @if ($i == $services->currentPage())
                        <li class="page-item active">
                            <span class="page-link">{{ $i }}</span>
                        </li>
                    @else
                        <li class="page-item">
                            <a class="page-link" href="{{ $services->url($i) }}">{{ $i }}</a>
                        </li>
                    @endif
                @endfor

                {{-- Next Page Link --}}
                @if ($services->hasMorePages())
                    <li class="page-item">
                        <a class="page-link" href="{{ $services->nextPageUrl() }}">Next <i
                                class="arrow right"></i></a>
                    </li>
                @else
                    <li class="page-item disabled">
                        <span class="page-link">Next <i class="arrow right"></i></span>
                    </li>
                @endif
            </ul>
        </div>
      </div>

    </div>

    </div>
    <!-- Job listing start -->
@endsection
@push('front-script')
<script>
       $('#sortFilter').on('change', function() {
        var selectedValue = $(this).val(); // Get the selected value
        if (selectedValue != null && selectedValue) {
            var currentUrl = window.location.href;
            var newUrl;

            // Create a URL object to manipulate the query parameters easily
            if (currentUrl.includes('?')) {
                // If it has, use '&' to append the sorting parameter
                currentUrl = currentUrl + '&sorting=' + selectedValue;
            } else {
                // If it doesn't, use '?' to append the sorting parameter
                currentUrl = currentUrl + '?sorting=' + selectedValue;
            }
            var url = new URL(currentUrl);

            if (url.searchParams.has('sorting')) {
                // If it exists, update its value
                url.searchParams.set('sorting', selectedValue);
            } else {
                // If it doesn't exist, add it
                url.searchParams.append('sorting', selectedValue);
            }

            window.location.href = url.toString();
            // Check if the current URL already has a '?'
        }

        
    });
    
    $(document).ready(function() {
        // Load States based on selected country
        function loadStates(countryId) {
                $.ajax({
                    url: '{{ route('stateList') }}', // Named route
                    type: 'GET',
                    data: {
                        country_id: countryId
                    },
                    success: function(response) {
                        if (response.status === 'success') {
                            var stateSelect = $('#state_id');
                            stateSelect.empty();
                            stateSelect.append('<option value="">Select State</option>');

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

                            // Preselect the user's state if it exists
                            @if (isset(auth()->guard('service_provider')->user()?->userInformations) && auth()->guard('service_provider')->user()?->userInformations?->state)
                                stateSelect.val({{ auth()->guard('service_provider')->user()?->userInformations?->state->id }});
                            @endif
                        }
                    },
                    error: function(xhr) {
                        console.error('Request failed:', xhr);
                    }
                });
            }

            // Load Cities based on selected state
            function loadCities(stateId) {
                $.ajax({
                    url: '{{ route('cityList') }}', // Named route
                    type: 'GET',
                    data: {
                        state_id: stateId
                    },
                    success: function(response) {
                        if (response.status === 'success') {
                            var citySelect = $('#city_id');
                            citySelect.empty();
                            citySelect.append('<option value="">Select City</option>');

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

                            // Preselect the user's city if it exists
                            @if (isset(auth()->guard('service_provider')->user()?->userInformations) && auth()->guard('service_provider')->user()?->userInformations?->city)
                                citySelect.val({{ auth()->guard('service_provider')->user()?->userInformations?->city->id }});
                            @endif
                        }
                    },
                    error: function(xhr) {
                        console.error('Request failed:', xhr);
                    }
                });
            }

            // Load states when the country is selected
            $('#country_id').change(function() {
                var countryId = $(this).val();
                loadStates(countryId);
            });

            // Load cities when the state is selected
            $('#state_id').change(function() {
                var stateId = $(this).val();
                loadCities(stateId);
            });

            // Initial load based on user's country
            var initialCountryId =
                "{{ old('country_id', optional(auth()->guard('service_provider')->user()?->userInformations)?->country_id) }}";
            if (initialCountryId) {
                loadStates(initialCountryId);
            }

            // Initial load for cities if the state is already selected
            var initialStateId = "{{ old('state_id', optional(auth()->guard('service_provider')->user()?->userInformations)?->state_id) }}";
            if (initialStateId) {
                loadCities(initialStateId);
            }


            $(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('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('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>
@endpush
