if (document.getElementById("veridyPay")) {
  document.getElementById("veridyPay").addEventListener("click", verifyPaymentRef);
}
if (document.getElementById("veridyBindingPay")) {
  document.getElementById("veridyBindingPay").addEventListener("click", verifyPaymentRefBinding);

}
const getProjectByDepartment = async (id,pageNumber=1,sessionId) => {
    jQuery.ajax({
        url:`/research/view/${id}?sessionId=${sessionId}&pageNumber=${pageNumber}&pageSize=10`,
        method:'GET',
        error: function (request, error) {
          Swal.fire({
            position: 'top-end',
            icon: 'error',
            title: error,
            showConfirmButton: false,
            timer: 1500
          })
        },
         success:function(data)
            {
              if(data.projects.length < 1){
                Swal.fire({
                  position: 'top-end',
                  icon: 'error',
                  title: "No record to fetch",
                  showConfirmButton: false,
                  timer: 1500
                })
              }
                document.getElementById("filterType").value = "dept";
                document.getElementById("projectContainer").innerHTML = "";
                for (project of data.projects){
                    document.getElementById("projectContainer")
                    .innerHTML += projectTemplateForDepartment (
                      project.id,
                      project.topic, 
                      {firstname:project.firstname, lastname:project.firstname, username:project.firstname }, 
                      {},
                      project.username, 
                      new Date(project.createdAt).toLocaleDateString('en-us', { weekday:"long", year:"numeric", month:"short", day:"numeric"}), 
                      project.project_types_name,
                      project.department_name, 
                      project.institute_name
                        ) 
                }  
            }
        });
}
const getProjectLoadMore = async (pageNumber=1,sessionId) => {
  jQuery.ajax({
      url:`/research/view-inner?sessionId=${sessionId}&pageNumber=${parseInt(pageNumber)}`,
      method:'GET',
      error: function (request, error) {
        Swal.fire({
          position: 'top-end',
          icon: 'error',
          title: error,
          showConfirmButton: false,
          timer: 1500
        })
      },
       success:function(data)
          {
            if(data.projects.length < 1){
              Swal.fire({
                position: 'top-end',
                icon: 'error',
                title: "No record to fetch",
                showConfirmButton: false,
                timer: 1500
              })
            }
              document.getElementById("filterType").value = "dept";
              document.getElementById("projectContainer").innerHTML = "";
              for (project of data.projects){
                  document.getElementById("projectContainer")
                  .innerHTML += projectTemplate (
                      project.id,
                      project.topic, 
                      project.student, 
                      project.lecturer, 
                      project.student.username, 
                      new Date(project.createdAt).toLocaleDateString('en-us', { weekday:"long", year:"numeric", month:"short", day:"numeric"}), 
                      project.project_type?.name,
                      project.student.profile.department?.name, 
                      project.student.profile.department?.institute.name
                      ) 
              }
              $("#pageNumber").val(pageNumber++); 
              $("#loadMore").html("Load More");          
          }
      });
}
const getProjectByProjectType = async (projectType,sessionId) => {
  jQuery.ajax({
      url:`/research/view-inner?sessionId=${sessionId}&projectType=${projectType}`,
      method:'GET',
      error: function (request, error) {
        Swal.fire({
          position: 'top-end',
          icon: 'error',
          title: error,
          showConfirmButton: false,
          timer: 1500
        })
      },
       success:function(data)
          {
            if(data.projects.length < 1){
              Swal.fire({
                position: 'top-end',
                icon: 'error',
                title: "No record found",
                showConfirmButton: false,
                timer: 1500
              })
            }
              document.getElementById("filterType").value = "dept";
              document.getElementById("projectContainer").innerHTML = "";
              for (project of data.projects){
                  document.getElementById("projectContainer")
                  .innerHTML += projectTemplate (
                    project.id,
                    project.topic, 
                    project.student, 
                    project.lecturer, 
                    project.student.username, 
                    new Date(project.createdAt).toLocaleDateString('en-us', { weekday:"long", year:"numeric", month:"short", day:"numeric"}), 
                    project.project_type?.name,
                    project.student.profile.department?.name, 
                    project.student.profile.department?.institute.name
                      ) 
              }         
          }
      });
}
const getProjectBySearch = async (searchTerm, sessionId) => {
  jQuery.ajax({
      url:`/research/search?searchTerm=${searchTerm}&sessionId=${sessionId}`,
      method:'GET',
      error: function (request, error) {
        Swal.fire({
          position: 'top-end',
          icon: 'error',
          title: "An error occured " + JSON.stringify(error),
          showConfirmButton: false,
          timer: 1500
        })
      },
       success:function(data)
          {
            if(data.projects.length < 1){
              Swal.fire({
                position: 'top-end',
                icon: 'error',
                title: "No record found",
                showConfirmButton: false,
                timer: 1500
              })
            }
              document.getElementById("filterType").value = "dept";
              document.getElementById("projectContainer").innerHTML = "";
              for (project of data.projects){
                  document.getElementById("projectContainer")
                  .innerHTML += projectTemplate (
                    project.id,
                    project.topic, 
                      project.student, 
                      project.lecturer, 
                      project.student.username, 
                      new Date(project.createdAt).toLocaleDateString('en-us', { weekday:"long", year:"numeric", month:"short", day:"numeric"}), 
                      project.project_type?.name,
                      project.student.profile.department?.name, 
                      project.student.profile.department?.institute.name
                    ) 
              }         
          }
      });
}
const getTopicStudentDashboard = (term, props) => {
  jQuery.ajax({
    url:`/getProjectStudentForLecturer/${term}/${props}`,
    method:'GET',
    error: function (request, error) {
      Swal.fire({
        position: 'top-end',
        icon: 'error',
        title: "An error occured " + JSON.stringify(error),
        showConfirmButton: false,
        timer: 1500
      })
    },
     success:function(data)
        {

          document.getElementById("projectList").innerHTML = "";
          if(data?.length < 1){
            Swal.fire({
              position: 'top-end',
              icon: 'error',
              title: "No record found",
              showConfirmButton: false,
              timer: 1500
            })
          }
            for (project of data){
                document.getElementById("projectList")
                .innerHTML += staffProjectTemplate (project) 
            }         
        }
    }); 
}
const getTopicStudentDashboardSearch = (term) => {
  jQuery.ajax({
    url:`/searchStudentProject`,
    method:'GET',
    error: function (request, error) {
      Swal.fire({
        position: 'top-end',
        icon: 'error',
        title: "An error occured " + JSON.stringify(error),
        showConfirmButton: false,
        timer: 1500
      })
    },
     success:function(data)
        {

          document.getElementById("projectList").innerHTML = "";
          if(data?.length < 1){
            Swal.fire({
              position: 'top-end',
              icon: 'error',
              title: "No record found",
              showConfirmButton: false,
              timer: 1500
            })
          }
            for (project of data){
                document.getElementById("projectList")
                .innerHTML += staffProjectTemplate (project) 
            }         
        }
    }); 
}
const getStudentRecord = (term, props) => {
  jQuery.ajax({
    url:`/studentManagemtFilter/${term}/${props}`,
    method:'GET',
    error: function (request, error) {
      Swal.fire({
        position: 'top-end',
        icon: 'error',
        title: "An error occured " + JSON.stringify(error),
        showConfirmButton: false,
        timer: 1500
      })
    },
     success:function(data)
        {

          document.getElementById("studentList").innerHTML = "";
          if(data?.length < 1){
            Swal.fire({
              position: 'top-end',
              icon: 'error',
              title: "No record found",
              showConfirmButton: false,
              timer: 1500
            })
          }
            for (student of data){
                document.getElementById("studentList")
                .innerHTML += studentListTemplate (student) 
            }         
        }
    }); 
}
const getStudentRecordsearchFilter = (term) => {
  jQuery.ajax({
    url:`/studentManagemtSearchFilter/${term}`,
    method:'GET',
    error: function (request, error) {
      Swal.fire({
        position: 'top-end',
        icon: 'error',
        title: "An error occured " + JSON.stringify(error),
        showConfirmButton: false,
        timer: 1500
      })
    },
     success:function(data)
        {

          document.getElementById("studentList").innerHTML = "";
          if(data?.length < 1){
            Swal.fire({
              position: 'top-end',
              icon: 'error',
              title: "No record found",
              showConfirmButton: false,
              timer: 1500
            })
          }
            for (student of data){
                document.getElementById("studentList")
                .innerHTML += studentListTemplate (student) 
            }         
        }
    }); 
}
const getProjectBySession = async (sessionId) => {
  jQuery.ajax({
      url:`/research/view-inner?sessionId=${sessionId}`,
      method:'GET',
      error: function (request, error) {
        Swal.fire({
          position: 'top-end',
          icon: 'error',
          title: error,
          showConfirmButton: false,
          timer: 1500
        })
      },
       success:function(data)
          {
            if(data.projects.length < 1){
              Swal.fire({
                position: 'top-end',
                icon: 'error',
                title: "No record to fetch",
                showConfirmButton: false,
                timer: 1500
              })
            }
              document.getElementById("filterType").value = "dept";
              document.getElementById("projectContainer").innerHTML = "";
              for (project of data.projects){
                  document.getElementById("projectContainer")
                  .innerHTML += projectTemplate (
                    project.id,
                      project.topic, 
                      project.student, 
                      project.lecturer, 
                      project.student.username, 
                      new Date(project?.createdAt).toLocaleDateString('en-us', { weekday:"long", year:"numeric", month:"short", day:"numeric"}), 
                      project.project_type?.name,
                      project.student.profile.department?.name, 
                      project.student.profile.department?.institute.name
                      ) 
              }         
          }
      });
}
$('#dept').on('change', function() {

    let sessionId = $("#sessionLoad").val();
    let pageNumber = $("#pageNumber").val();
    const projects = getProjectByDepartment(this.value,pageNumber,sessionId)
  });
