<?php
class QuestionnairesController extends AppController {

	var $name = 'Questionnaires';
	var $helpers = array('Html', 'Form', 'Text', 'Time');

	
	function beforeFilter(){
	  parent::beforeFilter();
	}		

	
	function index() {
		$this->Questionnaire->recursive = 0;
		$this->set('questionnaires', $this->paginate());
	}

	
	function view($id = null) {
		$this->idEmptyRedirect($id, 'index');
		$this->set('questionnaire', $this->Questionnaire->read(null, $id));
	}
			

	function add() {
		if (!empty($this->data)) {
			$this->Questionnaire->create();
			if ($this->Questionnaire->save($this->data)) {
				$this->flashSuccess(__('El cuestionario ha sido creado.', true), 'index');
			} else {
				$this->flashWarning(__('El cuestionario no ha sido creado. Corrija el error.', true));
			}
		}
		$services = $this->Questionnaire->Service->find('list');
		$this->set(compact('services'));
	}
		

	function edit($id = null) {
		$this->idEmptyRedirect($id, 'index');
		if (!empty($this->data)) {				
			if ($this->Questionnaire->save($this->data)) {
				# save Question	
				$itemsCount = count($this->data['Question']);
				for ($i=0; $i < $itemsCount; $i++) {					
					$this->Questionnaire->Question->id = $this->data['Question'][$i]['id'];
					if (!$this->Questionnaire->Question->save($this->data['Question'][$i])){				
						$this->flashWarning(__('El cuestionario no ha sido actualizado. Corrija el error.', true));
					}
				}							
				if ($i == $itemsCount) {
					$this->flashSuccess(__('El cuestionario ha sido actualizado.', true), 'index');
				}
			} else {
				$this->flashWarning(__('El cuestionario no ha sido creado. Corrija el error.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Questionnaire->read(null, $id);
		}
	}

	function cancel() {
		$this->redirect('/questionnaires'); 
	}	
	
  # attaches Invoice.id to $this->data['Item']
	function __attachQuestionnaireIdToQuestions($id) {
		$questionsCount = isset($this->data['Question']) ? count($this->data['Question']) : 0;
	  for ($i=0; $i < $questionsCount; $i++)
	  {
	    $this->data['Question'][$i]['questionnaire_id'] = $id;
	  }
	}	
}
?>