<?php
App::uses('AppController', 'Controller');
class ContentsController extends AppController {

   var $name = 'Contents';  
   public $components = array('Paginator');
   
   public function beforeFilter(){	  
	   parent::beforeFilter();
	}
   
   public function admin_index() {
        $this->Content->recursive = 0;
		$contents = $this->Paginator->paginate($this->Content);
        $this->set('contents', $contents);
    }
	
  public function admin_add() {
        if (!empty($this->request->data)) {
            $this->Content->create();
            if (isset($this->request->data['Content']['pagebody']))
                $this->request->data['Content']['pagebody'] = preg_replace('/<img src="..\/..\/app\/webroot/', '<img src="http://' . env('HTTP_HOST') . $this->request->base, $this->request->data['Content']['pagebody']);
            if ($this->Content->save($this->request->data)) {
                $this->Session->setFlash(__('The content has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The content could not be saved. Please, try again.'));
				$this->redirect(array('action' => 'add'));
            }
        }
    }

  public function admin_edit($id = null) {
        
		if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid content'));
            $this->redirect(array('action' => 'index'));
        }
		
        if (!empty($this->request->data)) {
            if (isset($this->request->data['Content']['pagebody']))
                $this->request->data['Content']['pagebody'] = preg_replace('/<img src="..\/..\/../', '<img src="http://' . env('HTTP_HOST') . $this->request->base, $this->request->data['Content']['pagebody']);

            if ($this->Content->save($this->request->data)) {
                $this->Session->setFlash(__('The content has been saved'));
               $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The content could not be saved. Please, try again.'));
				$this->redirect(array('action' => 'edit',$this->request->data['Content']['id']));
            }
        }
        if (empty($this->request->data)) {
            $this->request->data = $this->Content->read(null, $id);
        }
    }

   public function admin_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for content'));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->Content->delete($id)) {
            $this->Session->setFlash(__('Content deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Content was not deleted'));
        $this->redirect(array('action' => 'index'));
    }
   
}
?>