<?php
class controller_setting extends controller
{
    ////////////////////////////////////////////////////////////////////////////
    // Construct and destruct functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Overload functions.

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
    
    protected function execute_index($type = 'admin')
    {
        $data['setting'] = setting::get_list($type);
        $data['type'] = $type;
        $this->render('index.html', $data);
    }
    
    protected function execute_edit($name, $type)
    {
        $setting = setting::get($name, $type);
        
        if (!$setting)
        {
            throw new exception();
        }
        
        if ($this->request->is_post())
        {
            $form = new form(include $this->directory . 'config/' . $setting['form'] . '.php');
            
            if (!$form->is_valid($this->request->post()))
            {
                $this->session->flash('form', $form);
                $this->redirect('setting/edit/' . $name . '/' . $type);
                return;
            }
            
            setting::set($form->name, $form->type, $form->value);
            $this->redirect(($type !== 'theme') ? 'setting/index/' . $type : 'theme');
        }
        else
        {
            if (isset($this->session->form))
            {
                $form = $this->session->form;
            }
            else
            {
                $form = new form(include $this->directory . 'config/' . $setting['form'] . '.php');
                $form->name = $setting['name'];
                $form->type = $setting['type'];
                $form->value = $setting['value'];
            }
            
            $data['form'] = $form;
            $data['setting'] = $setting;
            $this->render('edit.html', $data);
        }
    }
}
