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

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    public static function get($id)
    {
        $menu_item_type = db::query()->select(self::TABLE)
                          ->where('id', $id)
                          ->execute()->fetch();
        
        if ($menu_item_type) {
            $menu_item_type['data'] = json_decode($menu_item_type['data'], false);
        }
        
        return $menu_item_type;
    }
    
    public static function get_list()
    {
        $menu_item_type = array();
        
        foreach (db::query()->select(self::TABLE)->execute() as $mit) {
            $mit['data'] = json_decode($mit['data'], false);
            $menu_item_type[] = $mit;
        }
        
        return $menu_item_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)
                   ->execute();
        
        menu_item::delete_by_menu_item_type($id);
    }
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
}
