<?php
/*********************************************
Desciption: Database Grids
File: /management/includes/classe.bd.grelhas.php
Project: dShop
Developers: João Vieira (brevespot.com)
Start Date: 2007/04/19
*********************************************/

class DB_Grid
{
	var $connectDb;
	
	var $sqlStmt;
        
        var $recordsTotal;
        var $recordsPagesTotal;
        
        var $lngDefault = "pt";
        	
	var $pagingRecordsPerPage;
	var $pagingCurrentPage;
	var $pagingEnabled = True;
	
	var $navigationSee;
	var $navigationAdd;
	var $navigationChange;
	var $navigationDelete;
	var $navigationQueryString;
	
	var $featureDelete = True;
	var $featureAdd = True;
	var $featureChange = True;
	
	var $showNotAfter = 1000;
	var $showNotBefore = -1;
	var $showLikeTree = False;
		       
	var $designTableHeaderFields = array (
	       'title' => '', 
	       'width'  => ''
	       );
	
	var $designTableHighlight;
	       
	var $designTableHighlight2;
	var $designTableHighlight3;
	
	var $designTable = array (
	       'table' => '', 
	       'thead'  => '',
	       'tfoot' => '',
	       'tr' => '',
	       'trodd' => '',
	       'td' => '',
	       'th' => '',
	       'tbody' => '',
	       'highlight' => '',
	       'formselect' => '',
	       'forminput' => '',
	       'formtextarea' => '',
	       'formbutton' => '',	       
	       'tablextra' => ''
	       );
	
	var $dirImagens = '/bsk/media/img/';
	
	function DB_Grid ($connectDb) {
		$this->connectDb = $connectDb;
	}
	
	function sqlStmt ($sqlStmt) {
		$this->sqlStmt = $sqlStmt;
	}
	
        function navigationSee ($navigationSee) {
		$this->navigationSee = $navigationSee;
	}	
        
        function navigationAdd ($navigationAdd) {
		$this->navigationAdd = $navigationAdd;
	}	
        
        function navigationChange ($navigationChange) {
		$this->navigationChange = $navigationChange;
	}	
        
        function navigationDelete ($navigationDelete) {
		$this->navigationDelete = $navigationDelete;
	}	
	
        function navigationQueryString ($navigationBrowse) {
		$this->navigationQueryString = $navigationBrowse;
	}	
	
	function pagingRecordsPerPage ($pagingRecordsPerPage) {
		$this->pagingRecordsPerPage = $pagingRecordsPerPage;
	}	
	
	function pagingCurrentPage ($pagingCurrentPage) {
		$this->pagingCurrentPage = $pagingCurrentPage;
	}	
	
	function pagingEnabled ($pagingEnabled) {
		$this->pagingEnabled = $pagingEnabled;
	}	
	
        function featureDelete ($featureDelete) {
		$this->featureDelete = $featureDelete;
	}
        
        function featureAdd ($featureAdd) {
		$this->featureAdd = $featureAdd;
	}
		
        function featureChange ($featureChange) {
		$this->featureChange = $featureChange;
	}
	
        function showNotAfter ($showNotAfter) {
		$this->showNotAfter = $showNotAfter;
	}	
	
        function showLikeTree ($showLikeTree) {
		$this->showLikeTree = $showLikeTree;
	}		
	
        function showNotBefore ($showNotBefore) {
		$this->showNotBefore = $showNotBefore;
	}	
	
	function processTree($id_parent = 0, $indent = 0) {
	    $tt = array();
	    $x = 0;
	    $loop = 0;
	    	
	    foreach($this->treeGetree as $n) {         
		if( $n['id_parent'] == $id_parent)
		{
		    $tt[$x++] = $loop;  
		}  
		$loop++;
	    }
	    if( $x != 0) {             
		foreach($tt as $d) {
		    $tmp = array();		    
		    foreach($this->treeGetree[$d] as $key => $value) {                
			$tmp[$key] = $value; 		
		    }
		    $tmp['indent'] = $indent;
		    $this->treeRetree[] = $tmp;		    
		    $this->processTree($tmp['id'], $indent+1);
		}
	    }
	    else {
		return;
	    }
	}
	
