<?php

class Produto_Model_CondicoesPagamento extends Agro_Db_Table_Abstract {
	protected $_schema = 'produto';
	protected $_name = 'condicoes_pagamento';
	protected $_view = 'v_condicoes_pagamento';
	protected $_primary = 'id';
	public 	  $_order = 'fl_condicao_padrao desc';

	public $executeJsAfterDelete = '$.listCondicoesPagamento';

	public function save(array $values) {
		try {
			$Row = $this->getRow($values['id']);

			if ($values['fl_condicao_padrao']) {
				$this->update(array('id_usuario_alteracao' => Zend_Auth::getInstance()->getIdentity()->id, 'dt_alteracao' => 'now()', 'fl_condicao_padrao' => 0), "id_produto = {$values['id_produto']}");
			}

			$Row->id_produto = $values['id_produto'];
			$Row->ds_nome_condicao = $values['ds_nome_condicao'];
			$Row->fl_condicao_padrao = ($values['fl_condicao_padrao'] ? 1 : 0);
			$Row->fl_data_flexivel = ($values['fl_data_flexivel'] ? 1 : 0);
			$Row->fl_percentual_flexivel = ($values['fl_percentual_flexivel'] ? 1 : 0);
			$Row->fl_inadimplentes = ($values['fl_inadimplentes'] ? 1 : 0);
			$Row->fl_fixar_parcela_maxima = ($values['fl_fixar_parcela_maxima'] ? 1 : 0);
			$Row->tp_grupo = ($values['tp_grupo'] ? $values['tp_grupo'] : null);
			$Row->fl_selecao_data = ($values['fl_selecao_data']) ? 1 : 0;
			if($values['id']){
				if (!$values['fl_data_flexivel'] && !$values['fl_percentual_flexivel']) {
					$list = $this->getItens($values['id']);
					if (count($list) > 0) {
						$ItensOpcoes = new Produto_Model_CondicoesPagamentoItensOpcoes();
						foreach ($list as $item) {
							$ItensOpcoes->delete($item['id']);
						}
					}
				 }
			}

			$Row->save();
            return $Row->id;
			//$this->getAdapter()->commit();

		} catch (Exception $e) {
			// $this->getAdapter()->rollBack();
			return false;
		}

	}

	public function getCombo($nofirst=true) {
		$idProduto = new Zend_Session_Namespace('id_produto');

		$select = $this->select();
		$select->where("fl_ativo = true");
		$select->order('ds_nome_condicao');

		if ($idProduto->value) {
			$select->where('id_produto = ?', $idProduto->value);
		}

		$Rs = $this->fetchAll($select)->toArray();

		$options = array();
		if (is_array($Rs)) {
			if ($nofirst) {
				$options[] = null;
			}

			foreach ($Rs as $row) {
				$options[$row['id']] = $row[$this->_order];
			}

			return $options;
		} else {
			return false;
		}
	}

	public function checkPrincipal($idProduto, $idCondicao) {
		$Row = $this->fetchRow("id_produto = $idProduto and fl_condicao_padrao = true");

		if ($Row) {
			return true;
		} else {
			return false;
		}
	}

	public function getData($where=null){
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from("{$this->_schema}.{$this->_name}");
		$select->order($this->_order);

		if (is_array($where)) {
			foreach ($where as $clause) {
				$field = $clause['field'];
				$operator = $clause['operator'];
				$value = $clause['value'];

				$select->where("$field $operator ?", $value);
			}
		} else {
			$select->where($where);
		}

		$rs = $this->fetchAll($select)->toArray();

		$return = array();
		if (is_array($rs)) {
			foreach ($rs as $row) {
				$row['itens'] = $this->getItens($row['id']);
				$return[] = $row;
			}
		}

		return $return;
	}

	public function getItens($idCondicaoPagamento) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from("produto.condicoes_pagamento_itens");
		$select->where("id_condicao_pagamento = ?", $idCondicaoPagamento);
		$select->order(array('ds_mes ASC', 'ds_ano ASC'));

