<?php

class Seguro_ClienteController extends Agro_Controller_Action {

	public function init() {
		$this->view->title = 'Seguro » Clientes';
	}

	public function getModel() {
		return new Seguro_Model_Cliente();
	}

	public function getForm() {
		return new Seguro_Form_Cliente();
	}

	public function getFilter() {
		$where = array();

		if ($this->getRequest()->getParam('ds_nome_cliente')) {
			$where[] = array(
				'field' => 'ds_nome_cliente',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_nome_cliente').'%'
			);
		}
		if ($this->getRequest()->getParam('ds_descricao_cliente')) {
			$where[] = array(
				'field' => 'ds_descricao_cliente',
				'operator' => 'ilike',
				'value' => '%'.$this->getRequest()->getParam('ds_descricao_cliente').'%'
			);
		}

		if ($this->getRequest()->getParam('fl_ativo')) {
			$where[] = array (
				'field' => 'fl_ativo',
				'operator' => ' = ',
				'value' => $this->getRequest()->getParam('fl_ativo')
			);
		}
		if ($this->getRequest()->getParam('ds_cpf_cnpj')) {
			$where[] = array (
				'field' => 'ds_cpf_cnpj',
				'operator' => ' = ',
				'value' => $this->getRequest()->getParam('ds_cpf_cnpj')
			);
		}
		return $where;
	}

	public function relacionarAction() {
		$this->getHelper('layout')->disableLayout();
		$this->view->id_cliente = $this->getRequest()->getParam('id_cliente');
		$this->view->form = new Seguro_Form_PropostaSearch();
	}

	public function listrelacionadosAction() {
		$this->getHelper('layout')->disableLayout();
		$Model = $this->getModel();
		$where[] = array(
			'field' => 'sc.id_cliente',
			'operator' => '=',
			'value' => $this->getRequest()->getParam('id_cliente')
		);

		$propostas = $Model->getRelacionadas($where);
		//print_r($propostas);die;
		if(!$propostas)  $propostas = array();
		$this->view->propostas = $propostas;
	}

	public function listencontradosAction() {
		$this->getHelper('layout')->disableLayout();
		$where = $this->getFilterProposta();
		$Model = $this->getModel();
		$propostas = $Model->getEncontradas($where);
		if(!$propostas)  $propostas = array();
		$this->view->propostas = $propostas;
	}

	public function marcarAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$dados = $this->getRequest()->getParams();
		$Model = new Seguro_Model_ClienteProposta();
		$arr['id_cliente'] = $dados['id_cliente'];
		foreach($dados['id_proposta'] as $id_proposta) {
			$arr['id_proposta'] = $id_proposta;
			$Model->save($arr);
		}
		$this->getResponse()->setBody(Zend_Json::encode('1'));
	}

	public function desmarcarAction() {
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();
		$dados = $this->getRequest()->getParams();
		$Model = new Seguro_Model_ClienteProposta();
		$Model->delete($dados['id_cliente'], $dados['id_proposta']);
		$this->getResponse()->setBody(Zend_Json::encode('1'));
	}

	public function getFilterProposta() {
		$User = Zend_Auth::getInstance()->getIdentity();
		$where = array();

		if ($this->getRequest()->getParam('dt_inicio')) {
			$where[] = array(
				'field' => 'spr.dt_criacao',
				'operator' => '>=',
				'value' => Agro_Util::formatDate($this->getRequest()->getParam('dt_inicio'), Zend_Date::W3C)
			);
		}

		if ($this->getRequest()->getParam('dt_fim')) {
			$where[] = array(
				'field' => 'spr.dt_criacao',
				'operator' => '<=',
				'value' => Agro_Util::formatDate($this->getRequest()->getParam('dt_fim'), Zend_Date::W3C)
			);
		}

		if ($this->getRequest()->getParam('id_status')) {
			$where[] = array(
				'field' => 'spr.id_status',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_status')
			);
		}

		if ($this->getRequest()->getParam('id_produto')) {
			if ($this->getRequest()->getParam('id_safra')) {
				$where[] = array(
					'field' => 'ppr.id_safra',
					'operator' => '=',
					'value' => $this->getRequest()->getParam('id_safra')
				);
			}
			$where[] = array(
				'field' => 'spr.id_produto',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_produto')
			);
		}

		if ($this->getRequest()->getParam('vl_pesquisar_por')) {
			switch ($this->getRequest()->getParam('pesquisar_por')) {
				case 'ds_nome_proponente':
				case 'ds_cpf_proponente':
				    $field = "spt.".$this->getRequest()->getParam('pesquisar_por');
					$value = "%".$this->getRequest()->getParam('vl_pesquisar_por')."%";
					$operator = 'ilike';
					break;
				default:
				    $field = "spr.".$this->getRequest()->getParam('pesquisar_por');
					$value = $this->getRequest()->getParam('vl_pesquisar_por');
					$operator = '=';
					break;
			}

			$where[] = array (
				'field' => $field,
				'operator' => $operator,
				'value' => $value
			);

		}

		return $where;
	}

	public function relacionarclientesAction(){
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		$Adapter = new Zend_File_Transfer_Adapter_Http();
		$Adapter->setDestination(APPLICATION_PATH.'/upload_files/temp/');
		$file = $Adapter->getFileInfo();
		$result = 0;

		if(!$file['file']['name']) {
		    $this->getResponse()->setBody("<script>alert('Arquivo inválido!');window.top.window.stopUpload($result);</script>");
		    return false;
		} else {
			$extensao = explode('.',$file['file']['name']);

			if($extensao[1] == 'csv'){
				$arquivo = fopen($file['file']['tmp_name'],"r");
				$linha = 0;

				$Model = new Seguro_Model_ClienteProposta();

				//processa o csv
				while(($dados = fgetcsv($arquivo, 0, ";")) != false){
					for($i = 0; $i < count($dados); $i++){
						$result['id_cliente']  = !Agro_Util::filterVariable($dados[0])
							? 0
							: $dados[0];
						$result['id_proposta'] = !Agro_Util::filterVariable($dados[1])
							? 0
							: $dados[1];
					}

					//pula a primeira linha pois é cabeçalho
					if($linha > 0){
					    try {
					        $Model->save($result);
					    } catch (Exception $e) {
                		    $this->getResponse()->setBody("<script>alert('Erro ao relacionar clientes: ".$e->getCode()."'); window.top.window.stopUpload($result);</script>");
                		    return false;
					    }
					}
					$linha++;
				}
	  			fclose($arquivo);
			}else{
    		    $this->getResponse()->setBody("<script>alert('Formato de arquivo inválido!'); window.top.window.stopUpload($result);</script>");
    		    return false;
			}
		}
		$this->getResponse()->setBody("<script>alert('Processamento concluído com sucesso!'); window.top.window.stopUpload($result);</script>");
		return true;
	}

}