<?php


class ProductPropValueTable extends Doctrine_Table
{
    
    public static function getInstance()
    {
        return Doctrine_Core::getTable('ProductPropValue');
    }
    
    public function updateOrCreate($product_id, $fields, $offer_id = null)
    {
        $existPropTypesQ = Doctrine_Query::create()
            ->select('*, CONCAT_WS(\'_\', product_id, prop_id, offer_id) as key_index')
            ->from('ProductPropValue INDEXBY key_index')
            ->whereIn('prop_id', array_keys($fields))
            ->andWhere('product_id = ?', $product_id);
        if($offer_id) {
            $existPropTypesQ->andWhere('offer_id = ?', $offer_id);
        }
    
        $existPropTypes = $existPropTypesQ->execute();
        foreach ($fields as $prop_id => $value) {
            $key = $product_id . '_' . $prop_id  . (is_null($offer_id) ? '' : '_' . $offer_id);
            $propProductValue = isset($existPropTypes[$key]) ? $existPropTypes[$key] : new ProductPropValue();
            
            $propProductValue->setPropId($prop_id);
            $propProductValue->setProductId($product_id);
            
            if(key_exists('ru', $value) && key_exists('en', $value)) {
                $propProductValue->getTranslation()->ru->set('value', $value['ru']);
                $propProductValue->getTranslation()->en->set('value', $value['en']);
            } else {
                $propProductValue->getTranslation()->ru->set('value', $value);
                $propProductValue->getTranslation()->en->set('value', $value);
            }
            $propProductValue->save();
        }
    }
}