
<!-- dropzone css -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.css"/>

<div class="right_col mt-sm-3" role="main">
  <div class="bussniess_setting">
    <h2 class="titleheading"></h2>
    <div class="row row-gap-30">
      <div class="col-xl-3 col-lg-4">
        <%- include('./partials/user_profile.ejs'); %> 
        <%- include('./partials/tutor_notes_preview.ejs'); %> 
        <%- include('./partials/tutor_attachments_preview.ejs'); %>
        <div class="card student-notes mt-4">
          <div class="note-top tutor-subject d-flex justify-content-between align-items-center">
            <h4>Subjects</h4>
            <a href="javascript:void(0)" class="cursor-pointer" data-tutor-id="6603ebce7193986564d705c0"><img src="/images/arrowdown.svg" alt=""></a>
          </div>
          <div class="subject-data">
            <ul class="">
              <% for(let subject of user.subject_ids) { %>
              <li><%=subject.name%></li>
              <% } %>
            </ul>
          </div>
        </div>
      </div>

      <div class="col-xl-9 col-lg-8">
        <div class="row row-gap-30 mx-0">
          <div class="col-12 px-0">
            <div class="card setting_tab">
              <div class="card-body">
                <ul class="nav nav-pills" id="pills-tab" role="tablist">
                  <!-- <li class="nav-item">
                    <a class="nav-link active" id="tutor-student-tab" data-toggle="pill" href="#tutor-students" role="tab" aria-controls="tutor-students" aria-selected="true">Students</a>
                  </li> -->
                  <li class="nav-item">
                    <a
                      class="nav-link active tutor-preferences-tab"
                      id="tutor-general-tab"
                      data-toggle="pill"
                      href="#tutor-general"
                      role="tab"
                      aria-controls="tutor-general"
                      aria-selected="false"
                      >Preference</a>
                  </li>
                  <li class="nav-item">
                    <a
                      class="nav-link tutor-preferences-tab"
                      id="tutor-availability-tab"
                      data-toggle="pill"
                      href="#tutor-availability"
                      role="tab"
                      aria-controls="tutor-availability"
                      aria-selected="false"
                      >Availability</a>
                  </li>
                  <li class="nav-item">
                    <a
                      class="nav-link tutor-preferences-tab"
                      id="tutor-leaves-tab"
                      data-toggle="pill"
                      href="#tutor-leaves"
                      role="tab"
                      aria-controls="tutor-leaves"
                      aria-selected="false"
                      >Leave Request </a>
                  </li>
                  <!-- <li class="nav-item">
                    <a class="nav-link" id="tutor-attendance-notes-tab" data-toggle="pill" href="#tutor-attendance-notes" role="tab" aria-controls="tutor-attendance-notes" aria-selected="false">Attendance and Notes</a>
                  </li> -->
                  <!-- <li class="nav-item">
                    <a class="nav-link" id="tutor-payroll-tab" data-toggle="pill" href="#tutor-payroll" role="tab" aria-controls="tutor-payroll" aria-selected="false">Payroll</a>
                  </li> -->
                </ul>
              </div>
            </div>
          </div>
          <div class="col-12 px-0">
            <div class="tab-content settings_content" id="pills-tabContent">
              <%- include('./tabs/students.ejs'); %> <%-
              include('./tabs/general.ejs'); %> <%-
              include('./tabs/availability.ejs'); %><%-
              include('./tabs/leaves.ejs'); %>  <%-
              include('./tabs/attendance-and-notes.ejs'); %> <%-
              include('./tabs/payroll.ejs'); %>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<%- include('./modals/private_note.ejs'); %> 
<%- include('./modals/add_attachment.ejs'); %>
<%- include('./modals/edit_attachment.ejs'); %>

<!-- dropzone js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.js"></script>

<script type="text/javascript">
  const userId= '<%=user.id%>';
  /*--------------dropzone code started----------------*/
  Dropzone.autoDiscover = false;
  let CountFiles = 0;
  let privateAttachments = []; 
  const allowedExtensions = ['jpg', 'png', 'mp4', 'mp3', 'm4a', 'pdf', 'docx', 'xlsx'];
  const mimeTypes = 'image/jpeg,image/png,video/mp4,audio/mpeg,audio/mp4,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

  const dropzone = new Dropzone("div#images-dropzone", {
     paramName: "user_attachments",
     url: "/tutor-preferences/dropzone-upload-attachments",
     parallelUploads: 10,
     uploadMultiple: true,
     maxFilesize: 10, // MB
     acceptedFiles: mimeTypes ,
     addRemoveLinks: true,
     autoProcessQueue: true,
     success: function (file, response) {
      privateAttachments.push(...response.attachments);
     },
     init: function () { 
      this.on("addedfile", function(file) { 
        const extension = file.name.split('.').pop().toLowerCase();
        if (this.files.length) {
          var _i, _len;
          _len = this.files.length;
          for (_i = 0; _i < _len - 1; _i++) { // -1 to exclude current file
            if(this.files[_i].name === file.name || !allowedExtensions.includes(extension)){
              this.removeFile(file);
              // alert('Invalid file type. Only the following formats are allowed: ' + allowedExtensions.join(', '));

            }
          }
        }
      });
     },
     removedfile: function (file) {
          file.previewElement.remove();
          let targetObject;
          $.each(privateAttachments, function(index, obj) {
            if (obj.originalname == file.name) {
              targetObject = obj;
              return false; // Exit the loop after finding the object
            }
          });

          $.ajax({
            url: '/tutor-preferences/dropzone-remove-attachment', 
            type: 'POST',
            data: { 
              user_id: userId, 
              filename: targetObject.name 
            }, 
            success: function(response) {
              console.log('File removed from server:', response);
            },
            error: function(error) {
              console.error('Error removing file:', error);
            },
            complete: function () {
                privateAttachments = privateAttachments.filter(obj => obj.originalname !== file.name);
            }
          });
      },
  });
  