	function MakeTree() {
	    $resultDb = $this->connectDb->pedido($this->sqlStmt);
	    $this->recordsTotal = $this->connectDb->registosNumero();
	    
	    while ($row = $resultDb->fetch(PDO::FETCH_NUM)) {
	        if ( !isset($row[3]) ) $row[3] = "";
		$this->treeGetree[]  = array(
		'id'        => $row[0],
		'id_parent' => $row[1],
		'title'     => $row[2],
		'state'     => $row[3]
		);
	    }
	    $this->processTree(0, 0);
	    
	    $htmlOutBody = "";
	    $htmlOutHeader = "";
	    $htmlOutFooter = "";

            if ($this->recordsTotal) {
                $classCSSOdd = "class=\"" . $this->designTable['tr'] . "\"";
            
                $doingFirstTime = True;
            
                if ( !isset($this->designTableHighlight['css']) ) $this->designTableHighlight['css'] = "";
                if ( !isset($this->designTableHighlight['eq']) ) $this->designTableHighlight['eq'] = "";
                if ( !isset($this->designTableHighlight['field']) ) $this->designTableHighlight['field'] = "";
            
                $countLess = 1;
		foreach($this->treeRetree as $cat)
		{
		    if ($cat['id_parent'] == 0 ) {
#		    dbg(strlen($this->designTableHighlight['css']));
		        if ( strlen($this->designTableHighlight['css'])>2 && $cat['state'] == $this->designTableHighlight['eq'] ) {
		             $classCSSOdd = "class=\"" . $this->designTableHighlight['css'] . "\"";
			}elseif ($classCSSOdd == "class=\"" . $this->designTable['tr'] . "\"") {
			     $classCSSOdd = "class=\"" . $this->designTable['trodd'] . "\"";
			} else {
			     $classCSSOdd = "class=\"" . $this->designTable['tr'] . "\"";
			}
                    }
		
		
		    if ($doingFirstTime == True) {
			$htmlOutHeader .= "<table class=\"" . $this->designTable['table'] . "\">";
			$htmlOutHeader .= "
				    <thead class=\"" . $this->designTable['thead'] . "\">
					<tr>";
                        
                        if ($this->featureChange) $htmlOutHeader .= "<th>\n";
                        
                        if ($this->featureAdd) $htmlOutHeader .= "   <a href=\"" . $this->navigationAdd . "\"><img src=\"" . $this->dirImagens . "icon.criar.png\" border=\"0\"/></a>\n";
                        
                        if ($this->featureChange) $htmlOutHeader .= "</th>\n";

                        $htmlOutHeader .= "<th scope=\"col\">" . $this->designTableHeaderFields['title'][2]  . "</th>\n";
			
			 if ($this->featureDelete) $htmlOutHeader .= "<th scope=\"col\">&nbsp;</th>\n";
			
			$htmlOutHeader .= "		</tr>\n
				    </thead>\n	
				    <tbody class=\"" . $this->designTable['tbody'] . "\">\n";
			$doingFirstTime = False;
		    }
		
		    $indent = '';
		    
    		    $htmlOutBody .= "
			    <tr " . $classCSSOdd . ">\n";
                    
                    if ($this->featureChange) $htmlOutBody .= "
				<th class=\"" . $this->designTable['th'] . "\" width=\"20\" scope=\"row\" id=\"r" . $cat['id'] . "\"><a href=\"" . str_replace("[ID]", $cat['id'], $this->navigationChange) . "\"><img src=\"" . $this->dirImagens . "icon.alterar.png\" border=\"0\"/></a></th>\n";
                    
		    $fieldReturn = "";
		    for($i=0;$i<$cat['indent'];$i++) {                        
			$indent .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
		    }
		    
		    if ( stripos($cat['title'], "[pt]") !== false ) $cat['title'] = trd($cat['title'], $this->lngDefault);
		    
		    if ($cat['id_parent'] > 0 ) {
		          $fieldReturn .= $indent."&nbsp;|-".$cat['title'];
		    }else $fieldReturn = $cat['title'];
		    
		    
		    
		     $htmlOutBody .= "<td class=\"" . $this->designTable['td'] . "\" width=\"" . $this->designTableHeaderFields['width'][2] . "\">" . $fieldReturn . "</td>\n";
		    
		    if ( $this->featureDelete && $cat['id_parent'] > 0) $htmlOutBody .= "<td class=\"" . $this->designTable['td'] . "\" width=\"20\" align=\"right\"><a href=\"" . str_replace("[ID]", $cat['id'], $this->navigationDelete) . "\" onclick=\"javascript: if (confirm('Remove?')){return true;} else {return false;}\"><img src=\"" . $this->dirImagens . "icon.apagar.png\" border=\"0\"/></a></td>\n";
		    else $htmlOutBody .= "<td class=\"" . $this->designTable['td'] . "\" width=\"20\" align=\"right\">&nbsp;</td>\n";
		    
		    $htmlOutBody .="   </tr>\n";
		    

		} 
		 $htmlOutFooter = "
					</tbody>	
				</table>";
            }	    
	   print $htmlOutHeader . $htmlOutBody . $htmlOutFooter;
	}
	
	
	function Make() {
	   
            if ($this->showLikeTree) {
                $this->MakeTree();
                return;
            }	
	
	    $resultDb = $this->connectDb->pedido($this->sqlStmt);
	    $this->recordsTotal = $this->connectDb->registosNumero();
	    
	    $htmlOutBody = "";
	    $htmlOutHeader = "";
	    $htmlOutFooter = "";
	    
	    if ($this->recordsTotal) {
		$classCSSOdd = "class=\"" . $this->designTable['tr'] . "\"";
		
		$this->recordsPagesTotal = ceil($this->recordsTotal/$this->pagingRecordsPerPage);
	        if ( intval($this->pagingCurrentPage) == 0 || intval($this->pagingCurrentPage) > $this->recordsPagesTotal)
	           $this->pagingCurrentPage = 1;
		
		
		$doingFirstTime = True;
                
                $this->sqlStmt .= " LIMIT " . (($this->pagingCurrentPage-1)*$this->pagingRecordsPerPage) . ", " .$this->pagingRecordsPerPage;
                $resultDb = $this->connectDb->pedido($this->sqlStmt);
                if ( 
                    isset($this->designTableHighlight['field']) && isset($this->designTableHighlight['css']) && (isset($this->designTableHighlight['eq']) || isset($this->designTableHighlight['gt']) || isset($this->designTableHighlight['lt'])) ) $highlightToDo = True;
                else $highlightToDo = False;
                $countLess = 1;
		if ($highlightToDo) $countLess++;
    		
		while ($row = $resultDb->fetch(PDO::FETCH_NUM)) { 
		    
		    if ($doingFirstTime == True) {
			$htmlOutHeader .= "<table class=\"" . $this->designTable['table'] . "\">";
			$htmlOutHeader .= "
				    <thead class=\"" . $this->designTable['thead'] . "\">
					<tr>";
                        
                        if ($this->featureChange) $htmlOutHeader .= "<th>\n";
                        
                        if ($this->featureAdd) $htmlOutHeader .= "   <a href=\"" . $this->navigationAdd . "\">+Add</a>\n";
                        
                        if ($this->featureChange) $htmlOutHeader .= "</th>\n";

                        for($i=0; $i<$this->connectDb->camposNumero()-$countLess; $i++) {
                        	if ( $i+1 >= $this->showNotBefore && $i+1 <= $this->showNotAfter )
                            $htmlOutHeader .= "<th scope=\"col\">" . $this->designTableHeaderFields['title'][$i+1]  . "</th>\n";
						}
			
			 if ($this->featureDelete) $htmlOutHeader .= "<th scope=\"col\">&nbsp;</th>\n";
			
			$htmlOutHeader .= "		</tr>\n
				    </thead>\n	
				    <tbody class=\"" . $this->designTable['tbody'] . "\">\n";
			$doingFirstTime = False;
		    }
		    
		    if ($highlightToDo){	
                        if (isset($this->designTableHighlight['eq']))
                            if ($this->connectDb->campo($this->designTableHighlight['field']) == $this->designTableHighlight['eq']) {
                                $classCSSOdd = "class=\"" . $this->designTableHighlight['css'] . "\"";
                            }
                            
                        if (isset($this->designTableHighlight2['eq']))
                            if ($this->connectDb->campo($this->designTableHighlight2['field']) == $this->designTableHighlight2['eq']) {
                                $classCSSOdd = "class=\"" . $this->designTableHighlight2['css'] . "\"";
                            }
                        if (isset($this->designTableHighlight3['eq']))
                            if ($this->connectDb->campo($this->designTableHighlight3['field']) == $this->designTableHighlight3['eq']) {
                                $classCSSOdd = "class=\"" . $this->designTableHighlight3['css'] . "\"";
                            }
                                
		     }
		    
		    $htmlOutBody .= "
			    <tr " . $classCSSOdd . ">\n";
                    
                    if ($this->featureChange) $htmlOutBody .= "
				<th class=\"" . $this->designTable['th'] . "\" width=\"80\" scope=\"row\" id=\"r" . $this->connectDb->campo(0) . "\"><a href=\"" . str_replace("[ID]", $this->connectDb->campo(0), $this->navigationChange) . "\">Manage</a></th>\n";
                    
                    $fieldReturn = "";
                    for($i=1; $i<$this->connectDb->camposNumero(); $i++) {
                      
                        
                        if ($highlightToDo){
                            if ($this->designTableHighlight['field']==$i) break;
                        }
                       if ( $i >= $this->showNotBefore && $i <= $this->showNotAfter ) { 
                        if (!is_numeric($this->connectDb->campo($i)))
                            $fieldReturn = substr($this->connectDb->campo($i), 0, (int)($this->designTableHeaderFields['width'][$i]*0.14));
                        else
                            $fieldReturn = $this->connectDb->campo($i);
                       
                        $htmlOutBody .= "<td class=\"" . $this->designTable['td'] . "\" width=\"" . $this->designTableHeaderFields['width'][$i] . "\">" . $fieldReturn . "</td>\n";
                      }
                    }				
				
		    if ($this->featureDelete) $htmlOutBody .= "<td class=\"" . $this->designTable['td'] . "\" width=\"50\" align=\"right\"><a href=\"" . str_replace("[ID]", $this->connectDb->campo(0), $this->navigationDelete) . "\" onclick=\"javascript: if (confirm('Do you really want to delete this record?')){return true;} else {return false;}\">Delete</a></td>\n";
		    
		    $htmlOutBody .="   </tr>\n";
		    
		    if ($classCSSOdd == "class=\"" . $this->designTable['tr'] . "\"") {
		      $classCSSOdd = "class=\"" . $this->designTable['trodd'] . "\"";
		    } else {
		      $classCSSOdd = "class=\"" . $this->designTable['tr'] . "\"";
		    }
		    
		    
		}
	        if (!$doingFirstTime) {
		    $pagingPreviousPage = 0;
		    $pagingNextPage = 0;
		    if ($this->pagingCurrentPage > 1) {
			$pagingPreviousPage = $this->pagingCurrentPage - 1;
		    } 
		    else {
			$pagingPreviousPage = $this->pagingCurrentPage;	    
		    }
		    if ($this->pagingCurrentPage < $this->recordsPagesTotal) {
			$pagingNextPage = $this->pagingCurrentPage + 1;
		    } 
		    else {
			$pagingNextPage = $this->recordsPagesTotal;
		    }	    
		    if ($this->pagingEnabled) {
			$htmlOutFooter = "
					</tbody>	
					<tfoot class=\"" . $this->designTable['tfoot'] . "\">
					    <tr>
						<td scope=\"col\" colspan=\"" . ($i+1) . "\">
						    <div align=\"center\">
							<a href=\"" . str_replace("index.php", "", $_SERVER['SCRIPT_NAME']) . "?pagina=1&" . $this->navigationQueryString . "\">" . htmlentities("|<<") . "</a>   
							&nbsp;&nbsp;&nbsp;<a href=\"" . str_replace("index.php", "", $_SERVER['SCRIPT_NAME']) . "?pagina=" . $pagingPreviousPage . "&" . $this->navigationQueryString . "\">" . htmlentities("<<") . "</a>   
							&nbsp;&nbsp;&nbsp;" . $this->pagingCurrentPage . "/" . $this->recordsPagesTotal . "   
							&nbsp;&nbsp;&nbsp;<a href=\"" . str_replace("index.php", "", $_SERVER['SCRIPT_NAME']) . "?pagina=" . $pagingNextPage . "&" . $this->navigationQueryString . "\">" . htmlentities(">>") . "</a>   
							&nbsp;&nbsp;&nbsp;<a href=\"" . str_replace("index.php", "", $_SERVER['SCRIPT_NAME']) . "?pagina=" . $this->recordsPagesTotal . "&" . $this->navigationQueryString . "\">" . htmlentities(">>|") . "</a>  
							<br/><small>(" . $this->recordsTotal . " registos)</small>
						    </div>
						</td>
					    </tr>
					</tfoot>				    	
				</table>";
		    }else {
                        $htmlOutFooter = "
					</tbody>	
				</table>";		  
		  }
                }
	    } else {
		$htmlOutBody .= "<p><big><b>SEM RESULTADOS...</b></big></p>";
		$htmlOutFooter = "
				</tbody>	
			</table>";
	    }
            
            print $htmlOutHeader . $htmlOutBody . $htmlOutFooter;	    
	}
}

?>