<?php

        include('../../config/config.php');
        date_default_timezone_set('Africa/Lagos');
        
        
      include ('../messaging/whatsapp/index.php');
            
            
            
               // Set CORS headers to allow requests from any origin (*)
        header("Access-Control-Allow-Origin: *");
        
        // Allow specific HTTP methods
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
        
        // Allow specific HTTP headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        
        // Allow cookies to be included in the request (if needed)
        header("Access-Control-Allow-Credentials:true");
        
        // Retrieve the raw POST data
        
        
        $userID =  mysqli_real_escape_string($link, trim(isset($_POST['UserID']) ? $_POST['UserID'] : ''));
        $UserType =  mysqli_real_escape_string($link, trim(isset($_POST['UserType']) ? $_POST['UserType'] : ''));
        $tribe_id =  mysqli_real_escape_string($link, trim(isset($_POST['tribe_id']) ? $_POST['tribe_id'] : ''));
        $minitribe_id =  mysqli_real_escape_string($link, trim(isset($_POST['minitribe_id']) ? $_POST['minitribe_id'] : ''));
   
      
        $currentDateTime = date('Y-m-d H:i:s');
        
        
        
          $sql = ("SELECT * FROM `Users` WHERE UserID='$userID'");
          $result = mysqli_query($link, $sql);
          $row = mysqli_fetch_assoc($result);
          $row_cnt = mysqli_num_rows($result);
    
          if ($row_cnt > 0) 
          {
              
                   
                   $UserType_new = trim($row['UserType']);
                   
                   
                   if($UserType_new == 'pastor') 
                   {
                     
                       $select_user = mysqli_query($link, "SELECT * FROM `Users` WHERE  DeleteStatus='0'
                        AND  (TribeAssigenedID=$tribe_id OR $tribe_id IS NULL) AND (MiniTribeAssigenedID = $minitribe_id OR $minitribe_id IS NULL) ORDER BY UserFirstName ASC");
                       $select_user_cnt = mysqli_num_rows($select_user);
                        
                   }else
                   {
                       
                               $pros_load_tribe_leader = mysqli_query($link, "SELECT * FROM `tribe` WHERE `TribeLeaderID`='$userID' ");
                               $pros_load_tribe_leader_cnt = mysqli_num_rows($pros_load_tribe_leader);
                               $pros_load_tribe_leader_cnt_row = mysqli_fetch_assoc($pros_load_tribe_leader);
                              
                              if($pros_load_tribe_leader_cnt > 0)
                              {
                                  
                                    $TribeID =  $pros_load_tribe_leader_cnt_row['TribeID'];
                                     
                                     
                                  
                              }else
                              {
                                  $TribeID =  0;
                              }
                                
                       
                       
                            $select_user = mysqli_query($link, "SELECT * FROM `Users` WHERE  DeleteStatus='0' AND UserType != 'pastor' AND TribeAssigenedID='$TribeID' AND (TribeAssigenedID=$tribe_id OR $tribe_id IS NULL) AND (MiniTribeAssigenedID = $minitribe_id OR $minitribe_id IS NULL)
                            ORDER BY UserFirstName ASC");
                            $select_user_cnt = mysqli_num_rows($select_user);
                           
                           
                           
                           
                       
                   }
                            
                           
                           
                           
                            $prosload_user_array = [];
                           
                           if($select_user_cnt > 0)
                           {
                               
                               
                               
                              
                               
                               
                                 while($select_user_cnt_row = mysqli_fetch_assoc($select_user))
                                 {
                                     
                                     
                                       
                                        $UserIDnew =  $select_user_cnt_row['UserID'];
                                        $UserFirstName =  $select_user_cnt_row['UserFirstName'];
                                        $UserLastName =  $select_user_cnt_row['UserLastName'];
                                        $Photo =  $select_user_cnt_row['Photo'];
                                        
                                         $TribeAssigenedID = $select_user_cnt_row['TribeAssigenedID'];
                                               
                                         $DateJoin=  $select_user_cnt_row['DateJoin'];
                                        
                                        $select_user_invites = mysqli_query($link, "SELECT * FROM `Users` WHERE  DeleteStatus='0' AND UserType != 'pastor' AND RefereeNameOrSource = '$UserIDnew' ORDER BY UserFirstName ASC");
                                        $select_user_invites_cnt = mysqli_num_rows($select_user_invites);
                                        
                                        $NumberofInvite =  $select_user_invites_cnt;
                                        $UserTypenew=  $select_user_cnt_row['UserType'];
                                        
                                        
                                          $select_check_rferrcnt = mysqli_query($link, "SELECT * FROM `Users` WHERE `RefereeNameOrSource`='$UserIDnew' AND DeleteStatus='0'");
                                          $select_check_rferrcnt_row = mysqli_num_rows($select_check_rferrcnt);
                                          
                                          
                                          
                                          
                                            $DateJoinDateOnly = substr($DateJoin, 0, 10);
                                        
                                            $count_num_event = mysqli_query($link,"SELECT DISTINCT(`event`.EventID) FROM `event` INNER JOIN
                                            `attendance` ON  `event`.`EventID` =  `attendance`.`EventID` 
                                            WHERE `event`.TribeID IN('church', '$TribeAssigenedID') AND `event`.`EventDate` >= '$DateJoinDateOnly'");
                                          
                                           $count_num_event_rows = mysqli_num_rows($count_num_event);
                                     
                                          
                                          $select_attendance_count = mysqli_query($link, "SELECT * FROM `attendance` INNER JOIN `event` ON `attendance`.`EventID` = `event`.`EventID` WHERE `attendance`.TribeID IN('church', '$TribeAssigenedID')
                                          
                                             AND `attendance`.`AttendanceStatus`='present' AND `attendance`.UserID='$UserIDnew' AND `event`.EventDate >= '$DateJoinDateOnly'");
                                                     
                                           $select_attendance_count_row = mysqli_num_rows($select_attendance_count);
                                             
                                             
                                             if($count_num_event_rows == 0)
                                             {
                                                  $percentageAttendance =0;
                                             }else
                                             {
                                                  $percentageAttendance = ($select_attendance_count_row / $count_num_event_rows) * 100;
                                             }
                                                         
                                        
                                        
                                         $prosload_user_array[] = array(
                                                'user_id' => $UserIDnew,
                                                'user_fname' => $UserFirstName,
                                                'user_lname'=> $UserLastName,
                                                'photo'=> $Photo,
                                                'numofinvite'=> number_format($select_check_rferrcnt_row),
                                                'usertype'=> $UserTypenew,
                                                 'percentage'=> $percentageAttendance
                                                
                                                
                                                                                        
                                            );
                                        
                                        
                                        
                                        
                                      
                                 }
                                 
                                 
                               
                           }else
                           {
                               
                               
                               
                               $prosload_user_array[] = array(
                                                'user_id' => '',
                                                'user_fname' => '',
                                                'user_lname'=> '',
                                                'photo'=> '',
                                                'numofinvite'=> '',
                                                'usertype'=> '',
                                                'percentage'=> ''
                                                
                                                                                        
                                            );
                               
                           }
                           
                           
                            $response = array(
                                "requestSuccessful" => true, // Assuming the request was successful
                                "responseMessage" => "success",
                                "responseDescription" => "member's record found",
                                "numberofmembers" => $select_user_cnt,
                                 "responseBody" => $prosload_user_array
                             );
                           
                       
                             
                   
              
                     
          }
          else
          {
              
             
                   $response = array(
                        "requestSuccessful" => true, // Assuming the request was successful
                        "responseMessage" => "failed",
                        "responseDescription" => "User not found",
                        "numberofmembers" => '',
                         "responseBody" => array(
                                'user_id' => '',
                                'user_fname' => '',
                                'user_lname'=> '',
                                'photo'=> ''
                                                                                
                            )
                        
                      );
              
          }
      
      
         $json_response = json_encode($response);
    
        // // Output the JSON response
        echo $json_response;
       

?>