<?

namespace Shop\Repositories;

use Core\Repository\CrudInterface;
use Core\Repository\DropdownInreface;
use Core\Repository\PropelQueryAbstract;
use Shop\Models\Order\OrderQuery;
use Shop\Models\Order\Order as OrderEntity;

/**
 * Description of Payment
 *
 * @author Admin
 */
class Order extends PropelQueryAbstract implements CrudInterface, DropdownInreface, 
        \Shop\Contracts\ShopCurrentInterface
{
    use \Shop\Concrete\ShopAuthUserTrait;
    
    public function buildEntity()
    {
        return new OrderEntity;
    }

    /**
     * 
     * @return OrderQuery
     */
    public function buildQuery(): OrderQuery
    {
        
        return OrderQuery::create()
                ->_if($this->curShop)
                    ->filterByShop($this->curShop)
                ->_endif();
    }

    public function getDropdownList(){
	return $this->buildQuery()
		->find()
		->toKeyValue('id','title');
    }

    /**
     * 
     * @param type $id
     * @return OrderEntity
     */
    public function findById($id){
        return parent::findById($id);
    }
    
    public function findByIds(array $ids){
        return $this->buildQuery()->filterByPrimaryKeys($ids)->find();
    }

    /**
     * 
     * @return OrderEntity
     */
    public function findLast($userId)
    {
        return $this->buildQuery()
                ->filterByCustomerId($userId)
                ->orderById(\Propel\Runtime\ActiveQuery\Criteria::DESC)
                ->findOne();
    }    
    
    /**
     * общая сумма всех заказов
     */
    public function summAllOrders($ignoreStates):int
    {
        return (int)$this->getQuery()
                ->useOrderItemQuery()
                    ->withColumn("SUM(price*amount)","summ")
                ->endUse()
                ->filterByShopId($ignoreStates,\Propel\Runtime\ActiveQuery\Criteria::NOT_EQUAL)
                ->findOne()
                ->getVirtualColumn("summ")
                ;
    }
}