<?php
namespace front\factory;
class Layouts
{
  static public function category_default_layout()
  {
    global $mdb;
    return $mdb -> get( 'pp_layouts', 'id', [ 'categories_default' => 1 ] );
  }

  static public function product_layout( $product_id )
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Layouts::product_layout:$product_id";

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

    if ( !$objectData )
    {
      $layout = $mdb -> get( 'pp_layouts', [ '[><]pp_shop_products' => [ 'id' => 'layout_id' ] ], '*', [ 'pp_shop_products.id' => (int)$product_id ] );

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

    return $layout;
  }

  static public function article_layout( $article_id )
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Layouts::article_layout:$article_id";

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

    if ( !$objectData )
    {
      $layout = $mdb -> get( 'pp_layouts', [ '[><]pp_articles' => [ 'id' => 'layout_id' ] ], '*', [ 'pp_articles.id' => (int)$article_id ] );

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

    return $layout;
  }

  static public function category_layout( $category_id )
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Layouts::category_layout:$category_id";

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

    if ( !$objectData )
    {
      $layout = $mdb -> get( 'pp_layouts', '*', [ '[><]pp_layouts_categories' => [ 'id' => 'layout_id' ] ], [ 'category_id' => (int)$category_id ] );
      if ( !$layout )
        $layout = $mdb -> get( 'pp_layouts', '*', [ 'categories_default' => 1 ] );

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

    return $layout;
  }

  static public function active_layout( $page_id )
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Layouts::active_layout:$page_id";

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

    if ( !$objectData )
    {
      $layout = $mdb -> get( 'pp_layouts', [ '[><]pp_layouts_pages' => [ 'id' => 'layout_id' ] ], '*', [ 'page_id' => (int)$page_id ] );

      if ( !$layout )
        $layout = $mdb -> get( 'pp_layouts', '*', [ 'status' => 1 ] );

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

    return $layout;
  }
}
