<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {


	    function __construct() {
        parent::__construct();
        $this->load->database();
        $this->grocery_database = $this->load->database('grocery_database', TRUE); 
        $this->load->model('Login_model');
         $this->load->helper('email');
         
  
    }
    
    
   
    public function login_validate()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status=0;
		$message='Invalid Request';

        $email=$_POST['login_email'];
        $password=$_POST['login_password'];
        $token=$_POST['fcm_token']; 
        if($email && $password)
        {
            
            $row = $this->Login_model->selectusersdata($email); 
             
            if(!empty($row)) 
            {
                if($password == $this->encryption->decrypt($row->password)) 
                {
                    $session_data  = array('user_id' => $row->id,
                                        'name' => $row->name, 
                                        'email' => $row->email, 
                                        'phone' => $row->phone,
                                    );
                     $this->session->set_userdata($session_data);
                     
                     if($token) {             
                        $this->Login_model->set_f_token_web($row->user_id,  $token);  
                      }
                      
                    $status=1;
                    $message="Login Successfully..!";  
                }
                else
                {
                    $status=0;
                    $message="Password doesn't match.";
                }
            }
            else
            {
                $status=0;
                $message='Email OR Mobile Number not exist. Please, create your account first!';
            }
            
        }
        else
        {
            $status=0;
            $message='Please Fill in all required fields.';
        }
        

       
        $response['status']=$status;
		$response['message']=$message;
		echo json_encode($response);
    }
    
    public function send_otp_latest() {
        
        $mobile_number = '8280178292';
$user_name = 'satyaprangya behera';
$otp_now = '123456';
        
        
        
        // Fetch the API URL from the database
        $api_url = $this->Login_model->get_api_url();

        // Replace placeholders with actual values
        $api_url = str_replace('mobile_number', $mobile_number, $api_url);
        $api_url = str_replace('user_name', urlencode($user_name), $api_url);
        $api_url = str_replace('otp_now', $otp_now, $api_url);

        // Send the request
        $response = $this->send_request($api_url);

        // Handle the response
        if ($response) {
            // Assuming the API returns a success message
            echo 'OTP sent successfully.';
        } else {
           echo 'Failed to send OTP.';
        }
    }

    private function send_request($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    
    
   public function ValidateNumber()
    {
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
        $status=0;
        $message='Invalid Request';
        
        $phone_no= $_POST['phone'];
        
        if($phone_no)
        {
        
           $data = $this->Login_model->is_registered($phone_no);
        
           if(!empty($data))
           {
               $otp = sprintf("%06d", mt_rand(0, 999999));
               
                $sql = "SELECT * FROM sms_template where status = '0' and type = 'send_otp_new'";		
        		$exist = $this->grocery_database->query($sql)->result();
        
        		$d_msg = $exist[0]->body ;
        
        		$user_name = isset($data['name'])?$data['name']:' ';
        		//$number=$data['mobile_no'];
        		$number=$phone_no;
        		if(empty($user_name)){
        		   $user_name = 'DeliveyBoy';
        		}
        		
        		$msg = str_replace("mobile_number", $number ,$d_msg) ;
        
        		$msg = str_replace("user_name", $user_name ,$msg) ;
        
        		$msg = str_replace("otp_now", $otp ,$msg) ;
        
        		$db_data = array(
        		'phone' => $number,
        		'otp' => $otp ,
        		'user_id' => isset($data['deli_user_id'])?$data['deli_user_id']:' ',
        		'added_by_web' => $_SERVER['HTTP_HOST'] ,
        		);
        
        		$insert_id = $this->db->insert('all_otp',$db_data);
        
                 if (isset($msg) && is_string($msg)) {
                 $api_url = trim($msg);
                 }
                 
                
                 $status1 = send_text_msg_new($api_url);
        
        		//$status1 = send_text_msg($msg);
        	
        		$status=1;
        		$message='OTP has been sent successfully';
        		
        		$txt='<p class="text-success" style="background: none;margin: 7px 0px;">Otp Sent Successfully</p><div style="color:red;" id="timer"></div>
                <style>
                  .rest{
                      background-color: #28a745;
                      color: white;
                      padding: 5px 10px;
                      margin-top: 5px;
                   }
                    </style>
                    <script>
                       var counter = 59;
                        
                       var interval = setInterval(function() {
                       counter--;
     
                       if (counter <= 0) {
                           clearInterval(interval);
                           $("#timer").html("<p>Not received your code? <a href=javascript:void(0) onclick=resendotp()><span class=text-primary>Resend OTP</a></span></p>");  
                           return;
                        }else{
                           $("#timer").text("Time Remaining "+" 0 : "+counter+"s");
        
                        }
                     }, 1000);</script> ';
                 
                
               
                    $response['txt']=$txt;
                    $status=1;
                    $message='OTP has been sent successfully';
               
                
                
           }
           else
           {
                $status=0;
                $message="Mobile Number not exist Please register first..!";
               
           }
        }
        else
        {
            $status=0;
		    $message='Please enter mobile number';
        }
       
       
       
        $response['status']=$status;
		$response['message']=$message;
		echo json_encode($response);
      
    }
    
    
    
    
    function send_text_msg_new($msg)
{
    $url = $msg;

    // Initialize cURL session
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $send_details = curl_exec($ch);
   
    // Check for cURL errors
    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        return "cURL error: " . $error_msg;
    }

    curl_close($ch);

    // If response received, decode JSON and return status or error
    if (!empty($send_details)) {
        $status = json_decode($send_details);
        if (isset($status)) {
            return $status; // Return the decoded response
        } else {
            return "Invalid JSON format in response";
        }
    } else {
        // Fallback method to get response data in case cURL fails
        $json_data = file_get_contents($url);

        if ($json_data !== false) {
            $response_data = json_decode($json_data);
            if (isset($response_data)) {
                return $response_data; // Return the decoded response
            } else {
                return "Invalid JSON format from file_get_contents";
            }
        } else {
            return "Failed to retrieve data using file_get_contents";
        }
    }

    // Return this if nothing works
    return "Unknown error occurred";
}

