<?php
/*
Project Name: Zalawadivisha
File Name: frontpages_model.php. Model File
Description: The file contains all Common pages database related functions.
*/
require_once './lib/simplemvcwf/model_base.php';
require_once './utility/guid_utility.php';
class FrontpagesModel extends ModelBase {
    private static $frontpagesModel = NULL;
    
    private function __construct() {
    }
	
    static function create() {
        if (NULL == self::$frontpagesModel) {
           self::$frontpagesModel = new FrontpagesModel();
        }
        return self::$frontpagesModel;
    }
	public function getSettings($option_name) {
		global $MyPdodb;		   
		$sql = "SELECT * FROM hi_settings where option_name = :option_name";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
		 
			$stm->bindParam(':option_name', $option_name, PDO::PARAM_INT);
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			return $results[0]->option_value;				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }
	public function getCommonpages() {
		global $MyPdodb;		   
		$sql = "SELECT * FROM hi_pages where status= :active order by id";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
			$active=1;
			$viewlink=1;
			$stm->bindParam(':active', $active, PDO::PARAM_INT);
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			return $results ;				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }
	public function getTopBanner(){
		global $MyPdodb;		   
		$sql = "SELECT * FROM hi_banners where bannertype_id= 1 and status = 1 and enddate >= CURDATE() order by rand() ";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
			
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			return $results;				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}
	public function getLeftBanner(){
		global $MyPdodb;		   
		$sql = "SELECT * FROM hi_banners where bannertype_id= 2 and status = 1 and enddate >= CURDATE() order by rand()";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
			
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			return $results;				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}
	public function getBottomBanner(){
		global $MyPdodb;		   
		$sql = "SELECT * FROM hi_banners where bannertype_id= 4 and status = 1 and enddate >= CURDATE() order by rand()";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
			
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			return $results;				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}
	public function getRightBanner(){
		global $MyPdodb;		   
		$sql = "SELECT * FROM hi_banners where bannertype_id= 3 and status = 1 and enddate >= CURDATE() order by rand()";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
			
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			return $results;				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}
	public function getAdminPhoto(){
		global $MyPdodb;		   
		$sql = "SELECT simage FROM hi_admin limit 1";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
			
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			return $results[0];				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}
	
