<?php

class Comercializacao_Model_TaxasValores extends Agro_Db_Table_Abstract {
	protected $_schema = 'comercializacao';
	protected $_name = 'taxas_valores';
	protected $_view = 'v_taxas_valores';
	protected $_primary = 'id';
	public $_order = array('ds_nome_cobertura', 'vl_franquia');

	public function save($post) {
		try {

			$Row = $this->getRow($post['id']);

			$Row->id_taxa_agrupamento = $post['id_taxa_agrupamento'];
			$Row->id_cobertura = $post['id_cobertura'];
			$Row->vl_franquia = $post['vl_franquia'];
			$Row->vl_taxa = $post['vl_taxa'];
			$Row->vl_produtividade_estimada = ($post['vl_produtividade_estimada'] ? $post['vl_produtividade_estimada'] : null);
			$Row->vl_taxa_renovacao = $post['vl_taxa_renovacao'];
			$Row->vl_taxa_inadimplente = $post['vl_taxa_inadimplente'];
			$Row->vl_taxa_reduzida = $post['vl_taxa_reduzida'];
			$Row->vl_percentual_subvencao_federal = ($post['vl_percentual_subvencao_federal'] ? $post['vl_percentual_subvencao_federal'] : '0.0');
			$Row->fl_franquia_disponivel = $post['fl_franquia_disponivel'];
			$Row->fl_ativo = ($post['fl_ativo'] ? 1 : 0);

			return $Row->save();
		} catch (Exception $e) {
			die($e);
		}
	}

	public function relacionaTaxas($data, $id) {
		if ($id) {
			$TaxasRelacionadas = new Comercializacao_Model_TaxasRelacionadas();
			$TaxasRelacionadas->delete($id, 'id_taxa');

			if (array_key_exists('id_taxa_relacionada', $data)) {
				$a = array();
				$a['id_taxa'] = $id;
				$a['id_taxa_relacionada'] = $data['id_taxa_relacionada'];

				$TaxasRelacionadas->insert($a);
			}
		}
	}

	public function relacionarTaxas($post, $id, $flApagar=false) {
		if ($id) {

			$this->_db->query("delete from comercializacao.taxas_relacionadas where id_taxa = {$id}");

			if(!$flApagar){
				if (!empty($post['relacionar']) && is_array($post['relacionar'])) {
					foreach ($post['relacionar'] as $relacionar) {
						$this->_db->query("insert into comercializacao.taxas_relacionadas (id_taxa, id_taxa_relacionada) values ($id, {$relacionar})");
					}
				}
			}
		}
	}