$('#projectType').on('change', function() {
  let sessionId = $("#sessionLoad").val();
    const projects = getProjectByProjectType(this.value,sessionId)
  });
$('.dashboardFilter').on('change', function() {
  const prop = this.value.split(" ")
    const projects = getStudentRecord(prop[0],prop[1])
  });
  $('.dashboardFilterProject').on('change', function() {
    const prop = this.value.split(" ")
      const projects = getTopicStudentDashboard(prop[0],prop[1])
    });
$('.studentRecordFilter').on('change', function() {
    const prop = this.value.split(" ")
      const projects = getStudentRecord(prop[0],prop[1])
    });
$('#dateRange').on('apply.daterangepicker', function() {
    alert(this.value)
  });

$('#addPage').on('click', function() {
    const filterType = $("#filterType").val();
    let pageNumber = this.value
    if(pageNumber = 1){
      pageNumber = 0
    }
    if(filterType === "dept"){
      const activeDept = $("#dept").val();
      getProjectByDepartment(activeDept, parseInt(pageNumber) + 1)
    }
  });
// Research Library Load more..................................................................
$('#loadMore').on('click', function() {
  $("#loadMore").html("loading..."); 
  let sessionId = $("#sessionLoad").val();
  let pageNumber = $("#pageNumber").val();
  getProjectLoadMore(parseInt(pageNumber) + 1, sessionId);

});

