<?php

Goweb::loadClass('Goweb_Db_Model');

/**
 * Goweb Sitemanager 5 Framework
 * @version    5.0.0
 * @category   Frontoffice
 * @package    Catalogo
 * @subpackage Model
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
 */
class Catalogo_Model_Produto extends Goweb_Db_Model {

    /**
     * Nome da Tabela
     *
     * @var string
     */
    protected $_table = 'catalogo_produto';

    /**
     * Chave Primaria
     *
     * @var string
     */
    protected $_primary = 'id';

    /**
     * Campo que sera retornado se um
     * echo do objecto for chamado
     *
     * @var string
     */
    protected $_toString = 'titulo';
    protected $_pontuacao = array('1' => '1',
                                  '2' => '2',
                                  '3' => '3',
                                  '4' => '4',
                                  '5' => '5');


    /**
     * Metodo obrigatorio. Informa a definicao da tabela
     * referente ao Model em questao.
     */
    protected function _setup() {
        $config = new Goweb_Config(Goweb_Config_Ini::load(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'Catalogo' . DIRECTORY_SEPARATOR . 'config.ini', 'base'));
        $this->initLang();
        $this->setSyncCols(array('ordem', 'referencia', 'promocao', 'promocao_inicio', 'promocao_fim', 'destaque', 'novidade', 'activo', 'visualizacoes', 'preco'));
        $this->ordem           = $this->Integer(array('default' => 0, 'label' => 'Ordem'));
        $this->categoria_id    = $this->ForeignKey(array('model' => 'Catalogo_Model_Categoria', 'alias' => 'categoria', 'label' => translate('Categoria')));
        /*$this->categoria_id = $this->ForeignKeyMultiple(array('model' => 'Catalogo_Model_Categoria',
         'col' => 'produto_id',
         'modelMultiple' => 'Catalogo_Model_ProdutoCategoria',
         'alias' => 'categorias',
         'label' => translate('Categorias')));*/
        $this->ficha_id        = $this->ForeignKey(array('model' => 'Catalogo_Model_Ficha', 'alias' => 'ficha', 'label' => translate('Ficha'), 'show' => false, 'default' => '0'));
        $this->iva_id          = $this->ForeignKey(array('model' => 'Catalogo_Model_Iva', 'alias' => 'iva', 'label' => translate('I.V.A.'), 'default' => '0'));
        $this->referencia      = $this->Char(array('maxlength' => 50, 'notnull' => false, 'label' => translate('Refer&ecirc;ncia')));
        $this->titulo          = $this->Char(array('maxlength' => 200, 'notnull' => true, 'label' => translate('T&iacute;tulo')));
        $this->url             = $this->Char(array('maxlength' => 200, 'label' => translate('Url Amig&aacute;vel'), 'on_update' => '_urlFromTitulo', 'show' => true));
        $this->descricao       = $this->Text(array('form' => 'Rte', 'height' => '200px', 'theme'=> 'advanced', 'label' => translate('Descri&ccedil;&atilde;o')));
        $this->preco           = $this->Float(array('max_digits' => 6, 'decimal_places' => 2, 'notnull' => false, 'label' => translate('Pre&ccedil;o')));
		$this->preco_promo     = $this->Float(array('max_digits' => 6, 'decimal_places' => 2, 'notnull' => false, 'label' => translate('Pre&ccedil;o em Promo&ccedil;&atilde;o')));
        $this->pontuacao       = $this->Char(array('maxlength' => 50, 'notnull' => false, 'label' => translate('Pontua&ccedil;&atilde;o'), 'options' => $this->_pontuacao, 'default' => '5'));
        $this->imagem = $this->Image(array('target' => $config->images->target,
                                           'prefix' => $config->images->prefix,
                                           'original' => $config->images->original->save,
                                           'max_size' => $config->images->original->max_size,
                                           'max_width' => $config->images->original->max_width,
                                           'max_height' => $config->images->original->max_height,
                                           'type_resize' => $config->images->original->type_resize,
                                           'sizes' => $config->images->sizes,
                                           'small_max_width' => $config->images->small->width,
                                           'small_max_height' => $config->images->small->height,
                                           'small_watermark' => $config->images->small->watermark,
                                           'small_type_resize' => $config->images->small->type_resize,
                                           'medium_max_width' => $config->images->medium->width,
                                           'medium_max_height' => $config->images->medium->height,
                                           'medium_watermark' => $config->images->medium->watermark,
                                           'medium_type_resize' => $config->images->medium->type_resize,
                                           'big_max_width' => $config->images->big->width,
                                           'big_max_height' => $config->images->big->height,
                                           'big_watermark' => $config->images->big->watermark,
                                           'big_type_resize' => $config->images->big->type_resize));

        $this->ficheiro    = $this->File(array('target'   => $config->files->target,
                                               'prefix'   => $config->files->prefix,
                                               'types'    => $config->files->types,
                                               'max_size' => $config->files->max_size));

        $this->promocao        = $this->Boolean(array('default' => 0, 'label' => translate('Promo&ccedil;&atilde;o')));
        $this->promocao_inicio = $this->Date(array('label' => translate('Data de inicio da promo&ccedil;&atilde;o'), 'default' => date('Y-m-d')));
        $this->promocao_fim    = $this->Date(array('label' => translate('Data de fim da promo&ccedil;&atilde;o'), 'default' => date('Y-m-d')));
        $this->destaque        = $this->Boolean(array('default' => '0', 'label' => translate('Destaque')));
        $this->novidade        = $this->Boolean(array('default' => '0', 'label' => translate('Novidade')));
        $this->peso		       = $this->Float(array('max_digits' => 6, 'decimal_places' => 2, 'notnull' => false, 'label' => translate('Peso')));
        $this->activo          = $this->Boolean(array('default' => '1', 'label' => translate('Activo')));
        $this->visualizacoes   = $this->Integer(array('unsigned' => true, 'show' => false, 'label' => translate('N&uacute;mero de visualiza&ccedil;&otilde;es')));
        $this->actualizado     = $this->Datetime(array('on_update' => '_currentDatetime', 'label' => translate('Actualizado em')));
        $this->criado          = $this->Datetime(array('on_insert' => '_currentDatetime', 'label' => translate('Criado em')));
        $this->ip              = $this->IpAddress(array('on_update' => '_remoteAddress', 'label' => translate('Endere&ccedil;o IP')));
    }

