<?php

class Agro_View_Helper_LaudoPreliminarItensSegurados2 extends Zend_View_Helper_Abstract {

	public function LaudoPreliminarItensSegurados2($params) {
        $desabilitar = ($params['controller'] == 'lp002' && $params['id_status'] == Sistema_Model_Status::LAUDOS_PRELIMINARES_ENVIADO) ? 'readonly="readonly" disabled="disabled"' : '';
        $somenteAtivos = ($params['controller'] == 'lp002' && in_array($params['id_status'], [Sistema_Model_Status::LAUDOS_PRELIMINARES_PENDENTE_ENVIO, Sistema_Model_Status::LAUDOS_PRELIMINARES_PENDENTE_LAUDO_PRELIMINAR]));
	    $selectIntensidades = $this->getSelectIntensidades($desabilitar);
        $selectEstadios = $this->getSelectEstadiosFenologicos($params['id_cultura'], $desabilitar, $somenteAtivos);

        foreach ($params['campos_especializacao'] as $campoEspecializacao){
        	if($campoEspecializacao['ds_nome_campo'] == 'fl_quadra_sinistrada'){
        		$mudaOrdem = true;
        	}
        }

?>

            <table width="100%" class="grid" cellpadding="1" cellspacing="1">
                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Quadra</th>
                        <th>Área</th>
                        <th>Variedade</th>

                        <?if($mudaOrdem){?>

	                        <?foreach ($params['campos_especializacao'] as $campoEspecializacao):?>
	                        	<th width="15%"><?=$campoEspecializacao['ds_nome_exibicao']?></th>
	                        <?endforeach?>

	                        <?if($params['controller'] != 'lp003'): ?>
		                        <th width="10%">Estimar a Intensidade do Evento</th>
                                <th >Estádio Fenológico</th>
                                <?if($params['controller'] != 'lp004'): ?>
                                    <th width="10%">Data prevista de início de coheita</th>
                                <?endif;?>
                            <?endif;?>
                            
	                    <?}else{?>

	                    	<?if($params['controller'] != 'lp003'): ?>
		                        <th width="10%">Estimar a Intensidade do Evento</th>
                                <th>Estádio Fenológico</th>
                                <?if($params['controller'] != 'lp004'): ?>
                                    <th width="10%">Data prevista de início de coheita</th>
                                <?endif?>
		                    <?endif;?>
	                        <?foreach ($params['campos_especializacao'] as $campoEspecializacao):?>
	                        	<th width="15%"><?=$campoEspecializacao['ds_nome_exibicao']?></th>
                            <?endforeach?>

	                    <?}?>

                        <?if($params['controller'] == 'lp004'):?>
                            <th width="20%">A ocorrência do evento está dentro do período para Cobertura Adicional de Qualidade?<br />Se Não, justifique nas observações</th>
                        <?endif;?>
                    </tr>
                </thead>
                <tbody align="center">
                    <?

                    $selecionados = array();

                    foreach($params['itens_segurados'] as $chave => $ItemSegurado):

                    	$id_estadio_fenologico = array_key_exists($ItemSegurado['id_item_segurado'], $params['valores']) ? $params['valores'][$ItemSegurado['id_item_segurado']]['id_estadio_fenologico'] : '0';
	                    $id_intensidade = array_key_exists($ItemSegurado['id_item_segurado'], $params['valores']) ? $params['valores'][$ItemSegurado['id_item_segurado']]['id_intensidade'] : '0';

                        foreach($params['itens_segurados_selecionados'] as $key => $itemSelecionado){
                        	if($ItemSegurado['id_item_segurado'] == $itemSelecionado){
                        		$selecionados[] = $ItemSegurado['id_item_segurado'];
                        	}
                        }


                        if($params['controller'] == 'lp001'){

	                        //marca como não sinistrado os itens não selecionados
	                        if(!in_array($ItemSegurado['id_item_segurado'], $selecionados) && !count($params['valores'][$ItemSegurado['id_item_segurado']])){

	                        	$id_intensidade = 10;

	                        }else if(in_array($ItemSegurado['id_item_segurado'], $selecionados)){
	                        	$id_intensidade = $id_intensidade;
	                        }
                        }


                    ?>
                    <tr>
                        <td>
                             <?=$ItemSegurado['nr_item_segurado']?>
                             <input type="hidden" name="itens_segurados[<?=$ItemSegurado['id_item_segurado']?>]" id="itens_segurados-<?=$ItemSegurado['id_item_segurado']?>" value="<?=$ItemSegurado['id_item_segurado']?>">
                        </td>
                        <td><?=$ItemSegurado['ds_item_segurado']?></td>
                        <td><?=$ItemSegurado['vl_area']?></td>
                        <td><?=$ItemSegurado['ds_nome_variedade']?></td>

                        <?if($mudaOrdem){?>
	                        <?foreach ($params['campos_especializacao'] as $campoEspecializacao):?>
	                        <td>
	                            <?
	                            echo $this->getInput(
	                                $campoEspecializacao,
	                                $ItemSegurado['id_item_segurado'],
	                                array_key_exists($ItemSegurado['id_item_segurado'], $params['valores']) ? $params['valores'][$ItemSegurado['id_item_segurado']][$campoEspecializacao['ds_nome_campo']] : null,
                                    $selecionados,
                                    $desabilitar)
	                             ?>
	                             </td>
	                        <?endforeach?>

                            <?if ($params['controller'] != 'lp003'): ?>
                                <td>
                                    <?=str_replace(array('{id_item_segurado}','{checked_'.$id_intensidade.'}'), array($ItemSegurado['id_item_segurado'],'selected'), $selectIntensidades)?>
                                </td>
		                        <td>
		                            <?=str_replace(array('{id_item_segurado}','{checked_'.$id_estadio_fenologico.'}'), array($ItemSegurado['id_item_segurado'],'selected'), $selectEstadios)?>
                                </td>
                                <?if($params['controller'] != 'lp004'):?>
                                    <td>
                                        <input type="text" class="data" id="dt_prevista_inicio_colheita-<?=$ItemSegurado['id_item_segurado']?>" name="dt_prevista_inicio_colheita[<?=$ItemSegurado['id_item_segurado']?>]" value="<?=array_key_exists($ItemSegurado['id_item_segurado'], $params['valores']) ? $params['valores'][$ItemSegurado['id_item_segurado']]['dt_prevista_inicio_colheita']: '';?>" <?=$desabilitar?>>
                                    </td>
                                <?else:?>
                                    <td><? 
                                            if($params['valores'][$ItemSegurado['id_item_segurado']]['fl_periodo_cob_qualidade']) {
                                                $fl_periodo_cob_qualidade_checked_1 = 'checked';
                                                $fl_periodo_cob_qualidade_checked_0 = '';
                                            } else {
                                                $fl_periodo_cob_qualidade_checked_0 = 'checked';
                                                $fl_periodo_cob_qualidade_checked_1 = '';
                                            }
                                        ?>
                                        <input type="radio" name="fl_periodo_cob_qualidade[<?=$ItemSegurado['id_item_segurado']?>]" <?=$fl_periodo_cob_qualidade_checked_1?> id="fl_periodo_cob_qualidade-<?=$ItemSegurado['id_item_segurado']?>-1" value="1" <?=$desabilitar?>>
                                        <label for="fl_periodo_cob_qualidade-<?=$ItemSegurado['id_item_segurado']?>-1">Sim</label>
                                        <input type="radio" name="fl_periodo_cob_qualidade[<?=$ItemSegurado['id_item_segurado']?>]" <?=$fl_periodo_cob_qualidade_checked_0?> id="fl_periodo_cob_qualidade-<?=$ItemSegurado['id_item_segurado']?>-0" value="0" <?=$desabilitar?>>
                                        <label for="fl_periodo_cob_qualidade-<?=$ItemSegurado['id_item_segurado']?>-0">Não</label>
                                    </td>
                                <?endif;?>
	                        <?endif;?>
                        <?}else{?>
                            <?if ($params['controller'] != 'lp003'): ?>
                                <td>
                                    <?=str_replace(array('{id_item_segurado}','{checked_'.$id_intensidade.'}'), array($ItemSegurado['id_item_segurado'],'selected'), $selectIntensidades)?>
                                </td>
    	                        <td>
		                            <?=str_replace(array('{id_item_segurado}','{checked_'.$id_estadio_fenologico.'}'), array($ItemSegurado['id_item_segurado'],'selected'), $selectEstadios)?>
                                </td>
                                <?if($params['controller'] != 'lp004'):?>
                                    <td>
                                        <input type="text" class="data" id="dt_prevista_inicio_colheita-<?=$ItemSegurado['id_item_segurado']?>" name="dt_prevista_inicio_colheita[<?=$ItemSegurado['id_item_segurado']?>]" value="<?=array_key_exists($ItemSegurado['id_item_segurado'], $params['valores']) ? $params['valores'][$ItemSegurado['id_item_segurado']]['dt_prevista_inicio_colheita']: '';?>" <?=$desabilitar?>>
                                    </td>
                                <?else:?>
                                    <td>
                                        <input type="radio" name="fl_periodo_cob_qualidade[<?=$ItemSegurado['id_item_segurado']?>]" id="fl_periodo_cob_qualidade-<?=$ItemSegurado['id_item_segurado']?>-1" value="1" <?=$desabilitar?>>
                                        <label for="fl_periodo_cob_qualidade-<?=$ItemSegurado['id_item_segurado']?>-1">Sim</label>
                                        <input type="radio" name="fl_periodo_cob_qualidade[<?=$ItemSegurado['id_item_segurado']?>]" id="fl_periodo_cob_qualidade-<?=$ItemSegurado['id_item_segurado']?>-0" value="0" <?=$desabilitar?>>
                                        <label for="fl_periodo_cob_qualidade-<?=$ItemSegurado['id_item_segurado']?>-0">Não</label>
                                    </td>
                                <?endif;?>
		                    <? endif; ?>
	                        <?foreach ($params['campos_especializacao'] as $campoEspecializacao):?>
	                        <td>
	                            <?
	                            echo $this->getInput(
	                                $campoEspecializacao,
	                                $ItemSegurado['id_item_segurado'],
	                                array_key_exists($ItemSegurado['id_item_segurado'], $params['valores']) ? $params['valores'][$ItemSegurado['id_item_segurado']][$campoEspecializacao['ds_nome_campo']] : null,
                                    $selecionados,
                                    $desabilitar)
	                             ?>
	                             </td>
	                        <?endforeach?>
                        <?}?>
                    </tr>
                    <?endforeach;?>
                </tbody>
            </table>
<?
	}

