$(document).ready(function() {


    var campus = $("#header-campusid").val();
   
    var userID = $('#user_id').val();


    //firstclass select
    $.ajax({
        type: "POST",
        url: "../../controller/scripts/student/assignment/ekene_select_subject.php",
        data: {
          
              campus: campus,
              userID: userID
           
        },
    
        success: function (output) { 

     
           
            $("#ekene_select_assignment_subject").html(output);
    
        }
    });


    $(document).ready(function () {
        // Get the icon element by its ID
        var receiptIcon = $('#receiptIcon');
    
        // Attach a click event handler
        receiptIcon.on('click', function () {
            // Redirect to another page (replace 'your_target_page.html' with the actual page URL)
            window.location.href = '#';
        });

       
    });
    $('body').on('change', '#ekene_select_assignment_subject', function () { 

        ekeneloadconassignmentcontent();
    });
 
    //select term 
    $('#ekene_select_assignment_term').html('<option>  <span class="visually-hidden">Loading...</span></option>'); 
    
    $.ajax({
        type: "POST",
        url: "../../controller/scripts/student/assignment/ekene_select_termalias.php",
        data: {
        
              campus: campus
           
        },
    
        success: function (output) { 
            
           
            $("#ekene_select_assignment_term").html(output);
    
        }
    });
    


    $.ajax({
        type: "POST",
        url: "../../controller/scripts/student/assignment/display_allassignment.php",
        data: {
        
              campus: campus,
              userID: userID
           
        },
    
        success: function (output) { 
      
             $("#ekeneallassignment").html(output);
    
        }
    });




});

$('body').on('click', '#ekene_load_assignment_question', function () { 

    ekeneloadconassignmentcontent();

});  


function  ekeneloadconassignmentcontent()
{



    $('#ekene_display_student_behavioural').html('<center><i class="fa fa-spinner fa-spin fs-3"></i></center>');

    var campus = $("#header-campusid").val();
    var userID = $('#user_id').val();
    // var diplay_class = $('#ekene_select_assignment_class option:selected').val();
    // var usertype = $('#user_type_holder').val();
    var ekene_subject = $('#ekene_select_assignment_subject option:selected').val();


        
    $.ajax({
        type: "POST",
        url: "../../controller/scripts/student/assignment/ekene_appendcard.php",
        data: {

            ekene_campus: campus,
            userID: userID,
           
            ekene_subject: ekene_subject
          
        },

        success: function (output) { 
        
      
            
            $('#ekene_display_student_behavioural').html(output);
           
            
        
        },
    });

}

$('body').on('click', '#ekene_download_fullassignment', function () { 

    var userID = $('#user_id').val();

    var campusid =  $(this).data("cam");
    var assignmentsettingsid = $(this).data("id");
    var ekene_subject = $('#ekene_select_assignment_subject option:selected').val();
 

     $('#downloadassignmentekene').html('<div class="text-center p-5"> <span class="spinner-border spinner-border-lg" role="status" aria-hidden="true" style="color:#007ffb;"></span></div>');
 

                $.ajax({
                    type: "POST",
                    url: '../../controller/scripts/student/assignment/ekene_dowload_assignment.php',
                    data: {
                        campusid: campusid,
                    
                        assignmentsettingsid: assignmentsettingsid,
                        userID: userID,
                        ekene_subject: ekene_subject
                
                        
                    },

                    success: function (response) {


                     
                    
                        $("#downloadassignmentekene").html(response);
                        // $(".answer").hide();
                    
                        


                    },

            });


});


$('body').on('click', '#ekene_print', function () {

    const element = document.getElementById("downloadassignmentekene");




   
    element.style.paddingRight = '40px';
    element.style.paddingLeft = '40px';
    var prosloadname = 'ASSIGNMENT QUESTION';
    // Clone the content and manipulate the clone
    var clone = element.cloneNode(true);

    // Remove elements to exclude from the clone
    $(clone).find('.proloadshowanserbtnforview').remove();
    // Generate PDF from the modified clone
    html2pdf().from(clone).output('blob').then(function (pdfBlob) {
        // Create a Blob and trigger the download
        var a = document.createElement('a');
        a.href = URL.createObjectURL(pdfBlob);
        a.download = prosloadname + '.pdf';
        a.click();
    });

  

});

