<?php
namespace shop;

class Category implements \ArrayAccess
{
  public function __construct( int $category_id, $lang_id = null )
  {

  }

  static public function get_category_products_id( int $category_id )
  {
    global $mdb;
    return $mdb -> select( 'pp_shop_products_categories', 'product_id', [ 'category_id' => $category_id ] );
  }

  static public function get_category_name( int $category_id, $lang_id = null )
  {
    global $mdb;

    if ( !$lang_id )
      $lang_id = ( new \Domain\Languages\LanguagesRepository( $mdb ) )->defaultLanguage();

    return $mdb -> get( 'pp_shop_categories_langs', 'title', [ 'AND' => [ 'category_id' => $category_id, 'lang_id' => $lang_id ] ] );
  }

  public function __get( $variable )
  {
    if ( array_key_exists( $variable, $this -> data ) )
      return $this -> $variable;
  }

  public function __set( $variable, $value )
  {
    $this -> $variable = $value;
  }

  public function offsetExists( $offset )
  {
    return isset( $this -> $offset );
  }

  public function offsetGet( $offset )
  {
    return $this -> $offset;
  }

  public function offsetSet( $offset, $value )
  {
    $this -> $offset = $value;
  }

  public function offsetUnset( $offset )
  {
    unset( $this -> $offset );
  }

  static public function get_subcategory_by_category( int $category_id )
  {
    global $mdb;

    $cacheHandler = new \Shared\Cache\CacheHandler();
    $cacheKey = "\shop\Category::get_subcategory_by_category:$category_id";

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

    if ( !$objectData )
    {
      $shop_categories = $mdb -> select( 'pp_shop_categories', '*', ['parent_id' => $category_id] );
      $shop_categories_langs = array();
      foreach ($shop_categories as $shop_categorie) {
        array_push($shop_categories_langs, $mdb -> get( 'pp_shop_categories_langs', '*', ['category_id' => $shop_categorie['id']] ));
      }

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

    return $shop_categories_langs;
  }
}