$('#subPage').on('click', function() {
    Swal.fire({
      position: 'top-end',
      icon: 'error',
      title: this.value+filterType,
      showConfirmButton: false,
      timer: 1500
    })
  });

// Research Library Search ..................................................................
$("#searchProject").on('paste input', function(){
  let sessionId = $("#sessionLoad").val();
    let searchTerm = this.value;
    if(searchTerm.split(' ').length > 2)
    getProjectBySearch(searchTerm, sessionId)
});

// Research Library Date Range Search ..................................................................
$('#dateRange').on('change', function() {
  alert(this.value)
});

// Session Change ..................................................................
$('#sessionLoad').on('change', function() {
  const sessionId = this.value
  getProjectBySession(sessionId);
});

$("#studentSearch").on('paste input', function(){
  let searchTerm = this.value;
  // if(searchTerm.split(' ').length > 1)
  getTopicStudentDashboardSearch(searchTerm)
});
$("#studentSearchFilter").on('paste input', function(){
  let searchTerm = this.value;
  if(searchTerm.split(' ').length > 1)
  getStudentRecordsearchFilter(searchTerm)
});
$("#projNum").on('change', function(){
  let topicNum = this.value;
  let moreBox = ""
  for( let i = 0; i < parseInt(topicNum); i++){
    moreBox += `
    <label> Topic ${i + 1}</label><br>
    <textarea name="" id="topic${i + 1}" class="form-control" cols="40" rows="2"></textarea>
    `
  }

  $('#topicBlock').html(moreBox); 
});
$("#submitTopic").on("click", function(){
  const projectType = $('#projType').val(); 
  const topic1 = $('#topic1').val(); 
  const topic2 = $('#topic2').val(); 
  const topic3 = $('#topic3').val(); 
  const user_id = $('#user_id').val(); 
  const lecturer_id = $('#lecturer_id').val(); 
  const cbo_username = $('#cbo_username').val(); 
  const cbo_otp = $('#cbo_otp').val(); 
  let topicArr = [];
  if(topic1 == ''){
    closeSideNav() 
    Swal.fire({
      position: 'top-end',
      icon: 'error',
      title: "Please input at least one topic",
      showConfirmButton: false,
      timer: 1500
    })
    // alert("Please input at least one topic")
    return
  }
  // if(!cbo_username || !cbo_otp){
  //   closeSideNav() 
  //   Swal.fire({
  //     position: 'top-end',
  //     icon: 'error',
  //     title: "Please input CBO details",
  //     showConfirmButton: false,
  //     timer: 1500
  //   })
  //   // alert("Please input CBO details")
  //   return
  // }
  if(topic1)
  topicArr.push(topic1)
  if(topic2)
  topicArr.push(topic2)
  if(topic3)
  topicArr.push(topic3)

  jQuery.ajax({
    url:`/user/newprojecttopic`,
    method:'POST',
    data:{
      projectTopics:topicArr,
      projectType,
      user_id,
      lecturer_id,
      cbo_username,
      cbo_otp
    },
    error: function (request, error) {
      closeSideNav() 
      Swal.fire({
        position: 'top-end',
        icon: 'error',
        title: error,
        showConfirmButton: false,
        timer: 1500
      })
    },
     success:function(data)
        {
          console.log(data)
          if(data.success == false){
          Swal.fire({
            position: 'top-end',
            icon: 'error',
            title: data.message,
            showConfirmButton: false,
            timer: 1500
          })
          closeSideNav()  
          return
          }
          Swal.fire({
            position: 'top-end',
            icon: 'success',
            title: "Topic added successfully",
            showConfirmButton: false,
            timer: 1500
          })
          closeSideNav()
          location.reload();        
        }
    });
})
$("#edit-submit-btn").on('click', function(){
  const lastname = $("#lastname").val();
  const ppo_id = $("#ppo_id").val();
  const firstname = $("#firstname").val();
  const middlename = $("#middlename").val();
  const user_id = $("#user_id").val();
  const email = $("#email").val();
  const contact = $("#contact").val();
  const level_id = $("#level_id").val();
  const supervisor = $("#supervisor").val();
  const study_mode_id = $("#study_mode_id").val();
  const username = $("#username").val();
  const department_id = $("#department_id").val();
  const reactivate = $("#reactivate").val();
  jQuery.ajax({
    url:`/user/profile`,
    method:'POST',
    data:{
      lastname,
      firstname,
      middlename,
      email,
      username,
      user_id,
      phone:contact,
      supervisor,
      study_mode_id,
      level_id,
      department_id,
      reactivate,
      ppo_id
    },
    error: function (request, error) {
      Swal.fire({
        position: 'top-end',
        icon: 'error',
        title: "An error occured " + JSON.stringify(error),
        showConfirmButton: false,
        timer: 1500
      })
    },
     success:function(data)
        {  
          Swal.fire({
            position: 'top-end',
            icon: 'success',
            title: "Record updated successfully",
            showConfirmButton: false,
            timer: 1500
          })     
        }
    }); 
});




