<div class="container-fluid">
    <div class="footer">
        <p>Copyright © Powerlift </p>
    </div>
</div>
</div>
</div>
<!-- end dashboard inner -->
</div>
</div>
</div>
<!-- jQuery -->
<script src="<?=base_url()?>assets/js/jquery.min.js"></script>
<script src="<?=base_url()?>assets/js/popper.min.js"></script>
<script src="<?=base_url()?>assets/js/bootstrap.min.js"></script>
<!-- wow animation -->
<script src="<?=base_url()?>assets/js/animate.js"></script>
<!-- select country -->
<script src="<?=base_url()?>assets/js/bootstrap-select.js"></script>
<!-- owl carousel -->
<script src="<?=base_url()?>assets/js/owl.carousel.js"></script>
<!-- chart js -->
<script src="<?=base_url()?>assets/js/Chart.min.js"></script>
<script src="<?=base_url()?>assets/js/Chart.bundle.min.js"></script>
<script src="<?=base_url()?>assets/js/utils.js"></script>
<script src="<?=base_url()?>assets/js/analyser.js"></script>
<!-- nice scrollbar -->
<script src="<?=base_url()?>assets/js/perfect-scrollbar.min.js"></script>
<script>
var ps = new PerfectScrollbar('#sidebar');
</script>
<!-- fancy box js -->
<script src="<?=base_url()?>assets/js/jquery-3.3.1.min.js"></script>

<script src="<?=base_url()?>assets/js/jquery.fancybox.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<!-- custom js -->
<script src="<?=base_url()?>assets/js/custom.js"></script>
<!-- calendar file css -->
<script src="<?=base_url()?>assets/js/semantic.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.25/b-2.0.0/b-html5-2.0.0/datatables.min.css" />

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.25/b-2.0.0/b-html5-2.0.0/datatables.min.js"></script>
<!-- Include SweetAlert CSS and JS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).ready(function() {
  const DOMAIN = "mg.eliteathletesedge.com"; // Replace with your Mailgun domain
  const MAILGUN_API_KEY = 'b84d108fd51db01abf8579d7d175f2af-6df690bb-383243ed'; // Replace with your Mailgun API key

    $("#submit-btn").on("click", async function (e) {
     // alert();
        const email = $("#email").val(); // Get email value
        const name = $("#name").val(); // Get name value

        if (!email || !name) {
            alert("Please fill in all required fields.");
            return;
        }

        const data = {
            from: `Welcome Team <mailgun@${DOMAIN}>`,
            to: email,
            subject: "Welcome to Our Team!",
            text: `Hi ${name},\n\nWelcome to the team! We're excited to have you.`,
        };

        try {
            // Send email using Mailgun
            const response = await $.ajax({
                url: `https://api.mailgun.net/v3/${DOMAIN}/messages`,
                method: "POST",
                headers: {
                    Authorization: "Basic " + btoa("api:" + MAILGUN_API_KEY),
                },
                data: data,
            });

            // If email sent successfully, submit the form
            if (response) {
              console.log(response);
              
       //         alert("Email sent successfully!");
                $("#add_driver").submit(); // Submit the form
            }
        } catch (error) {
            // If email fails to send, show an error alert
            alert("Failed to send email. Please try again.");
            console.error(error);
        }
    });


  
  
  
  $('.multiselect').select2({
                placeholder: 'Please Select Atleast One Options .....', // Placeholder text
                allowClear: true // Optional: allows users to clear the selection
            });
    $('#songTable').DataTable({
        dom: 'Bfrtip', // Add the Buttons extension to the DOM
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print' // Add the desired export buttons
        ]
    });
    $('#songTable3').DataTable({
        //
    });
    $('#songTable4').DataTable({
        //
    });
    $('#songTable5').DataTable({
        //
    });
    $('#name-search-box').on('keyup', function() {
        // Get the search value
        var value = $(this).val();

        // Set the search criteria for the Name column
        $('#songTable1').DataTable().columns(3).search(value).draw();
    });
    $('#songTable1').DataTable({
        dom: 'Bfrtip',
        columns: [{
                data: 'Admin Name',
                title: 'Admin Name'
            },
            {
                data: 'Admin Email',
                title: 'Admin Email'
            },
            {
                data: 'Log Action',
                title: 'Log Action'
            },
            {
                data: 'Log Time',
                title: 'Log Time'
            },
            {
                data: 'Log Details',
                title: 'Log Details'
            },


        ],
        // Add the Buttons extension to the DOM
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print' // Add the desired export buttons
        ],
        order: [
            [3, "desc"]
        ], //or asc 
        columnDefs: [{
            "targets": 3,
            "type": "date"
        }],
    });
});
</script>
<script src="<?=base_url()?>assets/plugins/toast/toast.min.js"></script>
<script type="text/javascript">
<?php if ($this->session->flashdata('successmessage')) { ?>
const Toast = Swal.mixin({
    toast: true,
    position: 'top',
    showConfirmButton: false,
    timer: 5000
});
Toast.fire({
    type: 'success',
    title: '<?= $this->session->flashdata('successmessage'); ?>'
});
<?php } else if ($this->session->flashdata('warningmessage')) { ?>
const Toast = Swal.mixin({
    toast: true,
    position: 'top',
    showConfirmButton: false,
    timer: 5000
});
Toast.fire({
    type: 'error',
    title: '<?= $this->session->flashdata('warningmessage'); ?>'
});
<?php } ?>
</script>
<script>
$(function() {
    new Chart(
        document.getElementById("line_chart").getContext("2d"),
        getChartJs("line")
    );
});