$("body").on('click', '#ekene_view_fullassignment', function () {
    var assignmentid = $(this).data("id");
    var campusid = $(this).data("cam");
    var questionCounter = 1;
    var questionCounterone = 1;

    $.ajax({
        type: "POST",
        url: '../../controller/scripts/student/assignment/ekene_view_assignment_one.php',
        data: {
            assignmentid: assignmentid,
           
            
            campusid: campusid
          
        },

        success: function (response) {

            var jsonDatacate = JSON.parse(response);
            $('#ekeneloadtheoryappendquestionsjon').val(0);
            $("#ekeneloadappededinputheresavechangetheory").empty();
           
            $('#ekeneloadobjectiveappendquestionsjon').val(0);
            $("#ekeneloadappededinputheresavechangeobjective").empty();
            for (var i = 0; i < jsonDatacate.length; i++) {
                   
                // Access the properties you need here
        
                var itemnew = jsonDatacate[i];
             
                //  var spotName = item.spot_name;
                 var AssignmentQuestion = itemnew.id;
                 var assignmentquestionid = itemnew.assignmentid;
                 var questionnew = itemnew.question;
                 var optionAnew = itemnew.optionA;
                 var optionBnew = itemnew.optionB;
                 var optionCnew = itemnew.optionC;
                 var optionDnew = itemnew.optionD;
                 var CampusIDnew = itemnew.CampusID;
                 
                //  var answernew = itemnew.answer;
                 var AssignmentCategorynew = itemnew.AssignmentCategory;
      

                 if(AssignmentCategorynew == "Theory")
                 {
            
                    var ekeneloadinputtag = questionCounterone++;

                    
                      var ekene_theoryquestion = `<div style="color: black;"class="ekeneremoveappendentheoryjson${ekeneloadinputtag}">
                    <div class="col-12" style="display: flex;">
                    <strong class="ekene_general_class_remove_inputtheory ekenetheoryquestjson" data-cam="${CampusIDnew}" data-status="${assignmentquestionid}" data-assignment_question="${AssignmentQuestion}">
                        Question ${ekeneloadinputtag}: ${questionnew}
                    </strong>

                      </div>
                      &nbsp; <textarea class="mymce textarea_questiontheory question mb-4 generaledit" data-status="edit" rows="3" cols="80" name="area"></textarea></br>
                  </div>`;
             
                  $('#ekeneloadappededinputheresavechangetheory').append(ekene_theoryquestion);
                  
                  $('.mymce').summernote();
                 }
                 else
                 {
                   
                    var ekeneloadinputtag = questionCounter++;

                    var ekene_objectivequestion =  `<div class="card g-3">
                    <div class="card-body ekeneremoveappendenobjjson ekeneremoveappendenobjjson${ekeneloadinputtag}">
                        <strong style="font-weight: bold;" class="objectivestrongtext" data-assignment_questionobjective="${AssignmentQuestion}">Question ${ekeneloadinputtag}: ${questionnew}</strong>
                    </div>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item">
                            <div class="row">
                                <div class="col-12">
                                <div class="option" style="display: inline-block; white-space: nowrap;">
                                <input type="radio" name="ekeneobjquest${AssignmentQuestion}" value="A"> A) ${optionAnew}
                            </div>

                            </div>
                        </li>
                        
                        <li class="list-group-item">
                            <div class="row">
                                <div class="col-12">
                                    <div class="option">
                                        <input type="radio" name="ekeneobjquest${AssignmentQuestion}" value="B"> B) ${optionBnew}
                                    </div>
                                </div>
                            </div>
                        </li>
                        
                        <li class="list-group-item">
                            <div class="row">
                                <div class="col-12">
                                    <div class="option">
                                        <input type="radio" name="ekeneobjquest${AssignmentQuestion}" value="C"> C) ${optionCnew}
                                    </div>
                                </div>
                            </div>
                        </li>
                        
                        <li class="list-group-item">
                            <div class="row">
                                <div class="col-12">
                                    <div class="option">
                                        <input type="radio" name="ekeneobjquest${AssignmentQuestion}" value="D"> D) ${optionDnew}
                                    </div>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>`;
                
                
                
                      $('#ekeneloadappededinputheresavechangeobjective').append(ekene_objectivequestion);
                
                 }

               
            }



        }

     }); 
});

