<?php
   
            error_reporting(E_ALL);
            ini_set('display_errors', 1);
            include('../../../config/config.php');
            
            $UserID = $_POST['UserID'];
            $UserType = $_POST['UserType'];

            $proscheckedpayementtype = $_POST['proscheckedpayementtype'];
            $Aamount = $_POST['amount'];
            
            $amountpaid = $Aamount;
            $amountpaiddect = $Aamount;

            $Aamountpayementtype = $_POST['paymentypeamount'];

            $CampusID  = $_POST['campusID'];

            $studentID = $_POST['studentID'];

           
             $currentDate = date("Y-m-d");


             $TermOrSemesterIDcurrent   = $_POST['term'];
            $sessionName  =  $_POST['session'];

             $referencenumber = $_POST['referencenumber'];

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

            

            $CampusIDarr  =  $CampusID[0];

            $select_termalias = mysqli_query($link,"SELECT * FROM `termalias` WHERE  TermOrSemesterID='$TermOrSemesterIDcurrent' AND CampusID= '$CampusIDarr'");

            $select_termaliascnt = mysqli_num_rows($select_termalias);
            $select_termaliascntrow = mysqli_fetch_assoc($select_termalias);

            $TermAliasName = $select_termaliascntrow['TermAliasName'];

            

                $select_agency_content = mysqli_query($link, "SELECT * FROM `institution` INNER JOIN `parent` ON `institution`.`InstitutionID` = `parent`.`InstitutionID` INNER JOIN `agencyorschoolowner` ON `institution`.`AgencyOrSchoolOwnerID` = `agencyorschoolowner`.`AgencyOrSchoolOwnerID` WHERE `parent`.`ParentID`='$UserID'");
                $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'];

               

                $InstitutionGeneralName = $select_agency_content_cnt_row['InstitutionGeneralName'];
                
                
                 $InstitutionID = $abba_institution_id2;

                $prosfullschool =  $InstitutionGeneralName;

                
                if($numberowner2  == '')
                {
                    $ownernumber = $numberowner1;
                }else{


                    $ownernumber = $numberowner2 ;
                }

           // SPACE %20,  COMMA %26 %OA
       
          

          
         


                $parent_details = mysqli_query($link, "SELECT `parent`.ParentFirstName AS ParentFirstName, `parent`.ParentLastName AS ParentLastName, `parent`.ParentOtherPhoneNumber AS
                ParentOtherPhoneNumber, `parent`.ParentWhatsappNumber AS ParentWhatsappNumber,  
                `parent`.WalletBalance AS WalletBalance 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'];

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


                    $parentnumber = $ParentWhatsappNumber;
                }

                $WalletBalance = $parent_details_cnt_row['WalletBalance'];


                

               
                $studentList = "";

                function generateTransactionReference($StudentID, $firstLettercampus) {
                                        
                    $timestamp = time();
                    $randomNumber = mt_rand(100, 999);
                
                    $transactionReference =  $firstLettercampus ."" . $StudentID ."" . $timestamp . "" . $randomNumber;
                    return $transactionReference;
                }
            
    
               
                 foreach($studentID as $key => $StudentID) {


                        $StudentID;
                        $Campusnew = $CampusID[$key];


                                    if($Aamount == '0')
                                    {

                                    }else
                                    {


                                                $studentnam = mysqli_query($link,"SELECT * FROM `student` INNER JOIN `campus` ON  `student`.CampusID = `student`.CampusID WHERE `student`.CampusID='$Campusnew' AND  `student`.StudentID='$StudentID'");
                                                $studentnamcnt = mysqli_num_rows($studentnam);
                                                $studentnamcntrow = mysqli_fetch_assoc($studentnam);


                                                   $StudentFirstName =  $studentnamcntrow['StudentFirstName'];
                                                   $StudentLastName =  $studentnamcntrow['StudentLastName'];
                                                   $CampusName =  $studentnamcntrow['CampusName'];

                                                    $firstLettercampus = substr($CampusName, 0, 1);
                                        
                                                   $studentList .= "$StudentFirstName $StudentLastName\n";

                                                        


                                                                                                
                                                        $selectstudentclass = mysqli_query($link,"SELECT * FROM `classordepartmentstudentallocation` WHERE StudentID='$StudentID' AND CampusID='$Campusnew' AND `Session`='$sessionName'");
                                                    
                                                        $selectstudentclasscnt = mysqli_num_rows($selectstudentclass);
                                                        $selectstudentclassrow = mysqli_fetch_assoc($selectstudentclass);
                                        
                                                        $ClassOrDepartmentID =  $selectstudentclassrow['ClassOrDepartmentID'];
                                        
                                                            // Function to generate a unique transaction reference
                                                          
                                                    
                                                            $transactionReference = generateTransactionReference($StudentID ,$firstLettercampus);






                                                            $pros_getcharge_for_termsent = mysqli_query($link,"SELECT SUM(Amount)  AS Amountverifiedcomp FROM `chargestructure` WHERE
                                                            `CampusID`='$Campusnew' AND `Session`='$sessionName' AND `TermOrSemesterID`='$TermOrSemesterIDcurrent' AND `ClassOrDepartmentID`='$ClassOrDepartmentID' AND `Status`='1'");
                                                        
                                                            $pros_getcharge_for_termsent_row = mysqli_fetch_assoc($pros_getcharge_for_termsent);
                                                        
                                                         $Amountverifiedcompnew = $pros_getcharge_for_termsent_row['Amountverifiedcomp'];
                                                        
                                                    
                                                        
                                                        // Select compulsory fees
                                                        $select_compulsory_fees = mysqli_query($link, "SELECT * FROM `chargestructure` WHERE CampusID='$Campusnew' AND ClassOrDepartmentID='$ClassOrDepartmentID' AND `Status`='1' AND TermOrSemesterID='$TermOrSemesterIDcurrent' AND `Session`='$sessionName'");
                                                        while ($compulsory_fee_row = mysqli_fetch_assoc($select_compulsory_fees)) {
                                                        
                                                            $categoryIDForcompFEE = $compulsory_fee_row['CategoryID'];
                                                            $SubcategoryIDForcompFEE = $compulsory_fee_row['SubcategoryID'];
                                                                $CompAmount = $compulsory_fee_row['Amount'];
                                                            $Statuscheckfee = $compulsory_fee_row['Status'];
                                                        
                                                            // Check if there's enough balance to make the payment for this category and subcategory
                                                            if ($Aamount >= $CompAmount) {
                                                                // Deduct the amount for this category and subcategory
                                                                    $Aamount -= $CompAmount;
                                                        
                                                                // Insert the payment record into the transaction table for compulsory fees
                                                                $insertPaymentQuery = "INSERT INTO `transactions`(`InstitutionID`, `CampusID`, `TransactionReference`, `TransactionType`,`ModeofTransaction`, `CategoryID`, `SubcategoryID`, `TuitionType`, `StudentID`, `ClassOrDepartmentID`, `Session`, `TermOrSemesterID`, `TransactionIn`, `Date`) 
                                                                                        VALUES ('$InstitutionID','$Campusnew','$transactionReference','income', 'Normal','$categoryIDForcompFEE','$SubcategoryIDForcompFEE','Normal','$StudentID','$ClassOrDepartmentID','$sessionName','$TermOrSemesterIDcurrent','$CompAmount','$currentDate')";
                                                        
                                                                // Execute the query to insert the payment record for compulsory fees
                                                                $inserttransaction =  mysqli_query($link, $insertPaymentQuery);
                                                            } else {
                                                
                                                                                // Insert the payment record into the transaction table for compulsory fees
                                                                    $insertPaymentQuery = "INSERT INTO `transactions`(`InstitutionID`, `CampusID`, `TransactionReference`, `TransactionType`, `ModeofTransaction`,  `CategoryID`, `SubcategoryID`, `TuitionType`, `StudentID`, `ClassOrDepartmentID`, `Session`, `TermOrSemesterID`, `TransactionIn`, `Date`) 
                                                                    VALUES ('$InstitutionID','$Campusnew','$transactionReference','income','Normal','$categoryIDForcompFEE','$SubcategoryIDForcompFEE','Normal','$StudentID','$ClassOrDepartmentID','$sessionName','$TermOrSemesterIDcurrent','$Aamount','$currentDate')";
                                                
                                                                    // Execute the query to insert the payment record for compulsory fees
                                                                    $inserttransaction =  mysqli_query($link, $insertPaymentQuery);
                                                                //    break; // Not enough balance to continue with compulsory fees
                                                
                                                
                                                            }
                                                        } 
                                                        
                                                        // Handle optional fees if there's still a remaining balance
                                                        if ($Aamount> 0) {
                                                            $select_optional_fees = mysqli_query($link, "SELECT * FROM `assignoptionalfees` INNER JOIN `chargestructure` ON `assignoptionalfees`.`CategoryID` = `chargestructure`.`CategoryID` AND `assignoptionalfees`.`SubcategoryID` = `chargestructure`.`SubcategoryID`  
                                                            WHERE `assignoptionalfees`.`CampusID`='$Campusnew' AND `assignoptionalfees`.`ClassOrDepartmentID`='$ClassOrDepartmentID' AND `assignoptionalfees`.`Session`='$sessionName' AND `assignoptionalfees`.`TermOrSemesterID`='$TermOrSemesterIDcurrent' AND `assignoptionalfees`.`StudentID`='$StudentID' AND `chargestructure`.`Status`='0'");
                                                            while ($optional_fee_row = mysqli_fetch_assoc($select_optional_fees)) {
                                                                $optionalSubcategoryID = $optional_fee_row['SubcategoryID'];
                                                                $optionalCategoryID = $optional_fee_row['CategoryID'];
                                                                $AmountOptional = $optional_fee_row['Amount'];
                                                        
                                                                
                                                                // Check if there's enough balance to make the payment for this optional fee
                                                                if ($Aamount >= $AmountOptional) {
                                                                    // Deduct the amount for this optional fee
                                                                    $Aamount-= $AmountOptional;
                                                        
                                                                        if($Aamount == '0')
                                                                        {
                                                        
                                                                        }else
                                                                        {
                                                                                // Insert the payment record into the transaction table for optional fees
                                                                                $insertPaymentQueryOptional = "INSERT INTO `transactions`(`InstitutionID`, `CampusID`, `TransactionReference`, `TransactionType`,`ModeofTransaction`, `CategoryID`, `SubcategoryID`, `TuitionType`, `StudentID`, `ClassOrDepartmentID`, `Session`, `TermOrSemesterID`, `TransactionIn`, `Date`) 
                                                                                VALUES ('$InstitutionID','$Campusnew','$transactionReference','income','Normal','$optionalCategoryID','$optionalSubcategoryID','Normal','$StudentID','$ClassOrDepartmentID','$sessionName','$TermOrSemesterIDcurrent','$AmountOptional','$currentDate')";
                                                        
                                                                                $inserttransaction =   mysqli_query($link, $insertPaymentQueryOptional);
                                                                        }
                                                        
                                                                    // Execute the query to insert the payment record for optional fees
                                                                    
                                                                } else {
                                                                    
                                                                    // Check if there's money in the wallet to cover the remaining amount
                                                                    if ($student_wallet_balance >= $Aamount) {
                                                        
                                                                        // Deduct the remaining amount from the wallet balance
                                                                        $student_wallet_balance -= $Aamount;
                                                        
                                                                            if($Aamount== '0')
                                                                            {
                                                        
                                                                            }else
                                                                            {
                                                        
                                                                                    // Insert the payment record into the transaction table for optional fees
                                                                                    $insertPaymentQueryOptional = "INSERT INTO `transactions`(`InstitutionID`, `CampusID`, `TransactionReference`, `TransactionType`, `ModeofTransaction`, `CategoryID`, `SubcategoryID`, `TuitionType`, `StudentID`, `ClassOrDepartmentID`, `Session`, `TermOrSemesterID`, `TransactionIn`, `Date`) 
                                                                                    VALUES ('$InstitutionID','$Campusnew','$transactionReference','income', 'Normal','$optionalCategoryID','$optionalSubcategoryID','Normal','$StudentID','$ClassOrDepartmentID','$sessionName','$TermOrSemesterIDcurrent','$Aamount','$currentDate')";
                                                        
                                                                                    // Execute the query to insert the payment record for optional fees
                                                                                    $inserttransaction = mysqli_query($link, $insertPaymentQueryOptional);
                                                                            }
                                                        
                                                        
                                                                                    // Reset the amount paying to zero
                                                                                    $Aamount = 0;
                                                                                    
                                                                    } else {
                                                                        break; // Not enough balance in the wallet to continue with optional fees
                                                                    }
                                                                }
                                                            }
                                                        }






                                    }

                  

                               



    
    
                 }



               




            if($proscheckedpayementtype == 'wallet')
            {

                        $walletnewamount =  $WalletBalance -  $amountpaiddect;
                        $updatewallete = mysqli_query($link,"UPDATE  `parent` SET WalletBalance='$walletnewamount' WHERE ParentID='$UserID'");
               
            }else if($proscheckedpayementtype == 'saved')
            {


                        $checkSavingsQuery = "SELECT `SaveLockID`, `Amount`, `SaveStatus` FROM `edumesssavelock` WHERE `UserID` = $UserID AND `SaveStatus` = 1 AND UserType='$UserType'";
                        $result = mysqli_query($link, $checkSavingsQuery);
                        
                        $totalSavingsAmount = 0;  // Initialize the variable outside the loop
                        
                        if ($result && mysqli_num_rows($result) > 0) {
                            // User has savings, process the payment
                        
                            $savingIDs = [];
                        
                            while ($row = mysqli_fetch_assoc($result)) {
                                $totalSavingsAmount += $row['Amount'];
                                $savingIDs[] = $row['SaveLockID'];
                            }
                        
                            if ( $amountpaiddect >= $totalSavingsAmount) {
                                // The amount to pay is equal to or greater than the total savings amount
                                // Process the payment and update SaveStatus to 3 (fully paid)
                        
                                $updatePaymentQuery = "UPDATE `edumesssavelock` SET `Amount` = 0, `SaveStatus` = 3 WHERE `SaveLockID` IN (" . implode(',', $savingIDs) . ")";
                                mysqli_query($link,  $updatePaymentQuery);
                        
                                // Now you can handle any remaining amount (if any)
                                $remainingAmount =  $amountpaiddect - $totalSavingsAmount;
                        
                                if ($remainingAmount > 0) {
                                    // Handle remaining amount, for example, update user's balance
                                    // $remainingAmount is the amount remaining after using the savings
                                }
                            } else {
                                // The amount to pay is less than the total savings amount
                                // Update the saving amounts and SaveStatus
                        
                                foreach ($savingIDs as $savingID) {
                                    $updatePaymentQuery = "UPDATE `edumesssavelock` SET `Amount` = 0, `SaveStatus` = 3 WHERE `SaveLockID` = $savingID";
                                    mysqli_query($link,  $updatePaymentQuery);
                                }
                        
                                // You can handle any remaining amount (if any) here
                            }
                        } else {
                            // User doesn't have savings
                            // Handle this case, for example, update user's balance
                        
                            // Optionally, you may update the SaveStatus to 3 to indicate fully paid
                            $updatePaymentQuery = "UPDATE `edumesssavelock` SET `SaveStatus` = 3 WHERE `UserID` = $UserID  AND UserType='$UserType'";
                            mysqli_query($link, $updatePaymentQuery);
                        }

            }else{



                            $checkSavingsQuery = "SELECT `SaveLockID`, `Amount`, `SaveStatus` FROM `edumesssavelock` WHERE `UserID` = $UserID  AND `SaveStatus` = 2 AND UserType='$UserType'";
                            $result = mysqli_query($link, $checkSavingsQuery);
                            
                            $totalSavingsAmount = 0;  // Initialize the variable outside the loop
                            
                            if ($result && mysqli_num_rows($result) > 0) {
                                // User has savings, process the payment
                            
                                $savingIDs = [];
                            
                                while ($row = mysqli_fetch_assoc($result)) {
                                    $totalSavingsAmount += $row['Amount'];
                                    $savingIDs[] = $row['SaveLockID'];
                                }
                            
                                if ($amountpaiddect >= $totalSavingsAmount) {
                                    // The amount to pay is equal to or greater than the total savings amount
                                    // Process the payment and update SaveStatus to 3 (fully paid)
                            
                                    $updatePaymentQuery = "UPDATE `edumesssavelock` SET `Amount` = 0, `SaveStatus` = 4 WHERE `SaveLockID` IN (" . implode(',', $savingIDs) . ")";
                                    mysqli_query($link, $updatePaymentQuery);
                            
                                    // Now you can handle any remaining amount (if any)
                                    $remainingAmount =  $amountpaiddect - $totalSavingsAmount;
                            
                                    if ($remainingAmount > 0) {
                                        // Handle remaining amount, for example, update user's balance
                                        // $remainingAmount is the amount remaining after using the savings
                                    }
                                } else {
                                    // The amount to pay is less than the total savings amount
                                    // Update the saving amounts and SaveStatus
                            
                                    foreach ($savingIDs as $savingID) {
                                        $updatePaymentQuery = "UPDATE `edumesssavelock` SET `Amount` = 0, `SaveStatus` = 4 WHERE `SaveLockID` = $savingID";
                                        mysqli_query($link,  $updatePaymentQuery);
                                    }
                            
                                    // You can handle any remaining amount (if any) here
                                }
                            } else {
                                // User doesn't have savings
                                // Handle this case, for example, update user's balance
                            
                                // Optionally, you may update the SaveStatus to 3 to indicate fully paid
                                $updatePaymentQuery = "UPDATE `edumesssavelock` SET `SaveStatus` = 4 WHERE `UserID` = $UserID AND AND UserType='$UserType'";
                                mysqli_query($link, $updatePaymentQuery);
                            }


            }









      


           


            // Check if compulsory fees or optional fees payments were successful
        if ($inserttransaction == true) {


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

                        
                        $select_wallettransactionsparent = mysqli_query($link, "INSERT INTO `wallettransactions`(`WalletTransactionID`, `UserID`, `UserType`, `TransactionType`, `Amount`, `TransactionFee`, `Reference`, `Date`, `Time`) 
                        VALUES (NULL,'$UserID','$UserType','Debit','$amountpaid','0','$referencenumber','$date','$time')");

                        $select_wallettransactionsparentowner = mysqli_query($link, "INSERT INTO `wallettransactions`(`WalletTransactionID`, `UserID`, `UserType`, `TransactionType`, `Amount`, `TransactionFee`, `Reference`, `Date`, `Time`) 
                        VALUES (NULL,'$AgencyOrSchoolOwnerID','owner','Credit','$amountpaid','0','$referencenumber','$date','$time')");






                                                                                    // 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);
                                            $formattedOwnerNumber = formatPhoneNumber($ownernumber);


                                                        
                                                            $parentMessage = rawurlencode(
                                                                '*Payment Successful!!*' . "\n\n" .
                                                                'Dear ' . $ParentFirstName . ' ' . $ParentLastName . ',' . "\n\n" .
                                                                'Payment has been received for your child(ren) at ' . $prosfullschool . '.' . "\n\n" .
                                                                $studentList . "\n" .
                                                                '*Amount Paid:* ₦' . number_format($amountpaid) . "\n" .
                                                                '*Date and Time:* ' . $currentDate . '  ' . $time . "\n" .
                                                                '*Transaction ID:* ' . $referencenumber . "\n\n" .
                                                                'Thank you' . "\n\n" .
                                                                '*(powered by EduMESS)*'
                                                            );

                                                        
                                                        $ownerMessage = rawurlencode(
                                                            '*Payment Notification!*' . "\n\n" .
                                                            'Dear ' . $AgencyOrSchoolOwnerName . ',' . "\n\n" .
                                                            'A payment has been made for a student at ' . $prosfullschool . '.' . "\n\n" .
                                                            '*Student name:* ' .  $studentList. "\n" .
                                                            '*Depositors name:* ' . $ParentFirstName . ' ' . $ParentLastName . "\n" .
                                                            '*Amount Paid:* ₦' . number_format($amountpaid) . "\n" .
                                                            '*Date and Time:* ' . $currentDate . '  ' . $time . "\n" .
                                                            '*Transaction ID:* ' . $referencenumber . "\n" .
                                                            '*Session:* ' . $sessionName . "\n" .
                                                            '*Term:* ' . $TermAliasName  . "\n\n" .
                                                            'Please ensure the transaction is updated in your records. If you have any inquiries,' . "\n" .
                                                            'kindly contact the parent or our support team.' . "\n\n" .
                                                            'Thanks for your continued partnership!' . "\n\n" .
                                                            'Best regards,' . "\n" .
                                                            '*(powered by EduMESS)*'
                                                        );
                                                        
                                                            $msg = $ownerMessage . ',' . $parentMessage;
                                                            $number = $formattedOwnerNumber . ',' . $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;


                                                                                    
                                    
            
           
         } else {
             echo 2;
         }
 


              
         
         
?>