<?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 GalleriesModel extends ModelBase {
    private static $GalleriesModel = 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::$GalleriesModel) {
           self::$GalleriesModel = new GalleriesModel();
        }
        return self::$GalleriesModel;
    }
    
    // Retrieves a common page row by its id    
    public function selectPagesByPageId($pageId) {
		
		global $MyPdodb;		        
		$pageId = (int) $pageId;
		$sql = "SELECT * FROM hi_photos 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();
		}

    }
	public function selectPagesByPageId_cat($pageId) {
		
		global $MyPdodb;		        
		$pageId = (int) $pageId;
		$sql = "SELECT * FROM hi_gallery 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_photos 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,$gallerycat_id) {
		
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		$sql = "SELECT * FROM hi_photos where gal_id=?";  
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->execute(array($gallerycat_id));
			$results = $stm->fetchAll(PDO::FETCH_CLASS);
			
			return $results ;		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		
    }
	
	public function selectPages_cat($start=0,$limit) {
		
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		$sql = "SELECT * FROM hi_gallery";  
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);
			$i=0;
			foreach($results as $result){
				//print_r($result);
				$sql = "select count(id) as cnt from hi_photos where gal_id='".$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]->subsec_count = $totalsubsec;
				}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
				}
				
				$i++;
			}
			return $results ;		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		
    }
	
	public function selectGalleries($postvars) {
		
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		$sql_count = "SELECT count(id) as cnt FROM hi_gallery where status=1  ";
	    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;	
		$sql = "SELECT * FROM hi_gallery where status=1 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);
				$sql = "select count(id) as cnt from hi_photos where gal_id='".$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]->subsec_count = $totalsubsec;
				}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
				}
				
				$i++;
			}
			return $results ;		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		
    }
	public function selectPhotos($postvars) {
		
		global $MyPdodb;
		$id = $postvars['gallery_id'];
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		$sql_count = "SELECT count(id) as cnt FROM hi_photos where gal_id=$id  ";
	    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;	
		 $sql = "SELECT a.*, b.gallerytitle, b.description FROM hi_photos a, hi_gallery b where a.gal_id=$id and a.gal_id=b.id LIMIT ?, ?";  
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$BindArr[] =(int) $postvars["eu"];
			$BindArr[] =(int) $postvars["limit"];	
			$stm->execute($BindArr);
			$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($gallerycat_id) {
       global $MyPdodb;
       $sql = "SELECT count(id) as cnt FROM hi_photos where gal_id=$gallerycat_id";        	       	  
	   $MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	   return $MyPdodb->queryFirst($sql);	   	  
    }
	public function selectCount_cat() {
       global $MyPdodb;
       $sql = "SELECT count(id) as cnt FROM hi_gallery";        	       	  
	   $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_photos 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_photos 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["download_id"];
		   $recStatus = $postvars["recStatus"];	   
		   if($recStatus == 1) { $recStatus=0; } else { $recStatus = 1; }	
			$sql = "UPDATE hi_photos 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('GALLERY_STATUS_MSG');					
				}catch(PDOException $e){
						Logger::newMessage($e);
						logger::customErrorMsg();
				}
			return $msg;
		
    }
	public function changeStatus_cat($postvars) {
        global $MyPdodb;
		   $recId = $postvars["gallery_id"];
		   $recStatus = $postvars["recStatus"];	   
		   if($recStatus == 1) { $recStatus=0; } else { $recStatus = 1; }	
			$sql = "UPDATE hi_gallery 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('GALLERY_STATUS_MSG');					
				}catch(PDOException $e){
						Logger::newMessage($e);
						logger::customErrorMsg();
				}
			return $msg;
		
    }
    
	// Remove a common page.
	public function delete($postvars) {
       global $MyPdodb;	
	   $Imgid = $postvars['ImgId'];
	   $Imgname = $postvars['Imgname'];    
	   $thumbFolder = UPLOADDIR_GALLERY;   
	    $sql = "Delete from hi_photos where  id = :id ";
		try{
			$stm  = $MyPdodb->prepare($sql);      			
			$stm->bindParam(':id', $Imgid, PDO::PARAM_INT);
			$stm->execute(); 
	  		@unlink($thumbFolder."/".$Imgname);     		
			$msg=CommonModel::create()->getSettings('GALLERY_DELETE_MSG');
			return $msg;			
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }
	
	public function deletegallery($recId) {
       global $MyPdodb;		        
	    $sql = "Delete from hi_gallery where  id = :id ";
		try{
			$stm  = $MyPdodb->prepare($sql);      			
			$stm->bindParam(':id', $recId, PDO::PARAM_INT);
			$stm->execute();       		
			$msg=CommonModel::create()->getSettings('GALLERY_DELETE_MSG');
			$sql = "Delete from hi_photos where  gal_id = :id ";
			try{
				$stm  = $MyPdodb->prepare($sql);      			
				$stm->bindParam(':id', $recId, PDO::PARAM_INT);
				$stm->execute();       		
				$msg=CommonModel::create()->getSettings('GALLERY_DELETE_MSG');
				return $msg;			
			}catch(PDOException $e){
				Logger::newMessage($e);
				logger::customErrorMsg();
			}
			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) {
       global $MyPdodb;
		  for($i=0;$i<count($_REQUEST['photoIds']);$i++){
			
				$sql = "UPDATE hi_photos SET ";
				$sql .= " title = :title, ";
				$sql .= " description = :description ";
				$sql .= " Where id= :id";
				
				try{
					$stm  = $MyPdodb->prepare($sql);				
					$stm->bindParam(":title", $_REQUEST['photoTitle'][$i], PDO::PARAM_STR);
					$stm->bindParam(":description", $_REQUEST['photoDesc'][$i], PDO::PARAM_STR);
					$stm->bindParam(":id", $_REQUEST['photoIds'][$i], PDO::PARAM_INT);		
					if($stm->execute()){
						
								
						$msg =CommonModel::create()->getSettings('GALLERY_EDIT_MSG');
					}else{
						$msg =CommonModel::create()->getSettings('GALLERY_EDIT_ERROR_MSG');
					}			
				}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
				}
					
			}
		return $msg;
    }
	public function editRecord_cat($postvars,$filevars) {
       global $MyPdodb;
	    $gallerytitle =$postvars['gallerytitle'];
		$description =$postvars['description'];
		$status =$postvars['status'];
		$simage = $filevars['simage'];
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
		$thumbFolder = UPLOADDIR_GALLERY;
		$validExtArr = explode(",",VALID_EXT_GALLERY);
		$recId = rand(1000,10000);
		$gallery_image_old = $postvars['gallery_image_old'];
	   
		 $id = $postvars['gallery_id'];
	   
		 if(!empty($filevars['simage']['name'])){
		 	$filerealname = basename($filevars['simage']['name']);
		   $file = explode('.',basename($filevars['simage']['name']));
		   $ext = ".".$file[count($file)-1];
			if(!in_array($ext,$validExtArr))
			{
			 	 $parentMsg=INVALID_PHOTO_MSG;
				 $gallery_name = "";
				 $filerealname = "";
			}else{	
				$gallery_name = "gallery_".$recId.".".$file[count($file)-1];
				$new_file = $thumbFolder."/".$gallery_name;		
				$copied = copy($filevars['simage']['tmp_name'], $new_file);
				@unlink($thumbFolder."/".$gallery_image_old);
			}
	   }else{
		   $gallery_name=$gallery_image_old;
		   $filerealname = $gallery_realname_old;
	   }
				
		
		$sql = "UPDATE hi_gallery SET ";
	   	$sql .= " gallerytitle = :title, ";
		$sql .= " description = :description, ";
		$sql .= " status = :status, ";
		$sql .= " simage = :simage ";
		$sql .= " Where id= :id";
		
		try{
			$stm  = $MyPdodb->prepare($sql);				
			$stm->bindParam(":title", $gallerytitle, PDO::PARAM_STR);
			$stm->bindParam(":description", $description, PDO::PARAM_STR);
			$stm->bindParam(":status", $status, PDO::PARAM_STR);
			$stm->bindParam(":simage", $gallery_name, PDO::PARAM_STR);
			$stm->bindParam(":id", $id, PDO::PARAM_INT);		
			if($stm->execute()){
				
						
				$msg =CommonModel::create()->getSettings('GALLERY_EDIT_MSG');
			}else{
				$msg =CommonModel::create()->getSettings('GALLERY_EDIT_ERROR_MSG');
			}			
			
			return $msg;
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }
	public function insertRecord($postvars){
		global $MyPdodb;
		$gal_id =$postvars['gallerycat_id'];
		$thumbFolder = UPLOADDIR_GALLERY;
		$validExtArr = explode(",",VALID_EXT_GALLERY);
		$recId = rand(1000,10000);
		for($i=1;$i<=($_POST["hdnLine"]);$i++)
		{	
			$maxid = md5(uniqid(rand(),1));
			
			if($_FILES["fileUpload".$i]["name"] != "")
			{
				$simage1 = "photo".$maxid.$_FILES["fileUpload".$i]["name"];
				
				$uploadfile = $thumbFolder."/".$simage1;	
				$desc = $_REQUEST['description'.$i];
				$title = $_REQUEST["title".$i];
				
				if(copy($_FILES["fileUpload".$i]["tmp_name"],$uploadfile))
				{
					$sql = "insert into hi_photos (gal_id, filename, description, title) values (?,?,?,?)";
					try{
						$stm  = $MyPdodb->prepare($sql);
								
						$stm->bindParam(1, $gal_id, PDO::PARAM_STR);
						$stm->bindParam(2, $simage1, PDO::PARAM_STR);
						$stm->bindParam(3, $desc, PDO::PARAM_STR);
						$stm->bindParam(4, $title, PDO::PARAM_STR);
						
						
							if($stm->execute()){
								$msg =CommonModel::create()->getSettings('GALLERY_INSERT_MSG');
							}else{
								$msg =CommonModel::create()->getSettings('GALLERY_INSERT_ERROR_MSG');
							}	
							
					}catch(PDOException $e){
								Logger::newMessage($e);
								logger::customErrorMsg();
					}
				}
			}
		}	
		return $msg;
	}
	public function insertRecord_cat($postvars,$filevars){
		global $MyPdodb;
		$gallerytitle =$postvars['gallerytitle'];
		$description =$postvars['description'];
		$status =$postvars['status'];
		$simage = $filevars['simage'];
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
		$thumbFolder = UPLOADDIR_GALLERY;
		$validExtArr = explode(",",VALID_EXT_GALLERY);
		$recId = rand(1000,10000);
		
		if(!empty($filevars['simage']['name'])){
			$filerealname = basename($filevars['simage']['name']);
		   $file = explode('.',basename($filevars['simage']['name']));
		   $ext = ".".$file[count($file)-1];
			if(!in_array($ext,$validExtArr))
			{
			 	 $parentMsg=INVALID_PHOTO_MSG;
				 $gallery_name = "";
				 $filerealname = "";
			}else{	
				$gallery_name = "gallery_".$recId.".".$file[count($file)-1];
				$new_file = $thumbFolder."/".$gallery_name;		
				$copied = copy($filevars['simage']['tmp_name'], $new_file);
			}
	   }else{
		   $gallery_name="";
		   $filerealname = "";
	   }
		
		$sql = "insert into hi_gallery (gallerytitle, description, simage, status) values (?,?,?,?)";
		try{
			$stm  = $MyPdodb->prepare($sql);
					
			$stm->bindParam(1, $gallerytitle, PDO::PARAM_STR);
			$stm->bindParam(2, $description, PDO::PARAM_STR);
			$stm->bindParam(3, $gallery_name, PDO::PARAM_STR);
			$stm->bindParam(4, $status, PDO::PARAM_INT);
			
				if($stm->execute()){
					$msg =CommonModel::create()->getSettings('GALLERY_INSERT_MSG');
				}else{
					$msg =CommonModel::create()->getSettings('GALLERY_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_photos 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 checkGallerycat($name,$recId=0){
		global $MyPdodb;	
		 	
		 if(!empty($recId)){		
			 $idSql=" and id != :id";
		 }else{
			 $idSql="";
		 }
		 $sql = "SELECT count(id) as cnt FROM hi_gallery where gallerytitle= :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 getGalleryCatName($subsecid) {
       global $MyPdodb;
       $sql = "SELECT gallerytitle FROM hi_gallery where id = $subsecid";        	       	  
	   $MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	   return $MyPdodb->queryFirst($sql);	   	  
    }
	public function getPhotos(){
		global $MyPdodb;		   
		$sql = "SELECT * FROM hi_photos order by rand() limit 8";		
		try{
			$stm  = $MyPdodb->prepare($sql);    
			
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);	
			return $results;				       
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}			
}
?>