<?php

class Sistema_Model_TreinamentosArquivos extends Agro_Db_Table_Abstract
{
    protected $_schema = 'sistema';
    protected $_name = 'treinamentos_arquivos';
    protected $_primary = 'id';

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

    /**
     * Insere um registro
     * 
     * @param array $dados
     * @return int
     */
    public function save(array $dados): int {  
        $row = $this->getRow($dados['id']);
        $row->id_treinamento = $dados['id_treinamento'];
        $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/fotos cadastrados para o treinamento informado
     * 
     * @param int $idTreinamento
     * @return array
     */
    public function getArquivosByTreinamento(int $idTreinamento): array
    {
        $select = $this->select()->setIntegrityCheck(false);
        $select->from(array('ta' => 'sistema.treinamentos_arquivos'));
        $select->where("ta.id_treinamento = {$idTreinamento}");
        $select->order('ta.id desc');

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

    /**
     * Delete os arquivos fisicamente e do banco para o treinamento informado
     * @param int $id
     * @return int
     * @throws Exception
     */
    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);
    }

    /**
     * Delete os arquivos fisicamente e do banco para o treinamento informado
     * @param int $idTreinamento
     * @return bool|int
     */
    public function deleteByTreinamento(int $idTreinamento)
    {
        $arquivos = $this->getArquivosByTreinamento($idTreinamento);

        if (empty($arquivos)) {
            return true;
        }

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

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

        return $this->delete($idTreinamento, 'id_treinamento');
    }
}
