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

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