@extends('frontend.layouts.app')

@section('content')
@php
    $breadCrump2 = 'Job Posting';
@endphp
{{-- <style>
    .select2-container--default .select2-selection--multiple {
    border: 1px solid #ced4da; /* Match input border */
    border-radius: .25rem; /* Match input border radius */
    padding: 0.4em; /* Add padding to the entire selection area */
}

.select2-container--default .select2-selection--multiple .select2-selection__choice {
    margin: 0 0.2em; /* Add margin between choices */
    padding: 0.2em 0.5em; /* Add padding for choices */
}

.select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
    color: #dc3545; /* Cross button color */
    margin-left: 0.5em; /* Add space before the cross sign */
}--}}
    <style>
.select2-selection--multiple{
    padding: 11px !important;
}
</style>

<div class="wrapper-inner">
    <div class="container">
        <div class="apply-job">
            <div class="headingBlock d-flex align-items-center justify-content-between">
                <h4>Job Posting</h4>
            </div>

            @if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
            <form action="{{ route('employer.jobPost.submit') }}" method="POST">
                @csrf <!-- CSRF protection -->
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="required">Job Title</label>
                            <input type="text" name="title" class="form-control @error('title') is-invalid @enderror" placeholder="Enter Title" value="{{ old('title') }}">
                            @error('title')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>


                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="required">Employment Type</label>
                            <select name="employment_type_id" class="form-control @error('employment_type_id') is-invalid @enderror">
                                <option value="">Select</option>
                                {{-- category
skill --}}
                                @foreach ($employmentTypes as $etid => $employmentType)
                                <option value="{{$etid}}" {{ old('employment_type_id') ? 'selected' : '' }}>{{$employmentType}}</option>
                                @endforeach
                            </select>
                            @error('employment_type_id')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>

                         <div class="col-md-4">
                        <div class="form-group">
                                <label class="required" for="country_id">Country</label>
                                <select id="country_id"  name="country_id" class="form-control @error('country_id') is-invalid @enderror">
                                    <option value="">Select Country</option>
                                    @foreach($countries as $country)
                                        <option value="{{ $country->id }}">{{ $country->name }}</option>
                                    @endforeach
                                </select>
                                @error('country_id')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                            </div>
                        </div>
                             <div class="col-md-4">
                        <div class="form-group">
                                <label class="required" for="state_id">State</label>
                                <select id="state_id" name="state_id" class="form-control @error('state_id') is-invalid @enderror">
                                    <option value="">Select State</option>
                                </select>
                                @error('state_id')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="required" for="city_id">City</label>
                                <select id="city_id" name="city_id" class="form-control @error('city_id') is-invalid @enderror">
                                    <option value="">Select City</option>
                                </select>
                                @error('city_id')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="required" for="address">Address</label>
                                <input type="text" id="address" name="address" class="form-control @error('address') is-invalid @enderror" placeholder="Enter address" value="{{ old('address') }}">
                                @error('address')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                            </div>
                        </div>







                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="required">Salary Range</label>
                            <select id="salary_range" name="salary_range" class="form-control @error('salary_range') is-invalid @enderror">
                                <option value="">Select Salary Range</option>
                                <option {{ old('salary_range')=='10000-20000' ? 'selected' : '' }} value="10000-20000">10000-20000</option>
                                <option {{ old('salary_range')=='20000-40000' ? 'selected' : '' }} value="20000-40000">20000-40000</option>
                                <option {{ old('salary_range')=='50000-70000' ? 'selected' : '' }} value="50000-70000">50000-70000</option>
                                <option {{ old('salary_range')=='70000-90000' ? 'selected' : '' }} value="70000-90000">70000-90000</option>
                            </select>
                            @error('salary_range')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="required">Job Category & Subcategory</label>
                            <select name="category_id" class="form-control @error('category_id') is-invalid @enderror">
                                <option value="">Select</option>
                                @foreach ($categories as $cat => $category)
                                <option value="{{$cat}}" {{ old('category_id') ? 'selected' : '' }}>{{$category}}</option>
                                @endforeach
                            </select>
                            @error('category_id')
                            <span class="invalid-feedback">{{ $message }}</span>
                        @enderror
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="required">Experience Level</label>
                            <select name="experience_level" class="form-control @error('experience_level') is-invalid @enderror">
                                <option value="">Select</option>
                                <option value="Entry" {{ old('experience_level') == 'Entry' ? 'selected' : '' }}>Entry</option>
                                <option value="Mid" {{ old('experience_level') == 'Mid' ? 'selected' : '' }}>Mid</option>
                                <option value="Senior" {{ old('experience_level') == 'Senior' ? 'selected' : '' }}>Senior</option>
                                <option value="Executive" {{ old('experience_level') == 'Executive' ? 'selected' : '' }}>Executive</option>
                            </select>
                            @error('experience_level')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="required">Number of Positions</label>
                            <input type="number" name="no_of_positions" class="form-control @error('no_of_positions') is-invalid @enderror" placeholder="Enter Number" value="{{ old('no_of_positions') }}">
                            @error('no_of_positions')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="required">Education & Qualification</label>
                            {{-- <input type="text" name="qualification" class="form-control @error('qualification') is-invalid @enderror" placeholder="Enter Qualification" value="{{ old('qualification') }}"> --}}
                            <select name="qualification" class="form-control" required>
                                <option value="">Select Education & Qualification</option>
                                    @foreach ($education_qualification as $key => $item)
                                        <option value="{{ $key }}" {{ ($user->userInformations?->qualification ?? '') == $key ? 'selected' : '' }}>
                                        {{ $item }}  </option>
                                @endforeach
                            </select>

                            @error('qualification')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="required">Application Deadline</label>
                                {{-- <input type="text" id="start_deadline" name="start_deadline" class="form-control @error('start_deadline') is-invalid @enderror" value="{{ old('start_deadline') }}" placeholder="Start Date"> --}}
                                <input type="text" id="deadline" name="deadline" class="form-control @error('deadline') is-invalid @enderror" value="{{ old('deadline') }}" placeholder="End Date">
                                @error('deadline')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                            {{-- @error('start_deadline')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror --}}
                            {{-- @error('deadline')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror --}}
                        </div>
                    </div>


                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="required">Skills Required</label>
                            <select name="skill_id[]" id="skills" class="form-control @error('skill_id') is-invalid @enderror" multiple>
                                <option value="">Select Skills</option>
                                @foreach ($skills as $s => $skill)
                                    <option value="{{ $s }}" {{ (is_array(old('skill_id')) && in_array($s, old('skill_id'))) ? 'selected' : '' }}>
                                        {{ $skill }}
                                    </option>
                                @endforeach
                            </select>
                            @error('skill_id')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>

                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="required">Work Place</label>
                            <select name="work_place" id="work_place" class="form-control @error('work_place') is-invalid @enderror">
                                <option value="">Select Work Place</option>
                                    <option name="work_place" value="in-place" {{ (is_array(old('work_place'))=='in-place') ? 'selected' : '' }}>
                                        In Place
                                    </option>
                                    <option name="work_place" value="remote" {{ (is_array(old('work_place'))=='remote') ? 'selected' : '' }}>
                                        Remote
                                    </option>
                                    <option name="work_place" value="on-site" {{ (is_array(old('work_place'))=='on-site') ? 'selected' : '' }}>
                                        On Site
                                    </option>
                                    <option name="work_place" value="hybrid" {{ (is_array(old('work_place'))=='hybrid') ? 'selected' : '' }}>
                                        Hybrid
                                    </option>

                            </select>
                            @error('work_place')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>



                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="required">Application Process</label>
                            <select name="application_process" class="form-control @error('application_process') is-invalid @enderror">
                                <option value="">Select Application Process</option>
                                <option value="direct" {{ old('application_process') == 'direct' ? 'selected' : '' }}>Direct apply</option>
                                <option value="external" {{ old('application_process') == 'external' ? 'selected' : '' }}>External link</option>
                                <option value="email" {{ old('application_process') == 'email' ? 'selected' : '' }}>Email applications</option>
                            </select>
                            @error('application_process')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="required">Screening Questions</label>
                            <div id="screening-questions-container">
                                <div class="screening-question">
                                    <input type="text" name="screening_questions[]" class="form-control @error('screening_questions.*') is-invalid @enderror" placeholder="Enter Screening Question" value="{{ old('screening_questions.0') }}">
                                    @error('screening_questions.*')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror

                                </div>
                            </div>
                            <button type="button" id="add-question" class="btn btn-secondary mt-2">+</button>
                        </div>
                    </div>

                    <div class="col-md-12">
                        <div class="form-group">
                            <label>Job Description</label>
                            <textarea id="description" name="description" rows="4" class="form-control @error('description') is-invalid @enderror" placeholder="Your message">{{ old('description') }}</textarea>
                            @error('description')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                    </div>




                </div>
                <div class="apply-btn">
                    <button type="submit" class="btn-custom">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection


