<?php

class Sinistro2_Form_LaudoPreliminar extends Agro_Form {
    private $_readOnly = null;
	private $_readOnlyAll = null;

    public function init($idLaudoPreliminar = null) {
		$dados = $this->getDados();

		$Configuracoes = array(
			'fl_exibe_botao_enviar'=>false,
			'fl_exibe_botao_devolver'=>false,
			'fl_exibe_botao_imprimir'=>true
		);

		if($idLaudoPreliminar) {

			$Configuracoes = $this->getConfiguracoes($idLaudoPreliminar, $dados);

			switch ($Configuracoes['readonly']) {
				case 'readOnly':
					$this->setReadOnly(true);
					break;
				case 'readOnlyAll':
					$this->setReadOnly(true);
					$this->setReadOnlyAll(true);
					break;
				default:
				break;
			}

		}

    	$this->setMethod('post');
        $this->setAttrib('id', 'form-laudo');

        $this->setDisableLoadDefaultDecorators(true);
        $this->setDecorators($this->decorators);

    	$this->addElement('hidden', 'id_laudo_preliminar', array(
    		'decorators' => $this->hiddendecorator,
    		'order' => 1
    	));

        $this->addElement('hidden', 'id_processo', array(
            'decorators' => $this->hiddendecorator,
    		'order' => 2
        ));

        $this->addElement('hidden', 'id_cobertura', array(
            'decorators' => $this->hiddendecorator,
    		'order' => 3
        ));

        $this->addElement('hidden', 'id_status', array(
            'decorators' => $this->hiddendecorator
		));

        $this->addElement('hidden', 'id_vistoria', array(
            'decorators' => $this->hiddendecorator,
    		'order' => 4
        ));

        $this->addElement('hidden', 'id_proposta', array(
            'decorators' => $this->hiddendecorator,
    		'order' => 5
        ));

        $this->addElement('hidden', 'module_name', array(
            'decorators' => $this->hiddendecorator,
        	'value' => $this->_request['module'],
    		'order' => 6
        ));

        $this->addElement('hidden', 'controller_name', array(
            'decorators' => $this->hiddendecorator,
        	'value' => $this->_request['controller'],
    		'order' => 7
        ));

        $this->addElement('radio', 'fl_evento_nao_constatado', array(
            'MultiOptions' => array(0=>'Sim',1=>'Não'),
            'decorators' => $this->multiElementDecorator,
            'disableLoadDefaultDecorators' => true,
            'separator'=>'',
            'label' => 'Evento constatado?',
            'required' => true,
    		'order' => 9,
		    //'ignore' => $this->getReadOnly(),
			//'readonly' => $this->getReadOnly()
        ));


        $this->addElement('radio', 'fl_dt_evento_em_cobertura', array(
            'MultiOptions' => array(1=>'Sim', 0=>'Não. Justifique nas observações.'),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->fieldDecorator,
            'separator'=>' ',
            'label' => 'A data de ocorrência do evento está dentro do período de cobertura?',
            'order' => 10,
            'required' => true,
            'ignore' => $this->getReadOnly(),
            'readonly' => $this->getReadOnly()
        ));

		$this->addElement('text', 'ds_coordenadas', array(
			'decorators' => $this->fieldDecorator,
			'disableLoadDefaultDecorators' => true,
			'label' => 'Coordenadas Geográficas da sede',
			'class' => 'coordenadas',
			'size' => 26,
    		'order' => 11,
			'required' => true,
			'ignore' => $this->getReadOnly(),
			'readonly' => $this->getReadOnly()
		));

        $this->addElement('radio', 'fl_area_atingida', array(
            'MultiOptions' => array('T'=>'Total','P'=>'Parcial'),
            'decorators' => $this->fieldDecorator,
            'disableLoadDefaultDecorators' => true,
            'separator'=>' ',
            'label' => 'Área atingida',
            'required' => true,
            'ignore' => $this->getReadOnly(),
            'readonly' => $this->getReadOnly(),
            'validators'=>array(new Agro_Validate_AreaParcial)
        ));

		$this->addElement('textarea', 'ds_observacao', array(
			'decorators' => $this->fieldDecorator,
			'disableLoadDefaultDecorators' => true,
			'label' => 'Observações',
			'maxlength' => 3000,
			'rows' => 7,
			'cols' => 100,
		    'ignore' => $this->getReadOnly(),
			'readonly' => $this->getReadOnly()
		));

        $this->addElement('radio', 'fl_assinatura_segurado', array(
            'MultiOptions' => array(1=>'Sim',0=>'Não'),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->fieldDecorator,
            'separator'=>' ',
            'label' => 'Assinatura do segurado coletada?',
            'required' => true,
		    'ignore' => $this->getReadOnly(),
			'readonly' => $this->getReadOnly()
        ));

        $this->addElement('radio', 'fl_assinatura_regulador', array(
            'MultiOptions' => array(1=>'Sim',0=>'Não'),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->fieldDecorator,
            'separator'=>' ',
            'label' => 'Assinatura do regulador coletada?',
            'required' => true,
		    'ignore' => $this->getReadOnly(),
			'readonly' => $this->getReadOnly()
        ));

        $this->addElement('text', 'dt_vistoria_data', array(
            'decorators' => $this->elementDecorator,
            'label' => 'Data',
            'class' => 'data inline-element',
            'required' => true,
            'ignore' => $this->getReadOnly(),
            'readonly' => $this->getReadOnly(),
            'validators'=>array(new Agro_Validate_DataVistoria)
        ));

        $this->addElement('select', 'dt_vistoria_hora', array(
            'MultiOptions' => array(
                0=>'00',
                1=>'01',
                2=>'02',
                3=>'03',
                4=>'04',
                5=>'05',
                6=>'06',
                7=>'07',
                8=>'08',
                9=>'09',
                10=>'10',
                11=>'11',
                12=>'12',
                13=>'13',
                14=>'14',
                15=>'15',
                16=>'16',
                17=>'17',
                18=>'18',
                19=>'19',
                20=>'20',
                21=>'21',
                22=>'22',
                23=>'23'
            ),
            'decorators' => $this->elementDecorator,
            'label' => 'Hora',
            'class' => 'inline-element',
            'required' => true,
            'ignore' => $this->getReadOnly(),
            'readonly' => $this->getReadOnly()
        ));

        $this->addElement('select', 'dt_vistoria_minutos', array(
            'MultiOptions' => array(
                0=>'00',
                5=>'05',
                10=>'10',
                15=>'15',
                20=>'20',
                25=>'25',
                30=>'30',
                35=>'35',
                40=>'40',
                45=>'45',
                50=>'50',
                55=>'55'
            ),
            'decorators' => $this->elementDecorator,
            'label' => ':',
            'class' => 'inline-element',
            'ignore' => $this->getReadOnly(),
            'readonly' => $this->getReadOnly()
        ));

        $Model_Funcionarios = new Sistema_Model_Funcionarios();

        $this->addElement('multiCheckbox', 'vistoriadores', array(
            'MultiOptions' => $Model_Funcionarios->getArrayVistoriadoresByEmpresa($dados['id_empresa_vistoriadora']),
            'decorators' => $this->fieldDecorator,
            'label' => 'Vistoriadores',
            'separator' => '',
            'required' => true,
            'ignore' => $this->getReadOnly(),
            'readonly' => $this->getReadOnly()
        )); 

        $this->addElement('multiCheckbox', 'auxiliares', array(
            'MultiOptions' => $Model_Funcionarios->getArrayAuxiliaresByEmpresa($dados['id_empresa_vistoriadora']),
            'decorators' => $this->fieldDecorator,
            'label' => 'Auxiliares',
            'separator' => '',
            'ignore' => $this->getReadOnly(),
            'readonly' => $this->getReadOnly()
        )); 

        if ($this->getReadOnlyAll()) {
	    	$this->addElement('hidden', 'Salvar', array(
	    		'decorators' => $this->hiddendecorator,
	    		'order' => 1008
	    	));
		} else {
	        $this->addElement('button', 'Salvar', array(
	        	'decorators' => $this->buttonDecorator,
	        	'order' 	=> 1008,
	        	'type' 		=> 'submit',
	            'value'		=> 'Salvar',
	            'ignore'	=> true
	        ));
		}

		if ($Configuracoes['fl_exibe_botao_enviar']) {
	        $this->addElement('button', 'Enviar', array(
	        	'decorators' => $this->buttonDecorator,
	        	'order' 	=> 1009,
	        	'type' 		=> 'button',
	            'value'		=> 'Enviar',
	            'ignore'	=> true
	        ));
	    } else {
	    	$this->addElement('hidden', 'Enviar', array(
	    		'decorators' => $this->hiddendecorator,
	    		'order' => 1009
	    	));
		}

		if ($Configuracoes['fl_exibe_botao_devolver']) {
	        $this->addElement('button', 'Devolver', array(
	        	'decorators' => $this->buttonDecorator,
	        	'order' 	=> 1010,
	        	'type' 		=> 'button',
	            'value'		=> 'Enviar',
	            'ignore'	=> true
	        ));
	    } else {
	    	$this->addElement('hidden', 'Devolver', array(
	    		'decorators' => $this->hiddendecorator,
	    		'order' => 1010
	    	));
		}

        $this->addElement('button', 'Sair', array(
        	'decorators' => $this->buttonDecorator,
        	'order' 	=> 1011,
        	'type' 		=> 'button',
            'value'		=> 'Sair',
            'ignore'	=> true
        ));

        $this->addDisplayGroup(
			array('Salvar', 'Enviar', 'Devolver'),
            'buttons',
            array(
            	'order'=>1012,
                'disableLoadDefaultDecorators' => true,
                'decorators'=>$this->buttonsDecorator
			)
        );

    }