$('body').on('click', '#studentsubmitassignment', function () {

    $('#studentsubmitwarning').modal('show');
    $('#student_answermodal').css('z-index', 1040); // Increase z-index of first modal
                // Reset z-index of first modal when second modal is closed
        $('#studentsubmitwarning').on('hidden.bs.modal', function () {
            $('#student_answermodal').css('z-index', 1050); // Reset z-index of firstmodal
    });
    
    var assignmentid = $(".ekenetheoryquestjson").data("status");
    var campusid = $(".ekenetheoryquestjson").data("cam");
    
       $("#studentcampussubmit").val(campusid);
       $("#studentassignmentidsubmit").val(assignmentid);

   

   
});

$('body').on('click', '#studentyesbutton', function () {
    var assignmentid = $("#studentassignmentidsubmit").val();
    var campusid = $("#studentcampussubmit").val();


    var userID = $('#user_id').val();
    var subjectid = $('#ekene_select_assignment_subject').val();
    var textareaquestion = [];
    var textareaquestiontheory = [];
    var assignmentquestiontheoryid = [];
    var Answer = [];


    
  
    // var Answer = [];
    // var assignmenttype = [];
    // var assignmenttypefortheory = [];


// Check if at least one textarea with the class 'textarea_questiontheory' exists
        if ($('.textarea_questiontheory').length > 0) {

            $.each($(".textarea_questiontheory"), function () {
                var question_value = $(this).val();
                
                // Check if the value is empty or equal to '###||'
                if (question_value === '' || question_value === '###||') {
                    textareaquestiontheory.push('');
                } else {
                    textareaquestiontheory.push(question_value + '###||');
                   
                }
        
            });

            $.each($(".ekenetheoryquestjson"), function () {
                var question_checktheory = $(this).data("assignment_question")
                // if (question_check == '') {
                //     textareaquestion.push('');
                // } else {
                    assignmentquestiontheoryid.push(question_checktheory);
                    // assignmenttype.push($(this).data('status'));
                // }
            });
        

        } else {
           
        }

        if ($('.objectivestrongtext').length > 0) {

            $.each($(".objectivestrongtext"), function () {
                var question_check = $(this).data("assignment_questionobjective");
                if (question_check == '') {
                    textareaquestion = [0];
                } else {
                    textareaquestion.push(question_check);
                    // assignmenttype.push($(this).data('status'));
                 }
            });
        
          
           $.each($(".option :checked"), function () {
            var question_check = $(this).val();
       
            if (question_check === '') {
                Answer.push("0");
            } else {
                Answer.push(question_check);
            }
            });
      
      
        }
        else
        {
         
            textareaquestion = [0];

            Answer = [0];
            
        }

    
   
  
      





   

//     // // Check if no radio button is checked
//     // if (Answer.length === 0) {
//     //    alert("hello");
//     // } else {
//     //    alert("uu");
//     // }


    var textareaquestiontheory1 = textareaquestiontheory.some(function (value) {
        return value.trim() == '';
    });
    

// // alert(textareaquestiontheory1);

    
   if (textareaquestiontheory1)
   {
    $.wnoty({
        type: 'warning',
        message: "Please fill in all the required fields",
        autohideDelay: 5000
    });
   }
   else if(Answer.length == '')
   {
    $.wnoty({
        type: 'warning',
        message: "No objective Answered",
        autohideDelay: 5000
    });
   }
   else
   {
  
    $.ajax({
        type: "POST",
        url: '../../controller/scripts/student/assignment/studentsubmit.php',
        data: {
            assignmentid: assignmentid,
            campusid: campusid,
            userID: userID,
            subjectid: subjectid,
            textareaquestiontheory: textareaquestiontheory,
            assignmentquestiontheoryid: assignmentquestiontheoryid,
            textareaquestion: textareaquestion,
            Answer: Answer
        },
    
        success: function (response) {

    
           
            var jsonDatacate = JSON.parse(response);
                   
               
                            for (var i = 0; i < jsonDatacate.length; i++) {
                             
                              // Access the properties you need here
                      
                              var itemnew = jsonDatacate[i];
                           
                              //  var spotName = item.spot_name;
                               var ParentWhatsappNumbernew = itemnew.ParentWhatsappNumber;
                               var messagenew = itemnew.message;
                               var filniializenew = itemnew.filniialize;
                               var institutioninitionnew = itemnew.institutioninition;
                               var apikeynew = itemnew.apikey;
                               var successnewone = itemnew.successnew;
                               var staffWhatsappNumbernew = itemnew.staffWhatsappNumber;
                               var messagestaffnew = itemnew.messagestaff;
                               var filniializestaffnew = itemnew.filniializestaff;
                               var apikeystaffnew = itemnew.apikeystaff;
                            
                            //    var InstitutionEmailnew = itemnew.InstitutionEmail;
                            //    var ParentEmailnew = itemnew.ParentEmail;
                            //    var messageemailnew = itemnew.messageemail;
                            //    var assignmentmessagenew = itemnew.assignmentmessage;



                            if (successnewone == 10) {
                                $.wnoty({
                                            type: 'success',
                                            message: "Submitted successfully..",
                                            autohideDelay: 5000
                                        });
                        
                                     $("#studentsubmitwarning").modal("hide");
                                     $("#student_answermodal").modal("hide");
                                       $.ajax({
                                        type: "POST",
                                        url: "../../controller/scripts/student/assignment/ekene_appendcard.php",
                                        data: {
                                
                                            ekene_campus: campusid,
                                            userID: userID,
                                           
                                            ekene_subject: subjectid
                                          
                                        },
                                
                                        success: function (output) { 
                                        
                                            $('#ekene_display_student_behavioural').html(output);
                                           
                                        },
                                    });
                            }

                      var dataToSend = {
                          number: ParentWhatsappNumbernew,
                          msg: messagenew,
                          file: filniializenew,

                          abba_institution_id: institutioninitionnew,
                          staffWhatsappNumbernewt: staffWhatsappNumbernew,
                          messagestaffnewt: messagestaffnew,
                          filniializestaffnewt: filniializestaffnew,
                          apikeystaffnewt: apikeystaffnew,
                          

                          // senderEmail: InstitutionEmailnew,
                          // recipientEmail: ParentEmailnew,
                          // email_content: messageemailnew,
                          // subject: assignmentmessagenew,
                          apikey: apikeynew
                        
                      };
                  
                        
                      // Make an AJAX request
                      $.ajax({
                          type: 'POST', // or 'GET' depending on your needs
                          url: '../../controller/scripts/student/assignment/send_whatsappmsg.php',
                          data: dataToSend,
                          
                          success: function(response) {
                             
                         
                          },
                      
                      });

                      $.ajax({
                        type: 'POST', // or 'GET' depending on your needs
                        url: '../../controller/scripts/student/assignment/send_whatsappmsgtwo.php',
                        data: {
                            abba_institution_id: institutioninitionnew,
                            staffWhatsappNumbernewt: staffWhatsappNumbernew,
                            messagestaffnewt: messagestaffnew,
                            filniializestaffnewt: filniializestaffnew,
                            apikeystaffnewt: apikeystaffnew

                        },
                        
                        success: function(response) {
                           
                       
                        },
                    
                    });


                            }
       
         },
      });
   }



});



