<?php
/*
Project Name: Jnannys
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 BannersModel extends ModelBase {
    private static $BannersModel = 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::$BannersModel) {
           self::$BannersModel = new BannersModel();
        }
        return self::$BannersModel;
    }
    
    // Retrieves a common page row by its id    
    public function selectPagesByPageId($pageId) {
		
		global $MyPdodb;		        
		$pageId = (int) $pageId;
		$sql = "SELECT * FROM hi_banners 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_banners 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();
		}
		
    }
	public function getBannerName($id) {
		
		global $MyPdodb;		        		
		$sql = "SELECT title FROM hi_banners WHERE id = :id LIMIT 1";        		
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->bindParam(':id', $id, 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,$btype) {
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		
		$sql = "SELECT * FROM hi_banners where bannertype_id = ? ";  
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->execute(array($btype));
			$results = $stm->fetchAll(PDO::FETCH_CLASS);
			$i=0;
			foreach($results as $result){
				//print_r($result);
				$sql = "select count(id) as cnt from hi_bannerclicks where bannerid='".$result->id."'";
				try{
					$MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	   				$res = $MyPdodb->queryFirst($sql);
					$totalsubsec = $res->cnt;
					//array_push($arrres,$totalsubsec);
					$results[$i]->clickcounts = $totalsubsec;
				}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
				}
				
				$i++;
			}
			return $results ;		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		
    }
	public function selectPages_bannersclick($start=0,$limit,$btype) {
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		
		$sql = "SELECT * FROM hi_bannerclicks where bannerid = ? order by id desc";  
		$_SESSION["sess_sql"] = "SELECT * FROM hi_bannerclicks where bannerid = ".$btype." order by id desc";
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->execute(array($btype));
			$results = $stm->fetchAll(PDO::FETCH_CLASS);
			
			return $results ;		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		
    }
	
	public function selectBanners() {
		
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		$sql = "SELECT * FROM hi_banners where user_type!=1";  
		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 getSBannerprop($btype) {
		
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		$sql = "SELECT * FROM hi_bannertype where id=$btype";  
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);
			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_banners";        	       	  
	   $MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	   return $MyPdodb->queryFirst($sql);	   	  
    }
	public function selectCount_bannersclick() {
       global $MyPdodb;
       $sql = "SELECT count(id) as cnt FROM hi_bannerclicks";        	       	  
	   $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_banners 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_banners 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["banner_id"];
		   $recStatus = $postvars["recStatus"];	   
		   if($recStatus == 1) { $recStatus=0; } else { $recStatus = 1; }	
			$sql = "UPDATE hi_banners 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('BANNER_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_banners where  id = :id ";
		try{
			$stm  = $MyPdodb->prepare($sql);      			
			$stm->bindParam(':id', $recId, PDO::PARAM_INT);
			$stm->execute();       		
			$msg=CommonModel::create()->getSettings('BANNER_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;
	$title =$postvars['title'];
		$btype =$postvars['btype'];
		$startdate =$postvars['startdate'];
		$enddate =$postvars['enddate'];
		$status =$postvars['status'];
		$surl =$postvars['surl'];
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
		$simage = $filevars['simage'];
		$thumbFolder = UPLOADDIR_BANNERS;
		$validExtArr = explode(",",VALID_EXT_BANNERS);
		$recId = rand(1000,10000);
		$id = $postvars['banner_id'];	
		$banner_image_old = $postvars['banner_image_old'];
		
		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;
				 $banner_name = "";
			}else{	
				$banner_name = "homebanner_".$recId.".".$file[count($file)-1];
				$new_file = $thumbFolder."/".$banner_name;		
				$copied = copy($filevars['simage']['tmp_name'], $new_file);
				@unlink($thumbFolder."/".$banner_image_old);
			}
	   }else{
		   $banner_name=$banner_image_old;
	   }
		
		$sql = "UPDATE hi_banners SET ";
	   	$sql .= " title = :title, ";
		$sql .= " startdate = :startdate, ";
		$sql .= " enddate = :enddate, ";
		$sql .= " updateby = :updateby, ";
		$sql .= " simage = :simage, ";
		$sql .= " surl = :surl, ";
		$sql .= " status = :status ";
		$sql .= " Where id= :id";
		
		try{
			$stm  = $MyPdodb->prepare($sql);				
			$stm->bindParam(":title", $title, PDO::PARAM_STR);
			$stm->bindParam(":startdate", $startdate, PDO::PARAM_STR);
			$stm->bindParam(":enddate", $enddate, PDO::PARAM_STR);
			$stm->bindParam(":updateby", $_SESSION['user_admin_login_id'], PDO::PARAM_STR);
			$stm->bindParam(":simage", $banner_name, PDO::PARAM_STR);
			$stm->bindParam(":surl", $surl, PDO::PARAM_STR);
			$stm->bindParam(":status", $status, PDO::PARAM_INT);
			$stm->bindParam(":id", $id, PDO::PARAM_INT);		
			if($stm->execute()){
				
						
				$msg =CommonModel::create()->getSettings('BANNER_EDIT_MSG');
			}else{
				$msg =CommonModel::create()->getSettings('BANNER_EDIT_ERROR_MSG');
			}			
			
			return $msg;
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }
	public function insertRecord($postvars,$filevars){
		global $MyPdodb;
		$title =$postvars['title'];
		$btype =$postvars['btype'];
		$startdate =$postvars['startdate'];
		$enddate =$postvars['enddate'];
		$status =$postvars['status'];
		$surl =$postvars['surl'];
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
		$simage = $filevars['simage'];
		$thumbFolder = UPLOADDIR_BANNERS;
		$validExtArr = explode(",",VALID_EXT_BANNERS);
		$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;
				 $banner_name = "";
			}else{	
				$banner_name = "banner_".$recId.".".$file[count($file)-1];
				$new_file = $thumbFolder."/".$banner_name;		
				$copied = copy($filevars['simage']['tmp_name'], $new_file);
			}
	   }else{
		   $banner_name="";
	   }
		
		$sql = "insert into hi_banners (title, bannertype_id, startdate, enddate, simage, updateby, status, surl) values (?,?,?,?,?,?,?,?)";
		try{
			$stm  = $MyPdodb->prepare($sql);
					
			$stm->bindParam(1, $title, PDO::PARAM_STR);
			$stm->bindParam(2, $btype, PDO::PARAM_INT);
			$stm->bindParam(3, $startdate, PDO::PARAM_STR);
			$stm->bindParam(4, $enddate, PDO::PARAM_STR);
			$stm->bindParam(5, $banner_name, PDO::PARAM_STR);
			$stm->bindParam(6, $_SESSION['user_admin_login_id'], PDO::PARAM_STR);
			$stm->bindParam(7, $status, PDO::PARAM_INT);
			$stm->bindParam(8, $surl, PDO::PARAM_STR);
			
				if($stm->execute()){
					$msg =CommonModel::create()->getSettings('BANNER_INSERT_MSG');
				}else{
					$msg =CommonModel::create()->getSettings('BANNER_INSERT_ERROR_MSG');
				}	
				return $msg;
		}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
		}
		
	}
	public function saveClicks($postvars){
		global $MyPdodb;
		$bannerid =$postvars['bannerid'];
		$ipaddr =$postvars['ipaddr'];
		$ttype =$postvars['ttype'];
		$WebUrl ="http://".$postvars['WebUrl'];
		
		$tdate = date("Y-m-d");	   
	   	$dt = date("Y-m-d h:i:s");
		
		
		$sql = "insert into hi_bannerclicks (bannerId, ipadd, weburl, tdate, dttime) values (?,?,?,?,?)";
		try{
			$stm  = $MyPdodb->prepare($sql);
					
			$stm->bindParam(1, $bannerid, PDO::PARAM_INT);
			$stm->bindParam(2, $ipaddr, PDO::PARAM_STR);
			$stm->bindParam(3, $WebUrl, PDO::PARAM_STR);
			$stm->bindParam(4, $tdate, PDO::PARAM_STR);
			$stm->bindParam(5, $dt, PDO::PARAM_STR);
			
			
				if($stm->execute()){
					$msg =true;
				}else{
					$msg =false;
				}	
				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_banners 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 checkBanner($name,$recId=0){
		global $MyPdodb;	
		 if(!empty($recId)){		
			 $idSql=" and id != :id";
		 }else{
			 $idSql="";
		 }
		 $sql = "SELECT count(id) as cnt FROM hi_banners 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();
			}
	}		
}
?>