<?php
namespace admin\factory;

class Adverts {

  public function getAcitveAdvert()
  {
    global $db, $config, $cache;
    
    $key = 'getAcitveAdvert';
    
    if ( !$advert = $cache -> fetch( $key ) )
    {    
      $query = $db -> query( 'SELECT * FROM pcms_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 function delete( $id )
  {
    global $db, $lang;
    
    $query = $db -> prepare( 'SELECT img FROM pcms_adverts WHERE id = :id' );
    $query -> bindValue( ':id' , $id , \PDO::PARAM_INT );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      if ( file_exists( '../' . $row['img'] ) )
        unlink( '../' . $row['img'] );
    }
    $query -> closeCursor();
    
    $query = $db -> prepare( 'DELETE FROM pcms_adverts WHERE id = :id' );
    $query -> bindValue( ':id' , $id , \PDO::PARAM_INT );
    $query -> execute();
    $query -> closeCursor();    

    \System::setAlert( $lang -> getTrans( 'T_USUNIETO_REKLAME' ) );
    \System::deleteCacheAdmin();
    \System::deleteCache();
  }
}
?>
