@extends('frontend.layouts.app')

@section('content')
    @php
        $breadCrump2 = 'Service Posting';
    @endphp

    <style>
        .select2-selection--multiple {
            padding: 11px !important;
        }

        .upload-progress {
            margin-bottom: 15px;
        }

        .file-name {
            font-weight: bold;
        }

        .progress-bar {
            width: 100%;
            height: 20px;
        }

        .progress-percentage {
            display: inline-block;
            margin-top: 5px;
            font-size: 14px;
        }
    </style>

    <div class="wrapper-inner">
        <div class="container">
            <div class="apply-service">
                <div class="headingBlock d-flex align-items-center justify-content-between">
                    <h4>Service Posting</h4>
                </div>
                <form action="{{ route('serviceProvider.servicePost.submit') }}" method="POST" id="service-post-form"
                    enctype="multipart/form-data">
                    @csrf <!-- CSRF protection -->
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="required">Service Title</label>
                                <input type="text" name="title"
                                    class="form-control @error('title') is-invalid @enderror" placeholder="Enter Title"
                                    value="{{ old('title') }}">
                                @error('title')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="required">Pricing Options</label>
                                <input type="text" class="form-control @error('pricing_option') is-invalid @enderror"  readonly  value="Hourly">
                                {{-- <select name="pricing_option"
                                    class="form-control @error('pricing_option') is-invalid @enderror"> --}}

                                    {{-- <option value="hourly" selected>Hourly
                                    </option> --}}
                                    {{-- <option value="project_based"
                                        {{ old('pricing_option') === 'project_based' ? 'selected' : '' }}>Project-Based
                                    </option>
                                    <option value="packages" {{ old('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</label>
                                <input type="text" name="pricing" id="pricing"
                                    class="form-control @error('pricing') is-invalid @enderror" placeholder="Enter Pricing"
                                    value="{{ old('pricing') }}">
                                @error('pricing')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>

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

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

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


                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Discounted Amount</label>
                                <input type="text" name="discounted_amount" class="form-control"
                                    placeholder="Discounted Amount " value="{{ old('discounted_amount') }}">
                            </div>
                        </div>

                        <div class="col-md-12">
                            <div class="form-group">
                                <label class="required">Service FAQs</label>
                                <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.0') }}">
                                        @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.0') }}">
                                        @error('answer.*')
                                            <span class="invalid-feedback">{{ $message }}</span>
                                        @enderror
                                    </div>
                                </div>
                                <button type="button" id="add-question" class="btn btn-secondary mt-2">+</button>
                            </div>
                        </div>

                        <div class="col-md-12">
                        <label class="required">Available Dates & Times</label>
                        </div>
                            <div class="col-md-3">

                                    <input type="datetime-local" name="start_datetime"
                                        class="form-control @error('start_datetime') is-invalid @enderror"
                                        value="{{ old('start_datetime') }}">
                                    </div>
                                    @error('start_datetime')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                <div class="col-md-3">
                                    <input type="datetime-local" name="end_datetime"
                                        class="form-control @error('end_datetime') is-invalid @enderror ml-2">
                                </div>
                                @error('end_datetime')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                @enderror
                        <div class="col-md-12">
                            <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" name="availability[sunday]">
                                                <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[]">
                                                <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[]"
                                                    checked="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[]">
                                                <span class="checkmark"></span>
                                                <div class="week-txt">We</div>

                                            </label>

                                        </div>
                                    </li>
                                    <li>
                                        <div class="remember-link mb-2 d-flex align-items-center justify-content-between">
                                            <label class="custom-checkbox">
                                                <input type="checkbox" value="thursday" name="availability[]"
                                                    checked="checked">
                                                <span class="checkmark"></span>
                                                <div class="week-txt">Th</div>
                                            </label>

                                        </div>
                                    </li>
                                    <li>
                                        <div class="remember-link mb-2 d-flex align-items-center justify-content-between">
                                            <label class="custom-checkbox">
                                                <input type="checkbox" value="friday" name="availability[]">
                                                <span class="checkmark"></span>
                                                <div class="week-txt">Fr</div>
                                            </label>

                                        </div>
                                    </li>
                                    <li>
                                        <div class="remember-link mb-2 d-flex align-items-center justify-content-between">
                                            <label class="custom-checkbox">
                                                <input type="checkbox" value="saturday" name="availability[]"
                                                    checked="checked">
                                                <span class="checkmark"></span>
                                                <div class="week-txt">Sa</div>
                                            </label>

                                        </div>
                                    </li>
                                </ul>
                            </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="form-group">
                                <label>Service Description</label>
                                <textarea name="description" rows="4" class="form-control @error('description') is-invalid @enderror"
                                    placeholder="Your message">{{ old('description') }}</textarea>
                                @error('description')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <div class="apply-btn">
                        <button type="submit" class="btn-custom">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection
@push('front-script')

    <script>
        $(document).ready(function() {


// Add custom validation methods
$.validator.addMethod("greaterThanZero", function(value, element) {
    return this.optional(element) || parseFloat(value) > 0;
}, "This value must be greater than 0.");


            $.validator.addMethod(
        "greaterThanDiscount",
        function(value, element, params) {
            const pricing = parseFloat($("#pricing").val());
            const discount = parseFloat(value);
            if (isNaN(pricing) || isNaN(discount)) {
                return true; // Skip validation if either field is empty
            }
            return pricing > discount;
        },
        "Pricing must be greater than the discounted amount"
    );


            $("#service-post-form").validate({
                rules: {
                    title: {
                        required: true,
                        minlength: 3
                    },
                    pricing_option: {
                        required: true
                    },
                    pricing: {
                        required: true,
                        number: true,
                        greaterThanZero: true
                    },
                    service_category_id: {
                        required: true
                    },
                    country_id: {
                        required: true
                    },
                    state_id: {
                        required: true
                    },
                    city_id: {
                        required: true
                    },
                    discounted_amount: {
                        number: true,
                        greaterThanDiscount: true,
                        greaterThanZero: 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
                    },
                    // 'file[]': {
                    //     extension: "jpg|jpeg|png|gif|mp4|avi|mov"
                    // }
                },
                messages: {
                    title: {
                        required: "Please enter a service title",
                        minlength: "Title must be at least 3 characters long"
                    },
                    pricing_option: {
                        required: "Please select a pricing option"
                    },
                    pricing: {
                        required: "Please enter pricing",
                        number: "Please enter a valid number"
                    },
                    service_category_id: {
                        required: "Please select a service category"
                    },
                    country_id: {
                        required: "Please select a country"
                    },
                    state_id: {
                        required: "Please select a state"
                    },
                    city_id: {
                        required: "Please select a city"
                    },
                    discount: {
                        number: "Please enter a valid discount"
                    },
                    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"
                    },
                    'question[]': {
                        required: "Please enter a question",
                        minlength: "Question must be at least 3 characters long"
                    },
                    'answer[]': {
                        required: "Please enter an answer",
                        minlength: "Answer must be at least 3 characters long"
                    },
                    'file[]': {
                        extension: "Only image and video files are allowed"
                    }
                },
                errorElement: "span",
                errorClass: "invalid-feedback",
                highlight: function(element) {
                    $(element).addClass("is-invalid");
                },
                unhighlight: function(element) {
                    $(element).removeClass("is-invalid");
                }
            });

            // 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");
        });

        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();
                $.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().append(
                            '<option value="">Select State</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
                    },
                    success: function(response) {
                        if (response.status === 'success') {
                            var citySelect = $('#city_id');
                            citySelect.empty().append('<option value="">Select City</option>');
                            $.each(response.data, function(index, city) {
                                citySelect.append('<option value="' + city.id + '">' +
                                    city.name + '</option>');
                            });
                        } else {
                            alert('No city found for the selected state.');
                        }
                    },
                    error: function(xhr) {
                        console.error('Request failed:', xhr);
                    }
                });
            });

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

            $('#add-question').click(function () {
                const newQuestion = `
                    <div class="screening-question-wrapper mb-2">
                        <div class="screening-question">
                            <input type="text" name="question[]" class="form-control @error('question.*') is-invalid @enderror" placeholder="Enter Question" value="{{ old('question.${questionIndex}') }}">
                            @error('question.*')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                        <div class="question">
                            <input type="text" name="answer[]" class="form-control @error('answer.*') is-invalid @enderror mb-4" placeholder="Enter Answer" value="{{ old('answer.${questionIndex}') }}">
                            @error('answer.*')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div> 
                        <button type="button" class="btn btn-danger remove-question"> - </button>
                    </div>
                `;
                $('#screening-questions-container').append(newQuestion);
                questionIndex++;
            });

            // Attach event handler to a static parent and delegate the click event
            $(document).on('click', '.remove-question', function () {
                $(this).closest('.screening-question-wrapper').remove(); // Remove the entire wrapper
            });

        });


        // 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 = '';

            const allowedTypes = ["image/jpeg", "image/png", "image/gif", "image/webp", "video/mp4", "video/webm", "video/ogg"];

            // Loop through selected files and upload them
            Array.from(files).forEach((file) => {

                if (!allowedTypes.includes(file.type)) {
                    Swal.fire({
                icon: 'error',
                title: 'Invalid File Type',
                text: `The file "${file.name}" is not a valid image or video. Please select a valid file.`,
                confirmButtonText: 'OK'
            });
            return;
        }
                // 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);
            });
        });

        // Function to upload a file
        function uploadFile(file, progressBar, progressPercentage) {
            const formData = new FormData();
            formData.append("file", file);

            // 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
                    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
            // Send the request to the server
        xhr.open("POST", "{{route('serviceProvider.service.uploadImage')}}"); // Replace with your server endpoint
        xhr.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content); // Add CSRF token
        xhr.send(formData);
        }
    </script>
@endpush
