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

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    public static function get($id)
    {
        return db::query()->select(self::TABLE)
                          ->where('id', $id)
                          ->execute()->fetch();
    }
    
    public static function get_by_path($path)
    {
        return db::query()->select(self::TABLE)
                          ->where('path', $path)
                          ->execute()->fetch();
    }
    
    public static function get_list()
    {
        return db::query()->select(self::TABLE . ' s')
                          ->column('s.*')
                          ->join('meta m', array('AND', array('=', 's.id', (object) array('type' => 'identifier', 'value' => 'm.type_id')), array('=', 'm.type', 'section')), 'left')
                          ->column('m.title meta')
                          ->execute();
    }
    
    public static function add(array $data)
    {
        db::query()->insert(self::TABLE)
                   ->column($data)
                   ->execute();
        
        $id = db::get()->get_last_id();
        return $id;
    }
    
    public static function edit($id, array $data)
    {
        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();
        
        page::delete_by_section($id);
    }
    
    public static function get_views($id = null)
    {
        $q = db::query()->select(self::TABLE)
                        ->column(sql::raw('SUM(views) as total'));
        
        if ($id !== null)
        {
            $q->where('id', $id);
        }
        
        $row = $q->execute()->fetch();
        return $row['total'];
    }
    
    public static function save_view($id)
    {
        db::query()->update(self::TABLE)
                   ->column('views', sql::raw('views + 1'))
                   ->where('id', $id)
                   ->execute();
    }
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
}
