<?php

class Sistema_Model_Status extends Agro_Db_Table_Abstract {
    const CORRETOR_AGUARDANDO_PENDENCIA = 'AGUARDANDO_PENDENCIA';
    const CORRETOR_ATUALIZACAO_CADASTRO = 'ATUALIZACAO_CADASTRO';
    const CORRETOR_CADASTRO_INICIAL = 'CADASTRO_INICIAL';
    const CORRETOR_CONCLUIDO_FINALIZADO = 'CONCLUIDO_FINALIZADO';
    const CORRETOR_EM_ANALISE = 'EM_ANALISE';
    const CORRETOR_EM_ANDAMENTO = 'EM_ANDAMENTO';
    const AGENDAMENTO_AGENDADO = 202;
    const AGENDAMENTO_AGENDAMENTO_CANCELADO = 203;
    const AGENDAMENTO_AGUARDANDO_DATA = 201;

	const DEVOLUCAO_PENDENCIA_CORRETOR = 288;

	const CH_NOVO = 58;
	const CH_ABERTO = 73;
    const CH_RESOLVIDO = 74;

	const AVISO_CANCELADO = 168;
	const AVISO_RECUSADO = 29;

    const LAUDOS_PRELIMINARES_CANCELADO = 206;
	const LAUDOS_PRELIMINARES_CANCELADO_CULPA_SEGURADOR = 208;
    const LAUDOS_PRELIMINARES_PENDENTE_ENVIO = 75;
    const LAUDOS_PRELIMINARES_ENVIADO = 76;
    const LAUDOS_PRELIMINARES_PENDENTE_LAUDO_PRELIMINAR = 210;

	const LF_PENDENTE_ENVIO = 109;
	const LF_ENVIADO = 110;
	const LF_ENVIADO_NAO_ASSINADO = 205;
    const LF_CANCELADO = 207;
    const LF_PENDENTE_LAUDO_FINAL = 211;

    const VP_AGUARDANDO_VISTORIA = 70;
    const VP_CANCELADA = 227;
    const VP_ENC = 66;
    const VP_TRANSMITIDA = 71;
    const VP_TRANSMITIDA_SEM_FOTOS = 226;
	const VP_DISPENSADA = 225;

    const SOLICITACAO_ENDOSSO_PENDENTE = 181;
    const SOLICITACAO_ENDOSSO_NAO_ANALISADO = 180;

	const RELATORIO_COBRANCA_CONFERIDO = 189;

	const ID_PROPOSTA_CANCELADA = 5;

	public $_order = array('id_tipo_status', 'cd_status');
	protected $_schema = 'sistema';
	protected $_name = 'status';
	protected $_primary = 'id';

	public $_columnExcel = array(
		'cd_status' => 'Cod.',
	    'ds_status' => 'Status',
		'ds_chave' => 'Chave',
	    'ds_tipo_status' => 'Tipo'
	);

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

		$Row->ds_status = $data['ds_status'];
		$Row->id_tipo_status = $data['id_tipo_status'];
		$Row->cd_status = $data['cd_status'];
		$Row->ds_chave = $data['ds_chave'];
		$Row->ds_cor = $data['ds_cor'];

