 <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('../../../config/config.php');


 $campusid = $_POST['campusid'];
$userID = $_POST['userID'];
$assignmentid = $_POST['assignmentid'];


$subjectid = $_POST['subjectid'];
if (isset($_POST['Answer'])) {
    // If set, assign the value to $Answer
    $Answer = $_POST['Answer'];
}




function formatPhoneNumber($phoneNumber) {
    // Remove non-numeric characters
    $numericPhoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
  
    // Check if the number starts with '0' and add '234' in that case
    if (substr($numericPhoneNumber, 0, 1) === '0') {
        return '234' . substr($numericPhoneNumber, 1);
    } else {
        // Check if the number starts with '+', if yes, remove the '+'
        if (substr($numericPhoneNumber, 0, 1) === '+') {
            $numericPhoneNumber = substr($numericPhoneNumber, 1);
        }
  
        // Return the numeric phone number
        return $numericPhoneNumber;
    }
  }
  
  
    $fullmessagearr = array();
    $fullnumarr= array();
    $fullfilearr= array();
    $fullinstit= array();
    $apikeynecont = array();

    $fullteachermessagearr = array();
    $fullteachernumarr= array();
    $fullteacherfilearr= array();
    $fullteacherinstit= array();
    $apikeyteachernecont = array();
  
    $fullInstitutionEmail= array();
    $fullparentemail = array();
    $fullemailmeeasge = array();
    $assignmenttitlearray = array();
  
    



$session = "SELECT * FROM `session` WHERE `sessionStatus` = 1";

$ekeneselect = mysqli_query($link, $session);
$ekene_get_select_details = mysqli_fetch_assoc($ekeneselect);
$ekene_row_select = mysqli_num_rows($ekeneselect);

$ekene_session_name = $ekene_get_select_details['sessionName'];


$term = "SELECT * FROM `termorsemester` WHERE `status` = 1";
 $ekeneterm = mysqli_query($link, $term);
 $ekene_get_term_details = mysqli_fetch_assoc($ekeneterm);
 $ekene_row_term = mysqli_num_rows($ekeneterm);
      
 $ekene_term = $ekene_get_term_details['TermOrSemesterID'];


$ekene_select_currentclass = "SELECT * FROM `classordepartmentstudentallocation` WHERE `CampusID` = '$campusid' AND `Session` = '$ekene_session_name' AND `StudentID` = '$userID'";
$ekene_query_link_classcurrent = mysqli_query($link, $ekene_select_currentclass);
$ekene_get_details_currentclass = mysqli_fetch_assoc($ekene_query_link_classcurrent);
 $ekene_row_cnt_ekenecurrentclass = mysqli_num_rows($ekene_query_link_classcurrent);

 if ($ekene_row_cnt_ekenecurrentclass > 0)
 {
     $classid = $ekene_get_details_currentclass['ClassOrDepartmentID'];
 }



 $ekene_select_subject = "SELECT * FROM `subjectorcourse` WHERE `SubjectOrCourseID` = '$subjectid'";

$ekene_query_link_subject = mysqli_query($link, $ekene_select_subject);
$ekene_get_details_subject = mysqli_fetch_assoc($ekene_query_link_subject);
$ekene_row_cnt_ekenesubject = mysqli_num_rows($ekene_query_link_subject);


if($ekene_row_cnt_ekenesubject > 0)
{

  $ekene_subjectname  = $ekene_get_details_subject['SubjectOrCourseTitle'];

}



    $selectteacherid = "SELECT * FROM `courseorsubjectallocation`WHERE CampusID = '$campusid' AND ClassOrDepartmentID = '$classid' AND SubjectOrCourseID = '$subjectid'";
    $ekene_query_link_teacherid = mysqli_query($link, $selectteacherid);
    $ekene_get_details_teacher = mysqli_fetch_assoc($ekene_query_link_teacherid);
    $ekene_row_cnt_teacher = mysqli_num_rows($ekene_query_link_teacherid);
    if($ekene_row_cnt_teacher > 0)
    {
    
      $teacherid = $ekene_get_details_teacher['CourseOrSubjectTeacherUserID'];
    
    }


 $ekene_select_class = "SELECT * FROM `classordepartment` WHERE `CampusID`= '$campusid' AND `ClassOrDepartmentID` = '$classid'";

 $ekene_query_link_class = mysqli_query($link, $ekene_select_class);
 $ekene_get_details_class = mysqli_fetch_assoc($ekene_query_link_class);
 $ekene_row_cnt_ekene = mysqli_num_rows($ekene_query_link_class);
 
 
 if($ekene_row_cnt_ekene > 0)
 {
 
   $ekene_subject = $ekene_get_details_class['ClassOrDepartmentName'];
 
 }
 
 //select from campus table to get institutionid  table 
 