	public function getCoberturas(int $idProduto = null, int $idTaxaAgrupamento = null) {
		$Session = new Zend_Session_Namespace('agrupamento');
        $idProduto = !empty($idProduto) ? $idProduto : $Session->taxa['id_produto'];
        $idTaxaAgrupamento = !empty($idTaxaAgrupamento) ? $idTaxaAgrupamento : $Session->taxa['id'];

		$select = $this->select();
		$select->distinct(true);
		$select->setIntegrityCheck(false);
		$select->from(array('t' => 'comercializacao.taxas_valores'), array('id', 'vl_franquia'));
		$select->join(array('pc' => 'produto.produtos_coberturas'), 't.id_cobertura = pc.id_cobertura', false);
		$select->join(array('c' => 'produto.coberturas'), 'pc.id_cobertura = c.id', 'ds_nome_cobertura');
		$select->where('pc.fl_cobertura_principal is true', '');
		$select->where('pc.id_produto = ?', $idProduto);
		$select->where('t.id_taxa_agrupamento = ?', $idTaxaAgrupamento);
		$select->order(array('c.ds_nome_cobertura', 't.vl_franquia'));

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

	public function getShowCoberturas() {
		$Session = new Zend_Session_Namespace('agrupamento');

		$select = $this->select();
		$select->distinct(true);
		$select->setIntegrityCheck(false);
		$select->from(array('pc' => 'produto.produtos_coberturas'));
		$select->where('pc.id_produto = ?', $Session->taxa['id_produto']);
		$select->where('pc.fl_taxa_relacionada is true');

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

	public function getCoberturasRelacionadas($id) {
		$ret = array();

		if ($id) {
			$select = $this->select();
			$select->setIntegrityCheck(false);
			$select->from(array('t'=>'comercializacao.taxas_relacionadas'));
			$select->where('t.id_taxa = ?', $id);
			$Taxas = $this->fetchAll($select);

			if ($Taxas->count()) {
				foreach ($Taxas as $taxa) {
					$ret[] = $taxa['id_taxa_relacionada'];
				}
			}
		}

		return $ret;
	}

	public static function calculaMediaPonderadaCar(array $taxas): array
	{
		$totalLmga = 0;

		$totalSomaProdutosSubvensaoFederal = 
		$totalSomaProdutosTaxaRenovacao = 
		$totalSomaProdutosTaxaInadimplente =
		$totalSomaProdutosTaxaReduzida =
		$totalSomaProdutosTaxa =
		$totalSomaProdutosComissao = 0;

		foreach ($taxas as $valores) {
			$totalLmga += $valores['vl_lmga'];

			$totalSomaProdutosSubvensaoFederal += ($valores['vl_percentual_subvencao_federal'] / 100) * $valores['vl_lmga'];
			$totalSomaProdutosTaxaRenovacao += ($valores['vl_taxa_renovacao'] / 100) * $valores['vl_lmga'];
			$totalSomaProdutosTaxaInadimplente += ($valores['vl_taxa_inadimplente'] / 100) * $valores['vl_lmga'];
			$totalSomaProdutosTaxaReduzida += ($valores['vl_taxa_reduzida'] / 100) * $valores['vl_lmga'];
			$totalSomaProdutosTaxa += ($valores['vl_taxa'] / 100) * $valores['vl_lmga'];
			$totalSomaProdutosComissao += ($valores['vl_comissao'] / 100) * $valores['vl_lmga'];
		}
		
		return [
			'vl_comissao' => round($totalSomaProdutosComissao / $totalLmga, 4) * 100,
			'vl_taxa' => round($totalSomaProdutosTaxa / $totalLmga, 4) * 100,
			'vl_taxa_renovacao' =>round($totalSomaProdutosTaxaRenovacao / $totalLmga, 4) * 100,
			'vl_taxa_inadimplente' => round($totalSomaProdutosTaxaInadimplente / $totalLmga, 4) * 100,
			'vl_taxa_reduzida' =>round( $totalSomaProdutosTaxaReduzida / $totalLmga, 4) * 100,
			'vl_percentual_subvencao_federal' =>round( $totalSomaProdutosSubvensaoFederal / $totalLmga, 4) * 100
		];
	}

	public function getTaxa($agrupamento, $cobertura, $taxa, $flSomenteAtivos = false) {

		if (!is_array($cobertura)) {
			$cobertura = explode(',',$cobertura);
		}

		$or = array();
		foreach ($cobertura as $clause) {
			$or[] .= "(id_cobertura = $clause)";
		}
		$or = implode(' or ', $or);

		if ($agrupamento && $taxa && $cobertura) {
			$Select = $this->select();
			$Select->setIntegrityCheck(false);
			$Select->from(array('t'=>'comercializacao.taxas_valores'), '*');
			$Select->join(array('r'=>'comercializacao.taxas_relacionadas'), 't.id = r.id_taxa', false);
			$Select->where('t.id_taxa_agrupamento = ?', $agrupamento);
			$Select->where('r.id_taxa_relacionada = ?', $taxa);
			$Select->where($or, $taxa);

			if ($flSomenteAtivos) {
				$Select->where('t.fl_ativo = ?', true);
			}

			return $this->fetchAll($Select);
		} else {
			return false;
		}
	}

	public function beforeDelete($id_taxa) {
		//exclui as taxas relacionadas
		$sql = "delete from comercializacao.taxas_relacionadas where id_taxa_relacionada = $id_taxa";
		try {
			$this->_db->query($sql);
		}catch (Exception $e) {}

		$sql = "delete from comercializacao.taxas_relacionadas where id_taxa = $id_taxa";
		try {
			$this->_db->query($sql);
		}catch (Exception $e) {}

		$sql = "delete from comercializacao.taxas_agrupamento_proponentes where id_taxa_agrupamento = $id_taxa ";
		try {
			$this->_db->query($sql);
		}catch (Exception $e) {}

		$sql = "delete from comercializacao.taxas_agrupamento_usuarios where id_taxa_agrupamento = $id_taxa ";
		try {
			$this->_db->query($sql);
		}catch (Exception $e) {}

		$sql = "delete from comercializacao.taxas_agrupamento_municipios where id_taxa_agrupamento = $id_taxa ";
		try {
			$this->_db->query($sql);
		}catch (Exception $e) {}

		$sql = "delete from comercializacao.taxas_agrupamento_estados where id_taxa_agrupamento = $id_taxa ";
		try {
			$this->_db->query($sql);
		}catch (Exception $e) {}

		$sql = "delete from comercializacao.taxas_agrupamento_car where id_taxa_agrupamento = $id_taxa ";
		try {
			$this->_db->query($sql);
		}catch (Exception $e) {}
	}

	public function delete($id, $field='') {
		parent::delete($id, $field);


		$sql = "delete from comercializacao.taxas_agrupamento where id = $id";
		try {
			return $this->_db->query($sql);
		}catch (Exception $e) {
			return false;
		}


		return false;
	}

	public function getTaxasValoresByTaxaAgrupamento(int $idTaxaAgrupamento, int $idCobertura = null, int $id = null)
    {
        $select = $this->select()->setIntegrityCheck(false);
        $select->from('comercializacao.taxas_valores', '*');
        $select->join(['ta' => 'comercializacao.taxas_agrupamento'], 'ta.id = comercializacao.taxas_valores.id_taxa_agrupamento', ['vl_comissao']);
        $select->where('id_taxa_agrupamento = ?', $idTaxaAgrupamento);

        if (!empty($idCobertura)) {
            $select->where('id_cobertura = ?', $idCobertura);
        }

		if (!empty($id)) {
			$select->where('taxas_valores.id = ?', $id);
		}

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

	public function getTaxasTooltipOrderBy(int $idTaxa) {
		$query = 'SELECT v_taxas_valores.*
			FROM '.$this->_schema.'.'.$this->_view.'
				JOIN comercializacao.taxas_agrupamento ON taxas_agrupamento.id = v_taxas_valores.id_taxa_agrupamento
				JOIN produto.produtos ON produtos.id = taxas_agrupamento.id_produto
				JOIN produto.produtos_coberturas ON produtos_coberturas.id_produto = produtos.id
				AND produtos_coberturas.id_cobertura = v_taxas_valores.id_cobertura
			WHERE (id_taxa_agrupamento = '.$idTaxa.')
			ORDER BY
				produtos_coberturas.fl_cobertura_principal DESC,
				v_taxas_valores.ds_nome_cobertura,
				v_taxas_valores.vl_franquia';

		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($query);

	}
}
