<?php

class Seguro_Model_PropostasCroquis extends Agro_Db_Table_Abstract
{
    protected $_log = true;
    protected $_schema = 'seguro';
    protected $_name = 'propostas_croquis';
    protected $_primary = 'id';

    public function save($dados) {

        $Row = $this->getRow($dados['id']);
        
        if (!$Row) {
            $Row = $this->createRow();
        }

        $Row->id_proposta = $dados['id_proposta'];
        $Row->ds_nome_arquivo = $dados['ds_nome_arquivo'];
        $Row->fl_vigente = $dados['fl_vigente'];

        $Row->save();

        return $Row->id;
    }

    public function delete($id_proposta) {
        try {
            if ($id_proposta) {
                $this->_db->query("delete from seguro.propostas_croquis where id_proposta = $id_proposta");
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }

        return true;
    }

    public function deleteName($id_proposta, $ds_nome_arquivo) { 
        try {
            if ($id_proposta and $ds_nome_arquivo) {
                $this->_db->query("delete from seguro.propostas_croquis where id_proposta = $id_proposta and ds_nome_arquivo = '$ds_nome_arquivo'" );
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    public function getNomeArquivoCroqui($id_proposta) {
        $select = $this->select()->setIntegrityCheck(false);
        $select->from(array('pc' => 'seguro.propostas_croquis'), 'ds_nome_arquivo');
        $select->where('pc.fl_vigente is true');
        $select->where('pc.id_proposta = ?', $id_proposta); 
        $nome = $this->getAdapter()->fetchOne($select);

        return $nome ? $nome : null;
    }

    public function getCroquis($id_proposta, $order = '') {
        $select = $this->select()->setIntegrityCheck(false);
        $select->from(array('pc' => 'seguro.propostas_croquis'), array('id','ds_nome_arquivo'));
        $select->join(array('pct' => 'seguro.propostas_croquis_talhoes'), 'pc.id = pct.id_croqui', 
            array("trim(regexp_replace(ds_nome, '\s+', '', 'g')) as ds_nome", 'fl_area', 'ds_coordenadas', 'ds_item_segurado','ds_coordenadas_centroide'));
        $select->where('pc.fl_vigente is true');
        $select->where('pc.id_proposta = ?', $id_proposta);

        if (!empty($order)) {
            $select->order($order);
        }
        return $this->getAdapter()->fetchAll($select);
    }

    public function getCroquisSolicitacao($id_solicitacao) {
        $select = $this->select()->setIntegrityCheck(false)
            ->from(array('pc' => 'seguro.propostas_croquis'), array('id','ds_nome_arquivo'))
            ->join(array('pct' => 'seguro.propostas_croquis_talhoes'), 'pc.id = pct.id_croqui', 
                array("trim(regexp_replace(ds_nome, '\s+', '', 'g')) as ds_nome", 'fl_area', 'ds_coordenadas', 'ds_item_segurado'))
            ->join(array('pesc' => 'seguro.propostas_endosso_solicitacao_croqui'), 'pc.id = pesc.id_croqui', false)
            ->where('pesc.id_solicitacao = ?', $id_solicitacao);
        return $this->getAdapter()->fetchAll($select);
    }

    /*
    * recupera o croqui mais atual não vigente da proposta
    */
    public function getLastInsertCroqui($id_proposta) {

        $select = $this->select()->setIntegrityCheck(false);
        $select->from(array('pct' => 'seguro.propostas_croquis_talhoes'), 
            array("trim(regexp_replace(ds_nome, '\s+', '', 'g')) as ds_nome",'fl_area','  ds_coordenadas', 'ds_item_segurado'));
        $select->join(array('pc' => new Zend_Db_Expr('(' .
            $this->select()->setIntegrityCheck(false)
            ->from(array('s' => 'seguro.propostas_croquis'), array('id', 'ds_nome_arquivo'))
            ->where('id_proposta = ?', $id_proposta)
            ->where('fl_vigente is false')
            ->order('dt_criacao DESC')
            ->limit(1)        
        . ')') ), 'pc.id = pct.id_croqui', 'ds_nome_arquivo');
        return $this->getAdapter()->fetchAll($select);
    }

    /*
    * copia o croqui para o endosso
    */
    public function copiaCroquiGeo($id_proposta, $id_endosso)
    {
        // @todo adicionar verificação se existe croqui na solicitação de endosso
        $croqui = $this->fetchAll('id_proposta = ' . $id_proposta . ' and fl_vigente = true')->current();

        if ($croqui) {
            $croquiTalhoes = new Seguro_Model_PropostasCroquisTalhoes();
            $talhoes = $croquiTalhoes->fetchAll('id_croqui = ' . $croqui->id);

            $rowCroqui = $this->createRow();
            $rowCroqui->id_proposta = $id_endosso;
            $rowCroqui->ds_nome_arquivo = $croqui->ds_nome_arquivo;
            $rowCroqui->fl_vigente = 't';

            if ($rowCroqui->save()) {
                foreach ($talhoes as $talhao) {
                    $ids_item = $this->updateRefItemSegurado($talhao->ds_item_segurado, $id_endosso);

                    $rowTalhao = $croquiTalhoes->createRow();
                    $rowTalhao->id_croqui = $rowCroqui->id;
                    $rowTalhao->ds_nome = $talhao->ds_nome;
                    $rowTalhao->fl_area = $talhao->fl_area;
                    $rowTalhao->ds_coordenadas = $talhao->ds_coordenadas;
                    $rowTalhao->ds_item_segurado = $ids_item !== '' ? $ids_item : $talhao->ds_item_segurado;
                    $rowTalhao->ds_coordenadas_centroide = $talhao->ds_coordenadas_centroide;

                    if (!$rowTalhao->save()) {
                        $rowCroqui->delete($rowCroqui->id);
                        return false;
                    }
                }
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    /*
    * atualiza a referência do item com o polígono no endosso
    */
    private function updateRefItemSegurado(string $ds_item_segurado,int $id_endosso) : string {
        $res = array();
        $items = explode(',', $ds_item_segurado);

        foreach ($items as $it) {
            $sub = new Zend_Db_Expr(
                $this->select()->setIntegrityCheck(false)
                    ->from(array('its' => 'seguro.itens_segurados'), array('nr_item_segurado'))
                    ->where('id = ?', $it)
            );

            $select = $this->select()->setIntegrityCheck(false)
                ->from(array('it' => 'seguro.itens_segurados'), array('id'))
                ->where('nr_item_segurado = ('.$sub.')')
                ->where('id_proposta = ?', $id_endosso);

            array_push($res, $this->fetchAll($select)->current()->id);
        }

        return implode(',', $res); 
    }
}