    public function setReadOnly($value){
        $this->_readOnly = ($value ? $value : null);
    }

    public function getReadOnly(){
        return $this->_readOnly;
    }

    public function setReadOnlyAll($value){
        $this->_readOnlyAll = ($value ? $value : null);
    }

    public function getReadOnlyAll(){
        return $this->_readOnlyAll;
    }

    public function populate(array $values) {
    	if (array_key_exists("dt_vistoria", $values)){
    		$values["dt_vistoria"] = Agro_Util::formatDate($values["dt_vistoria"], Zend_Date::DATES);
    	}

        parent::populate($values);
    }

	public function getConfiguracoes($idLaudoPreliminar, $dados = array()) {
		$Model_LaudoPreliminares = new Sinistro2_Model_LaudosPreliminares();
		$LaudoPreliminar = $Model_LaudoPreliminares->getLaudoPreliminar($idLaudoPreliminar);

		$Configuracoes = array();

		$User = Zend_Auth::getInstance()->getIdentity();

		$Funcionario = new Sistema_Model_Funcionarios();
		$f = $Funcionario->fetchRow('id_usuario = '.$User->id);
		$idEmpresaUserLogado = $f['id_empresa'];

		$VistoriaEmpresa = new Sistema_Model_VistoriasEmpresas();
		$idEmpresaVistoriadora = $VistoriaEmpresa->getIdEmpresaByLaudoPreliminar($idLaudoPreliminar);

		if ($LaudoPreliminar['ds_chave_status'] == 'ENVIADO' || ($idEmpresaUserLogado != $idEmpresaVistoriadora && $User->tp_usuario != 'F')) {
			$Configuracoes['readonly'] = 'readOnlyAll';
		}

		if(REGULACAO_ATIVA == 'S'){
			if ($LaudoPreliminar['ds_chave_status'] != 'ENVIADO' && $LaudoPreliminar['ds_chave_status'] != 'PENDENTE_LAUDO_PRELIMINAR') {
				$Configuracoes['fl_exibe_botao_enviar'] = true;
			}
		} else {
			if ($LaudoPreliminar['ds_chave_status'] != 'ENVIADO') {
				$Configuracoes['fl_exibe_botao_enviar'] = true;
			}
		}

		if ($LaudoPreliminar['ds_chave_status'] == 'ENVIADO' && (Agro_Util::checkPermission('sinistro2:laudopreliminar:devolvelaudopreliminar'))) {
			$Configuracoes['fl_exibe_botao_devolver'] = true;
		}

		$dados = $this->getDados();

		if (array_key_exists("fl_exibir_botao_imprimir", $dados)){
			$Configuracoes["fl_exibir_botao_imprimir"] = $dados["fl_exibir_botao_imprimir"];

		} else {
			$Configuracoes["fl_exibir_botao_imprimir"] = true;
		}

		return $Configuracoes;
	}