$ekene_select_instutionid = "SELECT * FROM `campus` WHERE  CampusID = '$campusid'";
$ekene_query_instutionid = mysqli_query($link, $ekene_select_instutionid);
$ekene_get_id_details = mysqli_fetch_assoc($ekene_query_instutionid);
$ekene_instutionid_row_cnt = mysqli_num_rows($ekene_query_instutionid);
if ($ekene_instutionid_row_cnt > 0)
{
  $abba_institution_id = $ekene_get_id_details ['InstitutionID'];
}

//select from institution table 
$select_institution =  "SELECT * FROM `institution` WHERE  InstitutionID = '$abba_institution_id'";
$ekene_selectinsttution = mysqli_query($link, $select_institution);
$ekene_get_institution_details = mysqli_fetch_assoc($ekene_selectinsttution);
$ekene_row_institution = mysqli_num_rows($ekene_selectinsttution);

if ($ekene_row_institution > 0)
{
$InstitutionGeneralName =  $ekene_get_institution_details['InstitutionGeneralName'];
$InstitutionEmail =  $ekene_get_institution_details['InstitutionEmail'];
if ($InstitutionEmail == '')
{
  $InstitutionEmailnew = "Hello.edumess.com";
}
else
{
  $InstitutionEmailnew = $InstitutionEmail;
}

}



 

 $textareaquestiontheory = $_POST[ 'textareaquestiontheory'];
 $assignmentquestiontheoryid = $_POST['assignmentquestiontheoryid'];
 $textareaquestion = $_POST['textareaquestion'];
$Answer = $_POST['Answer'];

//  if (!empty($textareaquestiontheory)) {
//     $implodetextareaquestiontheory = implode('###||', $textareaquestiontheory);
// } else {
//     $implodetextareaquestiontheory = '';
// }

// if (!empty($assignmentquestiontheoryid)) {
//     $implodedassignmentquestiontheoryid = implode(',', $assignmentquestiontheoryid);
// } else {
//     $implodedassignmentquestiontheoryid = '';
// }

// if (!empty($textareaquestion)) {
//     $implodedtextareaquestion = implode(',', $textareaquestion);
// } else {
//     $implodedtextareaquestion = '';
// }

