<?php
namespace front\factory;

class Banners
{
  public static function banners()
  {
    global $mdb, $lang;
    
    if ( !$banners = \Cache::fetch( 'banners' ) )
    {
      $results = $mdb -> query( 'SELECT '
                                  . 'id, name '
                                . 'FROM '
                                  . 'pp_banners '
                                . 'WHERE '
                                    . 'status = 1 '
                                  . 'AND '
                                    . '( date_start <= \'' . date( 'Y-m-d' ) . '\' OR date_start IS NULL ) '
                                  . 'AND '
                                    . '( date_end >= \'' . date( 'Y-m-d' ) . '\' OR date_end IS NULL ) '
                                  . 'AND '
                                    . 'home_page = 0' ) -> fetchAll();
      if ( is_array( $results ) and !empty( $results ) ) foreach ( $results as $row )
      {
        $row['languages'] = $mdb -> get( 'pp_banners_langs', '*', [ 'AND' => [ 'id_banner' => (int)$row['id'], 'id_lang' => $lang[0] ] ] );
        $banners[] = $row;
      }
      \Cache::store( 'banners', $banners );
    }
    return $banners;
  }
  
  public static function main_banner()
  {
    global $mdb, $lang;
    
    if ( !$banner = \Cache::fetch( "main_banner:" . $lang[0] ) )
    {
      $banner = $mdb -> query( 'SELECT '
                                  . '* '
                                . 'FROM '
                                  . 'pp_banners '
                                . 'WHERE '
                                    . 'status = 1 '
                                  . 'AND '
                                    . '( date_start <= \'' . date( 'Y-m-d' ) . '\' OR date_start IS NULL ) '
                                  . 'AND '
                                    . '( date_end >= \'' . date( 'Y-m-d' ) . '\' OR date_end IS NULL ) '
                                  . 'AND '
                                    . 'home_page = 1 '
                                . 'ORDER BY '
                                  . 'date_end ASC '
                                . 'LIMIT 1' ) -> fetchAll();
      $banner = $banner[0];
      if ( $banner )
        $banner['languages'] = $mdb -> get( 'pp_banners_langs', '*', [ 'AND' => [ 'id_banner' => (int)$banner['id'], 'id_lang' => $lang[0] ] ] );
      
      \Cache::store( "main_banner:" . $lang[0], $banner );
    }
    return $banner;
  }
}