<?php
class setting
{
    const TABLE = 'setting';
    
    ////////////////////////////////////////////////////////////////////////////
    // Construct and destruct functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Overload functions.

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    public static function get_list($type = null)
    {
        $query = db::query()->select(self::TABLE);
        
        if ($type !== null)
        {
            $query->where('type', $type);
        }
        
        return $query->execute();
    }
    
    public static function get_type()
    {
        $query = db::query()->select(self::TABLE)
                            ->column('type')
                            ->distinct()
                            ->order('type');
        
        return $query->execute();
    }
    
    public static function get($name, $type)
    {
        $row = db::query()->select(self::TABLE)
                          ->where('name', $name)
                          ->where('type', $type)
                          ->limit(1)
                          ->execute()->fetch();
        
        if ($row) {
            $row['parameters'] = json_decode($row['parameters'], true);
        }
        
        return $row;
    }
    
    public static function set($name, $type, $value, $form = 'basic', array $parameters = array())
    {
        $result = db::query()->select(self::TABLE)
                             ->where('name', $name)
                             ->where('type', $type)
                             ->limit(1)
                             ->execute();
        
        $q = db::query();
        
        if (count($result))
        {
            $q->update(self::TABLE)
              ->where('name', $name)
              ->where('type', $type)
              ->limit(1);
        }
        else
        {
            $q->insert(self::TABLE)
              ->column('name', $name)
              ->column('type', $type)
              ->column('form', $form)
              ->column('parameters', json_encode((object) $parameters));
        }
        
        $q->column('value', $value)
          ->execute();
    }
    
    public static function delete_by_type($type)
    {
        db::query()->delete(self::TABLE)
                   ->where('type', $type)
                   ->execute();
    }
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
}