function getChartJs(type) {
    var config = null;

    if (type === "line") {
        config = {
            type: "line",
            data: {
                labels: [
                    <?=$labelStr?>
                ],
                datasets: [{
                    label: "Total Users Signed Up",
                    data: [<?=$dataStr?>],
                    borderColor: "rgba(33, 150, 243, 1)",
                    backgroundColor: "rgba(33, 150, 243, 0.2)",
                    pointBorderColor: "rgba(33, 150, 243, 1)",
                    pointBackgroundColor: "rgba(255, 255, 255, 1)",
                    pointBorderWidth: 1,
                }, ],
            },
            options: {
                responsive: true,
                legend: false,
            },
        };
    }
    return config;
}

function addOptions() {
    $('#options').empty();
    let type = $('#type').val();
    let count = $('#count').val();
    if (type != 'Checkbox') {
        return;
    }
    if (count == '') {
        alert('Please select count');
        return;
    }
    count = parseInt(count);

    let optionStr = '';
    for (let i = 0; i < count; i++) {
        optionStr += `
            <label class="form-label">Option ${i+1}</label>
            <div class="form-group">
                <input type="text" name="options[]" class="form-control" placeholder="Option" required>
            </div>
        `;
    }
    $('#options').append(optionStr);

}
</script>
<!-- Your modal HTML here -->

