<?php
namespace guestbook;

class FGuestBook {

  const iLimit = 10;

  public function addEntry( $signature, $text )
  {
    global $db;

    $query = $db -> prepare( 'INSERT INTO pp_guest_book ( signature , text , date) VALUES ( :signature , :text , :date )' );
    $query -> bindValue( ':signature',  $signature,         \PDO::PARAM_STR );
    $query -> bindValue( ':text',       $text,              \PDO::PARAM_STR );
    $query -> bindValue( ':date',       \System::getDate(), \PDO::PARAM_STR );
    $query -> execute();
    $query -> closeCursor();
  }

  public function getLimit()
  {
    return self::iLimit;
  }

  public function getEntries( $from , $to )
  {
    global $db , $cache , $config;

    $key = "FGuestBook:getEntries:$from:$to";

    if ( !$entries = $cache -> fetch ( $key ) )
    {
			$query = $db -> prepare( 'SELECT signature, text, date FROM pp_guest_book ORDER BY date DESC LIMIT ' . $from . ',' . $to );
			$query -> execute();
			if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
			{
				$entry['signature']	= $row['signature'];
				$entry['text']      = nl2br( $row['text'] );
				$entry['date']      = date( "d/m/Y H:i", strtotime( $row['date'] ) );
				$entries[]          = $entry;
			}
      $cache -> store( $key, $entries, $config['cache_expire_short'] );
    }
    
    return $entries;
  }

  public function getCountEntries()
  {
    global $db, $cache, $config;

    $key = 'FGuestBook:getCountEntries';

    if ( !$count = $cache -> fetch( $key ) )
    {
      $query = $db -> prepare( 'SELECT COUNT(1) FROM pp_guest_book' );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $count 	= $row[0];
      $query -> closeCursor();
      
      $cache -> store( $key, $count, $config['cache_expire_short'] );
    }
    
    return $count;
  }
}
?>
