<?php

class Sistema_Model_AvisoTelaInicial extends Agro_Db_Table_Abstract
{
    const POSICAO_CANTO_INFERIOR_DIREITO = 'B';
    const POSICAO_CENTRALIZADO = 'C';

    protected $_schema = 'sistema';
    protected $_name = 'aviso_tela_inicial';
    protected $_primary = "id";
    public $_order = 'id desc';

    public function save($data)
    {
        try {
            $row = $this->getRow($data['id']);
            $row->ds_descricao = $data['ds_descricao'];
            $row->ds_posicao = $data['ds_posicao'];
            $row->vl_largura = $data['vl_largura'];
            $row->vl_altura = $data['vl_altura'];
            $row->dt_inicio = Agro_Util::formatDate($data['dt_inicio'], 'yyyy-MM-dd');
            $row->dt_termino = Agro_Util::formatDate($data['dt_termino'], 'yyyy-MM-dd');

            if (array_key_exists('fl_ativo', $data)) {
                $row->fl_ativo = $data['fl_ativo'];
            }

            if (array_key_exists('ds_texto', $data)) {
                $row->ds_texto = $data['ds_texto'];
            }

            if (isset($data['tipoAviso']) && $data['tipoAviso'] === 'texto') {
                $row->ds_arquivo = '';
            } else {
                $row->ds_texto = '';
                $adapter = new Zend_File_Transfer_Adapter_Http();
                $adapter->setDestination(APPLICATION_PATH . '/upload_files/aviso_tela_inicial');
                $file = $adapter->getFileInfo();

                if ($file['ds_arquivo']['name']) {
                    if ($adapter->receive($file['ds_arquivo']['name'])) {
                        if ($row->ds_arquivo) {
                            unlink(realpath(APPLICATION_PATH . '/upload_files/aviso_tela_inicial/' . $row->ds_arquivo));
                        }
                        $row->ds_arquivo = $file['ds_arquivo']['name'];
                    } else {
                        $this->setMessage("Não foi possível adicionar a imagem.<br>Erro: {$adapter->getErrors()}");
                        return true;
                    }
                }
            }

            $row->ds_url = array_key_exists('ds_url', $data) ? $data['ds_url'] : '';
            $row->fl_habilitar_confirmacao_leitura = array_key_exists('fl_habilitar_confirmacao_leitura', $data)
                ? 't'
                : 'f';

            return $row->save();
        } catch (Exception $e) {
            $this->setMessage($e->getMessage() . '<br><pre>' . $e->getTraceAsString() . '</pre>');
            return false;
        }
    }
}