    /* DECORATORS */

    public $decorators = array (
        'FormElements',
        'Form',
        array(
            array(
                'form-div'=>'HtmlTag'
            ),
            array(
                'tag' => 'div',
                'id' => 'form-div'
            )
        )
    );

    public $simpleFieldDecorator = array (
       'ViewHelper',
        array(
            'Description',
            array(
                'class'=>'help'
            )
        ),
        'Errors',
        array(
            'Label',
            array(
                'placement' => 'append',
            )
        )
    );

    public function _simpleFieldDecorator ($width = '30%') {
        return array (
            'ViewHelper',
            array(
                'Description',
                array(
                    'class'=>'help'
                )
            ),
            'Errors',
            'Label',
            array(
                array(
                    'field-div'=>'HtmlTag'
                ),
                array(
                    'tag' => 'div',
                    'class' => 'field',
                    'style' => 'width:'.$width
                )
            )
        );
    }

    public $fieldDecorator = array (
        'ViewHelper',
        array(
            'Description',
            array(
                'class'=>'help'
            )
        ),
        array(
            'Label',
            array(
                'tag' => 'div'
            )
        ),
    );

    public function _fieldDecorator ($width) {
        return array (
            'ViewHelper',
            array(
                'Description',
                array(
                    'class'=>'help'
                )
            ),
            'Errors',
            array(
                'Label',
                array(
                    'tag' => 'div'
                )
            ),
            array(
                array(
                    'field-div'=>'HtmlTag'
                ),
                array(
                    'tag' => 'div',
                    'class' => 'field',
                    'style' => 'width:'.$width
                )
            )
        );
    }

    public $fieldGroupDecorator = array (
        'FormElements'
    );

    public $fieldsetDecorator = array(
        'FormElements',
        'Fieldset'
    );

	public $buttonDecorator = array(
		'ViewHelper',
		array(array('elementLi'=>'HtmlTag'), array('tag' => 'li'))
	);


    public $buttonsDecorator = array(
        'FormElements',
        array(array('elementUl'=>'HtmlTag'), array('tag' => 'ul','class'=>'ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all'))
    );

	public $hiddendecorator = array(
		'ViewHelper',
	);

}
