<?php
      
      
        error_reporting(E_ALL);
        ini_set('display_errors', 1);
        include('../../../config/config.php');


        
  
        $UserID = $_POST['UserID'];
        $UserType = $_POST['UserType'];

        $amountschedule = $_POST['amount'];
        $date_scheduled = $_POST['datteshedule'];
        $monthschedule = $_POST['monthschedule'];

        $campusID = $_POST['campusID'];
        $studentID = $_POST['studentID'];

        $userschedulefor = implode(',',$studentID);

        $proscheckedpayementtype = $_POST['proscheckedpayementtype'];

       
       

        date_default_timezone_set("Africa/Lagos");
         
        $date = date("Y-m-d");
        $time = date("h:i:s");
        

       

        $select_scheduleverification = mysqli_query($link,"SELECT * FROM `salaryscheduledate` WHERE UserID='$UserID'  AND ScheduleMonth='$monthschedule' AND ScheduleDate='$date_scheduled'");
        $select_scheduleverification = mysqli_num_rows($select_scheduleverification);



        if($select_scheduleverification > 0)
        {
                  echo '2';

                 
        }else
        {


                                    

                          include('../../messaging/whatsapp/send_whatapp_msg.php');


                                   $insert_schedule =  mysqli_query($link, "INSERT INTO `salaryscheduledate`(`UserID`, `ScheduleMonth`, `ScheduleDate`, `ScheduleAmount`,`UserScheduledFor`,`ScheduleSource`,`Status`) 
                                   VALUES ('$UserID','$monthschedule','$date_scheduled','$amountschedule', '$userschedulefor','$proscheckedpayementtype','1')");


                                $parent_details = mysqli_query($link, "SELECT * FROM `parent`  WHERE `ParentID`='$UserID'");
                                




                               

                                $parent_details_cnt = mysqli_num_rows($parent_details);
                                $parent_details_cnt_row = mysqli_fetch_assoc($parent_details);

                                $ParentFirstName = $parent_details_cnt_row['ParentFirstName'];
                                $ParentLastName = $parent_details_cnt_row['ParentLastName'];

                                $ParentOtherPhoneNumber = $parent_details_cnt_row['ParentOtherPhoneNumber'];
                                $ParentWhatsappNumber = $parent_details_cnt_row['ParentWhatsappNumber'];


                                $InstitutionID = $parent_details_cnt_row['InstitutionID'];




                                $select_agency_content = mysqli_query($link, "SELECT * FROM `institution` INNER JOIN `campus` ON `institution`.`InstitutionID` = `campus`.`InstitutionID` INNER JOIN `agencyorschoolowner` ON `institution`.`AgencyOrSchoolOwnerID` = `agencyorschoolowner`.`AgencyOrSchoolOwnerID` WHERE `institution`.InstitutionID='$InstitutionID'");
                                $select_agency_content_cnt = mysqli_num_rows($select_agency_content);
                                $select_agency_content_cnt_row = mysqli_fetch_assoc($select_agency_content);
                
                
                                $abba_institution_id2 =  $select_agency_content_cnt_row['InstitutionID'];
                                $numberowner1 = $select_agency_content_cnt_row['AgencyOrSchoolOwnerMainPhone'];
                                $numberowner2 = $select_agency_content_cnt_row['AgencyOrSchoolOwnerWhatsAppPhone'];
                                $AgencyOrSchoolOwnerName = $select_agency_content_cnt_row['AgencyOrSchoolOwnerName'];
                                $AgencyOrSchoolOwnerID = $select_agency_content_cnt_row['AgencyOrSchoolOwnerID'];
                
                                $CampusName = $select_agency_content_cnt_row['CampusName'];
                
                                $firstLettercampus = substr($CampusName, 0, 1);
                
                                $InstitutionGeneralName = $select_agency_content_cnt_row['InstitutionGeneralName'];
                                
                                $prosfullschool =  $InstitutionGeneralName;





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

                                 $WalletBalance = $parent_details_cnt_row['WalletBalance'];



                                        // 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
                                        $formattedParentNumber = formatPhoneNumber($parentnumber);







                                      
                                        
                                        // Join the student names into a single string
                                        $studentNamesString = implode(', ', $_POST['studentname']);
                                        
                                        $scheduledMessage = rawurlencode(
                                            '*Automated School Fees Deduction Scheduled!*' . "\n\n" .
                                            'Dear ' . $ParentFirstName . ' ' . $ParentLastName . ',' . "\n\n" .
                                        
                                            'We want to inform you that an automated school fees deduction has been scheduled for your children at ' . $prosfullschool . '.' . "\n\n" .
                                            '*Scheduled Date:* ' . $date . "\n" .
                                            '*Deduction Month:* ' . $monthschedule . "\n\n" .
                                            '*Scheduled Amount:* ₦' . number_format($amountschedule) . "\n\n" .
                                        
                                            'The actual deduction will take place on ' . $date_scheduled . ' and will be deducted from your '.$proscheckedpayementtype.'.' . "\n\n" .
                                            'Students: ' . $studentNamesString . "\n\n" . // Include the list of student names
                                            'If you have any questions or concerns about this scheduled deduction, please feel free to reach out to our support team.' . "\n\n" .
                                            'Thank you for your cooperation.' . "\n\n" .
                                            'Best regards,' . "\n" .
                                            $prosfullschool . ' Team'."\n\n".
                                        
                                            '*(powered by EduMESS)*'
                                        );

                                            $msg =  $scheduledMessage ;
                                            $number = $formattedParentNumber;
                                            $file = '';
                                            $abba_institution_id = $abba_institution_id2; // corrected potential typo
                                            
                                            
                                            
                                            
                                              $pros_selectappi_details = mysqli_query($link,"SELECT * FROM `whatsappapikey` WHERE InstitutionID='$abba_institution_id' AND Purpose='finance'");
                                              $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'];
                                                     
                                              }
                                            
                                            send_whatsapp_msg($abba_institution_id, $number,$apikey, $msg, $file);

                                echo '1';

        }


       
      
       
       


?>



