<?php

namespace KupShop\CatalogBundle\Entity\Wrapper;

use KupShop\CatalogBundle\Section\SectionTree;
use KupShop\KupShopBundle\Template\CachingWrapperTrait;
use KupShop\KupShopBundle\Template\ObjectWrapper;
use KupShop\KupShopBundle\Util\Price\ProductPrice;
use KupShop\KupShopBundle\Wrapper\PriceWrapper;
use Query\Operator;

/**
 * Class ProductWrapper.
 *
 * @property \Product $object
 *
 * @method static \Product unwrap($object)
 */
class ProductWrapper extends ObjectWrapper
{
    use CachingWrapperTrait;

    protected static $objectType = \Product::class;
    /**
     * @var SectionTree
     */
    private $sectionTree;

    public function __construct(SectionTree $sectionTree)
    {
        $this->sectionTree = $sectionTree;
    }

    public function field_sections()
    {
        if (!$this->getCachedValue($sections)) {
            $rows = sqlQueryBuilder()->select('id_section')->from('products_in_sections', 'ps')
                ->where(Operator::equals(['ps.id_product' => $this->object->id]))
                ->execute();

            $sections = [];
            foreach ($rows as $row) {
                $sections[$row['id_section']] = $this->sectionTree->getSectionById($row['id_section']);
            }
        }

        return $sections;
    }

    public function field_productPrice()
    {
        return $this->object->field_productPrice();
    }

    public function field_originalPrice()
    {
        return $this->object->field_originalPrice();
    }

    public function field_priceCommon()
    {
        if (!empty($this->object->priceCommon)) {
            return PriceWrapper::wrap($this->object->priceCommon);
        }

        return $this->object->priceCommon;
    }

    public function field_data()
    {
        if (!$this->object->data) {
            return [];
        }

        return json_decode($this->object->data, true);
    }

    public function field_price_array()
    {
        return $this->object->field_productPrice();
    }

    public function field_price_buy()
    {
        if ($this->object->price_buy instanceof ProductPrice) {
            return PriceWrapper::wrap($this->object->price_buy);
        }

        return $this->object->price_buy;
    }

    public function field_priceMax()
    {
        if ($this->object->priceMax instanceof ProductPrice) {
            return PriceWrapper::wrap($this->object->priceMax);
        }

        return $this->object->priceMax;
    }

    public function field_bonus_points()
    {
        return $this->object->getBonusPoints($this->object->variationId);
    }
}
