
<?php $__env->startSection('title', 'Sample Question'); ?>
<?php $__env->startSection('content'); ?>
<style>
  .cke_notification{
    display: none;
  }
</style>

<div class="dashboard-content bg-light p-4 mt-5">
    <div class="content-card rounded-2 bg-white p-4 mt-lg-4 mt-md-4 mt-1">

        <div class="row align-items-center">

            <div class="col-md-12">
                <div class="d-flex justify-content-between">
                  
                  <div class="add-div-btn">
                      <button type="button" id="addbutton" class="btn btn add-btn px-4 py-2" data-toggle="modal" data-target="#exampleModal">
                          Add Question
                      </button>
                  </div>
                  
              
                  <div class="add-div-btn">
                        <form>
                            <div class="input-group">
                                <span class="input-group-text bg-white"><a href="#" class="text-dark"><i class="fa-solid fa-magnifying-glass"></i></a></span>
                                <input type="text" class="form-control border-start-0" placeholder="Search User" id="searchData">
                            </div>
                        </form>
                  </div>
                </div>
            </div>
         
            
        </div> 

        <div class="row mt-4">
            <div class="col-md-12">
                <div class="table-responsive user-table student-table" id="data-list">
                    <?php echo $__env->make('admin.sample_questions.ajax', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                    <!-- Loading Spinner -->
                    <div id="loading" class="position-absolute top-50 start-50" style="display:none;">
                        <div class="loader"></div>
                    </div>
                    
                </div>
            </div>
        </div>

    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="formModal" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header justify-content-between">
            <h5 class="modal-title" id="formModal">Sample Question</h5>
            <button type="button" class="btn-close" data-dismiss="modal"></button>
            
          </div>
          <div class="modal-body">
            <form id="posterForm" action="<?php echo e(route('admin.samplequestions-store')); ?>" method="POST" enctype="multipart/form-data">
              <?php echo csrf_field(); ?>
              <div class="form-group">
                <label for="question">Question<span class="text-danger">*</span></label>
                <div class="input-group mt-2 rounded-2">
                  <input type="text" class="form-control rounded-2" placeholder="Enter question" name="question" id="question">
                </div>
                <p class="text-danger custom-text" id="error-question"></p>
              </div>
    
              <div class="modal-footer d-flex justify-content-end border-0">
                <button class="btn btn add-btn px-4 py-2 " type="submit">Submit</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    
    <!-- The Modal -->
  <div class="modal fade" id="posteredit" tabindex="-1" aria-labelledby="formModal" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title" id="formModal">Edit Sample Question</h5>
                
                <button type="button" class="btn-close" data-dismiss="modal"></button>
            </div>

            <div class="modal-body p-4">
                <!-- This gets replaced by AJAX -->
            </div>

        </div>
    </div>
</div>

 
</div>
</div>

<!-- CSS in <head> -->
<!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"> -->

<!-- JS before </body> -->
<!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script> -->


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

        function fetchData(url){
            let search = $('#searchData').val();

            $.ajax({
                url: url,
                type: "GET",
                data: { search: search },
                beforeSend: function() {
                    $('#loading').show();
                },
                success: function(data){
                    $('#data-list').html(data);
                    $('#loading').hide();
                },
                error: function() {
                    alert('Error loading data.');
                    $('#loading').hide();
                }
            });
        }

        // Handle Pagination Click
        $(document).on('click', '.pagination-wrapper a', function(e) {
            e.preventDefault();
            let url = $(this).attr('href');
            fetchData(url);
        });

        // Handle Search Input Typing (with delay)
        let typingTimer;
        let doneTypingInterval = 500; // 0.5 second after user stops typing

        $('#searchData').on('keyup', function () {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(function() {
                //fetchData("<?php echo e(route('admin.revenue.index')); ?>");
                fetchData(window.location.href);
            }, doneTypingInterval);
        });

        $('#searchData').on('keydown', function () {
            clearTimeout(typingTimer);
        });

    });
</script>

<script>
  $('#addbutton').on('click', function() {
     $('p.custom-text').html("");
  });
