@extends('frontend.layouts.app')

@section('content')
@php
    $excludeBreadcrumb = true;
@endphp
<div class="wrapper-inner">
    <div class="job-listing">
      <div class="container">
        <h3 class="mb-md-4 mb-xl-5 job-title">Recommended blogs</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 -->

                </select>

            </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 ($blogs as $blog)

        <div class="col-md-4">
            <div class="blogcard" style="margin-bottom:5px;">
              <div class="cardImg mb-4">
                <a href="#!">
                    @if($blog->cover_letter)
                    <img style="height:290px" src="{{asset('images/blogs/coverletter/'.$blog->cover_letter)}}" alt="blog-img">
                    @else
                    <img style="height:290px" src="{{asset('images/blogs/default.jpg')}}" alt="blog-img">
                    @endif
                </a>
              </div>

              <div class="cardInfo">
                <ul class="d-flex mb-3">
                  <li><i class="far fa-calendar" style="margin-right: 5px;"></i>{{$blog->created_at->format('M d Y')}}</li>
                  <li><i class="far fa-user"></i> Post by: <strong>{{$blog->name}}</strong></li>
                </ul>
                <h4> <a href="#!">{{$blog->title}}</a></h4>

                <a href="{{route('blog.detail',$blog->slug)}}" class="btn btn-orange-outline">Read More <i class="ml-2"><img
                      src="{{asset('frontend/images/read-arrow.png')}}" alt="read-arrow"></i></a>
              </div>
            </div>
          </div>
            @endforeach
        </div>
    <!-- Pagination -->
    @if($blogs->isNotEmpty())
<div class="d-flex justify-content-center">
    <ul class="pagination">
        {{-- Previous Page Link --}}
        @if ($blogs->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="{{ $blogs->previousPageUrl() }}"><i class="arrow left"></i> Prev</a>
            </li>
        @endif

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

        {{-- Next Page Link --}}
        @if ($blogs->hasMorePages())
            <li class="page-item">
                <a class="page-link" href="{{ $blogs->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>
@else
<h2 colspan="10" class="text-center" style="font-weight: bold;">No record found !</h2>
@endif

      </div>

    </div>

    </div>
@endsection
<script>
       document.addEventListener('DOMContentLoaded', function() {


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

        //             if("{{request('country_id')}}"==''){
        //     alert('shubham');
        // }
                    // Preselect the user's state if it exists
                    @if("{{request('state_id')}}"!='')
                        stateSelect.val({{request('state_id')}});
                    @endif
                }
            },
            error: function(xhr) {
                console.error('Request failed:', xhr);
            }
        });
    }

    // Load cities based on the 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>');
                    });

                    @if("{{request('city_id')}}"!='')
                        citySelect.val({{request('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);
    });



    var initialCountryId = "{{ old('country_id', request('country_id')?? '') }}";
    if (initialCountryId) {
        loadStates(initialCountryId);
    }


    var initialStateId = "{{ old('state_id', request('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();
            console.log(countryId);
            $.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);
                }
            });
        });


        $('#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 '?'

                }

            });
    });
</script>
