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

    ////////////////////////////////////////////////////////////////////////////
    // Interface functions.
    
    ////////////////////////////////////////////////////////////////////////////
    // Internal functions.
    
    protected function execute_index($section)
    {
        $data['section'] = section::get($section);
        $data['page'] = page::get_list($section);
        $this->render('index.html', $data);
    }
    
    protected function execute_add($section)
    {
        if ($this->request->is_post())
        {
            $form = new form(include $this->directory . 'config/add.php');
            
            if (!$form->is_valid($this->request->post()))
            {
                $this->session->flash('form', $form);
                $this->redirect('page/add/' . $section);
                return;
            }
            
            page::add($form->get());
            $this->redirect('page/index/' . $section);
        }
        else
        {
            if (isset($this->session->form))
            {
                $form = $this->session->form;
            }
            else
            {
                $form = new form(include $this->directory . 'config/add.php');
            }
            
            $form->section_id = $section;
            $data['form'] = $form;
            $this->render('add.html', $data);
        }
    }
    
    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('page/edit/' . $id);
                return;
            }
            
            page::edit($form->get('id'), $form->get());
            $this->redirect('page/index/' . $form->section_id);
        }
        else
        {
            if (isset($this->session->form))
            {
                $form = $this->session->form;
            }
            else
            {
                $form = new form(include $this->directory . 'config/edit.php');
                $form->set(page::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;
        }
        
        page::delete($this->request->post('id'));
        $this->response->set(json_encode(array('error' => '')));
    }
}
