<?php

class Seguro_Model_PropostasDevolucoesArquivos extends Agro_Db_Table_Abstract {
	protected $_schema = 'seguro';
	protected $_name = 'propostas_devolucoes_arquivos';
	protected $_primary = 'id';
	public $_order = 'id';

    const FILE_PATH = APPLICATION_PATH . '/upload_files/propostas_devolucoes';

    /**
     * Insere um registro
     * 
     * @param array $dados
     * @return int
     */
    public function save(array $dados): int {  
        $row = $this->getRow($dados['id']);
        $row->id_proposta_devolucao = $dados['id_proposta_devolucao'];
        $row->ds_nome_arquivo = $dados['ds_nome_arquivo'];
        $id = $row->save();

        if (empty($id)) {
            throw new Exception("Erro salvar o arquivo.");
        }

        return $id; 
    }

    /**
     * Retorna os arquivos cadastrados para a devolução informada
     * 
     * @param int $idPropostaDevolucao
     * @return array
     */
    public function getArquivosByPropostaDevolucao(int $idPropostaDevolucao): array
    {
        $select = $this->select()->setIntegrityCheck(false);
        $select->from(array('ta' => 'seguro.propostas_devolucoes_arquivos'));
        $select->where("ta.id_proposta_devolucao = {$idPropostaDevolucao}");
        $select->order('ta.id desc');

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

    /**
     * Delete os arquivos fisicamente e do banco para o treinamento informado
     * @param int $id
     */
    public function deleteById(int $id)
    {
        $arquivo = $this->getRow($id);

        if (empty($arquivo['ds_nome_arquivo'])) {
            throw new Exception("Nenhum arquivo encontrado para o ID informado.");
        }

        $file = realpath(self::FILE_PATH . "/" . $arquivo['ds_nome_arquivo']);

        if (file_exists($file)) {
            unlink($file);
        }

        return $this->delete($id);
    }
}