</script>

  <script>
    
    $(document).ready(function() {
      new DataTable('#poster_id');

    });

    //delete
   
    $(document).on('click', ".delete-btn", function() {
    var itemId = $(this).attr('data-id'); 

    // Show confirmation dialog using SweetAlert2
    Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            // Send AJAX request to delete item
            $.ajax({
                url: "<?php echo e(route('admin.samplequestions-delete')); ?>",
                type: 'POST',
                data: {
                    id: itemId,
                    '_token': '<?php echo e(csrf_token()); ?>'
                },
                success: function(response) {
                    Swal.fire(
                        'Deleted!',
                        'The sample question has been successfully deleted',
                        'success'
                    );
                    setTimeout(function() {
                        window.location.reload(); 
                    }, 1000);
                    // Optionally, you can remove the deleted item from the DOM
                    // $(this).closest('.item').remove();
                },
                error: function(xhr, status, error) {
                    Swal.fire(
                        'Error!',
                        'An error occurred while deleting the item.',
                        'error'
                    );
                }
            });
        }
    });
});
        
</script>

<script>
    function editFunction(id) {
        $.ajax({
            url: '/admin/sample-questions/edit/' + id,
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                if (data.html) {
                    $('#posteredit .modal-body').html(data.html);
                    const modal = new bootstrap.Modal(document.getElementById('posteredit'));
                    modal.show();
                } else {
                    alert('No HTML received.');
                }
            },
            error: function (xhr) {
                console.error('AJAX error:', xhr.responseText);
                alert('Something went wrong.');
            }
        });
    }
</script>



<script>
    $(document).on('submit', 'form#UpdatePosterForm', function(e) {
        e.preventDefault();

        var form = $(this);
        var formData = new FormData(this);
        var submitButton = $('#updateBtn');
        submitButton.prop('disabled', true).text('Updating...');

        // Clear previous error messages
        $('.text-danger').html('');

        $.ajax({
            url: form.attr('action'),
            method: form.attr('method'),
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                submitButton.prop('disabled', false).text('Update');

                if (response.success) {
                    toastr.success(response.message || "Updated Successfully");

                    window.setTimeout(function() {
                        window.location.href = "<?php echo e(route('admin.sample-questions')); ?>";
                    }, 2000);
                } else if (response.errors) {
                    console.log(response.errors); 

                    $.each(response.errors, function(key, error) {
                        var errorId = `#error-${key.replace('.', '_')}`;
                        $(errorId).html(error[0]);
                        console.log('Displaying error for:', errorId);
                    });
                } else {
                    alert("No changes were made.");
                }
            },
            error: function(xhr) {
                submitButton.prop('disabled', false).text('Update');
                alert("An error occurred. Please try again.");
                console.log(xhr.responseText);
            }
        });
    });
</script>


<script>
      $(document).on('submit', 'form#posterForm', function(event) {
        event.preventDefault();

        $('p.error_container').html("");
        
        var form = $(this);
        var formid = $(this).attr('id');

        var data = new FormData($(this)[0]);
        var url = form.attr("action");
        var loadingText = '<i class="fa fa-circle-o-notch fa-spin"></i> loading...';
        $('.submit').attr('disabled', true);
        $('.form-control').attr('readonly', true);
        if ($('.submit').html() !== loadingText) {
            $('.submit').html(loadingText);
        }

        $.ajax({
            type: form.attr('method'),
            url: url,
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            success: function(response) {
              
                if (response.success == true) {
                    //notify
                    toastr.success("Created Successfully");

                    // redirect to google after 5 seconds
                    window.setTimeout(function() {
                        window.location = "<?php echo e(route('admin.sample-questions')); ?>";
                    }, 2000);
                }
                //show the form validates error
               
                if (response.success == false) {
                    for (control in response.errors) {
                        var error_text = control.replace('.', "_");
                        $('#'+formid+' #error-' + error_text).html(response.errors[control]);
                        
                    }

                    $('.submit').attr('disabled', false);
                    $('.form-control').attr('readonly', false);
                    $('.submit').html('Save');
                    // console.log(response.errors);
                }
            },
            error: function(response) {
                alert("Error: " + errorThrown);
                console.log(response);
                $('.submit').attr('disabled', false);
                    $('.form-control').attr('readonly', false);
                    $('.submit').html('Save');
            }
        });
        event.stopImmediatePropagation();
        return false;
    });
          
</script>

  <?php $__env->stopSection(); ?>
 



<?php echo $__env->make('layouts.admin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/quikwise-admin/resources/views/admin/sample_questions/index.blade.php ENDPATH**/ ?>