// multipal image upload js
jQuery(document).ready(function () {
  ImgUpload();
});

function ImgUpload() {
  var imgWrap = "";
  var imgArray = [];

  $(".upload__inputfile").each(function () {
    $(this).on("change", function (e) {
      imgWrap = $(this).closest(".upload__box").find(".upload__img-wrap");
      var maxLength = $(this).data("max_length");

      var files = e.target.files;
      var filesArr = Array.prototype.slice.call(files);

      filesArr.forEach(function (f, index) {
        if (!f.type.match("image.*")) {
          return;
        }

        if (imgArray.length >= maxLength) {
          return false;
        } else {
          imgArray.push(f);

          var reader = new FileReader();
          reader.onload = function (e) {
            var html =
              "<div class='upload__img-box'><div style='background-image: url(" +
              e.target.result +
              ")' data-number='" +
              $(".upload__img-close").length +
              "' data-file='" +
              f.name +
              "' class='img-bg'><div class='upload__img-close'></div></div></div>";
            imgWrap.append(html);
          };
          reader.readAsDataURL(f);
        }
      });
    });
  });

  $("body").on("click", ".upload__img-close", function (e) {
    var file = $(this).parent().data("file");
    for (var i = 0; i < imgArray.length; i++) {
      if (imgArray[i].name === file) {
        imgArray.splice(i, 1);
        break;
      }
    }
    $(this).parent().parent().remove();
  });
}

//multipal document upload
$(document).ready(function () {
  DocumentUpload();
});

function DocumentUpload() {
  $(".document-upload-input").on("change", function (e) {
    var previewDiv = $(this).closest(".upload__box").find(".document-preview");
    previewDiv.empty(); // Clear previous previews
    var files = e.target.files;
    var filesArr = Array.prototype.slice.call(files);

    filesArr.forEach(function (file) {
      var reader = new FileReader();
      reader.onload = function (e) {
        var fileContent = e.target.result;
        // Display document preview
        previewDiv.append(
          "<embed src='" + fileContent + "' width='200' height='200'>"
        );
      };
      reader.readAsDataURL(file);
    });
  });
}

// session script for subject details to class return