const projectTemplate = (id,topic, researcher, lecturer, matric, date,type, Institute, department) => {
    return `<div class="col-lg-6">
    <div class="card_box position-relative mb_10 white_bg">
      <div class="white_box_tittle green_bg">
        <div class="main-title2">
          <strong class="text-white"> ${topic.toUpperCase()} </strong>
        </div>
      </div>
      <div class="box_body">
        <ul>
            <li><b>Research By: </b> <span style="text-transform:uppercase;">${researcher.profile.firstname}</span> <span>${researcher.profile.lastname} </span><span style="color:#FFB167;">${matric.toUpperCase()}</span> </li>
            <li><b>Supervised By:</b> <span style="text-transform:uppercase;"> ${lecturer.profile.firstname} ${lecturer.profile.lastname}  </span> </li>
            <li><b>Date Created:</b> <span>${date} </span> </li>
            <li>
                <ul>
                    <li class="badgelist"><span class="badge bg-secondary">${type} </span></li>
                    <li class="badgelist"><span class="badge bg-success">${department} </span></li>
                    <li class="badgelist"><span class="badge bg-warning">${Institute} </span></li>
                    <a href="/research/download/${id}" target="_blank" rel="noopener noreferrer"><li><span class="badge" style="background-color: #068F3F;float: right;"><i class="ti-download"></i> Download</span></li></a>
                </ul>
            </li>
          </ul>
      </div>
    </div>
</div>`;
};
const projectTemplateForDepartment = (id,topic, researcher, lecturer, matric, date,type, Institute, department) => {
  return `<div class="col-lg-6">
  <div class="card_box position-relative mb_10 white_bg">
    <div class="white_box_tittle green_bg">
      <div class="main-title2">
        <strong class="text-white"> ${topic.toUpperCase()} </strong>
      </div>
    </div>
    <div class="box_body">
      <ul>
          <li><b>Research By: </b> <span style="text-transform:uppercase;">${researcher.firstname}</span> <span>${researcher.lastname} </span><span style="color:#FFB167;">${matric.toUpperCase()}</span> </li>
          
          <li><b>Date Created:</b> <span>${date} </span> </li>
          <li>
              <ul>
                  <li class="badgelist"><span class="badge bg-secondary">${type} </span></li>
                  <li class="badgelist"><span class="badge bg-success">${department} </span></li>
                  <li class="badgelist"><span class="badge bg-warning">${Institute} </span></li>
                  <a href="/research/download/${id}" target="_blank" rel="noopener noreferrer"><li><span class="badge" style="background-color: #068F3F;float: right;"><i class="ti-download"></i> Download</span></li></a>
              </ul>
          </li>
        </ul>
    </div>
  </div>
</div>`;
};
const staffProjectTemplate = (project) =>{
  return `
  <tr>
    <th scope="row">
      <a href="#" class="question_content">
      ${project.project.topic}
      </a>
    </th>
    <td>
      ${project.document_category?.name}
    </td>
    <td>
    <div class="container">
      <div class="row">
        <!-- <div class="col-lg-6"> <div class="profile_info">
           <img src="img/client_img.png" alt="#" />
         </div></div> -->
        <div class="col-lg-12"> ${project.project.student?.profile?.lastname } ${ project.project.student?.profile?.middlename} ${project.project.student?.profile?.firstname }</div>
      </div>
    </div>
    </td>
    <td> ${project.project.student?.username} </td>
    ${project.is_approved ? '<td class=""><span class="badge bg-success">Approved</span></td>' : '<td class=""><span class="badge bg-warning">Unapproved</span></td>' }
    <td> ${new Date(project.createdAt).toLocaleDateString('en-us', { weekday:"long", year:"numeric", month:"short", day:"numeric"}) } </td>
    <td><i class="ti-eye"></i></td>
  </tr>`;
};
const studentListTemplate =(student) => {
  return `
  <tr>
  <td>
  <div class="container">
    <div class="row">
      <!-- <div class="col-lg-6"> <div class="profile_info">
         <img src="img/client_img.png" alt="#" />
       </div></div> -->
      <div class="col-lg-12"> ${student?.firstname} ${student?.middlename } ${ student?.lastname}</div>
    </div>
  </div>
  </td>
  <td> ${student?.user?.username}</td>
  <td>${student?.level?.name}</td>
  <td> ${student?.study_mode?.name}</td>
  <td> ${student?.user?.email} <br/> ${student?.user?.phone }</td>
  <td><i class="ti-eye"></i></td>
</tr>`
}