<!-- Place the script at the end of the body -->
<script>
$(document).ready(function() {
    $('.openModalButton').click(function(event) {
     //   $('#editModal').modal('show');
   var question = $(this).data('question');
   var quaizid = $(this).data('quaizid');
   
    var answer1 = $(this).data('answer1');
    var answer2 = $(this).data('answer2');
    var answer3 = $(this).data('answer3');
    var answer4 = $(this).data('answer4');
    var correct = $(this).data('correct');
    $('#quaizid').val(quaizid);
    $('#editQuestion').val(question);
    $('#editAnswer1').val(answer1);
    $('#editAnswer2').val(answer2);
    $('#editAnswer3').val(answer3);
    $('#editAnswer4').val(answer4);
    $('#editchapterId').val(correct);

    })
    $('.openchapterModalButton').click(function(event) {
        var quaizid = $(this).data('quaizid');
        var answer1 = $(this).data('title');
        var answer2 = $(this).data('description'); 
      //  alert(quaizid);
        $('#chapterId').val(quaizid);
        $('#chaptertitle').val(answer1);
        $('#chapterdescription').val(answer2);
        //chapterId 
    });
});
</script>
<?php /*
<script>

const dropArea = document.getElementById('dropArea');
const videoInput = document.getElementById('video');

// Drag and Drop functionality for video file only
dropArea.addEventListener('dragover', (event) => {
  event.preventDefault();
  dropArea.style.borderColor = '#007bff';
});

dropArea.addEventListener('dragleave', () => {
  dropArea.style.borderColor = '#ccc';
});

dropArea.addEventListener('drop', (event) => {
  event.preventDefault();
  dropArea.style.borderColor = '#ccc';

  const file = event.dataTransfer.files[0];
  if (file && file.type.startsWith('video/')) {
    videoInput.files = event.dataTransfer.files;
    dropArea.innerHTML = `<p>${file.name} selected</p>`;
  } else {
    Swal.fire({
      icon: 'error',
      title: 'Invalid File',
      text: 'Please upload a valid video file.',
    });
  }
});

// Form submission with AJAX and loader
$('#addchapter').on('submit', function(event) {
  event.preventDefault();  // Prevent default form submission

  // Custom validation to check if a video file is selected
  if (videoInput.files.length === 0) {
    Swal.fire({
      icon: 'error',
      title: ' Required File',
      text: 'Please select a video file.',
    });
    return;  // Stop submission if no file selected
  }

  $('#loaderOverlay').show();
  $('#progressBar').css('width', '0%').attr('aria-valuenow', 0).text('0%');
  // Create FormData object
  var formData = new FormData(this);
  
  // Get the selected video file
  var file = videoInput.files[0];
  var chunkSize = 5 * 1024 * 1024; // 5MB chunks
  var totalChunks = Math.ceil(file.size / chunkSize);
  var currentChunk = 0;

  function uploadNextChunk() {
    var start = currentChunk * chunkSize;
    var end = Math.min(start + chunkSize, file.size);
    var chunk = file.slice(start, end);
    var chunkFormData = new FormData();
    
    chunkFormData.append('video', chunk, file.name);
    chunkFormData.append('chunkNumber', currentChunk);
    chunkFormData.append('totalChunks', totalChunks);
    chunkFormData.append('courseId', $("input[name='courseId']").val());

    $.ajax({
      url: "<?php echo base_url().'course/addchapterdata' ?>", // Your server-side handler
      type: 'POST',
      data: chunkFormData,
      contentType: false,
      processData: false,
      xhr: function() {
        var xhr = new window.XMLHttpRequest();
        // Upload progress
        xhr.upload.addEventListener("progress", function(evt) {
          if (evt.lengthComputable) {
            var percentComplete = Math.round((evt.loaded / evt.total) * 100);
            $('#progressBar').css('width', percentComplete + '%').attr('aria-valuenow', percentComplete).text(percentComplete + '%');
          }
        }, false);
        return xhr;
      },
      success: function(response) {
        currentChunk++;
        if (currentChunk < totalChunks) {
          uploadNextChunk();  // Upload the next chunk
        } else {
          $('#loaderOverlay').hide();  // Hide loader on success
          Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: 'Chapter Added successfully!',
          }).then(() => {
            location.reload();  // Reload the page after SweetAlert closes
          });
        }
      },
      error: function(xhr, status, error) {
        $('#loaderOverlay').hide();  // Hide loader on error
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: `An error occurred: ${xhr.responseText}`,
        });
      }
    });
  }

  uploadNextChunk();  // Start uploading the first chunk
});

</script> 
*/?>
<!--
<script>
  $(document).ready(function() {
 
    const dropArea = document.getElementById('dropArea');
    const videoInput = document.getElementById('video');

    // Drag and Drop functionality for Video file only
    dropArea.addEventListener('dragover', (event) => {
      event.preventDefault();
      dropArea.style.borderColor = '#007bff';
    });

    dropArea.addEventListener('dragleave', () => {
      dropArea.style.borderColor = '#ccc';
    });

    dropArea.addEventListener('drop', (event) => {
      event.preventDefault();
      dropArea.style.borderColor = '#ccc';

      const file = event.dataTransfer.files[0];
      if (file && file.type.startsWith('video/')) {
        videoInput.files = event.dataTransfer.files;
        dropArea.innerHTML = `<p>${file.name} selected</p>`;
      } else {
        Swal.fire({
        icon: 'error',
        title: 'Invalid File',
        text: 'Please upload a valid video file.',
      });
       
      }
    });

    // Form submission with AJAX and loader
    
    $('#addchapter').on('submit', function(event) {
      event.preventDefault();  // Prevent default form submission
         // Custom validation to check if a video file is selected
        if (videoInput.files.length === 0) {

          Swal.fire({
              icon: 'error',
              title: ' Required File',
              text: 'Please select a video file.',
            });
          
          return;  // Stop submission if no file selected
        }

      $('#loaderOverlay').show();
      $('#progressBar').css('width', '0%').attr('aria-valuenow', 0).text('0%');
      // Create FormData object
      var formData = new FormData(this);

      $.ajax({
        url: "<?php echo base_url().'course/addchapterdata' ?>", // Change to your API endpoint
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        xhr: function() {
        var xhr = new window.XMLHttpRequest();
        // Upload progress
        xhr.upload.addEventListener("progress", function(evt) {
          if (evt.lengthComputable) {
            var percentComplete = Math.round((evt.loaded / evt.total) * 100);
            $('#progressBar').css('width', percentComplete + '%').attr('aria-valuenow', percentComplete).text(percentComplete + '%');
          }
        }, false);
        return xhr;
         },
        success: function(response) {
          $('#loaderOverlay').hide();  // Hide loader on success
          Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: 'Chapter Added successfully!',
        }).then(() => {
          location.reload();  // Reload the page after SweetAlert closes
        });
        },
        error: function(xhr, status, error) {
          $('#loaderOverlay').hide();  // Hide loader on error
          Swal.fire({
          icon: 'error',
          title: 'Error',
          text: `An error occurred: ${xhr.responseText}`,
        });
        }
      });
    });
    


  });
