<?php

class ConfigRepository extends ModelRepository
{
  private static $_singletonInstance = null;

  public function __construct()
  {
    parent::__construct('Config');
  }


  /**
   * Returns an initiated ConfigRepository
   *
   * @return ConfigRepository
   */
  public static function getInstance()
  {
    if (self::$_singletonInstance === null)
    {
        self::$_singletonInstance = new ConfigRepository();
    }

    return self::$_singletonInstance;
  }


  /**
   * Cache all configs in APC
   *
   * @return array - Configuration
   */
  public function cacheAll()
  {
    // Query from the database
    $pdo = PDOMysqlConnection::getInstance();
    $stmt = $pdo->prepareAndExec('SELECT section, config_key, config_value, type FROM configuration ORDER BY section, config_key ASC');

    $config = [];

    while ($record = $stmt->fetch(PDO::FETCH_NUM))
    {
      if (!empty($record[0]))
      {
        if ($record[2] == 'json')
          $record[2] = json_decode($record[2]);
        else if ($record[2] == 'int')
          $record[2] = intval($record[2]);
        else if ($record[2] == 'bool')
          $record[2] = intval($record[2]) == 1 ? true : false;
      }
      $config[$record[0]][$record[1]] = $record[2];
    }

    // Attempt to pull the config from the memory cache
    if (apcu_enabled())
    {
      apcu_store('backend.config', $config);
    }

    return $config;
  }


  /**
   * Get all configs
   *
   * @param  int $id
   */
  public function getAll()
  {
    // Attempt to pull the config from the memory cache
    if (apcu_enabled() && apcu_exists('backend.config'))
    {
      $config = apcu_fetch('backend.config');
    }
    else
    {
      $config = $this->cacheAll();
    }

    return $config;
  }

}