    /**
     * Obter um url amigável com base no titulo
     *
     * @return String com um url amigável
     */
    protected function _urlFromTitulo() {
        if ($this->url == '') {
            $this->url = $this->_clearString($this->titulo);
            $this->url = $this->_getParents($this->categoria_id, $this->url);
        } else {
            $this->url = $this->_clearString($this->url);
        }
        $tmpModel = new Catalogo_Model_Produto('db', false);
        $url = $this->url;
        $count = 0;
        while ($tmpModel->findBy('url', $url) && $tmpModel->id != $this->id){
            $count++;
            if ($count == 1) $url .= '-';
            $url=$this->url . $count;
        }

        $this->url = $url;
        return $this->url;
    }

    /**
     * Obter o url dos pais da categoria
     *
     * @param int $pai_id
     * @param string $parents
     * @return string
     */
    protected function _getParents($pai_id = 0, $parents = ''){
        $categoriaModel = new Catalogo_Model_Categoria('db', false);
        
        if ($categoriaModel->find($pai_id)){
            if (strlen($parents) > 0 && strlen($categoriaModel->url) > 0) $parents = "/" . $parents;
            $parents = $categoriaModel->url . $parents;
            while ($categoriaModel->find($categoriaModel->pai_id)){
                if ($categoriaModel->url && strpos($parents, $categoriaModel->url) === false){
                    if (strlen($parents) > 0 && strlen($categoriaModel->url) > 0) $parents = "/" . $parents;
                    $parents = $categoriaModel->url . $parents;
                }
            }
        }
        return $parents;
    }
}