<?php
class position
{
    const TABLE = 'position';
    
    ////////////////////////////////////////////////////////////////////////////
    // 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_list()
    {
        $q = db::query()->select(self::TABLE . ' p');
        
        return $q->execute();
    }
    
    public static function add(array $data)
    {
        if (!array_key_exists('created', $data)) {
            $data['created'] = date('Y-m-d H:i:s');
        }
        
        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)
                   ->limit(1)
                   ->execute();
    }
    
    public static function render($position, $request)
    {
        $content = '';
        
        $render = function($module) use ($request) {
            ob_start();
            include fractal::find('module/' . $module['alias'] . '.php');
            return ob_get_clean();
        };
        
        $modules = db::query()->select(module::TABLE . ' m')
                              ->column('m.*')
                              ->column('mt.alias')
                              ->join(module_type::TABLE . ' mt', array('mt.id', 'm.module_type_id'))
                              ->join(position::TABLE . ' p', array('p.id', 'm.position_id'))
                              ->where('p.alias', $position)
                              ->order('m.order', 'ASC')
                              ->execute();
        
        foreach ($modules as $module) {
            $module['data'] = json_decode($module['data'], false);
            $content .= '<div class="module ' . htmlspecialchars($module['alias']) . '">' . $render($module) . '</div>';
        }
        
        return $content;
    }
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
}