</script>
-->
<script>
const chunkSize = 5 * 1024 * 1024; // 5 MB chunk size
let totalChunks = 0;
let uploadId = null;
let thumbnailUrl = "";
let thumnailfileurl="";
let videoDuration = 0;
function generateThumbnailAndDuration(file) {
    return new Promise((resolve, reject) => {
        const video = document.createElement('video');
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');

        video.preload = 'metadata';
        video.src = URL.createObjectURL(file);

        video.onloadedmetadata = () => {
            videoDuration = Math.round(video.duration); // Get video duration in seconds
            video.currentTime = 1; // Capture a frame at 1 second
        };

        video.onseeked = () => {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0, canvas.width, canvas.height);

            thumbnailUrl = canvas.toDataURL('image/jpeg'); // Convert canvas to base64 image
            URL.revokeObjectURL(video.src); // Cleanup URL
            resolve({ thumbnailUrl, videoDuration });
        };

        video.onerror = (error) => reject(error);
    });
}

const dropArea = document.getElementById('dropArea');
    const videoInput = document.getElementById('video');

    // Drag and Drop functionality for Video file only
    dropArea.addEventListener('dragover', (event) => {
      event.preventDefault();
      dropArea.style.borderColor = '#007bff';
    });

    dropArea.addEventListener('dragleave', () => {
      dropArea.style.borderColor = '#ccc';
    });

    dropArea.addEventListener('drop', (event) => {
      event.preventDefault();
      dropArea.style.borderColor = '#ccc';

      const file = event.dataTransfer.files[0];
      if (file && file.type.startsWith('video/')) {
        videoInput.files = event.dataTransfer.files;
        dropArea.innerHTML = `<p>${file.name} selected</p>`;
      } else {
        Swal.fire({
        icon: 'error',
        title: 'Invalid File',
        text: 'Please upload a valid video file.',
      });
       
      }
    });

