<?php
namespace front\factory;

class Banners
{
  public static function banners()
  {
    global $mdb, $lang;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Banners::banners";

    $objectData = $cacheHandler->get($cacheKey);

    if ( !$objectData )
    {
      $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;
      }

      $cacheHandler -> set( $cacheKey, $banners );
    }
    else
    {
      return unserialize($objectData);
    }

    return $banners;
  }

  public static function main_banner()
  {
    global $mdb, $lang_id;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Banners::main_banner:$lang_id";

    $objectData = $cacheHandler -> get( $cacheKey );

    if ( !$objectData )
    {
      $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_id ] ] );

      $cacheHandler -> set( $cacheKey, $banner );
    }
    else
    {
      return unserialize( $objectData );
    }

    return $banner;
  }
}