		return $Row->save();
	}

	public function getId($chave, $tipo_status = null) {
		return $this->getIdStatus($chave, $tipo_status);
	}

	public static function isStatusLaudoPreliminarCancelado(int $id): bool
	{
		return in_array($id, [
			Sistema_Model_Status::LAUDOS_PRELIMINARES_CANCELADO,
			Sistema_Model_Status::LAUDOS_PRELIMINARES_CANCELADO_CULPA_SEGURADOR
		]);
	}

	/**
	 * Monta combo de status para o filtro da gerência de avisos
	 * @param $chave_tipo_status
	 */
	public function getComboGerenciaAvisoSinistro($chave_tipo_status = "SA")
    {
        //Busca a categoria do funcionário para validar quais opções ele tem acesso
        $chave_categoria = (new Sistema_Model_Funcionarios())->getCategoriaEmpresaByidUsuario(
            $this->_user->id
        )->ds_chave;

        $select = $this->select()->setIntegrityCheck(false);
        $select->from(array('s' => 'sistema.status'), array('*', 'ds_chave as ds_chave_status'));
        $select->join(array('tp' => 'sistema.tipo_status'), 'tp.id = s.id_tipo_status', 'ds_chave');
        $select->where('tp.ds_chave = ?', $chave_tipo_status);
        $select->where('s.fl_ativo=true');
        $select->order('s.cd_status');

        $row = $this->fetchAll($select);

        $options = array();
        $options[''] = "--- Selecione ---";

        foreach ($row as $status) {
            /**
             * Não deve ser apresentada a opção de filtrar status "Pendente - em análise" para o vistoriador
             */
            if (
                (int)$status->id === Sinistro2_Model_AvisosSinistro::ID_STATUS_SA_PENDENTE
                && Sistema_Model_Usuarios::isTipoUsuarioVistoriador(Zend_Auth::getInstance()->getIdentity()->tp_usuario)
            ) {
                continue;
            }

            // Valida para que a seguradora possa ter acesso somente a avisos ACEITOS e RECUSADOS
            if ($chave_categoria != 'SEGURADORA' || ($chave_categoria == 'SEGURADORA' && ($status->ds_chave_status == 'ACEITO' || $status->ds_chave_status == 'RECUSADO'))) {
                $options[$status->id] = $status->ds_status;
            }
        }

        return $options;
    }


	public function getChave($id){
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->distinct(true);
		$select->from(array('s'=>'sistema.status'), 's.ds_chave');
		$select->where('s.id = ?', $id);

		return $this->getAdapter()->fetchOne($select);
	}

	public function getNameById($id){
		$Row = $this->getRow($id);
		return $Row->ds_status;
	}

	public function getCombo($type='', $flRestrito=false, $flComposto=false) {
		$Select = $this->select()->setIntegrityCheck(false)->distinct();
		$Select->from(array('s' => 'sistema.status'), array('id', 'cd_status', 'ds_status'));
		$Select->join(array('t' => 'sistema.tipo_status'), 's.id_tipo_status = t.id', false);
		$Select->where('t.ds_chave = ?', $type);
		$Select->where('s.fl_ativo = true');
		$Select->where('t.fl_ativo = true');

		if ((Zend_Auth::getInstance()->getIdentity()->ds_chave != 'ADMIN' && !Agro_Util::checkPermission(Atendimento_Model_Proposta::ACAO_TODOSSTATUSPROPOSTACOMBO)) && $type == 'PR' && $flRestrito == true) {
			$Select->where("s.ds_chave not in ('ENDOSSO_INCOMPLETO','ORCAMENTO_ENDOSSO','AGUARDANDO_EMISSAO','APOLICE_EMITIDA','ENDOSSO_AGUARDANDO_ENVIO_SEG','NAO_ENVIADA','DEVOLVIDA','CONF_PENDENCIAS','ENVIADA_AGUARDANDO_CONF', 'SOLICITACAO_CANCELADA')");
		}

		$Select->order('cd_status');
		$Rs = $this->fetchAll($Select);

		$options = $flComposto ? array() : array('');
		if ($Rs->count()) {
			foreach ($Rs as $row) {
				$options[$row['id']] = $row['cd_status']." - ".$row['ds_status'];
			}

			return $options;
		} else {
			return array();
		}
	}

	public function getComboVistoriaSolicitacao($type='', $flRestrito=false, $flComposto=false) {
		$Select = $this->select()->setIntegrityCheck(false)->distinct();
		$Select->from(array('s' => 'sistema.status'), array('id', 'cd_status', 'ds_status'));
		$Select->join(array('t' => 'sistema.tipo_status'), 's.id_tipo_status = t.id', false);
		$Select->where('t.ds_chave = ?', $type);
		$Select->where('s.cd_status <> 4'); //retira a Digitalização Finalizada/Transmitida pq não pode mais encaminhá-la
		$Select->where('s.fl_ativo = true');
		$Select->where('t.fl_ativo = true');

		if ((Zend_Auth::getInstance()->getIdentity()->ds_chave != 'ADMIN' && Zend_Auth::getInstance()->getIdentity()->ds_nome_usuario != 'karina.silva') && $type == 'PR' && $flRestrito == true) {
			$Select->where("s.ds_chave not in ('ENDOSSO_INCOMPLETO','ORCAMENTO_ENDOSSO','AGUARDANDO_EMISSAO','APOLICE_EMITIDA','ENDOSSO_AGUARDANDO_ENVIO_SEG','NAO_ENVIADA','DEVOLVIDA','CONF_PENDENCIAS','ENVIADA_AGUARDANDO_CONF', 'SOLICITACAO_CANCELADA')");
		}

		$Select->order('cd_status');
		$Rs = $this->fetchAll($Select);

		$options = $flComposto ? array() : array('');
		if ($Rs->count()) {
			foreach ($Rs as $row) {
				$options[$row['id']] = $row['cd_status']." - ".$row['ds_status'];
			}

			return $options;
		} else {
			return array();
		}
	}


	public function getComboSimples($type = '', $order = 'cd_status', $flagIsMultipleSelect = false) {
		$Select = $this->select()->setIntegrityCheck(false)->distinct();
		$Select->from(array('s' => 'sistema.status'), array('id', 'cd_status', 'ds_status'));
		$Select->join(array('t' => 'sistema.tipo_status'), 's.id_tipo_status = t.id', false);

		if (!empty($type)) {
			$Select->where('t.ds_chave = ?', $type);
		}

		$Select->where('s.fl_ativo = true');
		$Select->where('t.fl_ativo = true');

		$Select->order($order);

		$Rs = $this->fetchAll($Select);

		$options = $flagIsMultipleSelect ? [] : array('');
		if ($Rs->count()) {
			foreach ($Rs as $row) {
				$options[$row['id']] = $row['ds_status'];
			}

			return $options;
		} else {
			return array();
		}
	}


    public function getComboStatusArquivos($type='') {
        $Select = $this->select()->setIntegrityCheck(false)->distinct();
        $Select->from(array('s' => 'sistema.status'), array('id', 'cd_status', 'ds_status', 'ds_chave'));
        $Select->join(array('t' => 'sistema.tipo_status'), 's.id_tipo_status = t.id', false);
        $Select->where('t.ds_chave = ?', $type);
        $Select->where('s.fl_ativo = true');
        $Select->where('t.fl_ativo = true');
        $Select->order('cd_status');
        $Rs = $this->fetchAll($Select);

        $options = array();
        if ($Rs->count()) {
            foreach ($Rs as $row) {
                $options[] = array(
                    'id_status' => $row['id'],
                    'cd_status' => $row['cd_status'],
                    'ds_status' => $row['ds_status'],
                    'ds_chave' => $row['ds_chave'],
                );
            }

            return $options;
        } else {
            return array();
        }
    }

	public function getComboCodigo($type='') {
		$idTipoStatus = $this->getIdTipoStatus($type);

		$Rs = $this->fetchAll("id_tipo_status = $idTipoStatus", 'cd_status');
		$field = '';

		$options = array();
		if ($Rs->count()) {
			$field = $field ? $field : $this->_order;
			$options['0'] = ' ';
			$options['1'] = 'Não Encaminhada';
			foreach ($Rs as $row) {
				$options[$row['id']] = $row['ds_status'];
			}

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

	public function getComboCodigoEmpresa($type='') {
		$idTipoStatus = $this->getIdTipoStatus($type);

		$Rs = $this->fetchAll("id_tipo_status = $idTipoStatus", 'cd_status');
		$field = '';

		$options = array();
		if ($Rs->count()) {
			$field = $field ? $field : $this->_order;
			$options['0'] = ' ';
			foreach ($Rs as $row) {
				$options[$row['id']] = $row['ds_status'];
			}

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

	public function getComboTipo($tipo) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from('sistema.status', array('id', 'ds_status'));
		$Select->join('sistema.tipo_status', 'status.id_tipo_status = tipo_status.id', false);
		$Select->where('tipo_status.ds_chave = ?', $tipo);
		$Select->order('ds_status');

		return $this->getDefaultAdapter()->fetchPairs($Select);
	}

	public function getComboTipoStatus() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from('sistema.tipo_status');
		$Select->order('ds_tipo_status');
		$Rs = $this->fetchAll($Select);

		$options = array();
		if ($Rs) {
			$options = array('');
			foreach ($Rs as $row) {
				$options[$row['id']] = $row['ds_tipo_status'];
			}

			return $options;
		} else {
			return array();
		}
	}

	public function getIdTipoStatus($type) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->distinct(true);
		$select->from(array('ts'=>'sistema.tipo_status'), 'ts.id');
		$select->where('ts.ds_chave = ?', $type);

		return $this->getAdapter()->fetchOne($select);
	}

	public function getListStatus($dsChave) {
		$select = $this->select();
		$select->setIntegrityCheck(false);

		$select->from(array('s'=>'sistema.status'), array('*', 'ds_chave as ds_chave_status'));
		$select->join(array('tp'=>'sistema.tipo_status'), 'tp.id = s.id_tipo_status', 'ds_chave');

		$select->where('tp.ds_chave = ?', $dsChave);
		$select->where('s.fl_ativo=true');
		$select->order('s.cd_status');

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

	public function getByProposta($idProposta) {
		$select = $this->select();
		$select->setIntegrityCheck(false);

		$select->from(array('s'=>'sistema.status'), array('*'));
		$select->join(array('p'=>'seguro.propostas'), 'p.id_status = s.id', 'p.id as id_proposta');

		$select->where('p.id = ?', $idProposta);

		return $this->getAdapter()->fetchRow($select);
	}

	public function getData($where=false) {
		$select = $this->select()->setIntegrityCheck(false);
		$select->from(array('s' => "sistema.status"));
		$select->joinLeft(array('ts' => 'sistema.tipo_status'), 's.id_tipo_status = ts.id', 'ds_tipo_status');

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

					$select->where("$field $operator ?", $value);
				} else {
					$select->where($clause, '');
				}
			}
		} elseif ($where != '') {
			$select->where($where);
		}

		$select->order($this->_order);
		return $select;
	}

	public function getCodigoById ($idStatus) {
        $select = $this->select();
        $select->setIntegrityCheck(false);

        $select->from(array('s'=>'sistema.status'), 'cd_status');
        $select->where('s.id = ?', $idStatus);

        return $this->getAdapter()->fetchOne($select);
	}

	public function getOptions($Rs) {
		$options = array();
		$options[''] = '';

		foreach($Rs as $Row){
			$options[$Row['id']] = $Row['ds_status'];
		}

		return $options;
	}

	public function getByIdTipo($tipo){
        $select = $this->select();
        $select->setIntegrityCheck(false);

        $select->from(array('s'=>'sistema.status'));
        $select->where('s.id_tipo_status = ?', $tipo);
		$select->order('ds_status');

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

		$options = array();
		if ($Rs) {
			$options = array('');
			foreach ($Rs as $row) {
				$options[$row['id']] = $row['ds_status'];
			}

			return $options;
		} else {
			return array();
		}

	}


	public function getComboByChaveTipo($ds_chave,$id_tipo,$ismutiple=false,$where=null) {
		$Select = $this->select()->setIntegrityCheck(false)->distinct();
		$Select->from(array('s' => 'sistema.status'), array('id', 'cd_status', 'ds_status'));
		$Select->join(array('t' => 'sistema.tipo_status'), 's.id_tipo_status = t.id', false);
		$Select->where('t.ds_chave = ?', $ds_chave);
		$Select->where('s.id_tipo_status = ?', $id_tipo);
		$Select->where('s.fl_ativo = true');
		$Select->where('t.fl_ativo = true');
		if ($where) {
			$Select->where($where);
		}
		$Select->order('cd_status');
		$Rs = $this->fetchAll($Select);

		if ($ismutiple) { $options = array(); } else { $options = array(''); }

		if ($Rs->count()) {
			foreach ($Rs as $row) {
				$options[$row['id']] = $row['cd_status']." - ".$row['ds_status'];
			}

			return $options;
		} else {
			return array();
		}
	}

	public function getIdByTipoChaveCodigo($tipoChave, $codigo){
		$select = $this->select()->setIntegrityCheck(false);
		$select->from(array("s" => $this->_schema.".".$this->_name),'id');
		$select->join(array("ts" => "sistema.tipo_status"),'s.id_tipo_status = ts.id', false);
		$select->where("ts.ds_chave = ?", $tipoChave);
		$select->where("s.cd_status = ?", $codigo);

		return $this->_db->fetchOne($select);
	}

	public function getIdByChaveTipoChave($chave, $tipoChave){
		$select = $this->select()->setIntegrityCheck(false);
		$select->from(array("s" => $this->_schema.".".$this->_name),'id');
		$select->join(array("ts" => "sistema.tipo_status"),'s.id_tipo_status = ts.id', false);
		$select->where("ts.ds_chave = ?", $tipoChave);
		$select->where("s.ds_chave = ?", $chave);

		return $this->_db->fetchOne($select);
	}

    public function getDadosStatusByChaveTipoStatus(string $chaveTipoStatus) : Zend_Db_Table_Rowset_Abstract
    {
        $select = $this->select()
            ->setIntegrityCheck(true)
            ->from(['ss' => 'sistema.status'], ['id', 'ds_chave'])
            ->join(['stp' => 'sistema.tipo_status'], 'stp.id = ss.id_tipo_status', false)
            ->where('stp.ds_chave = ?', $chaveTipoStatus);

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