// if (!empty($Answer)) {
//     $implodedAnswer = implode(',', $Answer);
// } else {
//    $implodedAnswer = '';
// }

 $implodetextareaquestiontheory = implode('###||', $textareaquestiontheory);
 $implodedassignmentquestiontheoryid = implode(',', $assignmentquestiontheoryid);
 $implodedtextareaquestion = implode(',', $textareaquestion);
 $implodedAnswer = implode(',', $Answer);
 $success = 0;
 
       
        $theoryquestion = mysqli_real_escape_string($link, $implodetextareaquestiontheory);
        if(!empty($theoryquestion))
        {
      
            $insert_into_answertable = "INSERT INTO `assignmentanswer`
            ( `AssignmentSettingsID`, `StudentID`, `CampusID`,  `ClassOrDepartmentID`, 
            `SubjectOrCourseID`, `sessionID`, `TermOrSemesterID`, `ObjectiveQuestion`, `ObjectAnswer`,`TheoryQuestion`, `TheoryAnswer`, `submitstatus`)
             VALUES ('$assignmentid','$userID','$campusid','$classid','$subjectid','$ekene_session_name','$ekene_term','$implodedtextareaquestion','$implodedAnswer','$implodedassignmentquestiontheoryid','$implodetextareaquestiontheory','1')";
              $select_question = mysqli_query($link, $insert_into_answertable);
              $success++;
        
        }
        
        //   if(!empty($theoryquestion))
        //   {
        //   }
        
    

    
     //   if(!empty($theoryquestion))
     //   {
     //   }
     
 

    if ($success == 0)
    {
        echo "3";

    }
    else
    {
        // echo "10";
        $send_whatapp = array();
        $ekene_send_meeage = mysqli_query($link, "SELECT * FROM student  INNER JOIN  parent ON student.ParentID = parent.ParentID WHERE student.StudentID = '$userID'");
        $ekene_send_meeage_rowscnt = mysqli_num_rows($ekene_send_meeage);
        $ekene_send_meeagedetailcnt_rows = mysqli_fetch_assoc($ekene_send_meeage);
        if($ekene_send_meeage_rowscnt > 0)
        {

            $ParentWhatsappNumber =  $ekene_send_meeagedetailcnt_rows['ParentWhatsappNumber'];
            $ParentMainPhoneNumber =  $ekene_send_meeagedetailcnt_rows['ParentMainPhoneNumber'];
            $ParentFirstName=  $ekene_send_meeagedetailcnt_rows['ParentFirstName'];
            $ParentLastName=  $ekene_send_meeagedetailcnt_rows['ParentLastName'];
            $ParentEmail=  $ekene_send_meeagedetailcnt_rows['ParentEmail'];
            $StudentFirstName=  $ekene_send_meeagedetailcnt_rows['StudentFirstName'];
            $StudentLastName=  $ekene_send_meeagedetailcnt_rows['StudentLastName'];

            if($ParentWhatsappNumber == '')
            {
                $parentnumber = $ParentMainPhoneNumber;
            }else{


                $parentnumber = $ParentWhatsappNumber;
            }

            if($parentnumber != '')
            {
              $formattedParentNumber = formatPhoneNumber($parentnumber);

              $message = rawurlencode("* Hi ".$ParentFirstName."* \n\n" .
              " I am writing to inform you that your child. ".$StudentFirstName." ".$StudentLastName."\n" .
              "has successfully completed the recent assignment given in:\n" .
              "class: $ekene_subject\n\n".
              "subject: $ekene_subjectname\n\n".
                 "Thank you! ");

            //   $messageemail = <<<EOT
            //   * Hi $ParentFirstName *
            //   I am writing to inform you that your child.$StudentFirstName $StudentLastName
            //   has successfully completed the recent assignment given in :
            //  class: $ekene_subject
            //  subject: $ekene_subjectname
            //   Thank you!
            //   EOT;
            //   $assignmenttitle = "Assignment Notification";

              $filniialize = '';
              $institutioninition = $abba_institution_id;

              $pros_selectappi_details = mysqli_query($link,"SELECT * FROM whatsappapikey WHERE InstitutionID='$abba_institution_id' AND Purpose='adminstration'");
              $pros_selectappi_detailscnt = mysqli_num_rows($pros_selectappi_details);
              $pros_selectappi_detailscnt_rows = mysqli_fetch_assoc($pros_selectappi_details);


              if($pros_selectappi_detailscnt > 0)
              {
                  
                $apikey =  $pros_selectappi_detailscnt_rows['ApiKey'];
                  
              }else
              {
                  
                  $pros_selectappi_details_default = mysqli_query($link,"SELECT * FROM whatsappapikey WHERE InstitutionID='0' AND Purpose='Default'");
                $pros_selectappi_detailscnt_default = mysqli_num_rows($pros_selectappi_details_default);
                $pros_selectappi_detailscnt_rows_default = mysqli_fetch_assoc($pros_selectappi_details_default);
                
                $apikey  = $pros_selectappi_detailscnt_rows_default['ApiKey'];
                    
              }

              $fullmessagearr[] = $message;
              $fullnumarr[] = $formattedParentNumber;
              $fullfilearr[] = $filniialize;
              $fullinstit[] =  $institutioninition;
              $apikeynecont[] =  $apikey;
              // $fullInstitutionEmail[] = $InstitutionEmailnew;
              // $fullparentemail[] = $ParentEmail;
              // $fullemailmeeasge[] = $messageemail;
              // $assignmenttitlearray[] = $assignmenttitle;
              
            }
            else
            {

            }

        }
      

       $selectstaffid = mysqli_query($link,"SELECT * FROM `staff` WHERE StaffID = '$teacherid'");
       $ekene_send_staff_rowscnt = mysqli_num_rows($selectstaffid);
       $ekene_send_staffdetailcnt_rows = mysqli_fetch_assoc($selectstaffid);
       if($ekene_send_staff_rowscnt > 0)
       {
        $StaffWhatsappNumber =  $ekene_send_staffdetailcnt_rows['StaffWhatsappNumber'];
        $StaffMainNumber =  $ekene_send_staffdetailcnt_rows['StaffMainNumber'];
        $StaffFirstName=  $ekene_send_staffdetailcnt_rows['StaffFirstName'];
     
       

        if($StaffWhatsappNumber == '')
        {
            $staffnumber = $StaffMainNumber;

        }else{


            $staffnumber = $StaffWhatsappNumber;
        }


        if($staffnumber != '')
        {
          $formattedstaffnumber = formatPhoneNumber($staffnumber);

          $messageteacher = rawurlencode("* Hi ".$StaffFirstName."* \n\n" .
          " I am writing to inform you that your child. ".$StudentFirstName." ".$StudentLastName."\n" .
          "has successfully completed the recent assignment given in:\n" .
            "class: $ekene_subject\n\n".
            "subject: $ekene_subjectname\n\n".
             "Thank you! ");

        //   $messageemail = <<<EOT
        //   * Hi $ParentFirstName *
        //   I am writing to inform you that your child.$StudentFirstName $StudentLastName
        //   has successfully completed the recent assignment given in :
        //  class: $ekene_subject
        //  subject: $ekene_subjectname
        //   Thank you!
        //   EOT;
        //   $assignmenttitle = "Assignment Notification";

          $filniialize = '';
          $institutioninition = $abba_institution_id;

          $pros_selectappi_details = mysqli_query($link,"SELECT * FROM whatsappapikey WHERE InstitutionID='$abba_institution_id' AND Purpose='adminstration'");
          $pros_selectappi_detailscnt = mysqli_num_rows($pros_selectappi_details);
          $pros_selectappi_detailscnt_rows = mysqli_fetch_assoc($pros_selectappi_details);


          if($pros_selectappi_detailscnt > 0)
          {
              
            $apikey =  $pros_selectappi_detailscnt_rows['ApiKey'];
              
          }else
          {
              
              $pros_selectappi_details_default = mysqli_query($link,"SELECT * FROM whatsappapikey WHERE InstitutionID='0' AND Purpose='Default'");
            $pros_selectappi_detailscnt_default = mysqli_num_rows($pros_selectappi_details_default);
            $pros_selectappi_detailscnt_rows_default = mysqli_fetch_assoc($pros_selectappi_details_default);
            
            $apikey  = $pros_selectappi_detailscnt_rows_default['ApiKey'];
                
          }

          $fullteachermessagearr[] = $messageteacher;
          $fullteachernumarr[] = $formattedstaffnumber;
          $fullteacherfilearr[] = $filniialize;
          $fullteacherinstit[] =  $institutioninition;
          $apikeyteachernecont[] =  $apikey;
          // $fullInstitutionEmail[] = $InstitutionEmailnew;
          // $fullparentemail[] = $ParentEmail;
          // $fullemailmeeasge[] = $messageemail;
          // $assignmenttitlearray[] = $assignmenttitle;
          
        }
        else
        {

        }


       }
    



        $successnew = 10;
        $msg = implode(",", $fullmessagearr);
        $number = implode(",",  $fullnumarr);
        $file = implode(",",  $fullfilearr);
        $abba_institution_id = implode(",", $fullinstit);
        $apikey = implode(",", $apikeynecont);

        $msgt = implode(",", $fullteachermessagearr);
        $numbert = implode(",",  $fullteachernumarr);
        $filet = implode(",",  $fullteacherfilearr);
        $abba_institution_idt = implode(",", $fullteacherinstit);
        $apikeyt = implode(",", $apikeyteachernecont);


        // $Institutionmail = implode(",",  $fullInstitutionEmail);
        // $Parentmail = implode(",", $fullparentemail);
        // $messagemail = implode(",", $fullemailmeeasge);
        // $assignment = implode(",", $assignmenttitlearray);
        
        $send_whatapp[] = array(

          'ParentWhatsappNumber' => $number,
          'staffWhatsappNumber' => $numbert,
        

          'messagestaff' =>$msgt,
          'filniialize' =>$file,

          'message' =>$msg,
          'filniializestaff' =>$filet,
          // 'assignmentmessage' => $assignment,
          // 'InstitutionEmail' =>$Institutionmail,
          // 'ParentEmail' =>$Parentmail,
          // 'messageemail' =>$messagemail,

          'institutioninition' =>$abba_institution_id,
          'successnew' =>$successnew,
          'apikey' =>$apikey,
          'apikeystaff' =>$apikeyt
          
  
       );

       $json_data = json_encode($send_whatapp, JSON_PRETTY_PRINT);
       echo $json_data;

        
        // include('../messaging/whatsapp/send_whatapp_msg.php');
        // send_whatsapp_msg($abba_institution_id,$number,$apikey, $msg, $file);
      


    }
 
 ?> 