<?php
/*
Project Name: Zalawadi Visha Shreemali Sthanakwasi Jain Mitra Mandal
File Name: admin_model.php. Model File
Description: The file contains admin login related functions.
*/

require_once './lib/simplemvcwf/model_base.php';
require_once './utility/guid_utility.php';


class AdminModel extends ModelBase {
    private static $adminModel = NULL;
    
    private function __construct() {
    }
    
    static function create() {
        if (NULL == self::$adminModel) {
           self::$adminModel = new AdminModel();
        }
        return self::$adminModel;
    }
	
	// Admin user login authentication function. Function called from admin panel login page. Sets required session variables
	 public function authenticateUser($postvars) {
		 global $MyPdodb;
		 $username = $postvars['username'];
		 $password = $postvars['password'];
		        
		$sql = "SELECT * FROM hi_admin WHERE email = :email  and password = :password ";                         		
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->bindParam(':email', $username, PDO::PARAM_STR);
			$stm->bindParam(':password', md5($password), PDO::PARAM_STR);
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);			
			$UsersDetail = $results[0];	
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		if(count($UsersDetail) > 0){
			$_SESSION['user_admin_fname'] = $UsersDetail->first_name;
			$_SESSION['user_admin_lname'] = $UsersDetail->last_name;
			$_SESSION['user_type'] = '1';
			$_SESSION['user_admin_login'] = $UsersDetail->email;
			$_SESSION['user_admin_login_id'] = $UsersDetail->admin_id;
			return true;
		}		
		return false;
    }
	
	// Admin Profile
	public function profile($postvars,$filevars) {		
		 global $MyPdodb;
		 
		 $fname = $postvars['fname'];
		 $lname = $postvars['lname'];
		 $email = $postvars['email'];
		 $simage_old = $postvars['simage_old'];
		 $simage = $filevars['simage'];
		$thumbFolder = UPLOADDIR_MEMBERS;
		$validExtArr = explode(",",VALID_EXT_MEMBERS);
		$recId = rand(1000,10000);
		if(!empty($filevars['simage']['name'])){
		   $file = explode('.',basename($filevars['simage']['name']));
		   $ext = ".".$file[count($file)-1];
			if(!in_array($ext,$validExtArr))
			{
				 $parentMsg=INVALID_PHOTO_MSG;
				 $member_name = "";
			}else{	
				$member_name = "member_".$recId.".".$file[count($file)-1];
				$new_file = $thumbFolder."/".$member_name;		
				$copied = copy($filevars['simage']['tmp_name'], $new_file);
			}
		}else{
		   $member_name=$simage_old;
		}
		 $username = $_SESSION['user_admin_login'];
		 
		 $sql = "SELECT count(admin_id) as cnt FROM hi_admin where email = :email";   
		 try{
			 $stm  = $MyPdodb->prepare($sql);      		  
			 $stm->bindParam("email", $username, PDO::PARAM_STR);			
			 $stm->execute();
			 $results = $stm->fetchAll(PDO::FETCH_CLASS);		
			 $totalCounts = $results[0]->cnt;			
	      }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		  }
		 
		if($totalCounts == 0){
			$msg=CommonModel::create()->getSettings('ADMIN_CHANGE_PASSWORD_ERROR');
		}else{
			
			$sql = "update hi_admin set first_name= ?, last_name= ?, email=?, simage=? where admin_id = ?";
			try{
				$stm  = $MyPdodb->prepare($sql);      		
				$stm->bindParam(1, $fname, PDO::PARAM_STR);		
				$stm->bindParam(2, $lname, PDO::PARAM_STR);		
				$stm->bindParam(3, $email, PDO::PARAM_STR);		
				$stm->bindParam(4, $member_name, PDO::PARAM_STR);		
				$stm->bindParam(5, $_SESSION['user_admin_login_id'], PDO::PARAM_INT);
				$stm->execute();
				$msg=CommonModel::create()->getSettings('ADMIN_CHANGE_PASSWORD_SUCCESS');
				
				$_SESSION['user_admin_fname'] = $fname;
				$_SESSION['user_admin_lname'] = $lname;
				$_SESSION['user_admin_login'] = $email;
			
			}catch(PDOException $e){
				Logger::newMessage($e);
				logger::customErrorMsg();
			}
			
		}				
		 
		return $msg;
    }
	public function changepassword($postvars) {		
		 global $MyPdodb;
		 
		 $oldpass = md5($postvars['oldpass']);
		 $newpass = md5($postvars['newpass']);
		 $username = $_SESSION['user_admin_login'];
		 $sql = "SELECT count(admin_id) as cnt FROM hi_admin where email = :email and password = :oldpass";   
		 try{
			 $stm  = $MyPdodb->prepare($sql);      		  
			 $stm->bindParam("email", $username, PDO::PARAM_STR);
			 $stm->bindParam("oldpass", $oldpass, PDO::PARAM_STR);			
			 $stm->execute();
			 $results = $stm->fetchAll(PDO::FETCH_CLASS);		
			 $totalCounts = $results[0]->cnt;			
	      }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		  }
		 
		if($totalCounts == 0){
			$msg=CommonModel::create()->getSettings('ADMIN_CHANGE_PASSWORD_ERROR');
		}else{
			$sql = "update hi_admin set password= ? where admin_id = ?";
			try{
				$stm  = $MyPdodb->prepare($sql);      		
				$stm->bindParam(1, $newpass, PDO::PARAM_STR);		
				$stm->bindParam(2, $_SESSION['user_admin_login_id'], PDO::PARAM_INT);
				$stm->execute();
				$msg=CommonModel::create()->getSettings('ADMIN_CHANGE_PASSWORD_SUCCESS');
				
				//$_SESSION['user_admin_fname'] = $fname;
				//$_SESSION['user_admin_lname'] = $lname;
				//$_SESSION['user_admin_login'] = $email;
			
			}catch(PDOException $e){
				Logger::newMessage($e);
				logger::customErrorMsg();
			}
			
		}				
		 
		return $msg;
    }
	
	public function forgotpassword($postvars){		
		global $MyPdodb;
	    $email = $postvars['username'];
		
		$sql = "SELECT count(admin_id) as cnt FROM hi_admin where email = :email";   
		 try{
			 $stm  = $MyPdodb->prepare($sql);      		  
			 $stm->bindParam("email", $email, PDO::PARAM_STR);			
			 $stm->execute();
			 $results = $stm->fetchAll(PDO::FETCH_CLASS);					 
			 $totalCounts = $results[0]->cnt;			
	      }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		  }
		 
		if($totalCounts == 0){
			$msg=CommonModel::create()->getSettings('ADMIN_WRONG_EMAIL_ERROR');
		}else{
			
			$sql = "Select * from hi_admin where email= :email";
			try{
				$stm  = $MyPdodb->prepare($sql);      		
				$stm->bindParam(':email', $email, PDO::PARAM_STR);			
				$stm->execute();
				$results = $stm->fetchAll(PDO::FETCH_CLASS);			
				$AdminDetail = $results[0];	
				//print_r($AdminDetail);
				//exit;				
			}catch(PDOException $e){
				Logger::newMessage($e);
				logger::customErrorMsg();
			}
			$EmailBody=CommonModel::create()->getSettings('ADMIN_FORGOT_PWD_EMAIL');
			$EmailBody = nl2br($EmailBody);
			$adminName = $AdminDetail->first_name." ".$AdminDetail->last_name;
			$adminEmail = $AdminDetail->email;
			//$adminPassword = $AdminDetail->password;
			$len=7;
			$adminPassword = substr(md5(rand().rand()), 0, $len);
			
			 $sql = "update hi_admin set password= ? ";
				try{
					$stm  = $MyPdodb->prepare($sql);      		
					$stm->bindParam(1, md5($adminPassword), PDO::PARAM_STR);		
					$stm->execute();
					
				}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
				}
			
			$EmailBody = str_replace("[#ADMIN_NAME#]",$adminName,$EmailBody);
			$EmailBody = str_replace("[#USERNAME#]",$adminEmail,$EmailBody);
			$EmailBody = str_replace("[#PASSWORD#]",$adminPassword,$EmailBody);
			
			$subject="Password Recovery :: Jain Pragati Center ADMIN";
			$to = $adminEmail;
			$isHTML=true;
			CommonModel::create()->sendEmail($to,$subject,$EmailBody,$isHTML);
			
			$msg=CommonModel::create()->getSettings('ADMIN_FORGOT_PWD_SUCCESS');
		}
		
		return $msg;
	}
	
	public function changeSettings(){
		 global $MyPdodb;
		// echo "<pre>"; print_r($_POST);
		// exit;
		 $id_arr = $_POST['id'];
		 for($i = 0; $i<count($id_arr);$i++)
		 {
			 $txtName = 'txt_'.$id_arr[$i];
			 $radioName = 'r_'.$id_arr[$i];
			$option_value = $_POST[$txtName] ? $_POST[$txtName] : $_POST[$radioName];
			 
		  $sql = "update hi_settings set option_value= ? where id = ?";
			try{
				$stm  = $MyPdodb->prepare($sql);      		
				$stm->bindParam(1, $option_value, PDO::PARAM_STR);		
				$stm->bindParam(2, $id_arr[$i], PDO::PARAM_STR);
				$stm->execute();
				
			}catch(PDOException $e){
				Logger::newMessage($e);
				logger::customErrorMsg();
			}
		 }
		 $msg=CommonModel::create()->getSettings('SITE_SETTINGS_CHANGE_SUCCESS');			
		 return $msg;
		}
		
		
	public function selectSettings($postvars){
		global $MyPdodb;
		if($postvars!=''){
			$sql = "SELECT * FROM hi_settings where option_cat='".$postvars."' order by id";   
		}
		else{
			$sql = "SELECT * FROM hi_settings where option_cat='1' 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();
			}
		}
		
	public function getAdminDetails($adminId){
		global $MyPdodb;
		
		$sql = "Select * from hi_admin where admin_id= :id";
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->bindParam(':id', $adminId, PDO::PARAM_STR);			
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);			
			$UsersDetail = $results[0];	
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		return $UsersDetail;
	}
	
	
	
}