	public function userLogin($postvars){
		global $MyPdodb;	 
		$uname =$postvars['uname'];
		$pass = $postvars['pass'];
		$approved=1;
		$active=1;
			$sql ="Select * from hi_members where (username= ? or email = ? or mobile = ?) and password= ? and status= ? ";		    
		   try{
			   $stm  = $MyPdodb->prepare($sql);      			  		   
			   $stm->execute(array($uname,$uname,$uname,$pass,$active));		   
			   $resutls = $stm->fetchAll(PDO::FETCH_OBJ);
			   $UsersDetail = $resutls[0];
			}catch(PDOException $e){
				Logger::newMessage($e);
				logger::customErrorMsg();
			}
			if(count($UsersDetail) > 0){
					$_SESSION['member_name'] = $UsersDetail->fullname;
					$_SESSION['member_username'] = $UsersDetail->username;
					$_SESSION['member_id'] = $UsersDetail->id;
					$_SESSION['member_simage'] = $UsersDetail->simage;
					$_SESSION['member_email'] = $UsersDetail->email;
					
					$msg='true';
			}else{
				$msg='false';
			}
			return $msg;
	}
	public function forgotPassword($postvars) {
		   global $MyPdodb;	 
		 
		   $fpass_email = $postvars["email"];
		   $sql ="Select * from hi_members where email= ? or mobile= ?";		
		   try{
		   $stm  = $MyPdodb->prepare($sql);      			  		   
		   $stm->execute(array($fpass_email,$fpass_email));		   
		   $resutls = $stm->fetchAll(PDO::FETCH_OBJ);
		   $UsersDetail = $resutls[0];
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
   
		  								
			$utype = '1';
			$eventtype = 'Forgot Password - Member';
			$datetime = date ("Y-m-d H:i:s");
		   $flg=0;
		   if(count($UsersDetail) > 0){
			   		 $userEmail =$UsersDetail->email ;
					 $userMobile =$UsersDetail->mobile ; 
					 if($userEmail == $fpass_email){	
					 
						 $key = rand(123545,985457); // generating Unique key to send with a link for change password
											
						 $sql = "UPDATE hi_members set passkey= :passkey where email= :email";
						 try{
						 $stm  = $MyPdodb->prepare($sql);      		
						 $stm->bindParam(':passkey', $key, PDO::PARAM_STR);		
						 $stm->bindParam(':email', $fpass_email, PDO::PARAM_STR);
						 $stm->execute();       
						
						//Preparing template for email
						$subject = "JPC: Your Forgotten Password Request";
						$name = $UsersDetail->fullname;
						$email = $UsersDetail->email;
						
						$to = $email;
						$flg=1;
						$error_msg=CommonModel::create()->getSettings('FORGOT_PASSWORD_SUCCESS');
						 }catch(PDOException $e){
							Logger::newMessage($e);
							logger::customErrorMsg();
						}
						
					 }else if($userMobile == $fpass_email){	
					 	
						 $mobile_otp = mt_rand(100000,999999); // generating Unique key to send with a link for change password
											
						 $sql = "UPDATE hi_members set mobile_otp= :mobile_otp where mobile= :mobile";
						 try{
						 $stm  = $MyPdodb->prepare($sql);      		
						 $stm->bindParam(':mobile_otp', $mobile_otp, PDO::PARAM_STR);		
						 $stm->bindParam(':mobile', $fpass_email, PDO::PARAM_STR);
						 $stm->execute();       
						
						//Preparing template for email
						$subject = "JPC: OTP to reset the password";
						$name = $UsersDetail->fullname;
						$email = $UsersDetail->email;
						
						$to = $email;
						$flg=2;
						$error_msg="OTP";
						 }catch(PDOException $e){
							Logger::newMessage($e);
							logger::customErrorMsg();
						}
						
					 }
					
			   
		   }
		   else{
		   		$error_msg="Member Email Address not found, Contact Your Admin with your Member id";
		   }
		   
		   if($flg==1)
		   {
		   		$body = '<table align="left" border="0" width="100%">
							   <tr>	
									<td>Please click <a href="'.BASE_URL.'/resetpassword?key='.md5($key).'&member='.md5($member).'&e='.md5($email).'">here</a> to reset your JPC password.</td>
							   </tr>
							    <tr>	
									<td>&nbsp;</td>
							   </tr>
							   <tr>	
									<td>'."If this doesn't work, please copy and paste the following URL into your web browser.".'</td>
							   </tr>							   
							   <tr>	
									<td>'.BASE_URL.'/resetpassword?key='.md5($key).'&member='.md5($member).'&e='.md5($email).'</td>
							   </tr>
							    <tr>	
									<td>&nbsp;</td>
							   </tr>
								<tr>	
									<td>Email:'.$email.'</td>
							   </tr>
							   
							</table>';
					$emailBody = '<table align="center" border="0" width="100%">
								  <tr>
										<td>Hi '.$name.',</td>
								  </tr>	
								  <tr>
										<td>'.$body.'</td>
								  </tr>	
								  <tr>
										<td></td>
								  </tr>
								  </table>';
					$header="MIME-Version: 1.0\r\n";
					$header.="Content-type: text/html \r\n";
					$fromName = "JPC";
					$fromEmail = FrontpagesModel::create()->getSettings('MAIL_SEND_FROM_EMAIL');
					$header .= "From: ".$fromName." <".$fromEmail."> \r\n";
					@mail($to,$subject,$emailBody,$header);
		   }else if ($flg==2){
			   
			   $body = '<table align="left" border="0" width="100%">
							   <tr>	
									<td>Your OTP to reset the password.</td>
							   </tr>
							    <tr>	
									<td>&nbsp;</td>
							   </tr>
							   <tr>	
									<td style="font-size:25px;">OTP: <strong>'.$mobile_otp.'</strong></td>
							   </tr>							   							   
							   
							</table>';
					$emailBody = '<table align="center" border="0" width="100%">
								  <tr>
										<td>Hi '.$name.',</td>
								  </tr>	
								  <tr>
										<td>'.$body.'</td>
								  </tr>	
								  <tr>
										<td></td>
								  </tr>
								  </table>';
					$header="MIME-Version: 1.0\r\n";
					$header.="Content-type: text/html \r\n";
					$fromName = "JPC";
					$fromEmail = FrontpagesModel::create()->getSettings('MAIL_SEND_FROM_EMAIL');
					$header .= "From: ".$fromName." <".$fromEmail."> \r\n";
					@mail($to,$subject,$emailBody,$header);
			   
		   }
		   
		   return $error_msg;
	}
	
	public function validateOTP($data) {
		 global $MyPdodb;	 	 
		 $mobile_otp = $data["mobile_otp"];
		 $mobile_no = $data["email"];
		 $sql ="Select * from hi_members where mobile_otp= ? and mobile= ?";		
		   try{
		   $stm  = $MyPdodb->prepare($sql);      			  		   
		   $stm->execute(array($mobile_otp,$mobile_no));		   
		   $resutls = $stm->fetchAll(PDO::FETCH_OBJ);
		   $UsersDetail = $resutls[0];
			}catch(PDOException $e){
				Logger::newMessage($e);
				logger::customErrorMsg();
			}
			
			 if(count($UsersDetail) > 0){
				 
				     $key = rand(123545,985457); // generating Unique key to send with a link for change password
											
					 $sql = "UPDATE hi_members set passkey= :passkey where mobile= :mobile";
					 try{
						 $stm  = $MyPdodb->prepare($sql);      		
						 $stm->bindParam(':passkey', $key, PDO::PARAM_STR);		
						 $stm->bindParam(':mobile', $mobile_no, PDO::PARAM_STR);
						 $stm->execute();       		
						 $error_msg="Correct OTP";
						 
						 header("Location: ".BASE_URL.'/resetpassword?key='.md5($key).'&e='.md5($mobile_no));
						 								
					 }catch(PDOException $e){
						Logger::newMessage($e);
						logger::customErrorMsg();
					}
				 
			 }else{
				 $error_msg="Wrong OTP";
			 }
			
		return $error_msg;
	}
	
	public function resetPassword($data) {
	 global $MyPdodb;	 	 
	$datetime = date ("Y-m-d H:i:s");
	$new_password = $data["newpass"];
	$key = $data["passkey"];	
	$em = $data["e"];	
		    
		$sql_check ="Select count(id) as cnt from hi_members where md5(passkey)= :passkey and (md5(email)=:email or md5(mobile)=:mobile) ";
	
			try{
				$stm  = $MyPdodb->prepare($sql_check);      		  
				$stm->bindParam(':passkey', $key, PDO::PARAM_STR);
				$stm->bindParam(':email', $em, PDO::PARAM_STR);
				$stm->bindParam(':mobile', $em, PDO::PARAM_STR);
				
				$stm->execute();
				$results = $stm->fetchAll(PDO::FETCH_CLASS);		
				$totalCounts = $results[0];		
				 if($totalCounts->cnt  == 0){
					 return "Invalid reset password link";
					 exit;
				 }
			  }catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
			  }
	
	 try{
		 	 $sql = "UPDATE hi_members set password= :new_password,passkey= :newpasskey,mobile_otp= :mobile_otp where md5(passkey)= :passkey and (md5(email)=:email or md5(mobile)=:mobile)";
			/* echo $sql = "UPDATE hi_members set password= '$new_password',passkey= '$newpasskey',mobile_otp= '$newpasskey' where md5(passkey)= '$key' and (md5(email)='$em' or md5(mobile)='$em')";
			 exit;*/
			 $stm  = $MyPdodb->prepare($sql);   
			 $newpasskey="";   			
			 $stm->bindParam(':new_password', $new_password, PDO::PARAM_STR);
			 $stm->bindParam(':newpasskey', $newpasskey, PDO::PARAM_STR);	
			 $stm->bindParam(':mobile_otp', $newpasskey, PDO::PARAM_STR);						
			 $stm->bindParam(':passkey', $key, PDO::PARAM_STR);		
			 $stm->bindParam(':email', $em, PDO::PARAM_STR);
			 $stm->bindParam(':mobile', $em, PDO::PARAM_STR);				
			 
				if( $stm->execute()){
					$error_msg="Password successfully reseted";
				}
					
				
			 
		}catch(PDOException $e){
				Logger::newMessage($e);
				logger::customErrorMsg();
		}	
	 
	 return $error_msg;	
	}
	public function changePassword($data) {
	 global $MyPdodb;	 	 
	$datetime = date ("Y-m-d H:i:s");
	$new_password = $data["newpass"];
	$old_password = $data["oldpass"];
	
	    $sql = "UPDATE hi_members set password= :new_password where id= :memberid";
		$sql_check ="Select count(id) as cnt from hi_members where id=:memberid and  password=:oldpass";
	
	
			try{
				$stm  = $MyPdodb->prepare($sql_check);      		  
				$stm->bindParam(':memberid', $_SESSION["member_id"], PDO::PARAM_INT);
				$stm->bindParam(':oldpass', $old_password, PDO::PARAM_STR);
				
				$stm->execute();
				$results = $stm->fetchAll(PDO::FETCH_CLASS);		
				$totalCounts = $results[0];		
				 if($totalCounts->cnt  == 0){
					 return "Invalid Old password";
					 exit;
				 }
			  }catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
			  }
	
