<?php

namespace Shop\Models\Position;

use Shop\Models\Position\Base\PositionQuery as BasePositionQuery;

/**
 * Skeleton subclass for performing query and update operations on the 'shop_positions' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 */
class PositionQuery extends BasePositionQuery
{
    
 
    /**
     * 
     * @param \Shop\Contracts\CustomerComplexInterface $customer
     * @return type
     */
    static function getComplexRateQuery(\Shop\Contracts\CustomerComplexInterface $customer){
        $q  = 'IFNULL((SELECT rate  FROM shop_complex_rates scr 
        WHERE scr.active=1  AND 
        shop_products.category_id LIKE scr.category_id AND
        shop_products.brand_id LIKE scr.brand_id AND 
        "%s" LIKE scr.customer_id AND 
        "%s" LIKE scr.customer_group_id AND 
        `shop_positions`.pricelist_sheet_id 
        LIKE scr.pricelist_sheet_id ORDER BY scr.priority DESC LIMIT 1 ),0)';
        return sprintf($q, $customer->getId(), $customer->getGroupId());
    }
    
    /**
     * @todo избавиться от костыля
     * @return $this
     */
    public function withComplexRate(){
        $this->join("Product");
        $customer = \Core\Application\Loader::getInstance()->load("DI")->get(\Shop\Services\Customer::class)->buildCurrentCustomer();
        $this->addAsColumn('rate', self::getComplexRateQuery($customer));//, $brandId                
        return $this;
    }
}