@push('front-script')
<script>

$(document).ready(function() {
    // Existing code...

    // Form validation
    $("form").validate({
        rules: {
            title: {
                required: true,
                minlength: 3,
                maxlength: 150
            },
            employment_type_id: {
                required: true
            },
            country_id: {
                required: true
            },
            state_id: {
                required: true
            },
            city_id: {
                required: true
            },
            address: {
                required: true,
                minlength: 3,
                maxlength: 150
            },
            salary_range: {
                required: true
            },
            category_id: {
                required: true
            },
            experience_level: {
                required: true
            },
            no_of_positions: {
                required: true,
                min: 1
            },
            qualification: {
                required: true,
            },
            deadline: {
                required: true
            },
            'screening_questions[]': {
                required: function() {
                    // Check if at least one screening question is filled
                    return $('input[name="screening_questions[]"]').filter(function() {
                        return $(this).val().trim() !== ""; // Non-empty check
                    }).length === 0; // If none are filled, return true (requirement met)
                }
            },
            // description: {
            //     required: true,
            //     maxlength: 1000
            // },
            'skill_id[]': {
                required: true,
            },
            work_place: {
                required: true
            },
            application_process: {
                required: true
            }
        },
        messages: {
            title: {
                required: "Job title is required",
                minlength: "Job title must be at least 3 characters long",
                maxlength: "Job title cannot exceed 150 characters"
            },
            employment_type_id: "Employment type is required",
            country_id: "Country is required",
            state_id: "State is required",
            city_id: "City is required",
            address: {
                required: "Address is required",
                minlength: "Address must be at least 3 characters long",
                maxlength: "Address cannot exceed 150 characters"
            },
            salary_range: "Salary range is required",
            category_id: "Job category is required",
            experience_level: "Experience level is required",
            no_of_positions: {
                required: "Number of positions is required",
                min: "Number of positions must be at least 1"
            },
            qualification: {
                required: "Qualification is required",
                minlength: "Qualification must be at least 3 characters long",
                maxlength: "Qualification cannot exceed 150 characters"
            },
            deadline: "Application deadline is required",
            'screening_questions[]': {
                required: "Screening questions are required",
                minlength: "Each screening question must be at least 3 characters long",
                maxlength: "Screening question cannot exceed 150 characters"
            },
            description: {
                required: "Job description is required",
                maxlength: "Job description cannot exceed 1000 characters"
            },
            skill_id: "At least one skill is required",
            work_place: "Work place is required",
            application_process: "Application process is required"
        },
        errorPlacement: function(error, element) {
            // Custom placement for multi-select skills
            error.appendTo(element.parent());
            if (element.attr("name") === 'skill_id[]') {
                error.appendTo(element.parent());
            } else {
                error.appendTo(element.closest('.screening-question')); // For screening questions
            }
            // element.addClass('error'); // Add error class to the element
        },
        success: function(label, element) {
            $(element).removeClass('error'); // Remove error class on success
            label.remove(); // Remove the error message
        }
    });
});


