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

    <style>
        .select2-container--default .select2-selection--multiple {
            border: 1px solid #e7dfdf;
        }

        .select2-selection--multiple {
            padding: 10px !important;
        }

        .experience-entry {
            margin-bottom: 50px;
        }
    </style>
    <!--Job alerts start -->
    <!--Job alerts start -->
    <div class="wrapper-inner">
        <div class="container">
            <div class="profile-dash">
                @include('frontend.jobSeeker.sidebar')
                <div class="profile-dash-rt">
                    <div class="my-profile-inner">
                        <div class="headingBlock">
                            <h4>My Profile</h4>
                        </div>
                        <form method="post" action="{{ route('jobSeeker.profile.update') }}" id="profile-form"
                            enctype="multipart/form-data">
                            @csrf
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="required">First Name</label>
                                        <div class="form-group-input">
                                            <input type="text" name="first_name" class="form-control"
                                                placeholder="James Tim" minlength="3" maxlength="150"
                                                value="{{ $user->first_name ?? '' }}" required>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="required">Last Name</label>
                                        <div class="form-group-input">
                                            <input type="text" name="last_name" class="form-control" placeholder="Niro"
                                                minlength="3" maxlength="150" value="{{ $user->last_name ?? '' }}"
                                                required>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="required">Mobile</label>
                                        <div class="form-group-input">
                                            <input type="text" name="mobile" class="form-control" placeholder="Mobile"
                                                value="{{ $user->mobile ?? '' }}" required>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="required">Email</label>
                                        <div class="form-group-input">
                                            <input type="text" readonly name="email" class="form-control"
                                                placeholder="Email" value="{{ $user->email ?? '' }}" required>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="required">Resume Upload</label>
                                        <input type="file" name="resume" class="file" required>
                                        <div class="input-group mb-3 browse-bx">
                                            <input type="text" class="form-control" disabled placeholder="No file chosen"
                                                aria-label="No file chosen">
                                            <div class="input-group-append">
                                                <button type="button"
                                                    class="browse-resume input-group-text btn btn-primary"
                                                    id="basic-addon2">
                                                    Browse</button>
                                            </div>
                                        </div>
                                    </div>
                                    @if ($user->userInformations?->resume)
                                        @php
                                            $resumePath = $user->userInformations?->resume;
                                            $fileExtension = $resumePath
                                                ? pathinfo($resumePath, PATHINFO_EXTENSION)
                                                : null;

                                        @endphp
                                        @if ($fileExtension === 'doc' || $fileExtension === 'docx' || $fileExtension === 'pdf')
                                            <a target="_blank"
                                                href="{{ asset('frontend/jobseeker/resume/' . $user->userInformations?->resume) }}"><img
                                                    style="height: 20px;" src="{{ asset('frontend/images/adobelogo.png') }}"
                                                    alt=""></a>
                                        @else
                                            <a target="_blank"
                                                href="{{ asset('frontend/jobseeker/resume/' . $user->userInformations?->resume) }}"><img
                                                    style="height: 20px;"
                                                    src="{{ asset('frontend/jobseeker/resume/' . $user->userInformations?->resume) }}"
                                                    alt=""></a>
                                        @endif
                                    @endif
                                </div>

                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="required">Education & Qualification</label>
                                        <div class="form-group-input">
                                            <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>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Cover Letter</label>
                                        <input type="file" accept="image/*" name="cover_letter" class="file">
                                        <div class="input-group mb-3 browse-bx">
                                            <input type="text" class="form-control" disabled placeholder="No file chosen"
                                                aria-label="No file chosen">
                                            <div class="input-group-append">
                                                <button type="button"
                                                    class="browse-letter input-group-text btn btn-primary"
                                                    id="basic-addon3">
                                                    Browse</button>
                                            </div>
                                        </div>
                                    </div>
                                    <a target="_blank"
                                        href="{{ asset('frontend/jobseeker/coverletter/' . $user->userInformations?->cover_letter) }}"><img
                                            style="height: 20px;"
                                            src="{{ asset('frontend/jobseeker/coverletter/' . $user->userInformations?->cover_letter) }}"
                                            alt=""></a>

                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="required">Date of Birth</label>
                                        <input type="date" name="dob"
                                            max="{{ Carbon::yesterday()->format('Y-m-d') }}" class="form-control"
                                            placeholder="DD/MM/YYYY" value="{{ $user->userInformations?->dob ?? '' }}"
                                            required>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label class="required">Gender</label>

                                        <div class="formpaymentbox mt-1">
                                            <ul>
                                                <li>
                                                    <input type="radio" id="gender_male" name="gender" value="Male"
                                                        {{ isset($user->userInformations?->gender) && $user->userInformations?->gender == 'Male' ? 'checked' : 'checked' }}
                                                        required>
                                                    <label for="gender_male">Male</label>
                                                </li>
                                                <li>
                                                    <input type="radio" id="gender_female" name="gender"
                                                        value="Female"
                                                        {{ isset($user->userInformations?->gender) && $user->userInformations?->gender == 'Female' ? 'checked' : '' }}
                                                        required>
                                                    <label for="gender_female">Female</label>
                                                </li>
                                                <li>
                                                    <input type="radio" id="gender_other" name="gender"
                                                        value="Other"
                                                        {{ isset($user->userInformations?->gender) && $user->userInformations?->gender == 'Other' ? 'checked' : '' }}
                                                        required>
                                                    <label for="gender_other">Other</label>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="required">Professional Summary</label>
                                        <textarea name="about_us" rows="4" cols="20" placeholder="Your message" minlength="5" maxlength="1000"
                                            required>{{ $user->userInformations?->about_us ?? '' }}</textarea>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="agency-underline"></div>
                                </div>

                                <div class="col-md-12">
                                    <h5>Location</h5>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label class="required">Address Line</label>
                                                <div class="form-group-input">
                                                    <input type="text" name="address" class="form-control"
                                                        placeholder="132, My Street, Kingston, New York"
                                                        value="{{ $user->userInformations?->address ?? '' }}" required>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label class="required">Country</label>
                                                <div class="form-group-input">
                                                    <select class="form-control" name="country_id" id="country_id"
                                                        required>
                                                        <option value="">Select</option>
                                                        @foreach ($countries as $country)
                                                            <option value="{{ $country->id }}"
                                                                {{ (auth()->guard('job_seeker')->user()->userInformations->country_id ?? '') == $country->id ? 'selected' : '' }}>
                                                                {{ $country->name }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label class="required">State</label>
                                                <select class="form-control" name="state_id" id="state_id" required>
                                                    <option value="">Select</option>
                                                    <!-- Add state options here and use similar logic for selected -->
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label class="required">City</label>
                                                <select class="form-control" name="city_id" id="city_id" required>
                                                    <option value="">Select</option>
                                                    <!-- Add city options here and use similar logic for selected -->
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label for="post_code">Post Code</label>
                                                <input type="text" name="post_code" class="form-control"
                                                    placeholder="012345"
                                                    value="{{ $user->userInformations?->post_code ?? '' }}">
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-md-12">
                                    <div class="agency-underline"></div>
                                </div>




                                <div class="col-md-12">
                                    <h5>Experience Details</h5>
                                    <div id="experience-container">
                                        @if ($jobSeekerExperience->isEmpty())
                                            {{-- Default experience entry if none exists --}}
                                            <div class="experience-entry row">
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label class="required">Company Name</label>
                                                        <input type="text" name="company_name[0]" class="form-control"
                                                            placeholder="Company Name" required>
                                                    </div>
                                                </div>
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label class="required">Job Title</label>
                                                        <input type="text" name="job_title[0]" class="form-control"
                                                            placeholder="Job Title" required>
                                                    </div>
                                                </div>
                                                <div class="col-md-3">
                                                    <div class="form-group">
                                                        <label class="required">Start Date</label>

                                                        <input type="text" name="start_date[0]" flatpickr
                                                            class="form-control flatpickr start-date"
                                                            placeholder="Start Date" required>

                                                    </div>
                                                </div>
                                                <div class="col-md-3">

                                                    <div class="form-group">
                                                        <label class="required">End Date</label>
                                                        <input type="text" name="end_date[0]" flatpickr
                                                            class="form-control flatpickr end-date" placeholder="End Date"
                                                            required>
                                                    </div>
                                                    <div class="form-group">

                                                        <input type="checkbox" name="currently_working[0]"
                                                            class="currently-working-checkbox"> Currently Working
                                                    </div>
                                                </div>
                                                <div class="col-md-12">
                                                    <div class="form-group">
                                                        <label>Responsibilities</label>
                                                        <textarea name="responsibilities[0]" rows="4" class="form-control" placeholder="Your responsibilities"></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        @else
                                            @foreach ($jobSeekerExperience as $index => $experience)
                                                {{-- Display each existing experience entry --}}
                                                <div class="experience-entry row">
                                                    <div class="col-md-3">
                                                        <div class="form-group">
                                                            <label class="required">Company Name</label>
                                                            <input type="text"
                                                                name="company_name[{{ $index }}]"
                                                                class="form-control"
                                                                value="{{ $experience->company_name }}"
                                                                placeholder="Company Name" required>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <div class="form-group">
                                                            <label class="required">Job Title</label>
                                                            <input type="text" name="job_title[{{ $index }}]"
                                                                class="form-control" value="{{ $experience->job_title }}"
                                                                placeholder="Job Title" required>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <div class="form-group">
                                                            <label class="required">Start Date</label>
                                                            <input type="text" name="start_date[{{ $index }}]"
                                                                flatpickr class="form-control flatpickr start-date"
                                                                value="{{ $experience->start_date }}" required>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-3">

                                                        <div class="form-group">
                                                            <label class="required">End Date</label>
                                                            <input type="text" name="end_date[{{ $index }}]"
                                                                flatpickr class="form-control flatpickr end-date"
                                                                value="{{ $experience->end_date }}"
                                                                {{ $experience->currently_working ? 'disabled' : '' }}
                                                                required>
                                                        </div>
                                                        <div class="form-group">

                                                            <input type="checkbox"
                                                                name="currently_working[{{ $index }}]"
                                                                class="currently-working-checkbox"
                                                                {{ $experience->currently_working ? 'checked' : '' }}>
                                                            Currently Working
                                                        </div>
                                                    </div>
                                                    <div class="col-md-12">
                                                        <div class="form-group">
                                                            <label>Responsibilities</label>
                                                            <textarea name="responsibilities[{{ $index }}]" rows="4" class="form-control"
                                                                placeholder="Responsibilities">{{ $experience->responsibilities }}</textarea>
                                                        </div>
                                                    </div>
                                                    @if ($index > 0)
                                                        <div class="col-md-12">
                                                            <button type="button"
                                                                class="btn btn-danger remove-experience">Remove</button>
                                                        </div>
                                                    @endif
                                                </div>
                                            @endforeach
                                        @endif
                                    </div>
                                    <div class="text-right">
                                        <button type="button" class="btn btn-primary" id="add-more">Add More</button>
                                    </div>
                                </div>

                                <div class="col-md-12" id="skills-container">
                                    @if ($jobSeekerSkill->isEmpty())
                                        {{-- Default skill entry if none exists --}}
                                        <div class="row skill-bx skill-entry" data-index="0">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label class="skill-title">Skills & Competencies</label>
                                                    <select class="form-control" required name="skills[0]">
                                                        <option value="">Select Skill</option>
                                                        @foreach ($skills as $skill)
                                                            <option value="{{ $skill->id }}">{{ $skill->title }}
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label class="blank">&nbsp;</label>
                                                    <div class="d-flex duration-bx">
                                                        <select class="form-control" name="skill_level[0]">
                                                            <option>Select</option>
                                                            <option>Beginner</option>
                                                            <option>Intermediate</option>
                                                            <option>Expert</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    @else
                                        @foreach ($jobSeekerSkill as $jss => $jobSkill)
                                            {{-- Display each existing skill entry --}}
                                            <div class="row skill-bx skill-entry" data-index="{{ $jss }}">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label class="skill-title">Skills & Competencies</label>
                                                        <select class="form-control" required
                                                            name="skills[{{ $jss }}]">
                                                            <option value="">Select Skill</option>
                                                            @foreach ($skills as $skill)
                                                                <option value="{{ $skill->id }}"
                                                                    {{ $jobSkill->skill_id == $skill->id ? 'selected' : '' }}>
                                                                    {{ $skill->title }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label class="blank">&nbsp;</label>
                                                        <div class="d-flex duration-bx">
                                                            <select class="form-control"
                                                                name="skill_level[{{ $jss }}]">
                                                                <option>Select</option>
                                                                <option
                                                                    {{ $jobSkill->skill_level == 'Beginner' ? 'selected' : '' }}>
                                                                    Beginner</option>
                                                                <option
                                                                    {{ $jobSkill->skill_level == 'Intermediate' ? 'selected' : '' }}>
                                                                    Intermediate</option>
                                                                <option
                                                                    {{ $jobSkill->skill_level == 'Expert' ? 'selected' : '' }}>
                                                                    Expert</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        @endforeach
                                    @endif
                                </div>
                                <div class="col-md-12 text-right mb-3">
                                    <button type="button" id="add-more-skills" class="btn btn-primary">Add More
                                        Skills</button>
                                </div>

                                <div class="col-md-12">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label>LinkedIn</label>
                                                <div class="form-group-input">
                                                    <input type="text" name="linkedin" class="form-control"
                                                        placeholder="https://www.linkedin.com/in/your-profile"
                                                        value="{{ $user->userInformations?->linkedin ?? '' }}">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label>Portfolio URL</label>
                                                <div class="form-group-input">
                                                    <input type="text" name="portfolio" class="form-control"
                                                        placeholder="Portfolio URL"
                                                        value="{{ $user->userInformations?->portfolio ?? '' }}">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="required">Language</label>
                                        <div class="form-group-input">
                                            <select class="form-control" multiple name="language[]" id="language-select">
                                                <option value="English"
                                                    {{ in_array('English', $jobSeekerLanguage) ? 'selected' : '' }}>English
                                                </option>
                                                <option value="Hindi"
                                                    {{ in_array('Hindi', $jobSeekerLanguage) ? 'selected' : '' }}>Hindi
                                                </option>
                                                <option value="Spanish"
                                                    {{ in_array('Spanish', $jobSeekerLanguage) ? 'selected' : '' }}>Spanish
                                                </option>
                                                <option value="French"
                                                    {{ in_array('French', $jobSeekerLanguage) ? 'selected' : '' }}>French
                                                </option>
                                                <!-- Add more languages as needed -->
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label class="w-100 d-block mb-3">Calendar Availability</label>
                                        <label class="toggleSwitch large">
                                            <input id="availabilityToggle" name="availability_status" type="checkbox"
                                                {{ $user->userInformations?->availability_status == 1 ? 'checked' : '' }}>
                                            <span>
                                                <span>OFF</span>
                                                <span>ON</span>
                                            </span>
                                            <a></a>
                                        </label>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Set Availability</label>
                                        <input type="date" class="form-control mb-4" name="availability"
                                            placeholder="DD/MM/YYYY"
                                            value="{{ $user->userInformations?->availability ?? '' }}">
                                    </div>
                                </div>
                            </div>

                            <div class="profile-btn">
                                <button type="submit" class="btn-custom">Submit</button>
                            </div>
                        </form>

                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- Job alerts start -->
@endsection
@push('front-script')
    <script>
        $(document).ready(function() {

            $(document).ready(function() {
                flatpickr(".flatpickr", {
                    disableMobile: true
                });


                $('textarea[name="about_us"]').on('keypress', function(event) {
                    if (event.which === 32 && $(this).val().length === 0) {
                        // Prevent space if it's the first character
                        event.preventDefault();
                    }
                });
                $("#profile-form").validate({
                    rules: {
                        first_name: {
                            required: true,
                            minlength: 3,
                            maxlength: 150
                        },
                        last_name: {
                            required: true,
                            minlength: 3,
                            maxlength: 150
                        },
                        mobile: {
                            required: true,
                            minlength: 7,
                            maxlength: 15,
                            digits: true // Ensure mobile contains only numbers
                        },
                        email: {
                            required: true,
                            email: true
                        },
                        resume: {
                            required: true,
                            extension: "pdf,doc,docx" // Specify allowed file extensions
                        },
                        qualification: {
                            required: true
                        },
                        dob: {
                            required: true,
                            date: true // Validate date format
                        },
                        gender: {
                            required: true
                        },
                        about_us: {
                            required: true,
                            minlength: 5,
                            maxlength: 1000
                        },
                        address: {
                            required: true
                        },
                        country_id: {
                            required: true
                        },
                        state_id: {
                            required: true
                        },
                        city_id: {
                            required: true
                        },
                        post_code: {
                            postalCodeRequired:true,
                            minlength: 3,
                            maxlength: 10,
                            digits: true
                        },
                        "company_name[]": {
                            required: true,
                            minlength: 3,
                            maxlength: 150
                        },
                        "job_title[]": {
                            required: true
                        },
                        "duration[]": {
                            required: true
                        },
                        "responsibilities[]": {
                            required: true,
                            minlength: 5,
                            maxlength: 1000
                        },
                        "skills[]": {
                            required: true
                        },
                        "language[]": {
                            required: true
                        }
                    },
                    messages: {
                        first_name: {
                            required: "First name is required.",
                            minlength: "First name must be at least 3 characters.",
                            maxlength: "First name cannot exceed 150 characters."
                        },
                        last_name: {
                            required: "Last name is required.",
                            minlength: "Last name must be at least 3 characters.",
                            maxlength: "Last name cannot exceed 150 characters."
                        },
                        mobile: {
                            required: "Mobile number is required.",
                            minlength: "Mobile number must be at least 7 digits.",
                            maxlength: "Mobile number cannot exceed 15 digits."
                        },
                        email: {
                            required: "Email is required.",
                            email: "Please enter a valid email address."
                        },
                        resume: {
                            required: "Resume upload is required.",
                            extension: "Only PDF, DOC, or DOCX files are allowed."
                        },
                        qualification: {
                            required: "Qualification is required."
                        },
                        dob: {
                            required: "Date of birth is required.",
                            date: "Please enter a valid date."
                        },
                        gender: {
                            required: "Gender is required."
                        },
                        about_us: {
                            required: "Professional summary is required.",
                            minlength: "Professional summary must be at least 5 characters.",
                            maxlength: "Professional summary cannot exceed 1000 characters."
                        },
                        address: {
                            required: "Address is required."
                        },
                        country_id: {
                            required: "Country selection is required."
                        },
                        state_id: {
                            required: "State selection is required."
                        },
                        city_id: {
                            required: "City selection is required."
                        },
                        post_code: {
                            required: "Post code is required."
                        },
                        "company_name[]": {
                            required: "Company name is required.",
                            minlength: "Company name must be at least 3 characters.",
                            maxlength: "Company name cannot exceed 150 characters."
                        },
                        "job_title[]": {
                            required: "Job title is required."
                        },
                        "duration[]": {
                            required: "Duration is required."
                        },
                        "responsibilities[]": {
                            required: "Responsibilities are required.",
                            minlength: "Responsibilities must be at least 5 characters.",
                            maxlength: "Responsibilities cannot exceed 1000 characters."
                        },
                        "skills[]": {
                            required: "Skills are required."
                        },
                        "language[]": {
                            required: "Language selection is required."
                        }
                    },
                    errorPlacement: function(error, element) {
                        if (element.attr("name") === "language[]") {
                            // Append the error message after the Select2 container
                            error.insertAfter(element.next(".select2"));
                        } else {
                            error.insertAfter(element); // Default behavior for other fields
                        }
                    },
                    submitHandler: function(form) {
                        form.submit();
                    }
                });


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

                // Dynamic validation for added experience entries


                // Dynamic validation for added experience entries
                function addDynamicValidation() {
                    $("input[name='company_name[]']").each(function() {
                        $(this).rules("add", {
                            required: true,
                            minlength: 3,
                            maxlength: 150,
                            messages: {
                                required: "Company name is required.",
                                minlength: "Company name must be at least 3 characters.",
                                maxlength: "Company name cannot exceed 150 characters."
                            }
                        });
                    });

                    $("input[name='responsibilities[]']").each(function() {
                        $(this).rules("add", {
                            required: true,
                            minlength: 5,
                            maxlength: 1000,
                            messages: {
                                required: "Responsibilities are required.",
                                minlength: "Responsibilities must be at least 5 characters.",
                                maxlength: "Responsibilities cannot exceed 1000 characters."
                            }
                        });
                    });
                }

                // Event listeners for adding experience and skills
                let experienceCount = "{{ isset($index) ? $index : 0 }}";
                let skillCount = '{{ isset($jss) ? $jss : 0 }}';
                document.getElementById('add-more').addEventListener('click', function() {
                    var container = document.getElementById('experience-container');
                    var newEntry = document.querySelector('.experience-entry').cloneNode(true);

                    // Clear the values in the cloned entry
                    var inputs = newEntry.querySelectorAll('input, textarea, select');
                    inputs.forEach(function(input) {
                        input.value = '';
                        if (input.tagName.toLowerCase() === 'select') {
                            input.selectedIndex = 0;
                        }
                        input.classList.remove('is-invalid', 'is-valid', 'error');
                    });

                    // Remove validation error messages
                    var errorLabels = newEntry.querySelectorAll('label.error');
                    errorLabels.forEach(function(label) {
                        label.remove(); // Remove error labels
                    });

                    // Update the name attributes
                    experienceCount++;
                    newEntry.querySelectorAll('input, textarea').forEach(function(input) {
                        // Change the name to include the current count
                        if (input.name) {
                            input.name = input.name.replace(/\[\d+\]/,
                                `[${experienceCount}]`);

                        }
                        if (input.hasAttribute('index')) {
                            input.setAttribute('index', experienceCount);
                        }
                    });

                    // Create a new div for the "Remove" button with the specified structure
                    var removeDiv = document.createElement('div');
                    removeDiv.className = 'col-md-12'; // Set class for Bootstrap styling

                    var removeButton = document.createElement('button');
                    removeButton.type = 'button';
                    removeButton.className = 'btn btn-danger remove-experience';
                    removeButton.innerText = 'Remove';

                    // Append the Remove button to the new div
                    removeDiv.appendChild(removeButton);

                    // Find the existing col-md-12 div and append the new div with the button
                    // var col12Div = newEntry.querySelector('.col-md-12:last-child'); // Assuming last col-md-12 is where to append
                    newEntry.appendChild(removeDiv);

                    // Add event listener to the remove button
                    removeButton.addEventListener('click', function() {
                        container.removeChild(newEntry);
                        addDynamicValidation(); // Reapply validation after removal
                    });

                    container.appendChild(newEntry);
                    addDynamicValidation(); // Add validation to the new entry
                    initializeFlatpickr();
                });

                // Remove experience entry
                document.getElementById('experience-container').addEventListener('click', function(e) {
                    if (e.target.classList.contains('remove-experience')) {
                        e.target.closest('.experience-entry').remove();
                        addDynamicValidation(); // Reapply validation after removal
                    }
                });

                document.getElementById('add-more-skills').addEventListener('click', function() {
                    skillCount++;
                    var skillsContainer = document.getElementById('skills-container');
                    var newSkillEntry = document.createElement('div');
                    newSkillEntry.classList.add('row', 'skill-bx');
                    newSkillEntry.innerHTML = `
            <div class="col-md-6 skill-entry">
                <div class="form-group">
                    <label class="skill-title">Skills & Competencies</label>
                    <div class="form-group-input">
<select class="form-control" required name="skills[${skillCount}]" id="">
                                                        <option value="">Select Skill</option>
                                                        @foreach ($skills as $skill)
                                                        <option value="{{ $skill->id }}">{{ $skill->title }}</option>
                                                        @endforeach
                                                    </select>
                    </div>
                </div>
            </div>
            <div class="col-md-6 skill-entry">
                <div class="form-group">
                    <label class="blank">&nbsp;</label>
                    <div class="d-flex duration-bx">
                        <select name="skill_level[${skillCount}]" class="form-control" required>
                            <option>Select</option>
                            <option>Beginner</option>
                            <option>Intermediate</option>
                            <option>Expert</option>
                        </select>
                        <div class="input-group-append duration-bx">
                            <button type="button" class="browse input-group-text btn btn-danger remove-skill"><b>-</b></button>
                        </div>
                    </div>
                </div>
            </div>
        `;

                    skillsContainer.appendChild(newSkillEntry);

                    // Add event listener for removing the skill entry
                    newSkillEntry.querySelector('.remove-skill').addEventListener('click',
                    function() {
                        newSkillEntry.remove();
                    });
                });



                $('#language-select').select2({
                    placeholder: 'Language',
                    allowClear: true
                });




                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('job_seeker')->user()->userInformations) &&
                                        auth()->guard('job_seeker')->user()->userInformations->state)
                                    stateSelect.val(
                                        {{ auth()->guard('job_seeker')->user()->userInformations->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>');
                                });

                                // Preselect the user's city if it exists
                                @if (isset(auth()->guard('job_seeker')->user()->userInformations) &&
                                        auth()->guard('job_seeker')->user()->userInformations->city)
                                    citySelect.val(
                                        {{ auth()->guard('job_seeker')->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('job_seeker')->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('job_seeker')->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);
                        }
                    });
                });
            });




            function initializeFlatpickr() {
                document.querySelectorAll('.start-date').forEach(function(startDatePicker) {
                    flatpickr(startDatePicker, {
                        dateFormat: "Y-m-d",
                        allowInput: true,
                        maxDate: "today", // Prevent selecting a start date after today
                        onChange: function(selectedDates, dateStr, instance) {
                            const endDatePicker = instance.input.closest('.duration-bx')
                                .querySelector('.end-date');
                            if (endDatePicker) {
                                endDatePicker._flatpickr.set('minDate',
                                dateStr); // Ensure end date is not before start date
                            }
                        }
                    });
                });

                document.querySelectorAll('.end-date').forEach(function(endDatePicker) {
                    flatpickr(endDatePicker, {
                        dateFormat: "Y-m-d",
                        allowInput: true,
                        maxDate: "today" // Prevent selecting an end date after today
                    });
                });
            }



            initializeFlatpickr();





            $(document).on('change', '.file', function() {
                var fileName = $(this).val().split('\\').pop(); // Get the file name
                $(this).parent().find('input[type="text"]').val(fileName ? fileName : "No file chosen");
            });


            document.querySelector('.browse-resume').addEventListener('click', function() {
                document.querySelector('input[name="resume"]').click();
            });

            document.querySelector('.browse-letter').addEventListener('click', function() {
                document.querySelector('input[name="cover_letter"]').click();
            });

            document.querySelector('input[name="cover_letter"]').addEventListener('change', function(e) {
                const fileInput = e.target;
                const file = fileInput.files[0];

                if (file) {
                    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];

                    // Check if selected file is a valid image type
                    if (!allowedTypes.includes(file.type)) {
                        $('.cover-letter-error').text(
                            "Please select a valid image file (JPEG, PNG, or GIF).");
                        fileInput.value = ""; // Clear the file input
                        document.querySelector('.form-control[disabled]').value =
                            "No file chosen"; // Reset placeholder text
                        return;
                    } else {
                        $('.cover-letter-error').text("");

                    }

                    // Update the placeholder with the file name if it is valid
                    document.querySelector('.form-control[disabled]').value = file.name;
                }
            });
            document.querySelectorAll('.end-date').forEach(function(endDatePicker) {
                flatpickr(endDatePicker, {
                    dateFormat: "Y-m-d",
                    allowInput: true,
                    minDate: "today" // Prevent selecting past dates
                });
            });
            // }


            initializeFlatpickr();




            $(document).on('change', '.file', function() {
                var fileName = $(this).val().split('\\').pop(); // Get the file name
                $(this).parent().find('input[type="text"]').val(fileName ? fileName : "No file chosen");
            });
        });


















        document.getElementById('experience-container').addEventListener('change', function(event) {
            if (event.target.classList.contains('currently-working-checkbox')) {
                handleCurrentlyWorking(event.target);
            }
        });

        document.getElementById('add-more').addEventListener('click', function() {
            if (this.disabled) {
                alert("You cannot add more experiences when 'Currently Working' is selected.");
            }
        });

        function handleCurrentlyWorking(checkbox) {
            var container = document.getElementById('experience-container');
            var entries = Array.from(container.querySelectorAll('.experience-entry'));
            var currentEntry = checkbox.closest('.experience-entry');
            var endDateField = currentEntry.querySelector('.end-date');
            var currentIndex = entries.indexOf(currentEntry);

            if (checkbox.checked) {
                // Disable the end date field
                endDateField.value = '';
                endDateField.disabled = true;

                // Remove all entries after the currently selected one
                entries.slice(currentIndex + 1).forEach(function(entry) {
                    container.removeChild(entry);
                });

                // Disable the "Add More" button
                document.getElementById('add-more').disabled = true;

                // Uncheck all other "Currently Working" checkboxes
                entries.forEach(function(entry, index) {
                    if (index !== currentIndex) {
                        var otherCheckbox = entry.querySelector('.currently-working-checkbox');
                        if (otherCheckbox) {
                            otherCheckbox.checked = false;
                            var otherEndDateField = entry.querySelector('.end-date');
                            if (otherEndDateField) {
                                otherEndDateField.disabled = false; // Enable the end date field
                            }
                        }
                    }
                });
            } else {
                // Enable the end date field
                endDateField.disabled = false;

                // Check if all checkboxes are unchecked
                var anyChecked = entries.some(function(entry) {
                    var checkbox = entry.querySelector('.currently-working-checkbox');
                    return checkbox && checkbox.checked;
                });

                // Re-enable the "Add More" button if no checkboxes are checked
                document.getElementById('add-more').disabled = anyChecked;
            }
        }

        // Initialize the page with the correct values
        function initializeEndDateFields() {
            var entries = document.querySelectorAll('.experience-entry');
            entries.forEach(function(entry) {
                var endDateField = entry.querySelector('.end-date');
                if (endDateField && endDateField.value === '0000-00-00') {
                    endDateField.value = ''; // Clear the field if it's 0000-00-00
                }
            });
        }

        // Call the initialization function on page load
        initializeEndDateFields();
    </script>
@endpush
