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

    // $country = trim($_POST['country']);
     $lang = $_POST['lang'];
      $child = $_POST['child'];
     $Email = $_POST['Email'];
     $mname= $_POST['mname'];
     $fname= $_POST['fname'];
     $lname = $_POST['lname'];            
     $WhatsappNumberfull = implode(',',$_POST['WhatsappNumberfull']);      
     $password = trim($_POST['password']); 
     
     $InstitutionID = $_POST['GroupOfSchoolID']; 
     $image = $_POST['image_64']; 
     $parent_gendeder = $_POST['parent_gendeder']; 
     
      $UserName = $_POST['UserName']; 
     
      $WhatsappNumberfullmain = implode(',',$_POST['WhatsappNumberfullmain']); 
     $WhatsappNumberfullother = implode(',',$_POST['WhatsappNumberfullother']); 
     
     
     if($image == 'https://static.vecteezy.com/system/resources/previews/020/213/738/original/add-profile-picture-icon-upload-photo-of-social-media-user-vector.jpg')
     {
         
         $image_64 = '';
         
     }else
     {
          $image_64 = $image;
     }
     
    
     
        // Function to format a phone number
            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;
                }
            }


        //// Format the phone numbers
            $number = formatPhoneNumber($WhatsappNumberfull);


     
     $verfylogin = mysqli_query($link,"SELECT * FROM `userlogin` WHERE UserRegNumberOrUsername='$UserName'");
     $verfylogincnt = mysqli_num_rows($verfylogin);
     
     
     if($verfylogincnt > 0)
     {
         
                  echo 'WhatsApp number Already exist';
     }else
     {
      
              $selectedverify = mysqli_query($link,"SELECT * FROM `parent` WHERE ParentEmail='$Email'");  
              $verfyparent = mysqli_num_rows($selectedverify);
               
               
              if($verfyparent > 0)
              {
                     
                            echo 'Email Already exist';
                        
              }else
              {
                   
                          $insertpat = mysqli_query($link,"INSERT INTO `parent`(`InstitutionID`, `ParentFirstName`, `ParentMiddleName`, `ParentLastName`, `ParentGender`, 
                          `ParentWhatsappNumber`, `ParentMainPhoneNumber`, `ParentOtherPhoneNumber`,
                          `ParentEmail`,  `ReservedAccountStatus`,  `ParentPhoto`, `Lang_Val`) VALUES 
                          ('$InstitutionID','$fname','$mname','$lname','$parent_gendeder','$WhatsappNumberfull','$WhatsappNumberfullmain', '$WhatsappNumberfullother', '$Email','1','$image_64','$lang')");
                          
                          
                          if( $insertpat == true)
                          {
                                  
                                     echo 'Success';
                                  
                                    $parentID = mysqli_insert_id($link);
                                    $md5password = md5($password);

                              
                                  $insertlogin = mysqli_query($link,"INSERT INTO `userlogin`(`InstitutionIDOrCampusID`,
                                  `UserID`, `UserRegNumberOrUsername`, 
                                  `UserPassword`, `UserType`,
                                  `VerificationStatus`, `LoginStatus`) VALUES ('$InstitutionID','$parentID','$UserName','$md5password','parent','1','0')");
                                  
                                  
                                    //   $explodestuden = explode(',', $child);
                              
                              
                                        foreach ($child as $currentStudentID) {
                                            $prosselect_stud_parent = mysqli_query($link, "SELECT * FROM `student` WHERE StudentID='$currentStudentID'");
                                            $prosselect_stud_parentcnt = mysqli_num_rows($prosselect_stud_parent);
                                            $prosselect_stud_parentcntrow = mysqli_fetch_assoc($prosselect_stud_parent);
                                        
                                            $firstparentID = $prosselect_stud_parentcntrow['ParentID'];
                                            $secondparentID = $prosselect_stud_parentcntrow['SecParentID'];
                                        
                                            if ($firstparentID == '0') {
                                                $updatestudent_parentnew = mysqli_query($link, "UPDATE `student` SET `ParentID`='$parentID' WHERE `StudentID`='$currentStudentID'");
                                            } else {
                                                
                                                if ($secondparentID == '0') {
                                                    $updatestudent_parent = mysqli_query($link, "UPDATE `student` SET `SecParentID`='$parentID' WHERE `StudentID`='$currentStudentID'");
                                                }
                                            }
                                        }

                                  
                                  
                                             $pros_selectappi_details = mysqli_query($link,"SELECT * FROM `whatsappapikey` WHERE InstitutionID='$InstitutionID'");
                                              $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'];
                                                     
                                              }
                                              
                                              
                                              
                                              
                                              $pros_institutioncontent = mysqli_query($link,"SELECT * FROM `institution` WHERE InstitutionID='$InstitutionID'");
                                              $pros_institutioncontentcnt = mysqli_num_rows($pros_institutioncontent);
                                              $pros_institutioncontentcnt_rows = mysqli_fetch_assoc($pros_institutioncontent);
                                              
                                              
                                              $prosfullschool =  $pros_institutioncontentcnt_rows['InstitutionGeneralName'];
                                              $schoollink = 'https://'.$pros_institutioncontentcnt_rows['CustomUrl'];
                                              $file = '';  
                                              $abba_institution_id = $InstitutionID;
                                              
                                              
                                              
                                                  include('../messaging/whatsapp/send_whatapp_msg.php');
                                             
                                  
                                  
                                                 $msg = rawurlencode(
                                                    '*Login Details for ' . $fname . ' ' . $lname . '*' . "\n\n" .
                                                    'Dear ' . $fname . ' ' . $lname . ',' . "\n\n" .
                                                    'Welcome to ' . $prosfullschool . '! Your registration is successful.' . "\n\n" .
                                                    'Below are your login details:' . "\n\n" .
                                                    '*Username:* ' .$UserName . "\n" .
                                                    '*Password:* '.$password. "\n\n" .
                                                    '*URL:* '.$schoollink. "\n\n" .
                                                    'Please keep your login information confidential. If you have any questions or concerns, feel free to contact us.' . "\n\n" .
                                                    'Thank you' . "\n\n" .
                                                    '*(powered by EduMESS)*');
                                                
                                                    send_whatsapp_msg($abba_institution_id, $number,$apikey, $msg, $file);      
                                         
                                      
                                  
                                  

                                   
                          }else
                          {
                              echo 'Failed! please try again later'; 
                          }
                                                  
                         
              }
         
                 
     }
                    
                    
                    
                  
                                                          
?>