@extends('backend.layouts.app')
@section('content')
    <style>
        
        .file-upload {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            padding: 4rem 1.5rem;
            margin-top: 2rem;
            border: 3px dashed #dbedff;
            border-radius: .5rem;
            transition: background-color .25s ease-out;     max-width:700px;

            &:hover {
                background-color: #dbedff;
            }

            .file-input {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                opacity: 0;
                outline: none;
                cursor: pointer;
            }
        }
        .icon {
            width: 75px;
            margin-bottom: 1rem;
        }

        .image-container {
            position: relative;
            display: flex;
            justify-content: center; /* Centers content horizontally */
            align-items: center; /* Centers content vertically */
        }

        .delete-button-container {
            position: absolute; /* Position the button container inside the image container */
            bottom: 10px; /* Adjust position as needed */
        }

        .btn-danger {
            background-color: rgba(255, 0, 0, 0.7); /* Optional: slightly transparent background */
            border-color: rgba(255, 0, 0, 0.7); /* Optional: slightly transparent border */
        }


    </style>
    <div class="row page-titles">
        <div class="col-md-5 align-self-center">
            <h4 class="text-themecolor">Services Manager</h4>
        </div>
        <div class="col-md-7 align-self-center text-right">
            <div class="d-flex justify-content-end align-items-center">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('category') }}">Services Manager</a></li>
                    {{-- <li class="breadcrumb-item active">Create Job Manager</li> --}}
                </ol>
            </div>
        </div>
    </div>

    <div id="deleteModal" class="modal fade" role='dialog'>
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body">
                    <p>Are you sure you want to delete this?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <span id='deleteButton'></span>
                </div>
            </div>
        </div>
    </div>

    <!-- Content Wrapper. Contains page content -->
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                @if (session('status'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert"><i
                            class="far fa-check-circle"></i>
                        <strong></strong> {{ session('status') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                @endif
                <div class="col-md-12">
                    <div class="card card-primary">
                        <div class="tab-content">
                            <form action="{{ route('service.update', $service->id) }}" id="contentForm" method="POST"
                                enctype="multipart/form-data">
                                @csrf
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="required">Title <span
                                                    style="color: red;font-size:18px;"><b>*</b></span></label>
                                                <input type="text" name="title"
                                                    class="form-control @error('title') is-invalid @enderror" placeholder="Enter Title"
                                                    value="{{ old('title', @$service->title ) }}">
                                                @error('title')
                                                    <span class="invalid-feedback">{{ $message }}</span>
                                                @enderror
                                            </div>
                                        </div>      
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="required">Service Category & Subcategory<span
                                                    style="color: red;font-size:18px;"><b>*</b></span></label>
                                                <select name="service_category_id" class="form-control @error('service_category_id') is-invalid @enderror">
                                                    <option value="">Select</option>
                                                    @foreach ($categories as $cat => $category)
                                                        <option value="{{ $cat }}"
                                                            {{ old('service_category_id', @$service->service_category_id) == $cat ? 'selected' : '' }}>{{ $category }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                                @error('service_category_id')
                                                    <span class="invalid-feedback">{{ $message }}</span>
                                                @enderror
                                            </div>
                                        </div>  

                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label class="required">Pricing Options<span
                                                    style="color: red;font-size:18px;"><b>*</b></span></label>
                                                <select name="pricing_option"
                                                    class="form-control @error('pricing_option') is-invalid @enderror">
                                                    <option value="">Select Pricing Model</option>
                                                    <option value="hourly" {{ old('pricing_option',@$service->pricing_option) === 'hourly' ? 'selected' : '' }}>Hourly
                                                    </option>
                                                    <option value="project_based"
                                                        {{ old('pricing_option', @$service->pricing_option) === 'project_based' ? 'selected' : '' }}>Project-Based
                                                    </option>
                                                    <option value="packages" {{ old('pricing_option', @$service->pricing_option) === 'packages' ? 'selected' : '' }}>
                                                        Packages</option>
                                                </select>
                                                @error('pricing_option')
                                                    <span class="invalid-feedback">{{ $message }}</span>
                                                @enderror
                                            </div>
                                        </div>
                
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label class="required">Pricing <span
                                                    style="color: red;font-size:18px;"><b>*</b></span></label>
                                                <input type="text" name="pricing"
                                                    class="form-control @error('pricing') is-invalid @enderror" placeholder="Enter Pricing"
                                                    value="{{ old('pricing',@$service->pricing) }}">
                                                @error('pricing')
                                                    <span class="invalid-feedback">{{ $message }}</span>
                                                @enderror
                                            </div>
                                        </div>

                                        <div class="col-sm-12">
                                            <div class="form-group">
                                                <label>Description</label>
                                                <textarea id="description" name="description" rows="4"
                                                    class="form-control @error('description') is-invalid @enderror" placeholder="Your message">{{ $service->description }}</textarea>
                                                @error('description')
                                                    <span class="invalid-feedback">{{ $message }}</span>
                                                @enderror
                                            </div>
                                        </div>
                                        
                                        <div class="col-sm-6">
                                            <div class="form-group">
                                                <label class="required" for="country_id">Country<span
                                                        style="color: red;font-size:18px;"><b>*</b></span></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 }}"
                                                            {{ $service->country_id == $country->id ? 'selected' : '' }}>{{ $country->name }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                                @error('country_id')
                                                    <span class="invalid-feedback">{{ $message }}</span>
                                                @enderror
                                            </div>
                                        </div>

                                        <div class="col-sm-6">
                                            <div class="form-group">
                                                <label class="required" for="state_id">State<span
                                                        style="color: red;font-size:18px;"><b>*</b></span></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-sm-6">
                                            <div class="form-group">
                                                <label class="required" for="city_id">City<span
                                                        style="color: red;font-size:18px;"><b>*</b></span></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-6">
                                            <div class="form-group">
                                                <label class="required">Available Dates & Times</label>
                                                <div class="d-flex">
                                                    <div>
                                                        <input type="datetime-local" name="start_datetime"
                                                            class="form-control @error('start_datetime') is-invalid @enderror"
                                                        value="{{ old('start_datetime',@$service->start_datetime) }}">
                                                        <br>
                                                        <label id="start_datetime-error" class="error" for="start_datetime"></label>
                                                    </div>
                                                    <div>
                                                        <input type="datetime-local" name="end_datetime"
                                                            class="form-control @error('end_datetime') is-invalid @enderror ml-2" value="{{ old('end_datetime',@$service->end_datetime) }}">
                                                            <br>
                                                            <label id="end_datetime-error" class="error pl-1" for="end_datetime"></label>    
                                                    </div>
                                                </div>
                                                 @error('start_datetime')
                                                    <span class="invalid-feedback">{{ $message }}</span>
                                                @enderror
                                                @error('end_datetime')
                                                    <span class="invalid-feedback">{{ $message }}</span>
                                                @enderror
                                            </div>
                                        </div>
                                      
                                        
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label class="">Week</label>
                                                <ul class="d-flex week-list">
                                                    <li>
                                                        <div class="remember-link mb-2">
                                                            <label class="custom-checkbox">
                                                                <input type="checkbox" value="sunday" name="availability[]"
                                                                    {{ in_array('sunday', $serviceDays) ? 'checked' : '' }}>
                                                                <span class="checkmark"></span>
                                                                <div class="week-txt">Su</div>
                                                            </label>
                                                        </div>
                                                    </li>
                                                    <li>
                                                        <div class="remember-link mb-2">
                                                            <label class="custom-checkbox">
                                                                <input type="checkbox" value="monday" name="availability[]"
                                                                    {{ in_array('monday', $serviceDays) ? 'checked' : '' }}>
                                                                <span class="checkmark"></span>
                                                                <div class="week-txt">Mo</div>
                                                            </label>
                                                        </div>
                                                    </li>
                                                    <li>
                                                        <div class="remember-link mb-2">
                                                            <label class="custom-checkbox">
                                                                <input type="checkbox" value="tuesday" name="availability[]"
                                                                    {{ in_array('tuesday', $serviceDays) ? 'checked' : '' }}>
                                                                <span class="checkmark"></span>
                                                                <div class="week-txt">Tu</div>
                                                            </label>
                                                        </div>
                                                    </li>
                                                    <li>
                                                        <div class="remember-link mb-2">
                                                            <label class="custom-checkbox">
                                                                <input type="checkbox" value="wednesday" name="availability[]"
                                                                    {{ in_array('wednesday', $serviceDays) ? 'checked' : '' }}>
                                                                <span class="checkmark"></span>
                                                                <div class="week-txt">We</div>
                                                            </label>
                                                        </div>
                                                    </li>
                                                    <li>
                                                        <div class="remember-link mb-2">
                                                            <label class="custom-checkbox">
                                                                <input type="checkbox" value="thursday" name="availability[]"
                                                                    {{ in_array('thursday', $serviceDays) ? 'checked' : '' }}>
                                                                <span class="checkmark"></span>
                                                                <div class="week-txt">Th</div>
                                                            </label>
                                                        </div>
                                                    </li>
                                                    <li>
                                                        <div class="remember-link mb-2">
                                                            <label class="custom-checkbox">
                                                                <input type="checkbox" value="friday" name="availability[]"
                                                                    {{ in_array('friday', $serviceDays) ? 'checked' : '' }}>
                                                                <span class="checkmark"></span>
                                                                <div class="week-txt">Fr</div>
                                                            </label>
                                                        </div>
                                                    </li>
                                                    <li>
                                                        <div class="remember-link mb-2">
                                                            <label class="custom-checkbox">
                                                                <input type="checkbox" value="saturday" name="availability[]"
                                                                    {{ in_array('saturday', $serviceDays) ? 'checked' : '' }}>
                                                                <span class="checkmark"></span>
                                                                <div class="week-txt">Sa</div>
                                                            </label>
                                                        </div>
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                    
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label>Discount</label>
                                                <input type="text" name="discounted_amount" class="form-control"
                                                    placeholder="Enter special offers or discounts" value="{{ old('discounted_amount', $service->discounted_amount ) }}">
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label class="required " style="width: 100%" >Service FAQs<span style="color: red;font-size:18px;"><b>*</b></span>   <button type="button" id="add-question" class="btn btn-success mt-2 float-right">+</button></label>
                                                    <div id="screening-questions-container" class="mb-1 ">
                                                    @forEach($service->faqs as $key => $value)
                                                        <div class="faq-item row">
                                                            <div class="screening-question mb-2 col-md-5">
                                                                <input type="text" name="question[]"
                                                                    class="form-control @error('question.*') is-invalid @enderror"
                                                                    placeholder="Enter Question" value="{{ old('question', @$value->question ) }}">
                                                                @error('question.*')
                                                                    <span class="invalid-feedback">{{ $message }}</span>
                                                                @enderror
                                                            </div>
                                                            <div class="question mb-4 col-md-5">
                                                                <input type="text" name="answer[]"
                                                                    class="form-control @error('answer.*') is-invalid @enderror"
                                                                    placeholder="Enter Answer" value="{{ old('answer',@$value->answer ) }}">
                                                                @error('answer.*')
                                                                    <span class="invalid-feedback">{{ $message }}</span>
                                                                @enderror
                                                            </div>
                                                            @if($key != 0)
                                                                <div class="col-md-2">
                                                                    <button type="button" class="btn btn-danger remove-question float-right">-</button>
                                                                </div>
                                                            @endif
                                                        </div>
                                                    @endforeach
                                                </div>
                                                {{-- <div id="screening-questions-container" class="mb-1">
                                                    <div class="screening-question mb-2">
                                                        <input type="text" name="question[]"
                                                            class="form-control @error('question.*') is-invalid @enderror"
                                                            placeholder="Enter Question" value="{{ old('question') }}">
                                                        @error('question.*')
                                                            <span class="invalid-feedback">{{ $message }}</span>
                                                        @enderror
                                                    </div>
                                                    <div class="question mb-4">
                                                        <input type="text" name="answer[]"
                                                            class="form-control @error('answer.*') is-invalid @enderror"
                                                            placeholder="Enter Answer" value="{{ old('answer') }}">
                                                        @error('answer.*')
                                                            <span class="invalid-feedback">{{ $message }}</span>
                                                        @enderror
                                                    </div>
                                                </div> --}}
                                              
                                            </div>
                                        </div>   
                                        
                                        <div class="col-md-12">
                                            <div class="form-group">
                                                <label>Images/Videos Upload</label>
                
                                                <div class="file-upload">
                                                    <input type="file" class="file-input" name="file[]" multiple id="fileInput"
                                                        class="form-control @error('file') is-invalid @enderror">
                
                                                    <!-- Progress bar container -->
                                                    <div id="progressContainer"></div>
                
                                                    <svg class="icon" viewBox="0 0 60 60" xmlns="http://www.w3.org/2000/svg">
                                                        <!-- SVG content here (unchanged) -->
                                                    </svg>
                                                    <div class="card-subtitle">Drag n Drop your file here</div>
                                                </div>
                                            </div>
                                        </div>
                                          <!-- Progress bar template -->
                                        <script type="text/template" id="progressTemplate">
                                            <div class="upload-progress">
                                            <span class="file-name"></span>
                                            <progress class="progress-bar" value="0" max="100"></progress>
                                            <span class="progress-percentage">0%</span>
                                            </div>
                                        </script>
                                        
                                        <div class="col-md-12">
                                            <div class="row" id="images-preview">
                                                @foreach ($service->files as $file)
                                                    <div class="image-container position-relative m-2 d-flex justify-content-center align-items-center" id="removeid_{{$file->id}}">
                                                        <a target="blank" href="{{ asset('frontend/serviceProvider/service/'.$file->file) }}">
                                                            <img src="{{ asset('frontend/serviceProvider/service/'.$file->file) }}" alt="" width="150px" height="150px">
                                                        </a>
                                                        <div class="delete-button-container">
                                                            <button class="btn btn-danger btn-sm" title="Delete" onclick="deleteImage(@php echo $service->id; @endphp, @php echo $file->id; @endphp)">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                @endforeach  
                                            </div>                                               
                                        </div>

                                        <div class="col-sm-12">
                                            <div class="form-group">
                                                <div class="custom-control custom-checkbox mr-sm-2 m-b-15">
                                                    <input type="checkbox" class="custom-control-input" name="status"
                                                        id="checkbox0"
                                                        @if ($service->status == 1) checked @else @endif
                                                        value="1">
                                                    <label class="custom-control-label" for="checkbox0">Is Active </label>
                                                </div>
                                            </div>
                                        </div>

                                    </div>
                                    <div class="card-body">
                                        <button type="submit" id="submitButton" class="btn btn-primary">Submit</button>
                                        <a href="{{ route('service.index', request()->query()) }}"
                                            class="btn btn-secondary">Back</a>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    </div>
@endsection

@push('custom-script')
    {{-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> --}}
    <script src="https://cdn.ckeditor.com/4.16.2/standard/ckeditor.js"></script>
    <script>
        $(document).ready(function() {

            // Custom validation rule for checking if the end datetime is after start datetime
            $.validator.addMethod("greaterThanStartDate", function(value, element) {
                var startDate = $("input[name='start_datetime']").val();
                return Date.parse(value) > Date.parse(startDate);
            }, "End date must be after start date");
            // Form validation
            $("#contentForm").validate({
                rules: {
                    title: {
                        required: true,
                        minlength: 3,
                        maxlength: 150
                    },                   
                    country_id: {
                        required: true
                    },
                    state_id: {
                        required: true
                    },
                    city_id: {
                        required: true
                    },                   
                    service_category_id: {
                        required: true
                    },
                    pricing_option: {
                        required: true
                    },
                    pricing: {
                        required: true,
                        number: true
                    },
                    discount_id: {
                        number: true
                    },
                    start_datetime: {
                        required: true,
                        date: true
                    },
                    end_datetime: {
                        required: true,
                        date: true,
                        greaterThanStartDate: true // Custom validation to ensure end date is after start date
                    },
                    'question[]': {
                        required: true,
                        minlength: 3
                    },
                    'answer[]': {
                        required: true,
                        minlength: 3
                    },                    
                    description: {
                        required: true
                    }
                },
                messages: {
                    title: {
                        required: "Service title is required",
                        minlength: "Service title must be at least 3 characters long",
                        maxlength: "Service title cannot exceed 150 characters"
                    },
                    country_id: "Country is required",
                    state_id: "State is required",
                    city_id: "City is required",
                    description: {
                        required: "Service description is required",
                        maxlength: "Service description cannot exceed 1000 characters"
                    },
                    service_category_id: {
                        required: 'Service Category field is required'
                    },
                    pricing_option: {
                        required: "Please select a pricing option"
                    },
                    pricing: {
                        required: "Please enter pricing",
                        number: "Please enter a valid number"
                    },
                    start_datetime: {
                        required: "Please select a start date and time",
                        date: "Please enter a valid date"
                    },
                    end_datetime: {
                        required: "Please select an end date and time",
                        date: "Please enter a valid date",
                        greaterThanStartDate: "End date must be after start date"
                    },
                },
                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
                }
            });

            function loadStates(countryId) {
                $.ajax({
                    url: '{{ route('employer.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($service) && $service->state)
                                stateSelect.val({{ $service->state->id }});
                            @endif
                        }
                    },
                    error: function(xhr) {
                        console.error('Request failed:', xhr);
                    }
                });
            }

            // Load cities based on the selected state
            function loadCities(stateId) {
                $.ajax({
                    url: '{{ route('employer.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($service) && $service->city)
                                citySelect.val({{ $service->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', @$service->country_id) }}";
            if (initialCountryId) {
                loadStates(initialCountryId);
            }

            // Initial load for cities if the state is already selected
            var initialStateId = "{{ old('state_id', optional($service)->state_id) }}";
            if (initialStateId) {
                loadCities(initialStateId);
            }

        });


        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="faq-item row">
                        <div class="screening-question mb-2 col-md-5">
                            <input type="text" name="question[]"
                                class="form-control @error('question.*') is-invalid @enderror"
                                placeholder="Enter Question" value="{{ old('question') }}" required>
                            @error('question.*')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                        <div class="question mb-4 col-md-5">
                            <input type="text" name="answer[]"
                                class="form-control @error('answer.*') is-invalid @enderror"
                                placeholder="Enter Answer" value="{{ old('answer') }}" required>
                            @error('answer.*')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                        <div class="col-md-2">
                            <button type="button" class="btn btn-danger remove-question float-right">-</button>
                        </div>
                    </div>`;
                    
                // Append the new input field to the container
                $('#screening-questions-container').append(newQuestion);
                questionIndex++;
            });

            // Attach click event to dynamically remove FAQ item
            $(document).on('click', '.remove-question', function () {
                $(this).closest('.faq-item').remove();
            });
        });
    </script>
    <script>
        // Select the file input element
        const fileInput = document.getElementById("fileInput");
        const progressContainer = document.getElementById("progressContainer");

        // Listen for file selection
        fileInput.addEventListener("change", (event) => {
            const files = event.target.files;

            // Clear previous progress
            progressContainer.innerHTML = '';

            // Loop through selected files and upload them
            Array.from(files).forEach((file) => {
                // Create a new progress bar for each file
                const progressTemplate = document.getElementById("progressTemplate").innerHTML;
                const progressElement = document.createElement('div');
                progressElement.innerHTML = progressTemplate;
                const fileName = progressElement.querySelector('.file-name');
                const progressBar = progressElement.querySelector('.progress-bar');
                const progressPercentage = progressElement.querySelector('.progress-percentage');

                // Set the file name in the progress bar
                fileName.textContent = file.name;

                // Append the progress bar to the container
                progressContainer.appendChild(progressElement);

                // Start the upload for this file
                uploadFile(file, progressBar, progressPercentage);

                // update the preview
            });
        });

        // Function to upload a file
        function uploadFile(file, progressBar, progressPercentage) {
            const formData = new FormData();
            formData.append("file", file);
            let id  = "{{ $service->id}}";
            formData.append("service_id", id);

            // Create a new XMLHttpRequest to upload the file
            const xhr = new XMLHttpRequest();

            // Event listener for upload progress
            xhr.upload.addEventListener("progress", (event) => {
                if (event.lengthComputable) {
                    const percent = (event.loaded / event.total) * 100;
                    progressBar.value = percent;
                    progressPercentage.textContent = `${Math.round(percent)}%`;
                }
            });

            // Event listener for when the upload is complete
            xhr.addEventListener("load", () => {
                if (xhr.status === 200) {
                    // Success message or handling
                    const response = JSON.parse(xhr.responseText);

                    // Assuming the backend returns the file's ID and path
                    const fileId = response.data.id;  // Example: response should have 'id' and 'file'
                    const filePath = response.data.file;

                    // Dynamically append the image to the images-preview section
                    $('#images-preview').append(`
                       <div class="image-container position-relative m-2 d-flex justify-content-center align-items-center" id="removeid_${fileId}">
                            <a target="blank" href="${window.location.origin}/frontend/serviceProvider/service/${filePath}">
                                <img src="${window.location.origin}/frontend/serviceProvider/service/${filePath}" alt="" width="150px" height="150px">
                            </a>
                            <div class="delete-button-container">
                                <button class="btn btn-danger btn-sm" title="Delete" onclick="deleteImage(${id} , ${fileId})">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    `);
                    progressPercentage.textContent = "Upload complete!";
                } else {
                    // Error message handling
                    progressPercentage.textContent = "Upload failed!";
                }
            });

            // Event listener for upload failure
            xhr.addEventListener("error", () => {
                progressPercentage.textContent = "Error uploading file!";
            });

            // Send the request to the server
            xhr.open("POST", "/admin/services/image-upload"); // Replace with your server endpoint
            xhr.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content); // Add CSRF token
            xhr.send(formData);
        }

        function deleteImage(service_id, imageId) {            
            // AJAX request to delete the image
            $.ajax({
                url: '/admin/services/image-delete', // Route to your delete method
                method: 'POST',
                data: {
                    _token: '{{ csrf_token() }}', // Include CSRF token for security
                    image_id: imageId,
                    service_id: service_id
                },
                success: function(response) {
                    if (response.success) {
                        $(`#removeid_${imageId}`).remove();
                        // On success, remove the image element from the DOM                               
                        const files = response.data;
                        }
                    },
                error: function() {
                    alert('There was an error with the request.');
                }
            });
        }

    </script>
@endpush
