<?php

class Sistema_AssessoriaarquivoController extends Agro_Controller_Action {

	protected $_paginator = false;

	public function getModel() {
		return new Sistema_Model_AssessoriasArquivos();
	}	

	public function getFilter() {
		$session = new Zend_Session_Namespace('assessoria');
		$where = array();

		$where[] = array(
			'field' => 'id_assessoria',
			'operator' => '=',
			'value' => $this->getRequest()->getParam('id')
		);

		return $where;
	}

	public function salvaarquivoAction()
    {
        $this->isAjax();

        $post = $this->getRequest()->getParams();
        $idAssessoria = !Agro_Util::filterVariable($post['id_assessoria'])
            ? 0
            : (int)$post['id_assessoria'];

        $idTipoArquivo = !Agro_Util::filterVariable($post['id_tipo_arquivo'])
            ? 0
            : (int)$post['id_tipo_arquivo'];

        $file = $_FILES['arquivo'];
        $db = Agro_Db_Table_Abstract::getDefaultAdapter();
        $db->beginTransaction();

        try {
            $tipoArquivoCorretor = new Sistema_Model_TipoArquivoCorretor();
            $tipo = $tipoArquivoCorretor->fetchRow(
                $tipoArquivoCorretor->getAdapter()->quoteInto('id = ?', $idTipoArquivo)
            )->toArray();

            $assessoriaArquivo = new Sistema_Model_AssessoriasArquivos();
            $id = $assessoriaArquivo->nextSequenceId();

            $extensao = strtolower(end(explode('.', $file['name'])));

            if (Agro_File::isInvalidExtension($extensao)) {
                throw new TypeError('Extensão inválida');
            }

            $nomeArquivo = "{$idAssessoria}-$id-{$tipo['ds_chave_tipo_arquivo']}.$extensao";

            $target = APPLICATION_PATH . '/upload_files/assessorias/' . $nomeArquivo;

            if (copy($file['tmp_name'], $target)) {
                $data = array();
                $data['id'] = $id;
                $data['id_assessoria'] = $idAssessoria;
                $data['id_tipo_arquivo'] = $idTipoArquivo;
                $data['ds_nome_arquivo'] = $nomeArquivo;

                $assessoriaArquivo->save($data);

                $db->commit();

                $return['status'] = true;
                $return['message'] = 'Documento incluído com sucesso';
                $return['id'] = $data['id_assessoria'];
            }
        } catch (Throwable $e) {
            $db->rollback();
            $return['status'] = false;
            $return['message'] = 'Erro ao salvar arquivo: ' . $e->getMessage();
        }

        $this->getResponse()->setBody(Zend_Json::encode($return));
    }

	public function deleteAction()
    {
        $this->getHelper('ViewRenderer')->setNoRender();
        $this->getHelper('layout')->disableLayout();

        $id = !Agro_Util::filterVariable($this->getRequest()->getParam('id'))
            ? 0
            : (int)$this->getRequest()->getParam('id');

        $model = new Sistema_Model_AssessoriasArquivos();
        $row = $model->getRow($id);

        if ($model->delete($id)) {
            $file = realpath(APPLICATION_PATH . '/upload_files/assessorias/' . $row->ds_nome_arquivo);

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

            $return['message'] = 'Documento excluído com sucesso!';
            $return['id'] = $this->getRequest()->getParam('id_assessoria');
            $return['status'] = true;

        } else {
            $return['message'] = 'Erro ao excluir document!';
            $return['status'] = false;
        }

        $this->getResponse()->setBody(Zend_Json::encode($return));
    }
}