@extends('layouts.admin')
@section('content')
<div class="row">
    <div class="col-12">
        <div class="page-title-box d-sm-flex align-items-center justify-content-between bg-galaxy-transparent">
            <h4 class="mb-sm-0">{{ (!empty($faq->id)) ? 'Edit FAQ' : 'Create FAQ' }}</h4>

            <div class="page-title-right">
                <ol class="breadcrumb m-0">
                    <li class="breadcrumb-item"><a href="javascript: void(0);">Home</a></li>
                    <li class="breadcrumb-item"><a href="javascript: void(0);">FAQ's</a></li>
                    <li class="breadcrumb-item active">{{ (!empty($faq->id)) ? 'Update FAQ' : 'Create FAQ' }}</li>
                </ol>
            </div>
        </div>
    </div>
</div> 
<!-- end page title -->

<div class="row">
    <div class="col-lg-12">
        <div class="card" id="orderList">
            <div class="card-body">
                <form class="tablelist-form {{ !empty($faq->id) ? 'edit-form' : '' }}" autocomplete="off" action="{{ route('admin.faq.store') }}" method="POST" enctype="multipart/form-data" id="faq-form" name="faq-form">
                    <input type="hidden" name="id" id="id" value="{{ (!empty($faq->id)) ? $faq->id : '' }}" />
                    <div class="row">
                        <div class="mb-3 col-lg-8">
                            <label class="form-label">Question</label>
                            <input type="text" name="question" id="question" class="form-control" placeholder="Enter Question" required value="{{ (!empty($faq->question)) ? $faq->question : '' }}" />
                        </div>


                        <div class="col-lg-4 mb-3">
                            <label class="form-label">Status</label> 
                            <select class="form-select js-example-basic-single status-select" data-placeholder="Select Status" name="status" id="status">
                                <option value=""></option>
                                <option value="1" {{ (!empty($faq->status) && $faq->status == 1) ? 'selected' : '' }}>Active</option>
                                <option value="0" {{ (!empty($faq->status) && $faq->status == 0) ? 'selected' : '' }}>Inactive</option>
                            </select>
                        </div>

                        <div class="col-12 mb-3">
                            <label class="form-label">Answer</label>
                            <textarea name="answer"  class="form-control" id="answer"  placeholder="Answer"> {{ (!empty($faq->answer)) ? $faq->answer : '' }}</textarea>
                        </div>


                    </div>

                    

                    <div class="hstack gap-2 justify-content-between">
                        <a href="{{ route('admin.faq') }}" class="btn btn-success">Back</a>
                        <button type="submit" class="btn btn-success" id="submitBtn">{{ (!empty($faq->id)) ? 'Update FAQ' : 'Create FAQ' }}</button>
                        <!-- <button type="button" class="btn btn-success" id="edit-btn">Update</button> -->
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

@endsection
@section('script')
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/additional-methods.min.js"></script>
    <script src="{{ asset('assets/libs/%40ckeditor/ckeditor5-build-classic/build/ckeditor.js') }}"></script>

<!-- dropzone js -->
<script src="{{ asset('assets/libs/dropzone/dropzone-min.js') }}"></script>

<!-- <script src="{{ asset('assets/js/pages/ecommerce-product-create.init.js') }}"></script> -->
<script>
  let editor;

  // Create and initialize the editor
  ClassicEditor.create(document.querySelector('#answer'))
    .then(newEditor => {
      editor = newEditor; // Store the editor instance globally (so you can access it later)

      // Now the editor is initialized, add the event listener for changes
      editor.model.document.on('change:data', function () {
        var submitButton = document.getElementById('submitBtn');

        // Enable the submit button if it’s disabled
        if (submitButton && submitButton.disabled) {
          submitButton.disabled = false;
        }
      });
    })
    .catch(error => {
      console.error('Error initializing CKEditor:', error);
    });
</script>



<script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#faq-form").validate({
                rules: {
                    question: {
                        required: true,
                        minlength: 3,
                    },
                    status: {
                        required: true,
                    },
                    answer: {
                        required: true,
                    }
                },
                messages: {
                    question: {
                        required: "Please enter the question .",
                        minlength: "Question must be at least 3 characters.",
                    },
                    status: {
                        required: "Please select the status.",
                    },
                    answer: {
                        required: "Please enter the answer.",
                    }
                },
                onkeyup: function (element) {
                    $(element).valid(); // Real-time validation on keyup
                },
                onfocusout: function (element) {
                    $(element).valid(); // Validate when focus is lost
                },
                errorPlacement: function (error, element) {
                    if (element.is("select")) {
                        error.insertAfter(element.next('.select2')); 
                    }else if (element.is("textarea") && element.closest('.ck-editor')) {
                        
                        error.insertAfter(element.closest('.ck-editor').querySelector('.ck-editor__editable'));
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function (form) {
                    let formData = new FormData(form);

                    // AJAX submission
                    $.ajax({
                        url: form.action,
                        type: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        headers: {
                            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
                        },
                        success: function (response) {
                            

                            Swal.fire({
                                iconHtml: `<img src="{{ asset('assets/images/success-circle.svg') }}" class="img-fluid">`,
                               // title: "Success!",
                                text: response.message,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm' // Add your custom class here
                                }
                            }).then(() => {
                                window.location.href = "{{ route('admin.faq') }}"; // Redirect to company list
                            });
                        },
                        error: function (xhr) {
                            if (xhr.status === 422) {
                                let errors = xhr.responseJSON.errors;

                                // Display validation errors from the server
                                $.each(errors, function (key, value) {
                                    let field = $(`[name="${key}"]`);
    
                                    field.addClass("error");

                                    field.next('.error').remove();

                                    if (field.is("select")) {
                                        field.next('.select2').after(`<label class="error">${value[0]}</label>`);
                                    } else if (field.is("textarea") && field.hasClass("ckeditor-classic")) {

                                        let editorElement = field.closest('.ck-editor'); 
                                        editorElement.after(`<label class="error">${value[0]}</label>`);
                                    } else {
                                        
                                        field.after(`<label class="error">${value[0]}</label>`);
                                    }
                                });
                            } else {
                                Swal.fire({
                                    text: "Something went wrong. Please try later",
                                    iconHtml: `<img src="{{ asset('assets/images/error-circle.svg') }}" class="img-fluid">`,
                                    confirmButtonText: "OK", // Optional: Change the text of the button
                                    customClass: {
                                        confirmButton: 'custom-ok-button-class w-sm' // Add your custom class here
                                    }
                                });
                            }
                        }
                    });

                    return false; // Prevent default form submission
                },
                invalidHandler: function(event, validator) {
                    var firstInvalidField = $(validator.errorList[0].element);
                    
                    $('html, body').animate({
                        scrollTop: firstInvalidField.offset().top - 100 
                    }, 500); 
                }
            });
        });
    </script>
    
@endsection