	 try{
			 $stm  = $MyPdodb->prepare($sql);   
			 $newpasskey="";   			
			 $stm->bindParam(':new_password', $new_password, PDO::PARAM_STR);
			 $stm->bindParam(':memberid', $_SESSION["member_id"], PDO::PARAM_STR);		
			 
				if( $stm->execute()){
					$error_msg="Password successfully reseted";
				}
					
				
			 
		}catch(PDOException $e){
				Logger::newMessage($e);
				logger::customErrorMsg();
		}	
	 
	 return $error_msg;	
	}
	public function insertMemberRequest($postvars){
		global $MyPdodb;
		$name = $postvars["name"];
		$email = $postvars["email"];
		$mobile = $postvars["mobile"];
		$message = $postvars["message"];
		$status = 0;
		$tdate = date ("Y-m-d");
		$sql = "insert into hi_memberrequest (name, email, mobile, message, tdate, status) values (?,?,?,?,?,?)";
		try{
			$stm  = $MyPdodb->prepare($sql);
					
			$stm->bindParam(1, $name, PDO::PARAM_STR);
			$stm->bindParam(2, $email, PDO::PARAM_STR);
			$stm->bindParam(3, $mobile, PDO::PARAM_STR);
			$stm->bindParam(4, $message, PDO::PARAM_STR);
			$stm->bindParam(5, $tdate, PDO::PARAM_STR);
			$stm->bindParam(6, $status, PDO::PARAM_INT);
			
				if($stm->execute()){
					$msg =CommonModel::create()->getSettings('MEMBER_INSERT_MSG');
				}else{
					$msg =CommonModel::create()->getSettings('MEMBER_INSERT_ERROR_MSG');
				}	
				return $msg;
		}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
		}
	}
	
	public function getCommonBanner(){
		global $MyPdodb;		   	
		$sql = "SELECT banners.* FROM hi_homebanners banners where banners.status = 1 and banners.is_common=1 order by banners.id";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			return $results;				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}
	
	public function getHomeBanner(){
		global $MyPdodb;		   
		//$sql = "SELECT * FROM hi_homebanners where status = 1 order by rand()";		
		$sql = "SELECT banners.*,dynamic.bannerid,dynamic.section_ids,dynamic.subsection_ids,dynamic.pages_ids FROM hi_homebanners banners,hi_dynamicbanner dynamic where banners.status = 1 and dynamic.bannerid=banners.id order by banners.id";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
			
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			return $results;				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}
	
	public function getHomeBannerforPages($bannerIds){
		global $MyPdodb;		   
		if(empty($bannerIds)){
			$bannerIds=0;
		}
		$sql = "SELECT * FROM hi_homebanners where status = 1 and id IN (".$bannerIds.")order by id";			
		try{
			$stm  = $MyPdodb->prepare($sql);    
			
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			return $results;				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}
}