		return $this->fetchAll($select)->toArray();
	}

	public function getParcelamentoProposta($idProduto, $idCorretor, $idPreposto, $CpfCnpj) {
		$Rs = false;

		if ($CpfCnpj) {
			$Rs = $this->getParcelamentoProponente($CpfCnpj, $idProduto) or false;
		}

		if (!$Rs) {
			if ($idPreposto) {
				$Rs = $this->getParcelamentoUsuario($idPreposto, $idProduto) or false;
			}
		}

		if (!$Rs) {
			if ($idCorretor) {
				$Rs = $this->getParcelamentoUsuario($idCorretor, $idProduto);
			}
		}

		if (!$Rs) {
			$Rs = $this->getParcelamentoDefault($idProduto);
		}


		if ($Rs) {
			return $Rs->toArray();
		} else {
			return false;
		}
	}

	public function getParcelamentoDefault($idProduto) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('cp' => 'produto.condicoes_pagamento'));
		$Select->join(array('cpi' => 'produto.condicoes_pagamento_itens'), 'cp.id = cpi.id_condicao_pagamento');
		$Select->where('cp.id_produto = ?', $idProduto);
		$Select->where('cp.fl_condicao_padrao = ?', true);
		$Select->where('cpi.ds_mes = ?', date('m')-1);
		$Select->where('cpi.ds_ano = ?', date('Y'));

		return $this->fetchRow($Select);
	}

	public function getParcelamentoProponente($cpfCnpj, $idProduto) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('cp' => 'produto.condicoes_pagamento'));
		$Select->join(array('cpi' => 'produto.condicoes_pagamento_itens'), 'cp.id = cpi.id_condicao_pagamento');
		$Select->join(array('cpp' => 'produto.condicoes_pagamento_proponentes'), 'cp.id = cpp.id_condicao_pagamento');
		$Select->join(array('p' => 'seguro.proponentes'), 'cpp.id_proponente = p.id', null);
		$Select->where('p.cpf_cnpj = ?', $cpfCnpj);
		$Select->where('cp.id_produto = ?', $idProduto);
		$Select->where('cpi.ds_mes = ?', date('m')-1);
		$Select->where('cpi.ds_ano = ?', date('Y'));

		return $this->fetchRow($Select);
	}

	public function getParcelamentoUsuario($idUsuario, $idProduto) {
		$Select = $this->select();
		$Select->setIntegrityCheck(false);
		$Select->from(array('cpu' => 'produto.condicoes_pagamento_usuarios'));
		$Select->join(array('cp' => 'produto.condicoes_pagamento'), 'cp.id = cpu.id_condicao_pagamento');
		$Select->join(array('cpi' => 'produto.condicoes_pagamento_itens'), 'cp.id = cpi.id_condicao_pagamento');
		$Select->where('cpu.id_usuario = ?', $idUsuario);
		$Select->where('cp.id_produto = ?', $idProduto);
		$Select->where('cpi.ds_mes = ?', date('m')-1);
		$Select->where('cpi.ds_ano = ?', date('Y'));
		return $this->fetchRow($Select);
	}

	public function geraPadrao($idProduto) {
		$values = array();
		$values['id_produto'] = $idProduto;
		$values['ds_nome_condicao'] = 'Padrão';
		$values['fl_condicao_padrao'] = 1;
		$values['fl_data_flexivel'] = 0;
		$values['fl_percentual_flexivel'] = 0;
		$values['fl_inadimplentes'] = 0;
		
		$idCondicaoPagamento = $this->save($values);
		if ($idCondicaoPagamento) {
			$CondicaoPagamentoItens = new Produto_Model_CondicoesPagamentoItens();
			$CondicaoPagamentoItens->geraPadrao($idCondicaoPagamento);

		}
	}

	public function fetchCondicoes($where) {
		$Select = $this->select()->where($where);
		return $this->fetchAll($Select);
	}

	public function copiarCondicao($origem, $destino) {
		$Rs = $this->fetchAll(" id_produto = $origem");

		$CondicaoPagamentoItens = new Produto_Model_CondicoesPagamentoItens();

		foreach($Rs as $condicao) {
			$arr = array();
			$arr['id_produto'] = $destino;
			$arr['ds_nome_condicao'] = $condicao['ds_nome_condicao'];
			$arr['fl_condicao_padrao'] = $condicao['fl_condicao_padrao'];
			$arr['fl_data_flexivel'] = $condicao['fl_data_flexivel'];
			$arr['fl_percentual_flexivel'] = $condicao['fl_percentual_flexivel'];
			$arr['fl_inadimplentes'] = $condicao['fl_inadimplentes'];
			$arr['fl_fixar_parcela_maxima'] = $condicao['fl_fixar_parcela_maxima'];
			
			$CondPagto = $this->insert($arr);
			$RsItens = $CondicaoPagamentoItens->fetchAll("id_condicao_pagamento = {$condicao['id']}");
			if($RsItens) {
				foreach($RsItens as $itens) {
					$arr = array();
					$arr['id_condicao_pagamento'] = $CondPagto->id;
					$arr['nr_parcelas'] = $itens['nr_parcelas'];
					$arr['ds_ano'] = $itens['ds_ano'];
					$arr['ds_dia_preferencial'] = $itens['ds_dia_preferencial'];
					$arr['ds_mes'] = $itens['ds_mes'];
					$CondicaoPagamentoItens->insert($arr);
				}
			}
		}
	}

	public function beforeDelete($id, $field) {
		if ($field == 'id_produto') {
			$Rs = $this->fetchAll("id_produto = $id");
			if ($Rs->count()) {
				$id = array();
				foreach ($Rs as $Row) {
					$id[] = $Row->id;
				}
			}
		}
		
		try {
			$condicoesPagamentoItens = new Produto_Model_CondicoesPagamentoItens();
			$condicoesPagamentoItensOpcoes = new Produto_Model_CondicoesPagamentoItensOpcoes();
			
			$idsCondicaoPagamento = is_array($id) ? implode(',', $id) : $id;
			$rsItens = $condicoesPagamentoItens->fetchAll("id_condicao_pagamento IN ({$idsCondicaoPagamento})");
			
			foreach ($rsItens as $row) {
				$condicoesPagamentoItensOpcoes->delete($row->id, 'id_condicao_pagamento_item');
			}

			$Model = new Produto_Model_CondicoesPagamentoItens();
			$Model->delete($id, 'id_condicao_pagamento');

			$Model = new Produto_Model_CondicoesPagamentoUsuarios();
			$Model->delete($id, 'id_condicao_pagamento');

			$Model = new Produto_Model_Condicaopagamentoproponente();
			$Model->delete($id, 'id_condicao_pagamento');
		} catch (Exception $e) {
		    die($e);
			$this->setMessage("Não foi possível deletar as condições de pagamento, existem dependências que impedem a operação");
			return false;
		}
	}
}
