<?php

class Produto_CondicaoEspecialController extends Agro_Controller_Action {
	public $_columnList = array(
		'ds_titulo' => 'Título'
	);
	
	public function init() {
		$this->view->title = 'Produto » Cadastro » Condições Adicionais';
	}
	
	public function getModel() {
		return new Produto_Model_CondicoesEspeciais();
	}
	
	public function getForm() {
		if ($this->getRequest()->getParam('id')) {
			$Model = $this->getModel();
			$Row = $Model->find($this->getRequest()->getParam('id'))->current();
			$this->view->file = $Row->ar_condicoes_adicionais;
		}
		return new Produto_Form_CondicaoEspecial();
	}
	
	public function getFilter() {
		$where = array();
		
		if ($this->getRequest()->getParam('ds_titulo')) {
			$where[] = array(
				'field' => 'ds_titulo',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_titulo').'%'
			);
		}
		
		if ($this->getRequest()->getParam('fl_ativo')) {
			$where[] = array (
				'field' => 'fl_ativo',
				'operator' => ' = ',
				'value' => $this->getRequest()->getParam('fl_ativo')
			);
		}
		return $where;
	}

	public function afterSave($id) {
		try {
			$Adapter = new Zend_File_Transfer_Adapter_Http();
			$File = $Adapter->getFileInfo();
			$sanitizedPath = '';

			if ($File['ar_condicoes_adicionais']['error'] == 0) {
				$extensao = Agro_Util::getExtension($File['ar_condicoes_adicionais']['name']);
				$fileName = "AR_CONDICOES_ADICIONAIS_{$id}.$extensao";

				$sanitizedPath = realpath(APPLICATION_PATH."/upload_files/condicaoespecial/$fileName");
				
				$Adapter->addFilter('Rename', array(
					'target' => $sanitizedPath,
					'overwrite' => true
				));

				if (!$Adapter->receive()) {
					$this->view->showMessage(implode("<br />", $Adapter->getMessages()), 'alert');
				} else {
					$update['ar_condicoes_adicionais'] = $fileName;
					$model = $this->getModel();
					
					if (
						!$model->update($update, "id = {$id}")
						&& file_exists($sanitizedPath)
					) {
						unlink($sanitizedPath);
					}
				}
			}
		} catch (Exception $e) {
			Agro_Db_Table_Abstract::getDefaultAdapter()->rollback();
			if ($sanitizedPath != '' && file_exists($sanitizedPath)) {
				unlink($sanitizedPath);
			}
			$this->view->showMessage($e->getMessage(), 'alert');
		}
		
		$this->_forward("produto", "condicaoespecial", "form", array('id'=>$id));
	}
}