    public function getSelectEstadiosFenologicos($idCultura, $desabilitar = null, $somenteAtivos = false) {

        $selectEstadios = "<select id='id_estadio_fenologico-{id_item_segurado}' name='id_estadio_fenologico[{id_item_segurado}]' {$desabilitar}>";
        $selectEstadios .= '<option value=""></option>';

        $Model_Culturas = new Produto_Model_Culturas();
        $Estadios = $Model_Culturas->getEstadiosByCultura($idCultura, $somenteAtivos);

        foreach ($Estadios as $Estadio) {
            $selectEstadios .= '<option value="'.$Estadio['id_estadio_fenologico'].'"{checked_'.$Estadio['id_estadio_fenologico'].'}>'.$Estadio['ds_nome_estadio_fenologico'].'</option>';
        }
        $selectEstadios .= '</select>';

        return $selectEstadios;
    }

    public function getSelectIntensidades($desabilitar = null) {

        $selectIntensidades = "<select id='id_intensidade-{id_item_segurado}' name='id_intensidade[{id_item_segurado}]' {$desabilitar}>";
        $selectIntensidades .= '<option value=""></option>';

        $Model_Intensidades = new Sinistro2_Model_Intensidades();

        $Intensidades = $Model_Intensidades->getIntensidades();

        foreach ($Intensidades as $Intensidade) {
            $selectIntensidades .= '<option value="'.$Intensidade['id_intensidade'].'"{checked_'.$Intensidade['id_intensidade'].'}>'.$Intensidade['ds_intensidade'].'</option>';
        }
        $selectIntensidades .= '</select>';

        return $selectIntensidades;
    }

