<?php

class Sistema_Model_EmpresaArquivos extends Agro_Db_Table_Abstract {
	protected $_name = 'empresas_arquivos';
	protected $_schema = 'sistema';
	protected $_primary = 'id';
	
	public function save(array $data, $file) {
		$Row = $this->getRow($data['id']);
		
		$Row->id_tipo_arquivo = $data['id_tipo_arquivo'];
		$Row->ds_nome_arquivo = $file['new_name'];
		$Row->id_empresa = $data['id_empresa'];
		
		return $Row->save();
	}
	
	public function getArquivos($idEmpresa) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('a' => 'sistema.empresas_arquivos'));
		$Select->join(array('t' => 'sistema.tipo_arquivo_empresa'), 'a.id_tipo_arquivo = t.id', 'ds_tipo_arquivo');
		$Select->where('a.id_empresa = ?', $idEmpresa);
		$Select->order('ds_tipo_arquivo');
		
		return $this->fetchAll($Select);
	}

	public function getArquivosByChaveTipo($idEmpresa, $chaveTipoArquivo) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('a' => 'sistema.empresas_arquivos'));
		$Select->join(array('t' => 'sistema.tipo_arquivo_empresa'), 'a.id_tipo_arquivo = t.id', 'ds_tipo_arquivo');
		$Select->where('a.id_empresa = ?', $idEmpresa);
		$Select->where('t.ds_chave_tipo_arquivo = ?', $chaveTipoArquivo);
		$Select->order('ds_tipo_arquivo');
		
		//busca um somente pois deve ter somente um logo para cada empresa
		return $this->fetchRow($Select);
	}
	
	public function delete($id) {
		$Row = $this->find($id)->current();
		
		if (Agro_File::delete('empresas', $Row->ds_nome_arquivo)) {
			parent::delete($id);
			return true;
		}
		
		return false;
	}
}