<?php
/*
Project Name: Zalawadivisha
File Name: commonpages_model.php. Model File
Description: The file contains common pages related functions.
*/

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

// Encapsulates all common pages database table access. This method of encapsulation uses the singleton design pattern.
class EventsModel extends ModelBase {
    private static $EventsModel = NULL;
    
    private function __construct() {
    }
    
    // The create function is necessary to ensure there is only one instance of common pages table being used at any one time (eg. singleton)
    static function create() {
        if (NULL == self::$EventsModel) {
           self::$EventsModel = new EventsModel();
        }
        return self::$EventsModel;
    }
    
    // Retrieves a common page row by its id    
    public function selectPagesByPageId($pageId) {
		
		global $MyPdodb;		        
		$pageId = (int) $pageId;
		$sql = "SELECT * FROM hi_events WHERE id = :id  LIMIT 1";        		
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->bindParam(':id', $pageId, PDO::PARAM_INT);
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);			
			return $results[0];		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}

    }
	
	 // Retrieves a common page row by its pagename    
    public function selectPagesByPageName($pageName) {
		
		global $MyPdodb;		        		
		$sql = "SELECT * FROM hi_events WHERE url = :url  LIMIT 1";        		
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->bindParam(':url', $pageName, PDO::PARAM_STR);
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);			
			return $results[0];				
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }
    
    // Retrieves all pages
    public function selectPages($start=0,$limit,$etype) {
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		$start = (int) $start;
		$limit = (int) $limit;		
		if($etype=='Live'){
			$subsql = " where enddate>'".date('Y-m-d')."'";
		}
		if($etype=='Archive'){
			$subsql = " where enddate<'".date('Y-m-d')."'";
		}
		$sql = "SELECT * FROM hi_events $subsql limit ?, ?";  
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->execute(array($start,$limit));
			$results = $stm->fetchAll(PDO::FETCH_CLASS);
			$i=0;
			foreach($results as $result){
				//print_r($result);
				if($result->updateby_type==2){
					$sql = "select fullname as member, simage from hi_members where id='".$result->updateby."'";
					try{
						$MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
						$res = $MyPdodb->queryFirst($sql);
						$member = $res->member;
						$photo = $res->simage;
						//array_push($arrres,$totalsubsec);
						$results[$i]->member = $member;
						$results[$i]->photo = $photo;
					}catch(PDOException $e){
						Logger::newMessage($e);
						logger::customErrorMsg();
					}
				}else{
					$results[$i]->member = "Administrator";
					$results[$i]->photo = $_SESSION['adminphoto'];
				}
				$i++;
			}	
			return $results ;		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		
    }
	
	public function selectEvents_all($postvars) {
		
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));	
		
		$sql_count = "SELECT count(id) as cnt FROM hi_events where status=1 and startdate > NOW() - INTERVAL 30 DAY order by startdate desc ";
	    try {
				$stm  = $MyPdodb->prepare($sql_count);      		
				$stm->execute($BindArr);
				$results = $stm->fetchAll(PDO::FETCH_CLASS);
			}catch(PDOException $e){
				Logger::newMessage($e);
				logger::customErrorMsg();
		    }	
				
		$totalCounts = $results[0]->cnt;			
	    $_REQUEST["totalres"] = $totalCounts;
		$_REQUEST["nume"] = $totalCounts;	
		$sortby = $postvars['sortby'];
		if($sortby==''){
			$sortby_=' order by startdate desc ';
		}else{
			if($sortby=='startdate'){
				$sortby_=' order by startdate desc';
			}else{
				$sortby_=' order by '.$sortby.' asc ';
			}
			
		}
		$sql = "SELECT * FROM hi_events where status=1 and startdate > NOW() - INTERVAL 30 DAY $sortby_ LIMIT ?, ?";  
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$BindArr[] =(int) $postvars["eu"];
			$BindArr[] =(int) $postvars["limit"];	
			$stm->execute($BindArr);
			$results = $stm->fetchAll(PDO::FETCH_CLASS);
			$i=0;
			foreach($results as $result){
				//print_r($result);
				if($result->updateby_type==2){
					$sql = "select fullname as member, simage from hi_members where id='".$result->updateby."'";
					try{
						$MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
						$res = $MyPdodb->queryFirst($sql);
						$member = $res->member;
						$photo = $res->simage;
						//array_push($arrres,$totalsubsec);
						$results[$i]->member = $member;
						$results[$i]->photo = $photo;
					}catch(PDOException $e){
						Logger::newMessage($e);
						logger::customErrorMsg();
					}
				}else{
					$results[$i]->member = "Administrator";
					$results[$i]->photo = $_SESSION['adminphoto'];
				}
				$i++;
			}	
			return $results ;		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		
    }
	public function selectEvents_past($postvars) {
		
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));	
		$sql_count = "SELECT count(id) as cnt FROM hi_events where status=1 and startdate < NOW() - INTERVAL 30 DAY order by startdate desc ";
	    try {
				$stm  = $MyPdodb->prepare($sql_count);      		
				$stm->execute($BindArr);
				$results = $stm->fetchAll(PDO::FETCH_CLASS);
			}catch(PDOException $e){
				Logger::newMessage($e);
				logger::customErrorMsg();
		    }	
				
		$totalCounts = $results[0]->cnt;			
	    $_REQUEST["totalres"] = $totalCounts;
		$_REQUEST["nume"] = $totalCounts;	
		$sortby = $postvars['sortby'];
		if($sortby==''){
			$sortby_=' order by startdate desc ';
		}else{
			if($sortby=='startdate'){
				$sortby_=' order by startdate desc';
			}else{
				$sortby_=' order by '.$sortby.' asc ';
			}
			
		}	
		$sql = "SELECT * FROM hi_events where status=1 and startdate < NOW() - INTERVAL 30 DAY $sortby_ LIMIT ?, ?";  
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$BindArr[] =(int) $postvars["eu"];
			$BindArr[] =(int) $postvars["limit"];	
			
			$stm->execute($BindArr);
			$results = $stm->fetchAll(PDO::FETCH_CLASS);
			$i=0;
			foreach($results as $result){
				//print_r($result);
				if($result->updateby_type==2){
					$sql = "select fullname as member, simage from hi_members where id='".$result->updateby."'";
					try{
						$MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
						$res = $MyPdodb->queryFirst($sql);
						$member = $res->member;
						$photo = $res->simage;
						//array_push($arrres,$totalsubsec);
						$results[$i]->member = $member;
						$results[$i]->photo = $photo;
					}catch(PDOException $e){
						Logger::newMessage($e);
						logger::customErrorMsg();
					}
				}else{
					$results[$i]->member = "Administrator";
					$results[$i]->photo = $_SESSION['adminphoto'];
				}
				$i++;
			}	
			return $results ;		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		
    }
	
	// Retrieves total count of common pages
    public function selectCount() {
       global $MyPdodb;
       $sql = "SELECT count(id) as cnt FROM hi_events";        	       	  
	   $MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	   return $MyPdodb->queryFirst($sql);	   	  
    }
	public function needapprove() {
       global $MyPdodb;
       $sql = "SELECT count(id) as cnt FROM hi_events where status=0";        	       	  
	   $MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	   return $MyPdodb->queryFirst($sql);	   	  
    }
	public function getSectionName($secid) {
       global $MyPdodb;
       $sql = "SELECT name FROM hi_events where id = $secid";        	       	  
	   $MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	   return $MyPdodb->queryFirst($sql);	   	  
    }
	public function selectSectionName($section_id) {
       global $MyPdodb;
       $sql = "SELECT name FROM hi_events where id=:section_id";        	       	  
	   $stm  = $MyPdodb->prepare($sql);      		
		$stm->bindParam(':section_id', $section_id, PDO::PARAM_INT);
		$stm->execute();       
	  	$results = $stm->fetchAll(PDO::FETCH_CLASS);	
		$section_name = $results[0];		
		return $section_name->name;  
    }
	
	// Change disaply Status
    public function changeStatus($postvars) {
        global $MyPdodb;
		   $recId = $postvars["event_id"];
		   $recStatus = $postvars["recStatus"];	   
		   if($recStatus == 1) { $recStatus=0; } else { $recStatus = 1; }	
			$sql = "UPDATE hi_events set status = :status where id = :id ";
			try {
						$stm  = $MyPdodb->prepare($sql);      		
						$stm->bindParam(':status', $recStatus, PDO::PARAM_INT);		
						$stm->bindParam(':id', $recId, PDO::PARAM_INT);
						$stm->execute();       
						$msg=CommonModel::create()->getSettings('EVENT_STATUS_MSG');					
				}catch(PDOException $e){
						Logger::newMessage($e);
						logger::customErrorMsg();
				}
			return $msg;
		
    }
    
	// Remove a common page.
	public function delete($recId) {
       global $MyPdodb;		        
	    $sql = "Delete from hi_events where  id = :id ";
		try{
			$stm  = $MyPdodb->prepare($sql);      			
			$stm->bindParam(':id', $recId, PDO::PARAM_INT);
			$stm->execute();       		
			$msg=CommonModel::create()->getSettings('EVENT_DELETE_MSG');
			return $msg;			
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }
	
	
	
	// Update a common page row into the table and returns confirmation message
    public function editRecord($postvars,$filevars) {
       global $MyPdodb;
	    if($_SESSION['user_admin_login_id']!='' and $_SESSION["member_id"]==''){
	   		$updateby = $_SESSION['user_admin_login_id'];
			$updateby_type=1;
	   }else{
	   		$updateby = $_SESSION["member_id"];
			$updateby_type=2;
	   }
	 	$title =$postvars['title'];
		$description =$postvars['description'];
		$startdate =$postvars['startdate'];
		$enddate =$postvars['enddate'];
		$status =$postvars['status'];
		if($status==''){
			$status=0;
		}
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
		$id = $postvars['event_id'];	
		$simage = $filevars['simage'];
		$simage2 = $filevars['simage2'];
		$thumbFolder = UPLOADDIR_EVENTS;
		$validExtArr = explode(",",VALID_EXT_EVENTS);
		$recId = rand(1000,10000);
		$event_image_old = $postvars['event_image_old'];
		$event_image_old2 = $postvars['event_image_old2'];
		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;
				 $event_name = "";
			}else{	
				$event_name = "event_".$recId.".".$file[count($file)-1];
				$new_file = $thumbFolder."/".$event_name;		
				$copied = copy($filevars['simage']['tmp_name'], $new_file);
				@unlink($thumbFolder."/".$event_image_old);
			}
	   }else{
		   $event_name=$event_image_old;
	   }
	   $recId = rand(1000,10000);
	   if(!empty($filevars['simage2']['name'])){
		   $file = explode('.',basename($filevars['simage2']['name']));
		   $ext = ".".$file[count($file)-1];
			if(!in_array($ext,$validExtArr))
			{
			 	 $parentMsg=INVALID_PHOTO_MSG;
				 $event_name2 = "";
			}else{	
				$event_name2 = "update_".$recId.".".$file[count($file)-1];
				$new_file = $thumbFolder."/".$event_name2;		
				$copied = copy($filevars['simage2']['tmp_name'], $new_file);
				@unlink($thumbFolder."/".$event_image_old2);
			}
	   }else{
		   $event_name2=$event_image_old2;
	   }
		$sql = "UPDATE hi_events SET ";
	   	$sql .= " title = :title, ";
		$sql .= " description = :description, ";
		$sql .= " startdate = :startdate, ";
		$sql .= " enddate = :enddate, ";
		$sql .= " updateby = :updateby, ";
		$sql .= " updateby_type = :updateby_type, ";
		$sql .= " simage = :simage, ";
		$sql .= " simage2 = :simage2, ";
		$sql .= " status = :status ";
		$sql .= " Where id= :id";
		
		try{
			$stm  = $MyPdodb->prepare($sql);				
			$stm->bindParam(":title", $title, PDO::PARAM_STR);
			$stm->bindParam(":description", $description, PDO::PARAM_STR);
			$stm->bindParam(":startdate", $startdate, PDO::PARAM_STR);
			$stm->bindParam(":enddate", $enddate, PDO::PARAM_STR);
			$stm->bindParam(":updateby", $updateby, PDO::PARAM_STR);
			$stm->bindParam(":updateby_type", $updateby_type, PDO::PARAM_STR);
			$stm->bindParam(":simage", $event_name, PDO::PARAM_STR);
			$stm->bindParam(":simage2", $event_name2, PDO::PARAM_STR);	
			$stm->bindParam(":status", $status, PDO::PARAM_STR);
			$stm->bindParam(":id", $id, PDO::PARAM_INT);		
			if($stm->execute()){
				
						
				$msg =CommonModel::create()->getSettings('EVENT_EDIT_MSG');
			}else{
				$msg =CommonModel::create()->getSettings('EVENT_EDIT_ERROR_MSG');
			}			
			
			return $msg;
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }
	public function insertRecord($postvars,$filevars){
		global $MyPdodb;
		if($_SESSION['user_admin_login_id']!='' and $_SESSION["member_id"]==''){
			$updateby = $_SESSION['user_admin_login_id'];
			$updateby_type=1;
		}else{
			$updateby = $_SESSION["member_id"];
			$updateby_type=2;
		}
		$title =$postvars['title'];
		$description =$postvars['description'];
		$startdate =$postvars['startdate'];
		$enddate =$postvars['enddate'];
		$status =$postvars['status'];
		if($status==''){
			$status=0;
		}
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
		$simage = $filevars['simage'];
		$simage2 = $filevars['simage2'];
		$thumbFolder = UPLOADDIR_EVENTS;
		$validExtArr = explode(",",VALID_EXT_EVENTS);
		$recId = rand(1000,10000);
		$extlink =$postvars['extlink'];
		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;
				 $event_name = "";
			}else{	
				$event_name = "event_".$recId.".".$file[count($file)-1];
				$new_file = $thumbFolder."/".$event_name;		
				$copied = copy($filevars['simage']['tmp_name'], $new_file);
			}
	   }else{
		   $event_name="";
	   }
	   $recId = rand(1000,10000);
		if(!empty($filevars['simage2']['name'])){
		   $file = explode('.',basename($filevars['simage2']['name']));
		   $ext = ".".$file[count($file)-1];
			if(!in_array($ext,$validExtArr))
			{
			 	 $parentMsg=INVALID_PHOTO_MSG;
				 $event_name2 = "";
			}else{	
				$event_name2 = "event_".$recId.".".$file[count($file)-1];
				$new_file = $thumbFolder."/".$event_name2;		
				$copied = copy($filevars['simage2']['tmp_name'], $new_file);
			}
	   }else{
		   $event_name2="";
	   }
		
		$sql = "insert into hi_events (title, description, startdate, enddate, updateby, updateby_type, status, simage, simage2, extlink) values (?,?,?,?,?,?,?,?,?,?)";
		try{
			$stm  = $MyPdodb->prepare($sql);
					
			$stm->bindParam(1, $title, PDO::PARAM_STR);
			$stm->bindParam(2, $description, PDO::PARAM_STR);
			$stm->bindParam(3, $startdate, PDO::PARAM_STR);
			$stm->bindParam(4, $enddate, PDO::PARAM_STR);
			$stm->bindParam(5, $updateby, PDO::PARAM_STR);
			$stm->bindParam(6, $updateby_type, PDO::PARAM_STR);
			$stm->bindParam(7, $status, PDO::PARAM_INT);
			$stm->bindParam(8, $event_name, PDO::PARAM_STR);
			$stm->bindParam(9, $event_name2, PDO::PARAM_STR);
			$stm->bindParam(10, $extlink, PDO::PARAM_STR);
			
				if($stm->execute()){
					$msg =CommonModel::create()->getSettings('EVENT_INSERT_MSG');
				}else{
					$msg =CommonModel::create()->getSettings('EVENT_INSERT_ERROR_MSG');
				}	
				return $msg;
		}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
		}
		
	}
	public function checkUserEmail($emailAddress,$recId=0){
		global $MyPdodb;	
		 	
		 if(!empty($recId)){		
			 $idSql=" and user_id != :id";
		 }else{
			 $idSql="";
		 }
		 $sql = "SELECT count(user_id) as cnt FROM hi_events where email_address= :email ".$idSql;   
		 try{
				 $stm  = $MyPdodb->prepare($sql);      		  
				 $stm->bindParam(':email', $emailAddress, PDO::PARAM_STR);
				 if(!empty($recId)){
					 $stm->bindParam(':id', $recId, PDO::PARAM_STR);
				 }
				$stm->execute();
				$results = $stm->fetchAll(PDO::FETCH_CLASS);		
				$totalCounts = $results[0];		
				$totalCounts->cnt;
				 if($totalCounts->cnt > 0){
					 return false;
				 }else{
				 	return true;
				 }
			}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
			}
	}	
	public function checkEvent($name,$recId=0){
		global $MyPdodb;	
		 	
		 if(!empty($recId)){		
			 $idSql=" and id != :id";
		 }else{
			 $idSql="";
		 }
		 $sql = "SELECT count(id) as cnt FROM hi_events where title= :name".$idSql;   
		 try{
				 $stm  = $MyPdodb->prepare($sql);      		  
				 $stm->bindParam(':name', $name, PDO::PARAM_STR);
				 if(!empty($recId)){
				
					 $stm->bindParam(':id', $recId, PDO::PARAM_STR);
				 }
				$stm->execute();
				$results = $stm->fetchAll(PDO::FETCH_CLASS);
				$totalCounts = $results[0];		
				$totalCounts->cnt;
				 if($totalCounts->cnt > 0){
					 return false;
				 }else{
				 		
					 return true;
				 }
						
			}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
			}
	}		
	public function getEvents(){
		global $MyPdodb;		   
		$sql = "SELECT * FROM hi_events where status = 1 and enddate >= CURDATE() order by startdate desc limit 5";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
			
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);
			$i=0;
			foreach($results as $result){
				//print_r($result);
				if($result->updateby_type==2){
					$sql = "select fullname as member from hi_members where id='".$result->updateby."'";
					try{
						$MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
						$res = $MyPdodb->queryFirst($sql);
						$member = $res->member;
						//array_push($arrres,$totalsubsec);
						$results[$i]->member = $member;
					}catch(PDOException $e){
						Logger::newMessage($e);
						logger::customErrorMsg();
					}
				}else{
					$results[$i]->member = "Administrator";
					$results[$i]->photo = $_SESSION['adminphoto'];
				}
				$i++;
			}	
			return $results;				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}	
	public function selectEventDetail($id){
		global $MyPdodb;		   
		$sql = "SELECT * FROM hi_events where id = :id";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
			 $stm->bindParam(':id', $id, PDO::PARAM_INT);
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			if($results[0]->updateby_type==2){
					$sql = "select fullname as member,simage as photo from hi_members where id='".$results[0]->updateby."'";
					try{
						$MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
						$res = $MyPdodb->queryFirst($sql);
						$member = $res->member;
						$photo = $res->photo;
						//array_push($arrres,$totalsubsec);
						$results[0]->member = $member;
						$results[0]->photo = $photo;
					}catch(PDOException $e){
						Logger::newMessage($e);
						logger::customErrorMsg();
					}
				}else{
					$results[0]->member = "Administrator";
					$results[0]->photo = $_SESSION['adminphoto'];
				}
			return $results[0];				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}	
}
?>