    public function getInput($Campo, $idItemSegurado, $value = null, $selecionados, $desabilitar = null) {
        $input = '';
        if ($Campo['value']) {
            $value = $Campo['value'];
        }

        $checked = $value ? ' checked' : '';

        switch ($Campo['ds_tipo']) {
            case 'select':
                $input .= '<select name="'.$Campo['ds_nome_campo'].'['.$idItemSegurado.']" '. $desabilitar .' >';
                $input .= '<option value=""></option>';
                foreach ($Campo['ar_opcoes'] as $dsValue=>$dsCaption) {
                    $selected = (($value == $dsValue) ? ' selected' : '');
                    $input .= '<option value="'.$dsValue.'"'.$selected.'>'.$dsCaption.'</option>';
                }
                $input .= '</select>';
                break;
            case 'result':
                $input .= $value;
                break;
            case 'label-hidden':
                $input .= '<label for="'.$Campo['ds_nome_campo'].'_'.$idItemSegurado.'">'.$value.'</label>';
                $input .= '<input type="hidden" name="'.$Campo['ds_nome_campo'].'['.$idItemSegurado.']" id="'.$Campo['ds_nome_campo'].'_'.$idItemSegurado.'" value="'.$value.'" '. $desabilitar .' />';
                break;
            case 'checkbox':
                $input .= '<input type="hidden" name="'.$Campo['ds_nome_campo'].'['.$idItemSegurado.']" value="0"><input type="checkbox" name="'.$Campo['ds_nome_campo'].'['.$idItemSegurado.']" id="'.$Campo['ds_nome_campo'].'-'.$idItemSegurado.'" value="1"'.$checked.' '. $desabilitar .' >';
                break;
            case 'radio':
                foreach ($Campo['ar_opcoes']as $dsValue=>$dsCaption) {

                	//ajuste para mostrar os itens selecionados já marcados com SIM e os não selecionados com NÃO
                	if(in_array($idItemSegurado, $selecionados) && $dsCaption == 'Sim'){
                		$checked = 'checked';
                	}else if(!in_array($idItemSegurado, $selecionados) && $dsCaption == 'Não' && !$value){
                		$checked = 'checked';
                	//
                	}else{
	                    $checked = ($value == $dsValue) ? ' checked' : '';
	                    if ($value and $dsValue == 1) {
	                        $checked = ' checked';
	                    } elseif (!is_null($value) and !$value and  $dsValue == 0) {
	                        $checked = ' checked';
	                    } else {
	                        $checked = '';
	                    }
                	}

                    $input .= ' <input type="radio" name="'.$Campo['ds_nome_campo'].'['.$idItemSegurado.']" id="'.$Campo['ds_nome_campo'].'-'.$idItemSegurado.'-'.$dsValue.'" value="'.$dsValue.'"'.$checked.' '. $desabilitar .' ><label for="'.$Campo['ds_nome_campo'].'-'.$idItemSegurado.'-'.$dsValue.'">'.$dsCaption.'</label>';
                }
                break;
            default:
                $input .= '<input id="'.$Campo['ds_nome_campo'].'" type="text" name="'.$Campo['ds_nome_campo'].'['.$idItemSegurado.']" value="'.$value.'" class="'.$Campo['ds_class'].'" size="5" maxlenght="6" '.$Campo['readonly'].' '. $desabilitar .' />';
        }
        return $input;
    }
}
