<?php

	lt_include( PLOG_CLASS_PATH."plugins/ads/class/dao/adblock.class.php" );
	lt_include( PLOG_CLASS_PATH."class/dao/model.class.php" );

	/**
	 * cache id for this data
	 */
	define( "CACHE_AD_BLOCKS", "adblocks" );

	/**
	 * Model class that handles the ad_blocks table, where all the different ad blocks
	 * are stored.
	 */
	class AdBlocks extends Model
	{
		function AdBlocks()
		{
			$this->Model();
			
			$this->table = $this->getPrefix()."ad_blocks";
			$this->pk    = "id";
		}
		
		function updateAdBlocks( $blocks )
		{
			$this->deleteAll();
			$this->insertAdBlocks( $blocks );
		}
		
		function addAdBlock( &$block)
		{
			if( ($res = $this->add( $block ))) {
				$this->_cache->removeData( "_all_", CACHE_AD_BLOCKS );
			}
			
			return( $res );
		}
		
		function getAdBlock( $blockId )
		{
	        $query = "SELECT * FROM ".$this->table." WHERE id = '".Db::qstr( $blockId )."'";
        	$result = $this->Execute( $query );
        	
        	if( !$result )
        		return false;
        	
        	if( $result->RowCount() == 0 ){
                $result->Close();
        		return false;
            }
        		
        	$row = $result->FetchRow();
            $result->Close();

        	return( $this->mapRow( $row ));
		}
		
		function deleteAdBlock( $blockId )
		{
			if( ($result = $this->delete( "id", $blockId ))) {
				$this->_cache->removeData( "_all_", CACHE_AD_BLOCKS );
			}
			
			return( $result );
		}
		
		function updateAdBlock( &$block )
		{
			if(($result = $this->update( $block ))) {
				$this->_cache->removeData( "_all_", CACHE_AD_BLOCKS );
			}
			
			return( $result );
		}
		
		function insertAdBlocks( $blocks )
		{
			foreach( $blocks as $block )
				$this->add( $block );
				
			return( true );
		}
		
		function getAdBlocks()
		{
			$blocks = $this->getAll( "",  // key
			                         CACHE_AD_BLOCKS  // cache id
			                        );
			if( !$blocks )
				$blocks = Array();
				
			return( $blocks );
		}
		
		function deleteAll()
		{
			$query = "DELETE FROM ".$this->getPrefix()."ad_blocks";
			if( $this->Execute( $query )) {
				$this->_cache->removeData( "_all_", CACHE_AD_BLOCKS );
			}
			
			return( true );			
		}
		
		/**
		 * @private
		 */
		function mapRow( $row )
		{			
			$block = new AdBlock();
			$block->setId( $row["id"] );
			$block->setCode( $row["block_code"] );
			$block->setPosition( $row["block_position"] );
			$block->setName( $row["block_name"] );
			$block->setBlogs( unserialize( $row["block_blogs"] ));
			$block->setMode( $row["block_mode"] );
			
			return( $block );				 
		}
	}

?>