$('#skills').on('change', function () {
        // Revalidate the field
        $(this).valid();
    });

    CKEDITOR.replace('description');
      document.addEventListener('DOMContentLoaded', function() {
      $(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);
                }
            });
        });
        $('#skills').select2({
    placeholder: "Select Skills",
    allowClear: true // Allow clearing the selection
});



let questionIndex = 1; // Start from 1 since 0 is already used

// Function to add a new screening question
$('#add-question').click(function() {
    const newQuestion = `
        <div class="screening-question mt-2">
            <input type="text" inputId =${questionIndex}  name="screening_questions[]" class="form-control" placeholder="Enter Screening Question" value="{{ old('screening_questions.${questionIndex}') }}">
            <button type="button" class="btn btn-danger btn-sm remove-question mt-1">-</button>
        </div>
    `;

    // Append the new input field to the container
    $('#screening-questions-container').append(newQuestion);
    questionIndex++;
});

// Function to remove a screening question
$(document).on('click', '.remove-question', function() {
    var screen_quest = $(this).closest('.screening-question');
    if(screen_quest.children()?.attr('inputId')!=undefined){
        screen_quest.remove();
    }

    // .remove()
});



// flatpickr("#start_deadline", {
//             dateFormat: "Y-m-d", // Format for backend
//             onChange: function(selectedDates) {
//                 let startDate = selectedDates[0];
//                 flatpickr("#deadline", {
//                     minDate: startDate // Set minimum date for end date
//                 });
//             }
//         });

        flatpickr("#deadline", {
            dateFormat: "Y-m-d",
            minDate: new Date().fp_incr(1)  // Format for backend
        });

});




</script>
@endpush
