<?php

namespace Shop\Infrastructure\Models\Position;

use Shop\Domain\Customer\Contracts\CustomerEntityInterface;
use Shop\Infrastructure\Models\Position\Base\PositionQuery as BasePositionQuery;
use Shop\Presentation\Services\Customer\CustomerService;
use Shop\Presentation\UseCases\SecurePolicy\SecurePolicy;

/**
 * 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
{

    private static $cusrtomer;

    /**
     * @param CustomerEntityInterface $customer
     * @return string
     */
    static function getComplexRateQuery(CustomerEntityInterface $customer): string
    {
        $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 
        "%s" LIKE scr.shop_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(),
            $customer->getManager()->getShop()->getId()
        );
    }

    /**
     * @todo избавиться от костыля
     * @return $this
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function withComplexRate()
    {
        if (!self::$cusrtomer) {
            $customer = \Core\Application\Loader::getInstance()
                ->load('DI')
                ->get('current_customer');

            self::$cusrtomer = $customer;
        }

        $this->join('Product');

        $this->addAsColumn('rate', self::getComplexRateQuery(self::$cusrtomer));//, $brandId
        return $this;
    }
}
