<?php
namespace admin\factory;

class Adverts {

  public static function getAcitveAdvert()
  {
    global $db, $config, $cache;
    
    $key = 'getAcitveAdvert';
    
    if ( !$advert = $cache -> fetch( $key ) )
    {    
      $query = $db -> query( 'SELECT * FROM pp_adverts WHERE ( date_start <= "' . date( 'Y-m-d' ) . '" OR date_start = "0000-00-00" ) AND ( date_end >= "' . date( 'Y-m-d' ) . '" OR date_end = "0000-00-00" ) AND enabled = 1 LIMIT 1' );
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
        $advert = $row;
      $query -> closeCursor();
      
      $cache -> store( $key, $advert, $config['cache_expire'] );
    }    
    return $advert;
  }
  
  public static function deleteAdvert( $id )
  {
    global $db;
    
    try
    {
      $db -> beginTransaction();
      
      $query = $db -> prepare( 'SELECT image FROM pp_adverts WHERE id = :id' );
      $query -> bindValue( ':id' , $id , \PDO::PARAM_INT );
      $query -> execute();
      if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
      {
        if ( file_exists( '../' . $row['image'] ) )
          unlink( '../' . $row['image'] ); 

        $query2 = $db -> prepare( 'DELETE FROM pp_adverts WHERE id = :id' );
        $query2 -> bindValue( ':id' , $id , \PDO::PARAM_INT );
        $query2 -> execute();
        $query2 -> closeCursor();
      }
      $query -> closeCursor();
      
      $db -> commit();

      \System::deleteCacheAdmin();
      \System::deleteCache();
      return true;
    }
    catch ( \PDOException $ex )
    {
      $db -> rollBack();
      \System::setAlert( 'Błąd: ' . $ex -> getMessage() );
    }
    return false;
  }
}
?>
