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

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
    
    protected function execute_index()
    {
        $form = new form(include $this->directory . 'config/add.php');
        $data['form'] = $form;
        $data['section'] = section::get_list();
        $this->render('index.html', $data);
    }
    
    protected function execute_add()
    {
        if (!$this->request->is_post())
        {
            $this->response->set('{ error: "bad request" }');
            return;
        }
        
        $form = new form(include $this->directory . 'config/add.php');
        
        if (!$form->is_valid($this->request->post()))
        {
            $this->response->set(json_encode(array('error' => 'invalid data', 'message' => implode('-', array_keys($form->get_error())))));
            return;
        }
        
        $id = section::add($form->get());
        $this->response->set(json_encode(array('error' => '', 'id' => $id)));
    }
    
    protected function execute_edit($id)
    {
        if ($this->request->is_post())
        {
            $form = new form(include $this->directory . 'config/edit.php');
            
            if (!$form->is_valid($this->request->post()))
            {
                $this->session->flash('form', $form);
                $this->redirect('section/edit/' . $id);
                return;
            }
            
            section::edit($form->get('id'), $form->get());
            $this->redirect('section');
        }
        else
        {
            if (isset($this->session->form))
            {
                $form = $this->session->form;
            }
            else
            {
                $form = new form(include $this->directory . 'config/edit.php');
                $form->set(section::get($id));
            }
            
            $data['form'] = $form;
            $this->render('edit.html', $data);
        }
    }
    
    protected function execute_delete()
    {
        if (!$this->request->is_post())
        {
            $this->response->set('{ error: "bad request" }');
            return;
        }
        
        section::delete($this->request->post('id'));
        $this->response->set(json_encode(array('error' => '')));
    }
}