/*-------------- dropzone code end ----------------*/

/*-----------add private note-------------*/
  $(".note-edit").click(function () {
    const userId = $(this).data('tutor-id');
    const private_note = `<%=user.note%>`;
    $(".tutor_id").val(userId);
    $("#private-note-text-area").val(private_note);
    $("#studentNotes").modal("show");
  });

  /*----------- add attachments -------------*/
  $(document).ready(function () {
    $("#upload_user_attachments").submit(function (event) {
      event.preventDefault();
      let form = $('#upload_user_attachments');
      let formData = new FormData(form[0]);   
      $('.errors').remove();
      if(privateAttachments.length == 0){
        $("#images-dropzone").after('<p class="errors" style="color:red;">This field is required.</p>');
        return false;
      }
      formData.append('private_attachments', JSON.stringify(privateAttachments));
      $('.errors').remove();
      $.ajax({
        url: "/tutor-preferences/store-private-attachments",
        type: "POST",
        dataType: "json",
        data: formData,
        processData: false,
        contentType: false,
        success: function (response) {
          if(response.success){
            window.location.reload();
          }
        },
       error: function (response) {
            Swal.fire({
                title: 'Oops...',
                text: response.responseJSON.message,
            });
        },
      });
    });
    $(".tutor-subject").on("click", function(){
      $(this).next(".subject-data").slideToggle(300);
    });

    // Handle click event for edit setting elements
    $(".editsetting").on("click", function() {
      var tabcardParent = $(this).closest(".tabcard");
      if (tabcardParent.length > 0) {
        tabcardParent.toggleClass("active");

        // Get all input fields within the tabcard
        var inputFields = tabcardParent.find("input,select,textarea,.btn-disblock");

        // Toggle disabled attribute on input fields
        inputFields.prop("disabled", !tabcardParent.hasClass("active"));
      }
    });

    // Handle click event for Cancel button
    $(".cancel-btn").on("click", function() {
      var tabcardParent = $(this).closest(".tabcard");
      if (tabcardParent.length > 0) {
        tabcardParent.removeClass("active");

        // Get all input fields within the tabcard
        var inputFields = tabcardParent.find("input,select,textarea,.btn-disblock");

        // Disable all input fields
        inputFields.prop("disabled", true);
      }
    });

    // Handle click event for Save button
    $(".save-btn").on("click", function() {
      let tabcardParent = $(this).closest(".tabcard");

      saveBusinessSettings($(this));
      if (tabcardParent.length > 0) {
        tabcardParent.removeClass("active").addClass("change_value");

        // Get all input fields within the tabcard
        var inputFields = tabcardParent.find("input,select,textarea,.btn-disblock");
        // Disable all input fields
        inputFields.prop("disabled", true);
      }
    });

  });

/*-----------------edit attachment-------------------*/
  $(".edit-attachment").click(function(){
    let attachmentId = $(this).data('id');
    let userId = $(this).data('user-id');
    $('.user_id').val(userId);
    $('.attachment_id').val(attachmentId);
      $.ajax({
        url: "/tutor-preferences/edit-relative-attachment-note",
        type: "POST",
        dataType: "json",
        data: {
          user_id:userId,
          attachment_id:attachmentId
        },
        success: function (response) {
          $('#private-description-text-area').val(response.note);
          console.log("Form submission successful:", response);
        },
        error: function (jqXHR, textStatus, errorThrown) {
          console.error("Error submitting form:", textStatus, errorThrown);
        },
      });
    $("#editTutorAttachments").modal('show');
  });

  $('.delete-attachment').click(function(){
    let attachmentId = $(this).data('id');
    let userId = $(this).data('user-id');
      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) {
          deleteAttachment(userId, attachmentId);
        }
      });
  });

  /**
   * to delete an attachment.
   */
  function deleteAttachment(userId, attachmentId) {
    $.ajax({
      url: "/tutor-preferences/destroy-attachment",
      type: "POST",
      dataType: "json",
      data: {
        user_id: userId,
        attachment_id: attachmentId
      },
      success: function (response) {
        if(response.success){
          window.location.reload();
        }
      },
      error: function (jqXHR, textStatus, errorThrown) {
        console.error("Error submitting form:", textStatus, errorThrown);
      }
    });
  }

  $(document).ready(function () {
    setCurrentTab();
   
  });

  function setCurrentTab() {
    let currentTab = $('.tutor-preferences-tab.active').attr('id');
    sessionStorage.setItem('tabData', currentTab);
  }

  (function () {
            const storedTab = sessionStorage.getItem('tabData');
            if (storedTab) {
                $('#' + storedTab).trigger('click');
            }
        })();
</script>