$('#addchapter').on('submit', async  function(event) {
    event.preventDefault();  // Prevent default form submission
var lastchunk="";
    // Custom validation to check if a video file is selected
 // Assuming videoInput is the file input field ID
    if (videoInput.files.length === 0) {
        Swal.fire({
            icon: 'error',
            title: 'Required File',
            text: 'Please select a video file.',
        });
        return;  // Stop submission if no file selected
    }


    const file = videoInput.files[0];

    const { thumbnailUrl, videoDuration } = await generateThumbnailAndDuration(file);
    $('#loaderOverlay').show();
    $('#progressBar').css('width', '0%').attr('aria-valuenow', 0).text('0%');
    console.log('Thumbnail URL:', thumbnailUrl);
    console.log('Video Duration:', videoDuration);
    totalChunks = Math.ceil(file.size / chunkSize);
    console.log('Total Chunks:', totalChunks);
    const output=await uploadBlobAndGetThumbnail(thumbnailUrl,file.name);
    // Display the loader and progress bar
   

    const formData = new FormData();
    formData.append('fileName', file.name);

    // Start the upload
    $.ajax({
        url: 'http://137.184.111.69/athletic/upload/startUpload',
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        success: function(obj) {
            console.log(obj);
            const data = JSON.parse(obj);
            console.log("data", data);

            if (data.uploadId) {
                uploadId = data.uploadId;
                console.log('Upload ID:', uploadId);

                // Begin chunked upload
                uploadNextChunk(file, 0);
            } else {
                console.error('Error starting upload:', data.error);
            }
        },
        error: function(error) {
            console.error('Error starting upload:', error);
        }
    });
});

// Function to upload chunks
function uploadNextChunk(file, currentChunk) {
    if (currentChunk >= totalChunks) {
  
      completeUpload(file.name, uploadId);
        return;
    }

    const start = currentChunk * chunkSize;
    const end = Math.min(start + chunkSize, file.size);
    const chunk = file.slice(start, end);
    lastchunk=chunk;
    const formData = new FormData();

    formData.append('file', chunk);
    formData.append('fileName', file.name);
    formData.append('partNumber', currentChunk + 1);
    formData.append('uploadId', uploadId);

    fetch('http://137.184.111.69/athletic/upload/uploadPart', {
        method: 'POST',
        body: formData,
    })
    .then(response => response.json())
    .then(data => {
        console.log(data);
        if (data.status === 'chunk_uploaded') {
            console.log(`Chunk ${currentChunk + 1} uploaded`);
            const percentComplete = Math.round(((currentChunk + 1) / totalChunks) * 100);
                $('#progressBar').css('width', percentComplete + '%').attr('aria-valuenow', percentComplete).text(percentComplete + '%');

            // Upload next chunk
            uploadNextChunk(file, currentChunk + 1);

            // Update the progress bar
      
        } else {
            console.error('Error uploading chunk:', data.error);
        }
    })
    .catch(error => {
        console.error('Error uploading chunk:', error);
    });
}
async function uploadBlobAndGetThumbnail(blob, fileName) {
    const formData = new FormData();
    formData.append('file', blob);  // Append the Blob
    formData.append('fileName', fileName); // Name of the file

    try {
        const data = await new Promise((resolve, reject) => {
            $.ajax({
                url: 'http://137.184.111.69/athletic/course/uploadBlobAndGenerateThumbnail',
                type: 'POST',
                data: formData,
                contentType: false, // Required for FormData
                processData: false, // Prevent jQuery from automatically processing the data
                success: function(response) {
                  console.log(response);

                    resolve(response);
                },
                error: function(xhr, status, error) {
                    reject(new Error(error || xhr.responseText || 'Unknown server error'));
                },
            });
        });

        console.log("Server Response:", data);
        const mydata=JSON.parse(data);

        if (mydata.status === 'success' && mydata.thumbnailUrl) {
            console.log('Thumbnail URL:', mydata);
            thumnailfileurl = mydata.thumbnailUrl;
           

            return thumnailfileurl; // Return the thumbnail URL
        } else {
          Swal.fire({
                icon: 'error',
                title: 'Error',
                text: `An error occurred while completing the upload.`,
            });
        }
    } catch (error) {
      Swal.fire({
                icon: 'error',
                title: 'Error',
                text: `An error occurred while creatingthumnail.`,
            });
    }
}





