<?php

declare(strict_types=1);

class Seguro_Model_PropriedadeCarRestricao extends Agro_Db_Table_Abstract
{
    protected $_name = 'propriedade_car_restricao';
	protected $_schema = 'seguro';
	protected $_primary = 'id';
    public $_columnExcel = [
		'ds_car' => 'Número da Propriedade (CAR)',
		'ds_descricao' => 'Descrição',
    	'ds_orientacao' => 'Orientação'
    ];

    public function save(array $dados): Zend_Db_Table_Row_Abstract
    {
        $row = $dados['id']
            ? $this->getRow($dados['id'])
            : $this->createRow();
        
        $propriedadeCarRestricao = $this->fetchRow("ds_car = '{$dados['ds_car']}'");
        $id = !empty($propriedadeCarRestricao) ? $propriedadeCarRestricao['id'] : null;

        if (!empty($id) && $id != $dados['id']) {
            throw new Exception('Já existe restrição cadastrada para esse CAR.');
        }
        
        $row->ds_car = Agro_Util::carUnmask($dados['ds_car']);
        $row->id_orientacao_restricao_tecnica = $dados['id_orientacao_restricao_tecnica'];
        $row->ds_descricao = $dados['ds_descricao'];

        $rs = $row->save();

        if(!$rs) {
            throw new Exception('Erro ao salvar restrição da Propriedade CAR');
        }

        return $row;
    }

    public function getData($where=false) {
		$select = $this->select()
            ->setIntegrityCheck(false)
            ->from(['spcr' => "{$this->_schema}.{$this->_name}"])
            ->join(
                ['ort' => 'seguro.orientacao_restricao_tecnica'],
                'ort.id = spcr.id_orientacao_restricao_tecnica',
                'ds_orientacao'
            );
        
		$this->getWhere($select, $where);
		
		return $select;
	}

    public function getByIdTaxaAgrupamento(int $idTaxaAgrupamento): array
    {
        $sql = $this->select()
            ->setIntegrityCheck(false)
            ->from(['spcr' => "{$this->_schema}.{$this->_name}"])
            ->join(['ctac' => 'comercializacao.taxas_agrupamento_car'], 'ctac.ds_car = spcr.ds_car', false)
            ->where('ctac.id_taxa_agrupamento = ?', $idTaxaAgrupamento);

        return $this->fetchRow($sql)->toArray();
    }

    public function findRestricoes(array $numerosCar): array
	{
		return $this->fetchAll(
			$this->select()
				->setIntegrityCheck(false)
				->from(['spcr' => "{$this->_schema}.{$this->_name}"])
				->where('ds_car IN (?)', $numerosCar)
		)->toArray();
	}

    public function findRestricoesByIdProposta(int $idProposta): array
    {
        $sql = $this->select()
            ->setIntegrityCheck(false)
            ->from(['spcr' => "{$this->_schema}.{$this->_name}"], 'spcr.id_orientacao_restricao_tecnica, spcr.ds_car, spcr.ds_descricao')
            ->join(['sisc' => 'seguro.itens_segurados_car'], 'sisc.ds_car = spcr.ds_car', false)
            ->join(['sis' => 'seguro.itens_segurados'], 'sis.id = sisc.id_item_segurado', false)
            ->where('sis.id_proposta = ?', $idProposta)
            ->group('spcr.ds_car, spcr.id_orientacao_restricao_tecnica, spcr.ds_descricao');
        
        return $this->fetchAll($sql)->toArray();
    }
}