<?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 DownloadsModel extends ModelBase {
    private static $DownloadsModel = 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::$DownloadsModel) {
           self::$DownloadsModel = new DownloadsModel();
        }
        return self::$DownloadsModel;
    }
    
    // Retrieves a common page row by its id    
    public function selectPagesByPageId($pageId) {
		
		global $MyPdodb;		        
		$pageId = (int) $pageId;
		$sql = "SELECT * FROM hi_downloads 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_downloadcat 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_downloads 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,$downcat_id) {
		
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		$sql = "SELECT * FROM hi_downloads where cat_id=?";  
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->execute(array($downcat_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_downloadcat";  
		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_downloads where cat_id='".$result->id."'";
				try{
					$MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	   				$res = $MyPdodb->queryFirst($sql);
					$totalpages = $res->cnt;
					//array_push($arrres,$totalsubsec);
					$results[$i]->down_count = $totalpages;
				}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
				}
				$i++;
			}
			return $results ;		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		
    }
	
	public function selectDownloadCats($postvars) {
		
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));	
		
		$sql_count = "SELECT count(id) as cnt FROM hi_downloadcat 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_downloadcat 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_downloads where cat_id='".$result->id."' and status=1";
				try{
					$MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	   				$res = $MyPdodb->queryFirst($sql);
					$totalpages = $res->cnt;
					//array_push($arrres,$totalsubsec);
					$results[$i]->down_count = $totalpages;
				}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
				}
				$i++;
			}
			return $results ;		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		
    }
	public function selectDownloads($postvars) {
		
		global $MyPdodb;
		$id=$postvars["download_id"];
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));	
		
		$sql_count = "SELECT count(id) as cnt FROM hi_downloads where status=1 and cat_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.catname FROM hi_downloads a, hi_downloadcat b where a.status=1 and a.cat_id=$id and a.cat_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($downcat_id) {
       global $MyPdodb;
       $sql = "SELECT count(id) as cnt FROM hi_downloads where cat_id=$downcat_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_downloadcat";        	       	  
	   $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_downloads 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_downloads 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_downloads 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('DOWNLOAD_STATUS_MSG');					
				}catch(PDOException $e){
						Logger::newMessage($e);
						logger::customErrorMsg();
				}
			return $msg;
		
    }
	public function changeStatus_cat($postvars) {
        global $MyPdodb;
		   $recId = $postvars["download_id"];
		   $recStatus = $postvars["recStatus"];	   
		   if($recStatus == 1) { $recStatus=0; } else { $recStatus = 1; }	
			$sql = "UPDATE hi_downloadcat 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('DOWNLOAD_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_downloads where  id = :id ";
		try{
			$stm  = $MyPdodb->prepare($sql);      			
			$stm->bindParam(':id', $recId, PDO::PARAM_INT);
			$stm->execute();       		
			$msg=CommonModel::create()->getSettings('DOWNLOAD_DELETE_MSG');
			return $msg;			
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }
	public function deletecat($recId) {
       global $MyPdodb;		        
	    $sql = "Delete from hi_downloadcat where  id = :id ";
		try{
			$stm  = $MyPdodb->prepare($sql);      			
			$stm->bindParam(':id', $recId, PDO::PARAM_INT);
			$stm->execute();       		
			$msg=CommonModel::create()->getSettings('DOWNLOAD_DELETE_MSG');
			$sql = "Delete from hi_downloads where  cat_id = :id ";
			try{
				$stm  = $MyPdodb->prepare($sql);      			
				$stm->bindParam(':id', $recId, PDO::PARAM_INT);
				$stm->execute();       		
				$msg=CommonModel::create()->getSettings('DOWNLOAD_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,$filevars) {
       global $MyPdodb;
	  $title =$postvars['title'];
		$description =$postvars['description'];
		$status =$postvars['status'];
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
		$simage = $filevars['simage'];
		$thumbFolder = UPLOADDIR_DOWNLOADS;
		$validExtArr = explode(",",VALID_EXT_DOWNLOADS);
		$recId = rand(1000,10000);
		$download_image_old = $postvars['download_image_old'];
		$download_realname_old = $postvars['download_realname_old'];
		
	   $id = $postvars['download_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;
				 $download_name = "";
				 $filerealname = "";
			}else{	
				$download_name = "download_".$recId.".".$file[count($file)-1];
				$new_file = $thumbFolder."/".$download_name;		
				$copied = copy($filevars['simage']['tmp_name'], $new_file);
				@unlink($thumbFolder."/".$download_image_old);
			}
	   }else{
		   $download_name=$download_image_old;
		   $filerealname = $download_realname_old;
	   }
				
		
		$sql = "UPDATE hi_downloads SET ";
	   	$sql .= " title = :title, ";
		$sql .= " filename = :filename, ";
		$sql .= " filerealname = :filerealname, ";
		$sql .= " status = :status, ";
		$sql .= " udate = :udate ";
		$sql .= " Where id= :id";
		
		try{
			$stm  = $MyPdodb->prepare($sql);				
			$stm->bindParam(":title", $title, PDO::PARAM_STR);
			$stm->bindParam(":filename", $download_name, PDO::PARAM_STR);
			$stm->bindParam(":filerealname", $filerealname, PDO::PARAM_STR);
			$stm->bindParam(":status", $status, PDO::PARAM_STR);
			$stm->bindParam(":udate", $udate, PDO::PARAM_STR);
			$stm->bindParam(":id", $id, PDO::PARAM_INT);		
			if($stm->execute()){
				
						
				$msg =CommonModel::create()->getSettings('DOWNLOAD_EDIT_MSG');
			}else{
				$msg =CommonModel::create()->getSettings('DOWNLOAD_EDIT_ERROR_MSG');
			}			
			
			return $msg;
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }
	public function editRecord_cat($postvars,$filevars) {
       global $MyPdodb;
	  $title =$postvars['title'];
		$status =$postvars['status'];
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
	   $id = $postvars['download_id'];
	   
		 
				
		
		$sql = "UPDATE hi_downloadcat SET ";
	   	$sql .= " catname = :title, ";
		$sql .= " status = :status, ";
		$sql .= " udate = :udate ";
		$sql .= " Where id= :id";
		
		try{
			$stm  = $MyPdodb->prepare($sql);				
			$stm->bindParam(":title", $title, PDO::PARAM_STR);
			$stm->bindParam(":status", $status, PDO::PARAM_STR);
			$stm->bindParam(":udate", $udate, PDO::PARAM_STR);
			$stm->bindParam(":id", $id, PDO::PARAM_INT);		
			if($stm->execute()){
				
						
				$msg =CommonModel::create()->getSettings('DOWNLOAD_EDIT_MSG');
			}else{
				$msg =CommonModel::create()->getSettings('DOWNLOAD_EDIT_ERROR_MSG');
			}			
			
			return $msg;
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }
	public function insertRecord($postvars,$filevars){
		global $MyPdodb;
		$title =$postvars['title'];
		$catid =$postvars['downcat_id'];
		$description =$postvars['description'];
		$status =$postvars['status'];
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
		$simage = $filevars['simage'];
		$thumbFolder = UPLOADDIR_DOWNLOADS;
		$validExtArr = explode(",",VALID_EXT_DOWNLOADS);
		$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;
				 $download_name = "";
				 $filerealname = "";
			}else{	
				$download_name = "download_".$recId.".".$file[count($file)-1];
				$new_file = $thumbFolder."/".$download_name;		
				$copied = copy($filevars['simage']['tmp_name'], $new_file);
			}
	   }else{
		   $download_name="";
		   $filerealname = "";
	   }
		
		$sql = "insert into hi_downloads (cat_id, title, filename, filerealname,  udate, status) values (?,?,?,?,?,?)";
		try{
			$stm  = $MyPdodb->prepare($sql);
					
			$stm->bindParam(1, $catid, PDO::PARAM_STR);
			$stm->bindParam(2, $title, PDO::PARAM_STR);
			$stm->bindParam(3, $download_name, PDO::PARAM_STR);
			$stm->bindParam(4, $filerealname, PDO::PARAM_STR);
			$stm->bindParam(5, $udate, PDO::PARAM_STR);
			$stm->bindParam(6, $status, PDO::PARAM_INT);
			
				if($stm->execute()){
					$msg =CommonModel::create()->getSettings('DOWNLOAD_INSERT_MSG');
				}else{
					$msg =CommonModel::create()->getSettings('DOWNLOAD_INSERT_ERROR_MSG');
				}	
				return $msg;
		}catch(PDOException $e){
					Logger::newMessage($e);
					logger::customErrorMsg();
		}
		
	}
	public function insertRecord_cat($postvars,$filevars){
		global $MyPdodb;
		$title =$postvars['title'];
		$status =$postvars['status'];
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
		
		
		
		$sql = "insert into hi_downloadcat (catname, udate, status) values (?,?,?)";
		try{
			$stm  = $MyPdodb->prepare($sql);
					
			$stm->bindParam(1, $title, PDO::PARAM_STR);
			$stm->bindParam(2, $udate, PDO::PARAM_STR);
			$stm->bindParam(3, $status, PDO::PARAM_INT);
			
				if($stm->execute()){
					$msg =CommonModel::create()->getSettings('DOWNLOAD_INSERT_MSG');
				}else{
					$msg =CommonModel::create()->getSettings('DOWNLOAD_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_downloads 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 checkDowncat($name,$recId=0){
		global $MyPdodb;	
		 	
		 if(!empty($recId)){		
			 $idSql=" and id != :id";
		 }else{
			 $idSql="";
		 }
		 $sql = "SELECT count(id) as cnt FROM hi_downloadcat where catname= :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 getDownCatName($subsecid) {
       global $MyPdodb;
       $sql = "SELECT catname FROM hi_downloadcat where id = $subsecid";        	       	  
	   $MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	   return $MyPdodb->queryFirst($sql);	   	  
    }		
}
?>