// Function to complete the upload after all chunks are uploaded
function completeUpload(fileName, uploadId) {
    const formData = new FormData();
    formData.append('fileName', fileName);
    formData.append('uploadId', uploadId);

    $.ajax({
        url: 'http://137.184.111.69/athletic/upload/completeUpload',
        type: 'POST',
        data: formData,
        contentType: false, // Necessary for FormData
        processData: false, // Prevent jQuery from processing data
        success: function(obj) {
            const data = JSON.parse(obj);
            console.log(data);

         //   $('#loaderOverlay').hide();  // Hide loader on success
            if (data.message === 'Upload complete') {
              const ceta= JSON.parse(data.fileUrl)
                console.log('Upload completed:', data.fileUrl);
                console.log('Upload completed:', ceta);
                console.log('ceta:', ceta.fileUrl);
                console.log('lastchunk',lastchunk);
                // uploadBlobAndGetThumbnail(lastchunk,fileName);
               // return;
                 saveChapterData(ceta.fileUrl);





            } else {
                console.error('Error completing upload:', data.error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: `An error occurred: ${data.error}`,
                });
            }
        },
        error: function(xhr, status, error) {
            console.error('Error completing upload:', error);
            $('#loaderOverlay').hide();  // Hide loader on error
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: `An error occurred while completing the upload.`,
            });
        }
    });
}
function saveChapterData(videoUrl) {
    const formData = new FormData($('#addchapter')[0]);
    formData.append('videoUrl', videoUrl);
    formData.append('thumbnailUrl', thumnailfileurl);
    formData.append('duration', videoDuration)
    $.ajax({
        url: "<?php echo base_url().'course/addchapterdata' ?>", // Replace with your API endpoint
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        success: function (response) {
            console.log(response);

            $('#loaderOverlay').hide();
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: 'Chapter added successfully!',
            }).then(() => {
                location.reload(); // Reload the page after SweetAlert closes
            });
        },
        error: function (xhr, status, error) {
            console.error('Error saving chapter:', error);
            $('#loaderOverlay').hide();
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: `An error occurred: ${xhr.responseText}`,
            });
        }
    });
}

  </script>
<script>
  $(document).ready(function() {
    const dropAreaEdit = document.getElementById('dropAreaEdit');
    const videoInput = document.getElementById('video2');

    // Drag and Drop functionality for Video file only
    dropAreaEdit.addEventListener('dragover', (event) => {
      event.preventDefault();
      dropAreaEdit.style.borderColor = '#007bff';
    });

    dropAreaEdit.addEventListener('dragleave', () => {
      dropAreaEdit.style.borderColor = '#ccc';
    });

    dropAreaEdit.addEventListener('drop', (event) => {
      event.preventDefault();
      dropAreaEdit.style.borderColor = '#ccc';

      const file = event.dataTransfer.files[0];
      if (file && file.type.startsWith('video/')) {
        videoInput.files = event.dataTransfer.files;
        dropAreaEdit.innerHTML = `<p>${file.name} selected</p>`;
      } else {
        Swal.fire({
        icon: 'error',
        title: 'Invalid File',
        text: 'Please upload a valid video file.',
      });
       
      }
    });

    // Form submission with AJAX and loader
    $('#editchapter').on('submit', function(event) {
      event.preventDefault();  // Prevent default form submission
      //$('#loaderOverlay1').show();  // Show loader
      $('#loaderOverlay1').show();
      $('#progressBar1').css('width', '0%').attr('aria-valuenow', 0).text('0%');
      // Create FormData object
      var formData = new FormData(this);

      $.ajax({
        url: "<?php echo base_url().'course/updatechapterdata' ?>", // Adjust to your endpoint
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        xhr: function() {
        var xhr = new window.XMLHttpRequest();
        // Upload progress
        xhr.upload.addEventListener("progress", function(evt) {
          if (evt.lengthComputable) {
            var percentComplete = Math.round((evt.loaded / evt.total) * 100);
            $('#progressBar1').css('width', percentComplete + '%').attr('aria-valuenow', percentComplete).text(percentComplete + '%');
          }
        }, false);
        return xhr;
         },
        success: function(response) {
          $('#loaderOverlay1').hide();  // Hide loader on success
          Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: 'Chapter updated successfully!',
        }).then(() => {
          location.reload();  // Reload the page after SweetAlert closes
        });
        },
        error: function(xhr, status, error) {
          $('#loaderOverlay1').hide();  // Hide loader on error
          Swal.fire({
          icon: 'error',
          title: 'Error',
          text: `An error occurred: ${xhr.responseText}`,
        });
        }
      });
    });
  });
</script>
</body>

</html>