@extends('frontend.layouts.app')
@section('content')
@php
    $breadCrump2 = 'Active Job';
    use Carbon\Carbon; // Import Carbon once

@endphp

<style>.profile-menu {
    list-style-type: none;
    padding: 0;
}

.profile-menu li {
    position: relative;
}

.dropbtn {
    display: block;
    /* padding: 10px; */
    text-decoration: none;
}

.dropdown-content {
    display: none;
    position: absolute;
    background-color: white;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown:hover .dropdown-content {
    display: block;
}

</style>

  <!--Job alerts start -->
  <!--Job alerts start -->
<div class="wrapper-inner">
  <div class="container">
    <div class="profile-dash">
      @include('frontend.employer.sidebar')
      <div class="profile-dash-rt">
        <div class="my-profile-inner">
          <div class="headingBlock d-flex align-items-center justify-content-between">
              <h4>My Jobs</h4>
              <form id="filterForm" action="{{route('employer.active.job')}}">
                <div class="job-filter-box">
                    <select class="form-control" name="filter" onchange="submitFilter(this)">
                        <option value="" >Filter</option>
                        <option value="1" {{(request()->filter=="1")? "SELECTED":""}} >Active</option>
                        <option value="0" {{(request()->filter=="0")? "SELECTED":""}} >InActive</option>
                      <option value="3" {{(request()->filter=="3")? "SELECTED":""}} >Expired</option>
                    </select>
                  </div>
                </form>
          </div>
          <div class="table-responsive my-job-table employer-job-table">
            <table class="custom-table table table-condensed">
                <tr>
                    <th>Job Name</th>
                    <th>Location</th>
                    <th>Date</th>
                    <th>Employment</th>
                    <th>Salary</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
                @if($allJobs->isEmpty())
                <tr>
                    <td colspan="7" class="text-center" style="font-weight: bold;">No record found !</td>
                </tr>
                @else

                @foreach ($allJobs as $job)
                @php
                    $deadline = \Carbon\Carbon::parse($job->deadline);
                @endphp
                    <tr>
                        <td>
                            <div class="d-flex align-items-center">
                                <div class="job_img">
                                    @if($job->category?->image)
                                    <img src="{{asset('backend/category/'.$job->category?->image)}}" alt="">
                                    @else
                                    <img src="{{ asset('frontend/images/recent-img04.jpg') }}"
                                        alt="logo">
                                    @endif
                                </div>
                                <div class="job_info">
                                    <small>{{ $job->category ? $job->category->title : '' }}</small>
                                    <div class="designation-box"><a href="{{route('employer.job.detail',$job->id)}}"><strong>{{ $job->title }}</strong></a></div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <img src="{{ asset('frontend/images/icon-location.png') }}" alt="location">
                            {{
                                ($job->address ?? '') . ',' .
                                ($job->city?->name ?? '') . ',' .
                                ($job->state?->name ?? '') . ',' .
                                ($job->country?->name ?? '')
                            }}
                        </td>
                        @php
                        $createdAt = $job->created_at;
                        // Format the created_at date using Carbon
                        $formattedDate = $createdAt ? \Carbon\Carbon::parse($createdAt)->format(config('GET.front_date_format', 'd-m-Y'))
                        : 'N/A'; //



                            $min = 0;
                            $max = 0;
                            if ($job->salary_range) {
                                list($min, $max) = explode('-', $job->salary_range);
                            }
                        @endphp
                        <td>{{ $formattedDate }}</td>
                        <td>
                            <a href="#!" class="btn-custom">{{ $job->employmentType?->title }}</a>
                        </td>
                        <td>${{ number_format($min) }} - ${{ number_format($max) }}</td>
                        <td>
                            @if ($deadline->isPast())


                            <a href="#!" class="btn-custom btn interviews-bg" data-job-id="{{ $job->id }}">Expired</a>
                            @else
                             @if ($job->status == 1 )
                                <a href="#!" class="btn-custom btn approved-bg change-status" data-job-id="{{ $job->id }}">Active</a>
                            @elseif ($job->status == 0)
                            <a href="#!" class="btn-custom btn rejected-bg change-status" data-job-id="{{ $job->id }}">Inactive</a>
                            @endif

                                @endif
                        </td>
                        <td>

                            <a href="{{route('employer.edit.job',$job->id)}}" class="btn-custom btn interviews-bg action-btn">Edit </a>
                            <button ty="#" class="delete-button btn-custom btn rejected-bg action-btn" data-id="{{ $job->id }}">Delete</a>
                          </td>
                    </tr>
                @endforeach
                @endif
            </table>
            <div class="pagination-wrapper">

                {{ $allJobs->links('frontend.layouts.pagination') }}

            </div>
        </div>
        </div>
      </div>
    </div>
  </div>
</div>



<div class="deleteModal modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="deleteForm" method="POST">
                @csrf
                @method('DELETE')
                <div class="modal-body">
                    <p>Are you sure you want to delete this record?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" onclick="hideButtonAndDismiss(this)" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </div>
            </form>
        </div>
    </div>
</div>
<!-- Job alerts start -->
  <!-- Job alerts start -->
@include('frontend.layouts.modal', [
    'title' => 'Change Job Status',
    'message' => 'Are you sure you want to change the job status?',
    'confirmText' => 'Yes, Change Status'
])
@include('frontend.layouts.successModal', [
    'message' => 'Status updated successfully!'
])


@endsection
@push('front-script')
<script>
   $(document).ready(function() {
    var jobId; // Store job ID
    var newStatus; // Store new status

    $('.change-status').on('click', function(e) {
        e.preventDefault(); // Prevent default anchor click behavior

        var $this = $(this);
        jobId = $this.data('job-id'); // Get job ID
        var currentStatus = $this.text().trim(); // Get current status text

        // Determine new status
        newStatus = currentStatus === 'Active' ? 'Inactive' : 'Active';
        status = currentStatus === 'Active' ? 0 : 1;

        // Set the modal message
        $('#modal-message').text("Are you sure you want to change the status to " + newStatus + "?");

        // Show the modal
        $('#statusChangeModal').modal('show');


    });

    // Handle confirmation button click
    $('#confirmChange').on('click', function() {

        // AJAX request to update the status
        $.ajax({
            url: '{{route("employer.job.status.change")}}', // Your route to handle the status update
            type: 'POST',
            data: {
                job_id: jobId,
                status: status,
                _token: '{{ csrf_token() }}' // Include CSRF token for protection
            },
            success: function(response) {
                if (response.success) {
                    // Update button text based on new status
                    var $button = $('.change-status[data-job-id="' + jobId + '"]');
        $button.text(newStatus);


                    if (newStatus === 'Inactive') {
            $button.removeClass('approved-bg').addClass('rejected-bg');
        } else {
            $button.removeClass('rejected-bg').addClass('approved-bg');
        }
                    // Optionally update the button style if needed
                    // $('.change-status[data-job-id="' + jobId + '"]').toggleClass('approved-bg inactive-bg');
                     $('#statusChangeModal').modal('hide');
                     $('#successModal').modal('show');
                } else {
                    alert('Failed to update status: ' + response.message);
                }
            },
            error: function(xhr) {
                console.error('Error updating status:', xhr);
                alert('An error occurred while updating the status.');
            }

            // Close the modal after the request

        });
    });




});
function submitFilter(selectElement) {
    const form = document.getElementById('filterForm');
    form.action = "{{ route('employer.active.job') }}" + '?status=' + selectElement.value;
    form.submit();
}


// Trigger modal for delete confirmation
$(document).on('click', '.delete-button', function (e) {
    e.preventDefault();

    let id = $(this).data('id'); // Get the service ID
    let url = `/employer/job/delete/${id}`; // Construct the delete URL

    // Set the action URL of the form in the modal
    $('#deleteForm').attr('action', url);

    // Show the delete confirmation modal
    $('.deleteModal').modal('show');
});



function hideButtonAndDismiss(button) {
    $('.deleteModal').modal('hide');
    $('.modal-backdrop').remove(); // Remove the backdrop manually
}


</script>
@endpush
