<?php
/*
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 PagesModel extends ModelBase {
    private static $pagesModel = 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::$pagesModel) {
           self::$pagesModel = new PagesModel();
        }
        return self::$pagesModel;
    }
    
    // Retrieves a common page row by its id    
    public function selectPagesByPageId($pageId) {
		
		global $MyPdodb;		        
		$pageId = (int) $pageId;
		$sql = "SELECT * FROM hi_pages 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_pages WHERE page_alias = :page_alias LIMIT 1";        		
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->bindParam(':page_alias', $pageName, PDO::PARAM_STR);
			$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 selectPagesByURL($pageUrl) {
		
		global $MyPdodb;		        		
		$sql = "SELECT * FROM hi_pages WHERE pagelink = :pagelink LIMIT 1";        		
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->bindParam(':pagelink', $pageUrl, 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,$section_id,$subsection_id) {
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		$sql = "SELECT * FROM hi_pages where secid=? and subsecid=?";  
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->execute(array($section_id,$subsection_id));
			$results = $stm->fetchAll(PDO::FETCH_CLASS);
			return $results ;		
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
		
    }
	
	public function selectPages_() {
		
		global $MyPdodb;
		$MyPdodb->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyPDOStatement'));		
		$sql = "SELECT * FROM hi_pages where status=1";  
		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($secid,$subsecid) {
       global $MyPdodb;
       $sql = "SELECT count(id) as cnt FROM hi_pages where secid=$secid and subsecid=$subsecid";        	       	  
	   $MyPdodb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
	   return $MyPdodb->queryFirst($sql);	   	  
    }
	
	// Change disaply Status
    public function changeStatus($postvars) {
        global $MyPdodb;
		   $recId = $postvars["page_id"];
		   $recStatus = $postvars["recStatus"];	   
		   if($recStatus == 1) { $recStatus=0; } else { $recStatus = 1; }	
			$sql = "UPDATE hi_pages 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('PAGE_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_pages where  id = :id ";
		try{
			$stm  = $MyPdodb->prepare($sql);      			
			$stm->bindParam(':id', $recId, PDO::PARAM_INT);
			$stm->execute();       		
			$msg=CommonModel::create()->getSettings('PAGE_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) {
       global $MyPdodb;
	    $name =$postvars['name'];
		$pagelink =$postvars['pagelink'];
		$description =$postvars['description'];
		$pagetitle_seo =$postvars['pagetitle_seo'];
		$keywords =$postvars['keywords'];
		$description_seo =$postvars['description_seo'];
		$order =$postvars['ord'];
		$status =$postvars['status'];
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
		
	   $id = $postvars['page_id'];
	   $subsecid = $postvars['subsection_id'];
	   $secid = $postvars['section_id'];
	   $alias = $postvars['name'];
		$alias = preg_replace("/(\s){2,}/",'$1',$alias);					
		$alias = str_replace('-', ' ', $alias);			
		$alias = preg_replace(array('/\s+/','/[^A-Za-z0-9\-]/'), array('-',''), $alias);			
		$page_alias = str_replace("--","-",trim(strtolower($alias)));
						$sql = "select count(id) as cnt_sec from hi_sections where page_alias=:page_alias";
						$stm  = $MyPdodb->prepare($sql);	
						$stm->bindParam(':page_alias', $page_alias, PDO::PARAM_STR);
						$stm->execute(); 
						$results = $stm->fetchAll(PDO::FETCH_CLASS);
						$cnt_sec = $results[0]->cnt_sec;
						
						$sql = "select count(id) as cnt_subsec from hi_subsections where page_alias=:page_alias";
						$stm  = $MyPdodb->prepare($sql);	
						$stm->bindParam(':page_alias', $page_alias, PDO::PARAM_STR);
						$stm->execute(); 
						$results = $stm->fetchAll(PDO::FETCH_CLASS);
						$cnt_subsec = $results[0]->cnt_subsec;
					   
						$sql = "select count(id) as cnt_page from hi_pages where page_alias=:page_alias and id!=:id";
						$stm  = $MyPdodb->prepare($sql);	
						$stm->bindParam(':page_alias', $page_alias, PDO::PARAM_STR);
						$stm->bindParam(':id', $id, PDO::PARAM_STR);
						$stm->execute(); 
						$results = $stm->fetchAll(PDO::FETCH_CLASS);
						$cnt_page = $results[0]->cnt_page;
						
						if($cnt_sec > 0 || $cnt_subsec > 0 || $cnt_page > 0){
						
							$msg = "Page Alias already exists, Please try different Title";						   
							return $msg;
						}else{	
							$sql = "Select ord from hi_pages where secid=:secid and subsecid=:subsecid and id=:id";
											try{
												$stm  = $MyPdodb->prepare($sql);    
												$stm->bindParam(':secid', $secid, PDO::PARAM_INT);
												$stm->bindParam(':subsecid', $subsecid, PDO::PARAM_INT);  	
												$stm->bindParam(':id', $id, PDO::PARAM_INT);
												$stm->execute();
												$results = $stm->fetchAll(PDO::FETCH_CLASS);
												$old_disp_ord = $results[0]->ord;
												if($order > $old_disp_ord)								
														{
															$sql = "Update hi_pages SET ord =ord - 1 where secid=$secid and subsecid=$subsecid and ord >'$old_disp_ord' and ord <= '$order'";
															//$sql = "Update tbl_section SET ord =$old_disp_ord where  ord = '$ord'";
															$stm  = $MyPdodb->prepare($sql);      		
															$stm->execute();  
														}
													else if($order < $old_disp_ord)								
														{
															$sql = "Update hi_pages SET ord =ord + 1 where secid=$secid and subsecid=$subsecid and ord < '$old_disp_ord' and ord >= '$order'";
															//$sql = "Update tbl_section SET ord =$old_disp_ord where  ord = '$ord'";
															$stm  = $MyPdodb->prepare($sql);      		
															$stm->execute();  
														}	
																
											}catch(PDOException $e){
												Logger::newMessage($e);
												logger::customErrorMsg();
											}
									
									$sql = "UPDATE hi_pages SET ";
									$sql .= " name = :name, ";
									$sql .= " pagelink = :pagelink, ";
									$sql .= " page_alias = :page_alias, ";
									$sql .= " description = :description, ";
									$sql .= " pagetitle_seo = :pagetitle_seo, ";
							        $sql .= " keywords = :keywords, ";
							        $sql .= " description_seo = :description_seo, ";
									$sql .= " ord = :order, ";
									$sql .= " status = :status, ";
									
									
									$sql .= " udate = :udate ";
									$sql .= " Where id= :id";
									
									try{
										$stm  = $MyPdodb->prepare($sql);				
										$stm->bindParam(":name", $name, PDO::PARAM_STR);
										$stm->bindParam(":pagelink", $pagelink, PDO::PARAM_STR);
										$stm->bindParam(":page_alias", $page_alias, PDO::PARAM_STR);
										$stm->bindParam(":description", $description, PDO::PARAM_STR);
										$stm->bindParam(":pagetitle_seo", $pagetitle_seo, PDO::PARAM_STR);
							        	$stm->bindParam(":keywords", $keywords, PDO::PARAM_STR);
								        $stm->bindParam(":description_seo", $description_seo, PDO::PARAM_STR);
										$stm->bindParam(":order", $order, 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('PAGE_EDIT_MSG');
										}else{
											$msg =CommonModel::create()->getSettings('PAGE_EDIT_ERROR_MSG');
										}			
										
										return $msg;
									}catch(PDOException $e){
										Logger::newMessage($e);
										logger::customErrorMsg();
									}
						}
		
				
		
    }
	public function insertRecord($postvars){
		global $MyPdodb;
		$name =$postvars['name'];
		$pagelink =$postvars['pagelink'];
		$description =$postvars['description'];
		$pagetitle_seo =$postvars['pagetitle_seo'];
		$keywords =$postvars['keywords'];
		$description_seo =$postvars['description_seo'];
		$order =$postvars['ord'];
		$status =$postvars['status'];
		$tdate = date("Y-m-d");	   
	   	$udate = date("Y-m-d");
		$section_id = $postvars['section_id'];
		$subsection_id = $postvars['subsection_id'];
		$alias = $postvars['name'];
		$alias = preg_replace("/(\s){2,}/",'$1',$alias);					
		$alias = str_replace('-', ' ', $alias);			
		$alias = preg_replace(array('/\s+/','/[^A-Za-z0-9\-]/'), array('-',''), $alias);			
		$page_alias = str_replace("--","-",trim(strtolower($alias)));
						$sql = "select count(id) as cnt_sec from hi_sections where page_alias=:page_alias";
						$stm  = $MyPdodb->prepare($sql);	
						$stm->bindParam(':page_alias', $page_alias, PDO::PARAM_STR);
						$stm->execute(); 
						$results = $stm->fetchAll(PDO::FETCH_CLASS);
						$cnt_sec = $results[0]->cnt_sec;
						
						$sql = "select count(id) as cnt_subsec from hi_subsections where page_alias=:page_alias";
						$stm  = $MyPdodb->prepare($sql);	
						$stm->bindParam(':page_alias', $page_alias, PDO::PARAM_STR);
						$stm->execute(); 
						$results = $stm->fetchAll(PDO::FETCH_CLASS);
						$cnt_subsec = $results[0]->cnt_subsec;
					   
						$sql = "select count(id) as cnt_page from hi_pages where page_alias=:page_alias";
						$stm  = $MyPdodb->prepare($sql);	
						$stm->bindParam(':page_alias', $page_alias, PDO::PARAM_STR);
						$stm->execute(); 
						$results = $stm->fetchAll(PDO::FETCH_CLASS);
						$cnt_page = $results[0]->cnt_page;
						
						if($cnt_sec > 0 || $cnt_subsec > 0 || $cnt_page > 0){
						
							$msg = "Page Alias already exists, Please try different Title";						   
							return $msg;
						}else{	
							$sql = "insert into hi_pages (name, secid, subsecid, pagelink, page_alias, description, pagetitle_seo, keywords, description_seo, udate, tdate, ord, status) values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
							try{
								$stm  = $MyPdodb->prepare($sql);
										
								$stm->bindParam(1, $name, PDO::PARAM_STR);
								$stm->bindParam(2, $section_id, PDO::PARAM_INT);
								$stm->bindParam(3, $subsection_id, PDO::PARAM_INT);
								$stm->bindParam(4, $pagelink, PDO::PARAM_STR);
								$stm->bindParam(5, $page_alias, PDO::PARAM_STR);
								$stm->bindParam(6, $description, PDO::PARAM_STR);
								$stm->bindParam(7, $pagetitle_seo, PDO::PARAM_STR);
								$stm->bindParam(8, $keywords, PDO::PARAM_STR);
								$stm->bindParam(9, $description_seo, PDO::PARAM_STR);
								$stm->bindParam(10, $udate, PDO::PARAM_STR);
								$stm->bindParam(11, $tdate, PDO::PARAM_STR);
								$stm->bindParam(12, $order, PDO::PARAM_INT);
								$stm->bindParam(13, $status, PDO::PARAM_INT);
								
									if($stm->execute()){
										$msg =CommonModel::create()->getSettings('PAGE_INSERT_MSG');
									}else{
										$msg =CommonModel::create()->getSettings('PAGE_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_pages 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 checkPage($name,$secid,$subsecid,$recId=0){
		global $MyPdodb;	
		 	
		 if(!empty($recId)){		
			 $idSql=" and id != :id";
		 }else{
			 $idSql="";
		 }
		 $sql = "SELECT count(id) as cnt FROM hi_pages where name= :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 getMenuPages($secid,$subsecid) {
		
		global $MyPdodb;		        		
		$sql = "SELECT * FROM hi_pages WHERE status=1 and secid=$secid and subsecid=$subsecid order by ord ";        		
		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 getMenuPages_count($secid,$subsecid) {
		
		global $MyPdodb;		        		
		$sql = "SELECT  count(*) as cnt FROM hi_pages WHERE status=1 and secid=$secid and subsecid=$subsecid order by ord ";        		
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);			
			return $results[0];				
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
		
    }	
	public function contentseo_id($tbl,$pgalias){
		global $MyPdodb;		        		
		$sql = "SELECT  * FROM $tbl WHERE page_alias='".$pgalias."' ";        		
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);			
			return $results[0];				
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}
	public function contentseo_data($tbl,$id){
		global $MyPdodb;		        		
		$sql = "SELECT * FROM $tbl WHERE id='".$id."' ";        		
		try{
			$stm  = $MyPdodb->prepare($sql);      		
			$stm->execute();
			$results = $stm->fetchAll(PDO::FETCH_CLASS);			
			return $results[0];				
	    }catch(PDOException $e){
			Logger::newMessage($e);
			logger::customErrorMsg();
		}
	}
}
?>