function ThePaymentPlan(plan_name, plan_amount, paymentHashIn){
  const paymentType = document.getElementById("paymentType").innerHTML = plan_name
  const paymentAmount = document.getElementById("paymentAmount").innerHTML = "₦" + plan_amount
  const paymentFee = document.getElementById("paymentFee").innerHTML = "₦" + "350.00"
  const paymentTotal = document.getElementById("paymentTotal").innerHTML = "₦" + "2350.00"
  document.getElementById("paymentHash").value = paymentHashIn
}

if (document.getElementById("proceedToPayment")) {
  document.getElementById("proceedToPayment").addEventListener("click", proceedToPayment);
}

function proceedToPayment() {
  toastr.options.progressBar = true;
  toastr.info(
    "Initializing Transaction, Please wait.....",
    "NOTIFICATION", {
      timeOut: 9000
    }
  );
  const paymentHash = document.getElementById("paymentHash").value
  document.getElementById("proceedToPayment").innerHTML = "PROCESSING..."
  document.getElementById("proceedToPayment").disabled = true
  jQuery.ajax({
    url: `/user/transaction/initialize`,
    method: 'POST',
    data: {
      paymentHash
    },
    error: function (request, error) {
      document.getElementById("proceedToPayment").innerHTML = "Proceed to Payment"
      document.getElementById("proceedToPayment").disabled = false
      toastr.options.progressBar = true;
      toastr.error(
        error,
        "ERROR", {
          timeOut: 9000
        }
      );
      
    },
    success: function (data) {
      document.getElementById("proceedToPayment").innerHTML = "Proceed to Payment"
      document.getElementById("proceedToPayment").disabled = false
      if (data.success === false) {
        toastr.options.progressBar = true;
        toastr.error(
          data.error,
          "ERROR", {
            timeOut: 9000
          }
        );
      }
      if (data.success === true) {
        toastr.options.progressBar = true;
        toastr.success(
          "Redirecting...",
          "SUCCESS", {
            timeOut: 9000
          }
        );
        window.location.href = data.message 
      }

    }
  });
}
function verifyPaymentRefBinding() {

  const payref = document.getElementById("payref2").value
  
  document.getElementById("veridyBindingPay").innerHTML = "Verifying..."
  document.getElementById("veridyBindingPay").disabled = true
  jQuery.ajax({
    url: `/user/transaction-binding/verify`,
    method: 'POST',
    data: {
      reference: payref
    },
    error: function (request, error) {
      toastr.options.progressBar = true;
      toastr.error(
        error,
        "ERROR", {
          timeOut: 9000
        }
      );

      document.getElementById("veridyBindingPay").innerHTML = "Verify"
      document.getElementById("veridyBindingPay").disabled = false
      
    },
    success: function (data) {
      document.getElementById("veridyBindingPay").innerHTML = "Verify"
      document.getElementById("veridyBindingPay").disabled = false
      if (data.success === false) {
        toastr.options.progressBar = true;
        toastr.error(
          data.error,
          "ERROR", {
            timeOut: 9000
          }
        );
      }
      if (data.success === true) {
        window.alert(data.message)
        toastr.options.progressBar = true;
        toastr.info(
          `Transaction status: ${data.message}`,
          "MESSAGE", {
            timeOut: 9000
          }
        );
      }

    }
  });
}
function verifyPaymentRef() {

  const payref = document.getElementById("payref").value
  
  document.getElementById("veridyPay").innerHTML = "Verifying..."
  document.getElementById("veridyPay").disabled = true
  jQuery.ajax({
    url: `/user/transaction/verify`,
    method: 'POST',
    data: {
      reference: payref
    },
    error: function (request, error) {
      toastr.options.progressBar = true;
      toastr.error(
        error,
        "ERROR", {
          timeOut: 9000
        }
      );

      document.getElementById("veridyPay").innerHTML = "Verify"
      document.getElementById("veridyPay").disabled = false
      
    },
    success: function (data) {
      document.getElementById("veridyPay").innerHTML = "Verify"
      document.getElementById("veridyPay").disabled = false
      if (data.success === false) {
        toastr.options.progressBar = true;
        toastr.error(
          data.error,
          "ERROR", {
            timeOut: 9000
          }
        );
      }
      if (data.success === true) {
        toastr.options.progressBar = true;
        toastr.info(
          `Transaction status: ${data.message}`,
          "MESSAGE", {
            timeOut: 9000
          }
        );
      }

    }
  });
}