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

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    public static function get($id)
    {
        $module_type = db::query()->select(self::TABLE)
                          ->where('id', $id)
                          ->execute()->fetch();
        
        if ($module_type) {
            $module_type['data'] = json_decode($module_type['data'], false);
        }
        
        return $module_type;
    }
    
    public static function get_list()
    {
        $module_type = array();
        
        foreach (db::query()->select(self::TABLE . ' mt')->execute() as $m) {
            $m['data'] = json_decode($m['data'], false);
            $module_type[] = $m;
        }
        
        return $module_type;
    }
    
    public static function add(array $data)
    {
        if (array_key_exists('data', $data)) {
            if (!is_object($data['data']) && !is_array($data['data'])) {
                throw new Exception('Data is not valid.');
            }
        } else {
            $data['data'] = new stdClass();
        }
        
        $data['data'] = json_encode($data['data'], false);
        
        db::query()->insert(self::TABLE)
                   ->column($data)
                   ->execute();
        
        $id = db::get()->get_last_id();
        return $id;
    }
    
    public static function edit($id, array $data)
    {
        if (array_key_exists('data', $data)) {
            if (!is_object($data['data']) && !is_array($data['data'])) {
                throw new Exception('Data is not valid.');
            }
        } else {
            $data['data'] = new stdClass();
        }
        
        $data['data'] = json_encode($data['data'], false);
        
        db::query()->update(self::TABLE)
                   ->column($data)
                   ->where('id', $id)
                   ->limit(1)
                   ->execute();
    }
    
    public static function delete($id)
    {
        db::query()->delete(self::TABLE)
                   ->where('id', $id)
                   ->limit(1)
                   ->execute();
    }
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
}
