<?php
namespace shop;

class ProductCustomField implements \ArrayAccess
{
  public function __construct( int $custom_field_id )
  {
    global $mdb;

    $result = $mdb -> get( 'pp_shop_products_custom_fields', '*', [ 'id_additional_field' => $custom_field_id ] );
    if ( \Shared\Helpers\Helpers::is_array_fix( $result ) ) foreach ( $result as $key => $val )
      $this -> $key = $val;
  }

  static public function getFromCache( int $custom_field_id )
  {
    // Check if Redis extension is loaded
    if ( class_exists( 'Redis' ) )
    {
      try
      {
        $redis = \Shared\Cache\RedisConnection::getInstance() -> getConnection();

        if ( $redis )
        {
          $objectData = $redis -> get( "shop\ProductCustomField:$custom_field_id" );

          if ( !$objectData )
          {
            $object = new self( $custom_field_id );
            $redis -> setex( "shop\ProductCustomField:$custom_field_id", 60 * 60 * 24, serialize( $object ) );
          }
          else
          {
            $object = unserialize( $objectData );
          }
        }
        else
        {
          // Log the error if needed
          $object = new self( $custom_field_id );
        }
      }
      catch ( \Exception $e )
      {
        // Log the exception if needed
        $object = new self( $custom_field_id );
      }
    }
    else
    {
      // Redis extension not loaded, create a new instance
      $object = new self( $custom_field_id );
    }

    return $object;
  }

  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);
  }
}