<?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
        
        
        
      
        $f_name=  mysqli_real_escape_string($link, trim(isset($_POST['fname']) ? $_POST['fname'] : ''));
        $m_name = mysqli_real_escape_string($link,trim(isset($_POST['mname']) ? $_POST['mname'] : ''));
        $l_name = mysqli_real_escape_string($link,trim(isset($_POST['lname']) ? $_POST['lname'] : ''));
        $number = mysqli_real_escape_string($link,trim(isset($_POST['number']) ? $_POST['number'] : ''));
        $prayer_point = mysqli_real_escape_string($link,trim(isset($_POST['prayer_point']) ? $_POST['prayer_point'] : ''));
        $pros_meeber_referee = mysqli_real_escape_string($link,trim(isset($_POST['pros_meeber_referee']) ? $_POST['pros_meeber_referee'] : ''));

        $currentDateTime = date('Y-m-d H:i:s');

          $sql = ("SELECT * FROM `Users` WHERE Phone='$number'");
          $result = mysqli_query($link, $sql);
          $row = mysqli_fetch_assoc($result);
          $row_cnt = mysqli_num_rows($result);
    
          if ($row_cnt > 0) 
          {
              
              
              
                  
              
                        $AccValidStatus=  $row['AccValidStatus'];
                        $Phone =  $row['Phone'];
                        $UserIDnew =  $row['UserID'];
                        
                        
                        
                        
                        
                        if($AccValidStatus == 'validated')
                        {
                            
                                    
                                    
                                      $response = array(
                                        "requestSuccessful" => true, // Assuming the request was successful
                                        "responseMessage" => "failed",
                                        "responseDescription" => "User phone number already exist. please click to login",
                                        "UserID" => 'NULL',
                                        "timecount" => 'NULL'
                                        
                                      ); 
                            
                            
                            
                        }else
                        {
                            
                            
                                 
                                    $currentDateTime = date('Y-m-d H:i:s');
                                     $otp = random_int(1000, 9999);
                                
                                // Get the current timestamp
                                $currentTimestamp = time();
                                
                                // Add 5 minutes (5 * 60 seconds) to the current timestamp
                                 $expiryTimestamp = $currentTimestamp + (5 * 60);
                                
                                 // Optionally, you can convert the expiry timestamp to a human-readable format
                                
                                  $expiryTime = date('Y-m-d H:i:s', $expiryTimestamp);
                                  
                                  
                                  
                                     $update_otp = mysqli_query($link, "UPDATE `Users` SET OTP='$otp', OTPDuration='$expiryTime' WHERE UserID='$UserIDnew'");
                                     $update_otp_query = mysqli_num_rows($update_otp);
                                     
                                  
                                  
                                  
                                     $file = 'https://transformationembassy.com/assets/images/teblogo.png';
                                     $msg = rawurlencode("*Registration OTP*\n\nYour OTP is: $otp. Please enter this code to proceed.\n\nTransformtionEbassy.");
                                     $apikey = 'jLPphCxEaSLG';
        
                                     send_whatsapp_msg($number,$apikey, $msg, $file);
                            
                            
                            
                            
                            
                                        $response = array(
                                            "requestSuccessful" => true, // Assuming the request was successful
                                            "responseMessage" => "pending",
                                            "responseDescription" => "Account already exist please validate",
                                            "UserID" => $UserIDnew,
                                            "timecount" => $expiryTime
                                            
                                          ); 
                        }
    		   
        		   
                    
                    
                   
          }
          else
          {

                $currentDateTime = date('Y-m-d H:i:s');
                $otp = random_int(1000, 9999);
                
                // Get the current timestamp
                $currentTimestamp = time();
                
                // Add 5 minutes (5 * 60 seconds) to the current timestamp
                 $expiryTimestamp = $currentTimestamp + (5 * 60);
                
                 // Optionally, you can convert the expiry timestamp to a human-readable format
                
                  $expiryTime = date('Y-m-d H:i:s', $expiryTimestamp);
        
              
                  $insert_user_member = mysqli_query($link, "INSERT INTO `Users`(`UserID`, `UserFirstName`, `UserMiddleName`, `UserLastName`, `Email`, `Phone`, `DateJoin`, `UserType`, `Photo`, `DeleteStatus`, `OTP`, `OTPDuration`, `AccValidStatus`, `RefereeNameOrSource`)
                  VALUES (NULL,'$f_name','$m_name','$l_name','','$number','$currentDateTime','member','','0','$otp','$expiryTime','pending','$pros_meeber_referee')");
                 
                 
                 
                  if($insert_user_member == true)
                  {
                      
                       $lastInsertId = mysqli_insert_id($link);
                     
                     
                         $response = array(
                            "requestSuccessful" => true, // Assuming the request was successful
                            "responseMessage" => "success",
                            "responseDescription" => "Account created successfull",
                             "UserID" => $lastInsertId,
                             "timecount" => $expiryTime
                             ); 
                            
                            
                            
                            
                            $insert_login_here = mysqli_query($link, "INSERT INTO `userlogin`(`UserLoginID`, `UserID`, `UserName`, `Password`, `UserType`, `LastLoginDate`) 
                            VALUES (NULL,'$lastInsertId','$number','','member','')");
                            
                            
                            if($prayer_point == '')
                            {
                                
                            }else
                            {
                              
                             
                                     $insert_prayer =  mysqli_query($link, "INSERT INTO `prayerrequest`(`PrayerID`, `UserID`, `Des`, `DateRequested`, `PrayedSatus`) 
                                     VALUES (NULL, '$lastInsertId','$prayer_point','$currentDateTime','0')");
                            
                            }
                            
                            
                             $file = 'https://transformationembassy.com/assets/images/teblogo.png';
                             $msg = rawurlencode("*Registration OTP*\n\nYour OTP is: $otp. Please enter this code to proceed.\n\nTransformtionEbassy.");
                             $apikey = 'jLPphCxEaSLG';

                             send_whatsapp_msg($number,$apikey, $msg, $file);
                            
                      
                      
                  }else
                  {
                      
                         $response = array(
                            "requestSuccessful" => true, // Assuming the request was successful
                            "responseMessage" => "failed",
                            "responseDescription" => "Error!! insert failed please try again later",
                            "UserID" => 'NULL',
                            "timecount" => 'NULL'
                            
                          );  
                      
                  }
              
              
              
              
               
                
          }
      
      
         $json_response = json_encode($response);
    
        // // Output the JSON response
        echo $json_response;
       

?>