// Function to check OTP and send message
public function checking_otp_wrk()
{
    // SQL query to fetch SMS template
    $sql = "SELECT * FROM sms_template WHERE status = '0' AND type = 'send_otp_new'";
    $exist = $this->grocery_database->query($sql)->result();

    if (empty($exist)) {
        return "No template found or inactive template.";
    }

    // Get the message body from the template
    $d_msg = $exist[0]->body;

    // Variables to replace in the message
    $user_name = 'raman';
    $number = 8851385847;
    $otp = 12345;

    // Replace placeholders in the message
    $msg = str_replace("mobile_number", $number, $d_msg);
    $msg = str_replace("user_name", $user_name, $msg);
    $msg = str_replace("otp_now", $otp, $msg);

    if (isset($msg) && is_string($msg)) {
        $api_url = trim($msg); // Prepare the API URL

        // Call the function to send the text message
        $status1 = $this->send_text_msg_new($api_url);

        // Check and return the response or error
        if (isset($status1)) {
            echo "OTP Response: " . json_encode($status1); // Show the response of OTP sent
            return ;
        } else {
            echo "Failed to send OTP";
            return ;
        }
    } else {
        
        
       echo "Invalid message format";
       return ;
    }
}
   
    
    public function login_with_otp()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status=0;
		$message='Invalid Request';
		
		
       extract($_POST);  
       
      // $this->session->set_flashdata('Mobile_no',$phone_no);
                
       $data = $this->Login_model->is_registered($phone_no);
    
       if(!empty($data))
       {
           $otp = sprintf("%06d", mt_rand(0, 999999));
           
            $sql = "SELECT * FROM sms_template where (status = '0') and type = 'send_otp'";		
    		$exist = $this->db->query($sql)->result();
    
    		$d_msg = $exist[0]->body ;
    
    		$user_name = $data['name'] ;
    		$number=$data['phone'];
    		if(empty($user_name)){
    		   $user_name = 'User' ;
    		}
    
    		
    		$msg = str_replace("mobile_number", $number ,$d_msg) ;
    
    		$msg = str_replace("user_name", $user_name ,$msg) ;
    
    		$msg = str_replace("otp_now", $otp ,$msg) ;
    
    		$db_data = array(
    		'phone' => $number,
    		'otp' => $otp ,
    		'user_id' => $data['user_id'],
    		'added_by_web' => $_SERVER['HTTP_HOST'] ,
    		);
    
    		$insert_id = $this->db->insert('all_otp',$db_data);
    
    		$status1 = send_text_msg($msg) ;
    		
    	
    		$status=1;
    		$message='OTP has been sent successfully';
    		
    		$txt='<p class="text-success" style="background: none;margin: 7px 0px;">Otp Sent Successfully</p><div style="color:red;" id="timer"></div>
                <style>
                  .rest{
                      background-color: #28a745;
                      color: white;
                      padding: 5px 10px;
                      margin-top: 5px;
                   }
                </style>
                <script>
                   var counter = 59;
                    var phone = document.getElementById("phone_no").value;
                   var interval = setInterval(function() {
                   counter--;
 
                   if (counter <= 0) {
                       clearInterval(interval);
                       $("#timer").html("<span class=rest onclick=resendotp(phone)> Resend OTP</span>");  
                       return;
                    }else{
                       $("#timer").text("Time Remaining "+" 0 : "+counter+"s");
    
                    }
                 }, 1000);</script> ';
             
            
           
            $response['resp']=$txt;
           
            
            
       }
       else
       {
            $status=0;
            $message="Mobile Number not exist Please register first..!";
           
       }
       
       
       
        $response['status']=$status;
		$response['message']=$message;
		echo json_encode($response);
      
    }
    
    public function Verifyotp()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status=0;
		$message='Invalid Request';
		
		$phone_no_otp=$_POST['lfirst'].$_POST['lsecond'].$_POST['lthird'].$_POST['lfourth'].$_POST['lfifth'].$_POST['lsixth'];
		$phone_no=$_POST['phone']; 
		
		$fcm_token=$_POST['token_id']; 
    
        if($phone_no_otp && $phone_no)
        {
            $row = $this->Login_model->selectdeliverydata($phone_no); 
            
             
            if(!empty($row)) 
            {
                $is_validate = $this->Login_model->login_with_otp_validate($phone_no);
                  
                if(!empty($is_validate)) 
                {
                    
                    if($phone_no_otp==$is_validate['otp'])
                    {
                        $update=array(
                            'status'=>1,
                        );
                        
                        $this->db->where('phone',$phone_no);
                        $this->db->update('all_otp',$update);
                        
                        $user_id=$row->deli_user_id;
                        $session_data  = array('user_id' => $row->id,
                                            'name' => $row->name, 
                                            'email' => $row->email_id, 
                                            'phone' => $row->mobile_no,
                                            'user_login_id' =>$row->deli_user_id,
                                            'delivery_role' =>'Delivery_boy',
                                        );
                         $this->session->set_userdata($session_data);
                         
                         $token=$fcm_token;
                         if($token) {             
                            $this->Login_model->set_f_token__delgorcery_web($row->deli_user_id,  $token);  
                          }
                          
                         $token=$fcm_token;
                         if($token) 
                         {   
                             $this->food_db = $this->load->database('food_database', TRUE);
                            $this->db->where('deli_user_id', $user_id);
                            $this->db->update('grocery_deliveryboy', array('f_token_web' => $token));
                            
                            $this->food_db->where('deli_user_id', $user_id);
                            $this->food_db->update('deliveryboy', array('f_token_web' => $token));
                          }
                          
                          
                          
                        $status=1;
        	            $message='Login successfully';
        	            $userloginid=$row->deli_user_id;
        	            $deliveryrole='Delivery_boy';
                    }
                    else
                    {
                        $status=0;
    	                $message="Invalid OTP. Please try again..!";
                    }
                }
                else
                {
                    $status=0;
    	            $message="Something went wrong..!";
                }
            }
            else
            {
                $status=0;
	            $message='Something went wrong..!';
            }
        }
        else
        {
            $status=0;
	        $message='Something went wrong..!';
        }
        
        $response['status']=$status;
		$response['message']=$message;
		echo json_encode($response);
    }
    
    
    
    public function login_with_otp_validate()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status=0;
		$message='Invalid Request';
		
		extract($_POST);  
    
        if($phone_no_otp && $phone_no)
        {
            $row = $this->Login_model->selectusersdata($phone_no); 
             
            if(!empty($row)) 
            {
                $is_validate = $this->Login_model->login_with_otp_validate($phone_no);
                  
                if(!empty($is_validate)) 
                {
                    
                    if($phone_no_otp==$is_validate['otp'])
                    {
                        $update=array(
                            'status'=>1,
                        );
                        
                        $this->db->where('id',$is_validate['id']);
                        $this->db->update('all_otp',$update);
                        
                        
                        $session_data  = array('user_id' => $row->id,
                                            'name' => $row->name, 
                                            'email' => $row->email, 
                                            'phone' => $row->phone,
                                        );
                         $this->session->set_userdata($session_data);
                         $token=$fcm_token;
                         if($token) {             
                            $this->Login_model->set_f_token_web($row->user_id,  $token);  
                          }
                          
                        $status=1;
        	            $message='Login successfully';
                    }
                    else
                    {
                        $status=0;
    	                $message="Invalid OTP. Please try again..!";
                    }
                }
                else
                {
                    $status=0;
    	            $message="Something went wrong..!";
                }
            }
            else
            {
                $status=0;
	            $message='Something went wrong..!';
            }
        }
        else
        {
            $status=0;
	        $message='Something went wrong..!';
        }
        
        $response['status']=$status;
		$response['message']=$message;
		echo json_encode($response);
    }
    
    
    public function customer_register()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status=0;
		$message='Invalid Request';
		
		$name=$_POST['name'];
		$email=$_POST['email'];
		$phone=$_POST['phone'];
		$password=$_POST['password'];
		$conpasswords=$_POST['conpasswords'];
		$token=$_POST['fcm_token'];
		if($name && $email && $phone && $password && $conpasswords)
		{
		    $row = $this->Login_model->check_user_exist($email,$phone); 
             
            if(empty($row)) 
            {
                
                $otp = sprintf("%06d", mt_rand(0, 999999));
               
                $sql = "SELECT * FROM sms_template where (status = '0') and type = 'send_otp'";		
        		$exist = $this->db->query($sql)->result();
        
        		$d_msg = $exist[0]->body ;
        
        		$user_name = $name;
        		$number=$phone;
        		if(empty($user_name)){
        		   $user_name = 'User' ;
        		}
        
        		
        		$msg = str_replace("mobile_number", $number ,$d_msg) ;
        
        		$msg = str_replace("user_name", $user_name ,$msg) ;
        
        		$msg = str_replace("otp_now", $otp ,$msg) ;
        
        		$db_data = array(
        		'phone' => $number,
        		'otp' => $otp ,
        		'user_id' => 'New register',
        		'added_by_web' => $_SERVER['HTTP_HOST'] ,
        		);
        
        		$insert_id = $this->db->insert('all_otp',$db_data);
        
        		$status1 = send_text_msg($msg) ;
        		
        		$status=1;
        		$message='OTP has been sent successfully';
        		
        		$txt='<p class="text-success" style="background: none;margin: 7px 0px;">Otp Sent Successfully</p><div style="color:red;" id="timer"></div>
                    <style>
                      .rest{
                          background-color: #28a745;
                          color: white;
                          padding: 5px 10px;
                          margin-top: 5px;
                       }
                    </style>
                    <script>
                       var counter = 59;
                        var phone = document.getElementById("phone_no").value;
                       var interval = setInterval(function() {
                       counter--;
     
                       if (counter <= 0) {
                           clearInterval(interval);
                           $("#timer").html("<span class=rest onclick=resendotp(phone)> Resend OTP</span>");  
                           return;
                        }else{
                           $("#timer").text("Time Remaining "+" 0 : "+counter+"s");
        
                        }
                     }, 1000);</script> ';
                 
                
               
                $response['resp']=$txt;
                
        		
        		//$response['otp']=$otp;
        		$response['name']=$name;
        		$response['email']=$email;
        		$response['phone']=$phone;
        		$response['password']=$password;
        		$response['conpasswords']=$conpasswords;
        		$response['fcm_token']=$token;
        		
        		
                
               
            }
            else
            {
                $status=0;
		        $message='Your email or mobile number already exist';
            }
		}
		else
		{
		    $status=0;
		    $message='Please fill in all required fields.';
		}
		
		$response['status']=$status;
		$response['message']=$message;
		echo json_encode($response);
    }
    
    
    public function register_with_otp_validate()
    {
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
		$status=0;
		$message='Invalid Request';
		
		$name=$_POST['name'];
		$email=$_POST['email'];
		$phone=$_POST['phone'];
		$password=$_POST['password'];
		$conpasswords=$_POST['conpasswords'];
		$token=$_POST['fcm_token'];
		$otp=$_POST['otp'];
		if($name && $email && $phone && $password && $conpasswords)
		{
		    $row = $this->Login_model->check_user_exist($email,$phone); 
             
            if(empty($row)) 
            {
                
                $is_validate = $this->Login_model->login_with_otp_validate($phone);
                 
                if(!empty($is_validate)) 
                {
                    
                    if($otp==$is_validate['otp'])
                    {
                        $update=array(
                            'status'=>1,
                        );
                        
                        $this->db->where('id',$is_validate['id']);
                        $this->db->update('all_otp',$update);
                        
                        $Customer_id='Cust-'.sprintf("%08d", mt_rand(0, 999999));
                
                        $user_data = array('name'=> $name,
                          'email'=>$email,
                          'password'=> $this->encryption->encrypt($password),
                          'phone'=>$phone,
                          'domain'=> $_SERVER['HTTP_HOST'],
                          'user_id'=>$Customer_id,
                          'ip'=>$_SERVER['REMOTE_ADDR'],
                          'f_token_web'=>$token
                          );
                           
                        $register_id = $this->Login_model->register($user_data);
                    
                        if($register_id  > 0)
                        {
                            $session_data  = array('user_id' => $register_id,
                                    'name' => $name, 
                                    'email' => $email, 
                                    'phone' => $phone,
                                    );
                             $this->session->set_userdata($session_data);
                           
                            $status=1;
                    		$message='User has been created successfully..!';
                            
                        }
                          
                       
                    }
                    else
                    {
                        $status=0;
                        $message="Invalid OTP. Please try again..!";
                    }
                
                }
            }
            else
            {
                $status=0;
		        $message='Your email or mobile number already exist';
            }
		}
		else
		{
		    $status=0;
		    $message='Please fill in all required fields.';
		}
		
		$response['status']=$status;
		$response['message']=$message;
		echo json_encode($response);
    }
    
    public function forget_password(){
   
        header("Access-Control-Allow-Origin: *");
		header("Content-Type: application/json; charset=UTF-8");
       $email=$this->input->post("email_id");
       $data=array('password'=>$this->encryption->encrypt($this->input->post("password")));

        $response=array();

    
        $sql = "SELECT `email` FROM `grocery_users` WHERE `email`= '$email'";
        $que = $this->db->query($sql);
        // print_r($que);exit;
        $output2 = $que->num_rows();
        // print_r($output2); exit;
        if ($output2 == 1) {
            $otp = random_int(100000, 999999);
            $token = uniqid();
            $datesend = date("Y-m-d H:i:s");
            $reset_expiration = date("Y-m-d H:i:s", strtotime("+30 minutes"));
        //   print_r($reset_expiration); exit;
           $a = $this->db->update('grocery_users', ['p_reset_token' => $token, 'p_reset_otp' => $otp, 'p_reset_time' => $reset_expiration], ['email' => $email]);
         $validate = $this->Login_model->select_column_where(['id','user_id','name','phone','email'],'grocery_users',['email' => $email]);
        $validate = $validate[0]; 
          $user_name= $validate['name'];
        $email = $validate['email'];
      $to_email = $email ;
            $d_t = date("l, d-M-Y h:i:s a"); 
            
            $subjectotp = "Your Verification OTP for reset password ";
                

            $messageotp = 'Dear User ('.$user_name.'),  <br>Your   OTP is  '. $otp.' <br>
            <br> 
            Mail Sent at '.$d_t.', reset link<br><br>
            <button class="btn btn-secondary"  >This is an auto-generated mail. Please do not reply.</button>';
                    
    $url_link = "Reset Password Link: " . site_url("login/user_passwordch/$token");
            $data = array(
            'user_id' =>  $user_name ,
            'subjectotp' =>  $subjectotp ,
            'messageotp' =>  $messageotp ,
            'pass'   => $otp,
            'otp_now'   => $otp,
            'url_link' => $url_link,
            
            );
            
            $from = 'noreply@msgseva.in' ;
            
            $a =  send_mail_bits_gmail_smtp($to_email, $from , $data , 'reset_pss_otp') ; 
        
           $response['status']=1;
           $response['message']="Change password link has been sent on your email address..!";
            
            
        } else {
            
            $response['status']=0;
            $response['message']="Invalid Email Address";
            
        }
    

        echo json_encode($response);
      }
      
      
   
   
    
    function logout() {
        
        unset($_SESSION['user_id']);
        unset($_SESSION['name']);
        unset($_SESSION['email']);
        unset($_SESSION['phone']);
        $this->session->set_flashdata('feedback', 'logged_out');
        redirect(base_url(), 'refresh');
    }
    
    public function checkemailpassword()
    {
        $cond = array('email' => $this->input->post('email'),
                      'password' => md5($this->input->post('password')),
                      'status' => 1,
                     );   

        $result = $this->Login_model->SelectData('grocery_seller','*',$cond); 
        $resultC = $this->Login_model->SelectData('grocery_users','*',$cond); 
      
        if (!empty($result))
        {
            echo 1;
         
        }else {
            if(!empty($resultC)){
               echo 1;
          
             }else{
                 echo 0;
             }
        }
    } 
    
    

    
    
    
    
    public function check_eemail(){
   $email_id = $this->input->post('email_id');
 
    $is_registeredE = $this->Login_model->is_registeredE($email_id);
   
            echo $is_registeredE ;
          } 
          
          public function check_deliemail(){
   $email_id = $this->input->post('email_id');
 
    $is_registeredE = $this->Login_model->emailcheckdeliv($email_id);
   
            echo $is_registeredE ;
          } 
          
          public function check_wleemail(){
   $email_id = $this->input->post('email_id');
  $is_registeredE = $this->Login_model->is_registeredwlE($email_id);
            echo $is_registeredE ;
          } 
          
                  public function check_deliveryemail(){
   $email_id = $this->input->post('email_id');
  $is_registeredE = $this->Login_model->is_registereddelivery($email_id);
            echo $is_registeredE ;
          } 
           public function check_wlphone(){
   $phone = $this->input->post('phone');
 
    $is_registeredE = $this->Login_model->is_registeredwlp($phone);
    //print_r($is_registeredE);
            echo $is_registeredE ;
          }
         
          
          public function check_email(){
   $email_id = $this->input->post('email_id');
   
    $cond = array('email' => $this->session->userdata('email')); 
  $result = $this->Login_model->SelectData('grocery_seller','*',$cond); 
   
   if($result[0]->email==$email_id){
       echo '1';
   }else{
         echo '0';
   }
          }
          
         

          public function check_phone(){
   $phone = $this->input->post('phone');
 
    $is_registeredE = $this->Login_model->is_registered1($phone);
   // print_r($is_registeredE);
            echo $is_registeredE ;
          }
           
          
 public function change_password(){
   
   $email=$this->session->userdata('email');
   $data=array('password'=>$this->encryption->encrypt($_POST['password']));
    
    
     $this->Admin_model->update_data('grocery_seller','email',$email,$data);
   redirect('seller');
          } 
          
          
     
          
          
          
    public function forget_password2(){
   
   $email=$this->input->post("email_id");
//   print_r($data['check']); exit;
   $data=array('password'=>$this->encryption->encrypt($this->input->post("password")));
    $user = $this->db->get_where('grocery_users', ['email' => $email])->row();
    // $data['check']=$this->Login_model->select_column_where(['id','password','p_reset_otp','p_reset_time','p_reset_token'],'grocery_users',['email'=>$email]);
    // print_r($user->user_id ); exit;
     if ($user->user_id != '') {
            $sql = "SELECT `email` FROM `grocery_users` WHERE `email`= '$email'";
            $que = $this->db->query($sql);
            $output2 = $que->num_rows();
            // print_r($output2); exit;
                $otp = random_int(100000, 999999);
                $token = uniqid();
                $datesend = date("Y-m-d H:i:s");
                $reset_expiration = date("Y-m-d H:i:s", strtotime("+30 minutes"));
            //   print_r($reset_expiration); exit;
               $a = $this->db->update('grocery_users', ['p_reset_token' => $token, 'p_reset_otp' => $otp, 'p_reset_time' => $reset_expiration], ['email' => $email]);
                
                $this->Admin_model->update_data('grocery_users','email',$email,$data);
                
          $to   = $email;
        $subject  = 'Your Password Reset';
      
        // $message = "Your OTP is: $otp\nReset Password Link: " . site_url("login/user_passwordch/$token");
         // the message
                $message = "
                <html>
                    <body>
                        <h2><b> Dear User  </b></h2>
                        <p>You Can Change the password by clicking on below link</p>
                        <a>".site_url("login/user_passwordch/$token")."</a>
                        <br>
                        <p> Above link Will Be valid for 30 Minutes only or for one time use. </p>
                        <p> MAil Send at ".$datesend." </p>
                        
                    </body>
                </html>
                ";
                
        $headers  = 'From: akshay.gs@bitspanindia.com' . "\r\n" .
            'MIME-Version: 1.0' . "\r\n" .
            'Content-type: text/html; charset=utf-8';
            // print_r($message);die;
        if(mail($to, $subject, $message, $headers)){
   
           $this->session->set_flashdata('msg',' Email Send successful.');
          }
          else{
            $this->session->set_flashdata('error',' Not Send successful.');
          }
                
                
          
       
     }else{
         echo"error"; exit;
     }
    
      echo 'done';
       redirect('grossry');
          }
          
          
        public function user_passwordch($token)
        {
            // print_r($token); exit;
             $user = $this->db->get_where('grocery_users', ['p_reset_token' => $token])->row();
             
              if (!$user) {
        // Token not found
        echo 'Invalid or expired Url' ;
    } elseif (strtotime($user->p_reset_time) < time()) {
        // Token has expired
        echo 'Url has expired';
    }
    else {
        $data['resetdata'] = $this->db->query("SELECT * FROM `grocery_users` WHERE `p_reset_token` = '$token'" )->row();
        $this->load->view('forgot_pass_site',$data);
        
    }
            
            // if(!empty($token))
            // {
            //     $data['resetdata'] = $this->db->query("SELECT * FROM `grocery_users` WHERE `p_reset_token` = '$token'" )->row();
            //       $this->load->view('forgot_pass_site',$data);
            // } else{
            //     $this->load->view('forgot_passexpire');
            // }
        
        //   $data['resetdata'] = $this->db->query("SELECT * FROM `grocery_users` WHERE `p_reset_token` = '$token'" )->row();
        //   print_r($data); exit;
            // $this->load->view('forgot_pass_site',$data);
            
      
        }
         public function user_passchange()
        {
        $this->load->view('user_passchange');
        }
          
      public function userr_changepassword($token){
    //   $token = '' ;
            if (!empty($_POST)) 
            {   
                
                    $this->db->trans_start();
                    $data['check']=$this->Login_model->select_column_where(['password','p_reset_otp','p_reset_time','p_reset_token'],'grocery_users',['p_reset_token'=>$token])[0];
                    if($this->input->post('password') == $this->input->post('confirm_password'))
                    {
                    // if ($this->input->post('otp') == $data['check']['p_reset_otp']) 
                    // {
                        if ($this->Login_model->update('grocery_users',['id'=>$token],['password'=>$this->encryption->encrypt($this->input->post('password'))])) 
                        {
                            if ($this->db->trans_complete()) 
                            {
                                 $this->db->update('grocery_users', ['p_reset_token' => NULL, 'p_reset_otp' => NULL, 'p_reset_time' => NULL], ['p_reset_token' => $token]);
                                $this->session->set_flashdata('msg','Password Successfully Change');
                                redirect('login/user_passchange');
                               
                            }
                        }
                        else
                        {
                            $this->session->set_flashdata('error','unable to add Password!');
                            redirect('login/user_passwordc/'.$token);
                        }
                    // }
                    // else
                    // {
                    //     $this->session->set_flashdata('error','OTP Not Match');
                    //     redirect('login/user_passwordch/'.$token);
                    // }
                    }
                    else
                    {
                        $this->session->set_flashdata('error','New Password & Confirm Password Not Match');
                        redirect('login/user_passwordch/'.$token);
                    }
                // }
            }
            redirect('login/user_passwordch/'.$token);


    }
          
          
          
          
          
          
          
    public function forget_wlpassword(){
   
   $email=$this->input->post("email_id");
   $data=array('password'=>$this->encryption->encrypt($this->input->post("password")));
   
   
    $sql = "SELECT `email` FROM `grocery_wluser` WHERE `email`= '$email'";
        $que1 = $this->db->query($sql);
        $output = $que1->num_rows();
        if ($output == 0) {
            return false;
        } else {
             $otp = random_int(100000, 999999);
                $token = uniqid();
                $datesend = date("Y-m-d H:i:s");
                $reset_expiration = date("Y-m-d H:i:s", strtotime("+30 minutes"));
            //   print_r($reset_expiration); exit;
               $a = $this->db->update('grocery_wluser', ['p_reset_token' => $token, 'p_reset_otp' => $otp, 'p_reset_time' => $reset_expiration], ['email' => $email]);
                
               
                
          $to   = $email;
        $subject  = 'Your Password Reset';
       
       
         // the message
                $message = "
                <html>
                    <body>
                        <h2><b> Dear User  </b></h2>
                        <p>You Can Change the password by clicking on below link</p>
                        <a>".site_url("login/user_passwordchwl/$token")."</a>
                        <br>
                        <p> Above link Will Be valid for 30 Minutes only or for one time use. </p>
                        <p> MAil Send at ".$datesend." </p>
                        
                    </body>
                </html>
                ";
                
        $headers  = 'From: akshay.gs@bitspanindia.com' . "\r\n" .
            'MIME-Version: 1.0' . "\r\n" .
            'Content-type: text/html; charset=utf-8';
            // print_r($message);die;
        if(mail($to, $subject, $message, $headers)){
   
           $this->session->set_flashdata('msg',' Email Send successful.');
          }
          else{
            $this->session->set_flashdata('error',' Not Send successful.');
          }
        //   $this->Admin_model->update_data('grocery_wluser','email',$email,$data);
        }
    
    
      echo 'done';
          }
          
          
        public function user_passwordchwl($token)
        {
            // print_r($token); exit;
             $user = $this->db->get_where('grocery_wluser', ['p_reset_token' => $token])->row();
             
              if (!$user) {
        // Token not found
        echo 'Invalid or expired Url' ;
    } elseif (strtotime($user->p_reset_time) < time()) {
        // Token has expired
        echo 'Url has expired';
    }
    else {
        $data['resetdata'] = $this->db->query("SELECT * FROM `grocery_wluser` WHERE `p_reset_token` = '$token'" )->row();
        $this->load->view('forgot_passwl',$data);
        
    }
           
            
      
        }
           public function user_passchangewl()
        {
        $this->load->view('user_passchangewl');
        }  
          
        public function userr_changepassword_wluser($token){
    //   $token = '' ;
            if (!empty($_POST)) 
            {   
                
                    $this->db->trans_start();
                    $data['check']=$this->Login_model->select_column_where(['password','p_reset_otp','p_reset_time','p_reset_token'],'grocery_wluser',['p_reset_token'=>$token])[0];
                    if($this->input->post('password') == $this->input->post('confirm_password'))
                    {
                    // if ($this->input->post('otp') == $data['check']['p_reset_otp']) 
                    // {
                        if ($this->Login_model->update('grocery_wluser',['id'=>$token],['password'=>$this->encryption->encrypt($this->input->post('password'))])) 
                        {
                            if ($this->db->trans_complete()) 
                            {
                                 $this->db->update('grocery_wluser', ['p_reset_token' => NULL, 'p_reset_otp' => NULL, 'p_reset_time' => NULL], ['p_reset_token' => $token]);
                                $this->session->set_flashdata('msg','Password Successfully Change');
                                redirect('login/user_passchangewl');
                               
                            }
                        }
                        else
                        {
                            $this->session->set_flashdata('error','unable to add Password!');
                            redirect('login/user_passwordchwl/'.$token);
                        }
                    // }
                    // else
                    // {
                    //     $this->session->set_flashdata('error','OTP Not Match');
                    //     redirect('login/user_passwordchwl/'.$token);
                    // }
                    }
                    else
                    {
                        $this->session->set_flashdata('error','New Password & Confirm Password Not Match');
                        redirect('login/user_passwordchwl/'.$token);
                    }
                // }
            }
            redirect('login/user_passwordchwl/'.$token);


    }
          
          
        
        public function Wl_changepassword(){
         $changepass=$this->session->userdata('wl_id');
            if (!empty($_POST)) 
            {
                    $this->db->trans_start();
                    $data['check']=$this->Login_model->select_column_where(['password'],'grocery_wluser',['id'=>$changepass])[0];
                    if($this->input->post('password') == $this->input->post('confirm_password'))
                    {
                    if ($this->input->post('old_password') == $this->encryption->decrypt($data['check']['password'])) 
                    {
                        if ($this->Login_model->update('grocery_wluser',['id'=>$changepass],['password'=>$this->encryption->encrypt($this->input->post('password'))])) 
                        {
                            if ($this->db->trans_complete()) 
                            {
                                $this->session->set_flashdata('msg','Password Successfully Change');
                                redirect('Wlepanel');
                            }
                        }
                        else
                        {
                            $this->session->set_flashdata('error','unable to add!');
                            redirect('Wlepanel');
                        }
                    }
                    else
                    {
                        $this->session->set_flashdata('error','Old Password Not Match');
                        redirect('Wlepanel');
                    }
                    }
                    else
                    {
                        $this->session->set_flashdata('error','New Password & Confirm Password Not Match');
                        redirect('Wlepanel');
                    }
                // }
            }
            redirect('Wlepanel');


    }
    
   
    
    public function forget_deliverypassword(){
   
   $email=$this->input->post("email_id");
//   $data=array('password'=>$this->encryption->encrypt($this->input->post("password")));
   
   
    $sql = "SELECT `email_id` FROM `grocery_deliveryboy` WHERE `email_id`= '$email'";
        $que1 = $this->db->query($sql);
        $output = $que1->num_rows();
        if ($output == 0) {
            return false;
        } else {
             $otp = random_int(100000, 999999);
                $token = uniqid();
                $datesend = date("Y-m-d H:i:s");
                $reset_expiration = date("Y-m-d H:i:s", strtotime("+30 minutes"));
            //   print_r($reset_expiration); exit;
               $a = $this->db->update('grocery_deliveryboy', ['p_reset_token' => $token, 'p_reset_otp' => $otp, 'p_reset_time' => $reset_expiration], ['email_id' => $email]);
                 $validate = $this->Login_model->select_column_where(['id','deli_user_id','name','email_id'],'grocery_deliveryboy',['email_id' => $email]);
            $validate = $validate[0]; 
              $user_name= $validate['name'];
        $email = $validate['email_id'];
          $to_email = $email ;
                $d_t = date("l, d-M-Y h:i:s a"); 
                
                $subjectotp = "Your Verification OTP for reset password ";
                    

                $messageotp = 'Dear User ('.$user_name.'),  <br>Your   OTP is  '. $otp.' <br>
                <br> 
                Mail Sent at '.$d_t.', reset link<br><br>
                <button class="btn btn-secondary"  >This is an auto-generated mail. Please do not reply.</button>';
                        
        $url_link = "Reset Password Link: " . site_url("login/user_passwordchdeli/$token");
                $data = array(
                'user_id' =>  $user_name ,
                'subjectotp' =>  $subjectotp ,
                'messageotp' =>  $messageotp ,
                'pass'   => $otp,
                'otp_now'   => $otp,
                'url_link' => $url_link,
                
                );
                
                $from = 'noreply@msgseva.in' ;
                
                $a =  send_mail_bits_gmail_smtp($to_email, $from , $data , 'reset_pss_otp') ; 
               
                
        //   $to   = $email;
        // $subject  = 'Your Password Reset';
       
       
        //  // the message
        //         $message = "
        //         <html>
        //             <body>
        //                 <h2><b> Dear User  </b></h2>
        //                 <p>You Can Change the password by clicking on below link</p>
        //                 <a>".site_url("login/user_passwordchdeli/$token")."</a>
        //                 <br>
        //                 <p> Above link Will Be valid for 30 Minutes only or for one time use. </p>
        //                 <p> MAil Send at ".$datesend." </p>
                        
        //             </body>
        //         </html>
        //         ";
                
        //     $headers  = 'From: akshay.gs@bitspanindia.com' . "\r\n" .
        //     'MIME-Version: 1.0' . "\r\n" .
        //     'Content-type: text/html; charset=utf-8';
        //     // print_r($message);die;
        // if(mail($to, $subject, $message, $headers)){
   
        //   $this->session->set_flashdata('success',' Email Send successful.');
        //   }
        //   else{
        //     $this->session->set_flashdata('error',' Not Send successful.');
        //   }
        //   $this->Admin_model->update_data('grocery_wluser','email',$email,$data);
        }
    
 redirect('Delivery/login');

      echo 'done';
          }
    
           
        public function user_passwordchdeli($token)
        {
            // print_r($token); exit;
             $user = $this->db->get_where('grocery_deliveryboy', ['p_reset_token' => $token])->row();
             
              if (!$user) {
        // Token not found
        echo 'Invalid or expired Url' ;
    } elseif (strtotime($user->p_reset_time) < time()) {
        // Token has expired
        echo 'Url has expired';
    }
    else {
        $data['resetdata'] = $this->db->query("SELECT * FROM `grocery_deliveryboy` WHERE `p_reset_token` = '$token'" )->row();
        $this->load->view('forgot_passdelivery',$data);
        
    }
           
            
      
        }
        
            public function user_passchangedelivery()
        {
        $this->load->view('user_passchangedelivery');
        }  
    
            public function userr_changepassword_delivery($token){
    //   $token = '' ;
            if (!empty($_POST)) 
            {   
                
                    $this->db->trans_start();
                    $data['check']=$this->Login_model->select_column_where(['password','p_reset_otp','p_reset_time','p_reset_token'],'grocery_wluser',['p_reset_token'=>$token])[0];
                    if($this->input->post('password') == $this->input->post('confirm_password'))
                    {
                    // if ($this->input->post('otp') == $data['check']['p_reset_otp']) 
                    // {
                        if ($this->Login_model->update('grocery_deliveryboy',['id'=>$token],['password'=>$this->encryption->encrypt($this->input->post('password'))])) 
                        {
                            if ($this->db->trans_complete()) 
                            {
                                 $this->db->update('grocery_deliveryboy', ['p_reset_token' => NULL, 'p_reset_otp' => NULL, 'p_reset_time' => NULL], ['p_reset_token' => $token]);
                                $this->session->set_flashdata('msg','Password Successfully Change');
                                redirect('login/user_passchangedelivery');
                               
                            }
                        }
                        else
                        {
                            $this->session->set_flashdata('error','unable to add Password!');
                            redirect('login/user_passwordchdeli/'.$token);
                        }
                    // }
                    // else
                    // {
                    //     $this->session->set_flashdata('error','OTP Not Match');
                    //     redirect('login/user_passwordchdeli/'.$token);
                    // }
                    }
                    else
                    {
                        $this->session->set_flashdata('error','New Password & Confirm Password Not Match');
                        redirect('login/user_passwordchdeli/'.$token);
                    }
                // }
            }
            redirect('login/user_passwordchdeli/'.$token);


    }
    
      public function login_admin()
    {
        $cond = array('seller_id' => $this->input->post('user_id'),
                        'seller_role' =>'OWNER',
                     );   

        $result = $this->Login_model->SelectData('grocery_admin','*',$cond); 
       
      
        if (!empty($result))
        {
            
         
                $sess_array = array();

                foreach($result as $row)
                {
                     if($this->input->post('password') == $this->encryption->decrypt($row->password)) {
                    $session_data  = array('user_login_id' => $row->seller_id,
                                            'name' => $row->seller_name, 
                                            'email' => $row->email, 
                                            'phone' => $row->phone,
                                            'seller_role' => $row->seller_role,
                                            );
                                            
                                          
                    $this->session->set_userdata($session_data);
                    
                
       
                     if($row->seller_role == 'OWNER'){
                         
                          redirect('Admin');
                     }
                
                
                     } else{
                         $this->session->set_flashdata('error', 'Invalid Password');   
                         redirect('Admin/admin_login');
                    }
                } 
         
         
        }else{

            //$this->session->userdata('msg', 'Invalid User Email or Password'); //$_SESSION['msg']='Invalid User Email or Password';
            $this->session->set_flashdata('msg', 'Invalid User Email or Password');      
            redirect('Admin/admin_login','refresh');
                   
                   
                   
                   
        } 
    } 
    
    
    
    
    
   

}