<?php

class RCMS_Object_Product_ProductModel extends RCMS_Core_BaseModel {

    private $_table = 'shopping_products';
    private $_groups = 'shopping_groups';
    private $_group_and_product = 'shopping_products_groups';

    public function selectProductById($id)
    {
        $select = $this->_adapter->select()->from($this->_table)->where('id = ?', $id);
        return $this->_adapter->fetchRow($select);
    }

    public function selectGroupsForProduct($id)
    {
        $select = $this->_adapter->select()
                ->from(array('pg' => $this->_group_and_product), array('id' => 'id_group'))
                ->join( array('g' => $this->_groups), 'pg.id_group = g.id', array('name'))
                ->where('id_product = ?', $id);
        return $this->_adapter->fetchAll($select);
    }

    public function insertGroupForProduct($idProduct, $idGroup)
    {
        $sql = 'INSERT INTO '.$this->_group_and_product.' (id_product, id_group) VALUES (?,?)
        ON DUPLICATE KEY UPDATE id_product = ?, id_group = ?';
        return $this->_adapter->query($sql, array($idProduct, $idGroup, $idProduct, $idGroup));
    }

    public function deleteGroupForProduct($idProduct)
    {
        $where = sprintf("id_product = %d", $idProduct);
        return $this->_adapter->delete($this->_group_and_product, $where);
    }

    public function insertProduct(RCMS_Object_Product_Product $product)
    {
        $data = array (
            'name'      => $product->getName(),
            'item_id'   => $product->getItemId(),
            'price'     => $product->getPrice(),
            'photo'     => $product->getPhoto(),
            'brand'     => $product->getBrand(),
            'desc'      => $product->getDescription(),
            'options'   => $product->getOptions(),
            'related'   => $product->getRelated(),
            'page_id'   => $product->getPageId()
        );
        $this->_adapter->insert($this->_table, $data);
        return $this->_adapter->lastInsertId($this->_table);
    }

    public function updateProduct(RCMS_Object_Product_Product $product)
    {
        $data = array (
            'name'      => $product->getName(),
            'item_id'   => $product->getItemId(),
            'price'     => $product->getPrice(),
            'photo'     => $product->getPhoto(),
            'brand'     => $product->getBrand(),
            'desc'      => $product->getDescription(),
            'options'   => $product->getOptions(),
            'related'   => $product->getRelated(),
            'page_id'   => $product->getPageId()
        );
	    $where = sprintf("id = %d", $product->getId());
	    return $this->_adapter->update($this->_table, $data, $where);
    }

    public function deleteProduct($id)
    {
        $where = sprintf("id = %d", $id);
        return $this->_adapter->delete($this->_table, $where);
    }
}
