<?
$this->showPrint = true;
?>
<link rel="stylesheet" href="/resources/css/sinistro2/liquidacao.css" type="text/css" media="screen" />
<link rel="stylesheet" href="/resources/css/seguro/proposta.css" type="text/css" media="screen" />
<link rel="stylesheet" href="/resources/css/sinistro2/liquidacaoprint.css" type="text/css" media="print" />
<link rel="stylesheet" href="/resources/css/seguro/propostaview.css" type="text/css" media="screen" />

<?=$this->headerSinistro($this->dados['id_proposta'], $this->dados['id_processo'], true); ?>

<fieldset>
<legend><b>Liquidação</b></legend>
	<div class="area">
		<table width="100%" class="grid" cellpadding="1" cellspacing="1">
			<thead>
				<tr>
					<? if($this->dados['ds_nome_liquidacao_avulsa']){?>
						<th>Tipo</th>
					<? } ?>
					<th>Número</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<? if($this->dados['ds_nome_liquidacao_avulsa']){?>
						<td><?=$this->dados['ds_nome_liquidacao_avulsa'];?></td>
					<? } ?>
					<td align="center"><span style="font-size: 12pt; font-weight: bold;"><?=$this->dados['id_liquidacao']?></span></td>
				</tr>
			</tbody>
		</table>
	</div>
</fieldset>

<!-- AREA DOS DADOS DO SEGURADO -->
	<fieldset>
    <legend><b>Dados do Proponente</b></legend>
	<div class="area">
	<table id="borda" width="100%" class="grid" cellpadding="1" cellspacing="1">
		<thead>
			<tr>
				<th>Nome</th>
				<th>CPF/CNPJ</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>
            <?php
            $nomeProponente = $this->proponente['ds_nome_proponente'];

            if ($this->proponente['tp_pessoa'] === 'F') {
                $nomeProponente = explode(' ', $nomeProponente);
                $nomeProponente = $nomeProponente[0];
            }

            echo $nomeProponente;
            ?>
        </td>
			<td><?php echo $this->proponente['tp_pessoa'] === 'J' ? $this->proponente['cpf_cnpj'] : ''; ?></td>
		</tr>
		</tbody>
	</table>
	<table id="borda" width="100%" class="grid" cellpadding="1" cellspacing="1">
		<thead>
			<tr>
				<th>Estado</th>
				<th>Município</th>
				<th>Bairro</th>
				<th>Endereço</th>
				<th>Número</th>
				<th>Complemento</th>
				<th>CEP</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td><?php echo $this->proponente['ds_nome_estado'] ?></td>
				<td><?php echo $this->proponente['ds_nome_municipio'] ?></td>
				<td><?php echo $this->proponente['ds_endereco_bairro'] ?></td>
				<td><?php echo $this->proponente['ds_endereco_rua'] ?></td>
				<td><?php echo $this->proponente['ds_endereco_nro'] ?></td>
				<td><?php echo $this->proponente['ds_endereco_complem'] ?></td>
				<td><?php echo $this->proponente['ds_endereco_cep'] ?></td>
			</tr>
		</tbody>
	</table>
</div>
</fieldset>
<!-- /AREA DOS DADOS DO SEGURADO -->

<!-- AREA DE AVISO DE SINISTRO -->
	<fieldset>
    <legend><b>Avisos de Sinistro</b></legend>
	<div class="area">
		<table width="100%" class="grid avisos" cellpadding="1" cellspacing="1">
			<thead>
				<tr>
					<th>Nr do Aviso</th>
					<th>Dt. Sinistro</th>
					<th>Dt. Envio</th>
					<th>Dt Aceitação</th>
					<th>Evento</th>
					<th>Ações</th>
				</tr>
			</thead>
			<tbody align="center">
				<?
			$i = 0;
			foreach($this->avisos as $aviso):
				$class = ($i%2==0 ? 'on' : 'off');
			?>
			<tr class="<?=$class?>">
				<td>
					<?=$aviso['id']?>
				</td>
				<td><?=$aviso['dt_sinistro']?></td>
				<td><?=$aviso['dt_envio']?></td>
				<td><?=$aviso['dt_aceitacao']?></td>
				<td><?=$aviso['ds_nome_evento']?></td>
				<td>
					<a class="popup" href="/sinistro2/avisosinistro/view/id/<?=$aviso['id']?>/idProposta/<?=$this->dados['id_proposta']?>">
						<img src="/resources/imagens/mini/view.png" alt="view.png" title="Visualizar" border="0" />
					</a>
				</td>
			</tr>
			<?
			    $i++;
			endforeach;
			?>
		</tbody>
	</table>
</div>
</fieldset>
<!-- /AREA DE AVISO DE SINISTRO -->

<?if(count($this->beneficiarios)){?>
	<fieldset>
    <legend><b>Dados do Beneficiário</b></legend>
	<div class="area">
		<table id="borda" width="100%" class="grid avisos" cellpadding="1" cellspacing="1">
			<thead>
				<tr>
					<th>Beneficiário</th>
					<th>Limite Benefício</th>
				</tr>
			</thead>
			<tbody align="center">
				<?
        foreach($this->beneficiarios as $beneficiario){
          $nomeBeneficiario = $beneficiario['ds_nome_beneficiarios'];

          if ($beneficiario['tp_pessoa'] === 'F') {
            $nomeBeneficiario = explode(' ', $nomeBeneficiario);
            $nomeBeneficiario = $nomeBeneficiario[0];
          }
          ?>
					<tr>
						<td><?=$nomeBeneficiario;?></td>
						<td><?=Agro_Util::formatDbCurrency($beneficiario['vl_limite_beneficio']);?></td>
					</tr>
				<?}?>
			</tbody>
		</table>
	</div>
	</fieldset>
	<!-- /AREA DOS DADOS DO BENEFICIÁRIO -->
<?}?>

	<fieldset>
	<legend><b>Unidades Seguradas Liquidadas</b></legend>
	<? if ($this->dados["tipo_liquidacao"] == "LIQ18"): ?>
		<? $this->LIQ18ItensSegurados($this->dados); ?>
	<? elseif($this->dados["liq_pg"] && $this->dados["tipo_liquidacao"] != "LIQ05" && ($this->dados['tipo_liquidacao'] != 'LIQ16')): ?>
	<table width="100%" class="grid unidades" cellpadding="2" cellspacing="1">
		<thead>
			<tr>
	            <th width="1%">Item</th>
	            <th>Quadra</th>
	            <th>Variedade</th>
	            <th>Área</th>
	            <th>Área Atingida</th>
	            <th>LMGA (R$)</th>
	            <th>Produção Garantida(PG)</th>
	            <th>Produção Obtida(PO)</th>
	            <th>% Colhido</th>
	            <? if ($this->dados['tipo_liquidacao'] != 'LIQ17'): ?>
		            <th>% de Indenização</th>
		            <th>Indenização (R$)</th>
		        <? endif; ?>
			</tr>
		</thead>
		<tbody>
			<?if ($this->dados['itens_segurados']):?>
				<?foreach ($this->dados['itens_segurados'] as $Quadra):?>
					<tr align="center">
						<td><? echo $Quadra['nr_item_segurado']?></td>
						<td><? echo $Quadra['ds_item_segurado']?></td>
						<td><? echo $Quadra['ds_nome_variedade']?></td>
						<td><? echo $Quadra['vl_area']?></td>
						<td><? echo $Quadra['vl_area_atingida']?></td>
						<td><? echo Agro_Util::formatDbCurrency($Quadra['vl_lmga'])?></td>
						<td><? echo $Quadra['vl_producao_garantida']?></td>
						<td><? echo ($Quadra['vl_rendimento_final_lavoura'] > 0 ? $Quadra['vl_rendimento_final_lavoura'] : 0)?></td>
						<td><? echo ($Quadra["liquidacoes"][0]["vl_percent_colhido"] > 0 ? $Quadra["liquidacoes"][0]["vl_percent_colhido"] : 0)?></td>
						<? if ($this->dados['tipo_liquidacao'] != 'LIQ17'): ?>
							<td><? echo ($Quadra["indenizacao"][0]["vl_percent_indenizacao"] > 0 ? $Quadra["indenizacao"][0]["vl_percent_indenizacao"] : 0)?></td>
							<td><? echo Agro_Util::formatDbCurrency($Quadra["indenizacao"][0]["vl_indenizacao"] > 0 ? $Quadra["indenizacao"][0]["vl_indenizacao"] : 0)?></td>
						<? endif; ?>
					</tr>
				<?endforeach;?>
			<?endif;?>
		</tbody>
		<tfoot>
			<tr>
	            <td colspan="3" align="right"><b>Totais:</b></td>
	            <td align="left" colspan="2"><b><? echo $this->dados['vl_area_total']?></b></td>
	            <td align="center"><b><? echo Agro_Util::formatDbCurrency($this->dados['vl_lmga_total'])?></b></td>
	            <? if ($this->dados['tipo_liquidacao'] != 'LIQ17'): ?>
		            <td colspan="4"></td>
		            <td align="center">R$ <b><? echo Agro_Util::formatDbCurrency(($this->dados['vl_indenizacao_total'] > 0 ? $this->dados['vl_indenizacao_total'] : 0)) ?></b></td>
		        <? else: ?>
		        	<td colspan="3"></td>
		        <? endif; ?>
	        </tr>
		</tfoot>
	</table>
	</fieldset>
	<fieldset>
		<?
		if ($this->dados["tipo_liquidacao"] != "LIQ10") {
			if ($this->dados['itens_segurados']) {
				foreach ($this->dados['itens_segurados'] as $quadra) {

					$rendimento = round(((($quadra['liquidacoes'][0]['vl_percent_colhido']/100) * $quadra['vl_area'] * $quadra['vl_rendimento_tonelada']) + ((1 - ($quadra['liquidacoes'][0]['vl_percent_colhido']/100))
		* $quadra['vl_area'] * $quadra['vl_rendimento_final_lavoura']))/$quadra['vl_area'], 3);

					$soma_mpa += $rendimento * $quadra['vl_area'];
					$soma_pgm += $quadra['vl_area'] * $quadra['vl_producao_garantida'];
					$soma_lmga += $quadra['vl_lmga'];
				}

				$pmo = ($soma_mpa/$this->dados['vl_area_total']);
				$pgm = $soma_pgm / $this->dados['vl_area_total'];
				$perc_indenizacao = round((($pgm - $pmo) / $pgm), 4);
				$perc_indenizacao = round($perc_indenizacao * 100, 2);
				$perc_indenizacao = $perc_indenizacao < 0 ? 0 : $perc_indenizacao;
				$indenizacao = ($perc_indenizacao/100) * $soma_lmga;

			} ?>
		<legend><b>Resumo</b></legend>
		<table width="100%" class="grid" cellpadding="2" cellspacing="1">
			<thead><tr><th>Produtividade Obtida Média</th><th>Produtividade Garantida Média</th><th>Percentual de Indenização</th><th>Indenização</th></tr></thead>
			<tbody align="center"><tr>
				<td><?=number_format(round($pmo, 3), 3, ',', '.')?></td>
				<td><?=number_format(round($pgm, 3), 3, ',', '.')?></td>
				<td><?=number_format(round($perc_indenizacao, 2), 2, ',', '.')?></td>
				<td><?=number_format($indenizacao, 2, ',', '.')?></td></tr></tbody>
		</table>
	<? } ?>

	<? elseif ($this->dados["tipo_liquidacao"] == 'LIQ16'):?>
	<table width="100%" class="grid" cellpading="2" cellspacing="1">
		<thead>
			<tr>
				<th with="1%">Item</th>
				<th>Quadra</th>
				<th>Variedade</th>
				<th>Área</th>
				<th>Área Replantada</th>
				<th>% Área Replantada</th>
				<th>LMGA (R$)</th>
				<th>LMGA Área Replantada (R$)</th>
				<th>Percentual Indenizável sobre<br> LMGA da Área Replantada</th>
				<th>Indenização por Quadra/Talhão</th>
			</tr>
		</thead>
		<tbody>
			<?if ($this->dados['itens_segurados']): ?>
				<?foreach($this->dados['itens_segurados'] as $Quadra):?>
					<tr align="center">
						<td><?=$Quadra['nr_item_segurado']?></td>
						<td><?=$Quadra['ds_item_segurado']?></td>
						<td><?=$Quadra['ds_nome_variedade']?></td>
						<td><?=$Quadra['vl_area']?></td>
						<td><?=$Quadra['vl_ha_area_replantada']?></td>
						<td><?=$Quadra['percent_area_replantada']?></td>
						<td><?=Agro_Util::formatDbCurrency($Quadra['vl_lmga'])?></td>
						<td><?=Agro_Util::formatDbCurrency($Quadra['lmga_area_replantada'])?></td>
						<td>20</td>
						<td><?=Agro_Util::formatDbCurrency($Quadra['indenizacao'][0]['vl_indenizacao'])?></td>
					</tr>
				<?endforeach;?>
			<?else:?>
				<tr>
					<td colspan="9" align="center" style="padding: 2%;"><b>Não há liquidações para este processo</b></td>
				</tr>
			<?endif;?>
		</tbody>
		<tfoot>
			<tr>
				<td colspan="3" align="right"><b>Totais</b></td>
	            <td align="left" colspan="3"><b><? echo $this->dados['vl_area_total']?></b></td>
	            <td align="center"><b><? echo Agro_Util::formatDbCurrency($this->dados['vl_lmga_total'])?></b></td>
	            <td colspan="2"></td>
	            <td align="center">R$ <b><? echo Agro_Util::formatDbCurrency(($this->dados['vl_indenizacao_total'] > 0 ? $this->dados['vl_indenizacao_total'] : number_format(0, 2))) ?></b></td>
			</tr>
		</tfoot>
	</table>
	<?else:?>
	<table id="borda" width="100%" class="quebra unidades grid" cellpadding="2" cellspacing="1">
		<thead>
	        <tr>
	            <th width="1%">Item</th>
	            <th>Quadra</th>
	            <th>Variedade</th>
	            <?if ($this->dados['tipo_liquidacao'] != "LIQ05"):?>
		            <th>Área</th>
		            <th>Área Atingida</th>
	            <?endif;?>
	            <th>LMGA (R$)</th>
	            <?if ($this->dados['tipo_liquidacao'] != "LIQ05"):?>
	            	<th>Regulação de Perdas</th>
	            <?endif;?>
	            <th>Prejuizo Total (R$)</th>
				<?if ($this->dados['tipo_liquidacao'] != "LIQ05"):?>
                	<th>Franquia (R$)</th>
                <?endif;?>
	            <th>Indenização (R$)</th>
	            <th>Final de Colheita</th>
	            <?
	            if($User->ds_nome_usuario == 'maria.cristina' || $User->ds_chave == 'ADMIN'){?>
	            	<th>Ação</th>
	            <?
				}
	            ?>
	        </tr>
		</thead>
		<tbody id="overbody">
			<?if ($this->dados['itens_segurados']){?>
				<?foreach ($this->dados['itens_segurados'] as $Quadra):?>
					<?$count_pricipal = 1?>
					<?$count_avisos_por_quadra = count($Quadra['liquidacoes'])?>
					<tr align="center">
						<td valign="top"><? echo $Quadra['nr_item_segurado']?></td>
						<td valign="top"><? echo $Quadra['ds_item_segurado']?></td>
						<td valign="top"><? echo $Quadra['ds_nome_variedade']?></td>
						<?if ($this->dados['tipo_liquidacao'] != "LIQ05"):?>
							<td valign="top"><? echo $Quadra['vl_area']?></td>
							<td valign="top"><? echo $Quadra['vl_area_atingida']?></td>
						<?endif;?>
						<td valign="top"><? echo Agro_Util::formatDbCurrency($Quadra['vl_lmga'])?></td>
						<?if ($this->dados['tipo_liquidacao'] != "LIQ05"):
							//essa parte do if vai tratar a exibição das liquidações quando existe mais de 5 avisos -->
							//para não ter problema na geração do PDF. tarefa 3529 -->
							if ($count_avisos_por_quadra > 4):
								$n_dependente = count($Quadra['liquidacoes'][$count_pricipal]['liquidacoes_dependentes']);?>
								<td <?=($n_dependente > 0 ? 'width="200px"' : '')?>>
									<? if ($Quadra['liquidacoes']) { ?>
										<?foreach ($Quadra['liquidacoes'] as $laudo):?>	
											<table cellpadding="0" cellspacing="0" border="0" width="100%" id="subbody_<?=$Quadra['nr_item_segurado']?>">
											<tr><td valign="top"  rowspan="<?=count($laudo['liquidacoes_depentes'])?>" width="50%"">
												<div class="regulacao">
													<div class="titleCobertura"><?echo "$count_pricipal-{$laudo['ds_nome_cobertura']}";?></div>
													<div class="dadosCobertura">
														Dano (%): <?=($laudo['vl_percent_perdas'] > 0 ? $laudo['vl_percent_perdas'] : "0.00")?><!--<?=($laudo['percentual_convertido'] ? " ({$laudo['percentual_convertido']})" : '')?>--><br />
														Colhido (%): <?=($laudo['vl_percent_colhido'] > 0 ? $laudo['vl_percent_colhido'] : "0.00")?><br />
														<?if ($laudo["vl_percent_perdas_chocho"] != null || $laudo["vl_percent_colhido_chocho"] != null):?>
															Dano Chocho (%): <? echo $laudo['vl_percent_perdas_chocho']?><br />
															Colhido Chocho (%): <? echo " {$laudo['vl_percent_colhido_chocho']}"?><br />
														<?endif;?>
														Prejuízo (R$): <? echo Agro_Util::formatDbCurrency($laudo['vl_prejuizo'])?>
													</div>
												</div>
											</td>
											<?if(count($laudo['liquidacoes_dependentes']) > 0):?>
												<td valign="top">
													<?$count_dependente = 1;?>
													<?foreach ($laudo['liquidacoes_dependentes'] as $dependente):?>
														<b><?echo "$count_pricipal.$count_dependente-".$dependente['ds_nome_cobertura']?></b><br />
														Dano (%): <? echo " {$dependente['vl_percent_perdas']}"?><br />
														Prejuízo (R$): <?echo Agro_Util::formatDbCurrency($dependente['vl_prejuizo'])?>
														<?$count_dependente+=1;?>
													<?endforeach?>
												</td>
												<?endif;?>
											</tr>
											</table>
											<?$count_pricipal+=1?>
										<?endforeach;?>
									<?} else {?>
										<div class="semLaudos">Não há laudos liquidados</div>
									<?}?>
							<?else:?>
								<!--aqui a exibição das liquidações segue como sempre foi. tarefa 3529 -->
								<td>
								<? if ($Quadra['liquidacoes']) { ?>
									<?$count_pricipal = 1?>

									<?foreach ($Quadra['liquidacoes'] as $laudo):?>
										<div class="regulacao">
											<div class="titleCobertura"><?echo "$count_pricipal-{$laudo['ds_nome_cobertura']}";?></div>
											<div class="dadosCobertura">
												Dano (%): <?=($laudo['vl_percent_perdas'] > 0 ? $laudo['vl_percent_perdas'] : "0.00")?><!--<?=($laudo['percentual_convertido'] ? " ({$laudo['percentual_convertido']})" : '')?>--><br />
												Colhido (%): <?=($laudo['vl_percent_colhido'] > 0 ? $laudo['vl_percent_colhido'] : "0.00")?><br />
												<?if ($laudo["vl_percent_perdas_chocho"] != null || $laudo["vl_percent_colhido_chocho"] != null):?>
													Dano Chocho (%): <? echo $laudo['vl_percent_perdas_chocho']?><br />
													Colhido Chocho (%): <? echo " {$laudo['vl_percent_colhido_chocho']}"?><br />
												<?endif;?>
												Prejuízo (R$): <? echo Agro_Util::formatDbCurrency($laudo['vl_prejuizo'])?>
											</div>

											<?if(count($laudo['liquidacoes_dependentes']) > 0):?>
												<?$count_dependente = 1;?>
												<?foreach ($laudo['liquidacoes_dependentes'] as $dependente):?>
													<div class="regulacao">
														<div class="titleCobertura"><?echo "$count_pricipal.$count_dependente-".$dependente['ds_nome_cobertura']?></div>
														<div class="dadosCobertura">
															Dano (%): <? echo " {$dependente['vl_percent_perdas']}"?><!--<?=($laudo['percentual_convertido'] ? " ({$laudo['percentual_convertido']})" : '')?>--><br />
															Prejuízo (R$): <?echo Agro_Util::formatDbCurrency($dependente['vl_prejuizo'])?>
														</div>
													</div>
													<?$count_dependente+=1;?>
												<?endforeach;?>
											<?endif;?>
                                        </div>
                                        <?$count_pricipal+=1?>
                                    <?endforeach;?>
                                <?} else {?>
                                    <div class="semLaudos">Não há laudos liquidados</div>
                                <?}?>
							<?endif;?>
							</td>
						<?endif;?>
						<td valign="top"><? echo Agro_Util::formatDbCurrency($Quadra['vl_prejuizo_total'])?></td>
						<?if ($this->dados['tipo_liquidacao'] != "LIQ05"):?>
                			<td valign="top">
	                        <? foreach ($Quadra['indenizacao'] as $franquia): ?>
	                            <div class="regulacao">
	                                <div class="titleCobertura"><?echo $franquia['ds_nome_cobertura'];?></div>
	                                <div class="dadosCobertura">
	                                    Franquia (%): <? echo $franquia['vl_percent_franquia']?><br />
	                                    Franquia (R$): <? echo $franquia['vl_franquia']?><br />
	                                </div>
	                            </div>
	                        <? endforeach; ?>
	                        </td>
                		<?endif;?>
						<td valign="top"><? echo ($Quadra['vl_indenizacao_total'] >= 0 ? Agro_Util::formatDbCurrency($Quadra['vl_indenizacao_total']) : 0)?></td>
			            <td valign="top"><?=$Quadra['dt_encerramento_colheita']?></td>
                        <?
			            if($User->ds_nome_usuario == 'maria.cristina' || $User->ds_chave == 'ADMIN'){?>
			            <td valign="top">
							<a class="delete_quadra" href="/sinistro2/liquidacao/deleteitemseguradocobertura/id_liquidacao/<?=$this->dados['id_liquidacao']?>/id_item_segurado/<?=$Quadra['id_item_segurado']?>/id_proposta/<?=$this->dados['id_proposta']?>/id_processo/<?=$this->dados['id_processo']?>/id_cobertura/<?=$laudo['id_cobertura']?>/avulsa/0" class="delete_liquidacao" ><img src="/resources/imagens/mini/delete.png" alt="excluir" title="Excluir quadra liquidada" border="0"></a>
						</td>
						<?}?>
					</tr>
			    <?endforeach;?>
			<?} else {?>
				<tr>
					<td colspan="9" align="center" style="padding: 2%;"><b>Não há liquidações para este processo</b></td>
				</tr>
			<?}?>
		</tbody>
		<tfoot>
			<tr>
	            <td align="right" colspan="3"><b>Totais:</b></td>
	            <?if ($this->dados['tipo_liquidacao'] != "LIQ05"):?>
	            	<td align="left" colspan="2" style="padding-left: 10px"><b><? echo $this->dados['vl_area_total']?></b></td>
	            <?endif;?>
	            <td align="center"><b><? echo Agro_Util::formatDbCurrency($this->dados['vl_lmga_total'])?></b></td>
	            <?if ($this->dados['tipo_liquidacao'] != "LIQ05"):?>
	            	<td>&nbsp;</td>
	            <?endif;?>
	            <td align="center"><b><? echo Agro_Util::formatDbCurrency($this->dados['vl_prejuizo_total'])?></b></td>
	            <?if ($this->dados['tipo_liquidacao'] != "LIQ05"):?>
                	<td align="center"><b><? echo Agro_Util::formatDbCurrency($this->dados['vl_franquia_total']) ?></b></td>
                <?endif;?>
	            <td align="center"><b><? echo ($this->dados['vl_indenizacao_total'] >= 0 ? Agro_Util::formatDbCurrency($this->dados['vl_indenizacao_total']) : 0) ?></b></td>
	        </tr>
			<tr>
				<td colspan="11" align="center">
					<br /><font style="font-weight: bold; font-size: 200%"><?=$this->dados['tp_liquidacao'] == 'P' ? 'Parcial' : 'Total';?></font><br />
				</td>
			</tr>
		</tfoot>
	</table>
<?endif;?>
</fieldset>

<?if($this->dados['ds_observacao']):?>
	<fieldset>
    <legend><b>Observação</b></legend>
		<div><?echo $this->dados['ds_observacao']?></div>
	</fieldset>
<? endif; ?>
