<?php
namespace Diamond\Repositories;

use Core\Repository\CrudInterface;
use Core\Repository\PropelQueryAbstract;
use Diamond\Infrastructure\Models\Promoblock\Promoblock as PromoblockEntity;
use Diamond\Infrastructure\Models\Promoblock\PromoblockQuery;
use Propel\Runtime\ActiveRecord\ActiveRecordInterface;

/**
 * Промоблок
 * @todo Костыль!!! Shop\Contracts\ShopCurrentInterface и Shop\Concrete\ShopAuthUserTrait
 * @author Dmitriy
 */
class Promoblock extends PropelQueryAbstract implements CrudInterface #,
                #\Shop\Contracts\ShopCurrentInterface
        {
    
    #use \Shop\Concrete\ShopAuthUserTrait;
    
    protected $request;
            
    function __construct(\Symfony\Component\HttpFoundation\Request $request)
    {
        $this->request = $request;
    }


    public function buildEntity() {
        return new PromoblockEntity();
    }

    public function buildQuery() {

        /**
         * @todo Реализовать работу с поддоменами на уровне новых CRUD репозиторий и критерий выборки
         */
        #$id = is_a($this->curShop,ActiveRecordInterface::class) ? $this->curShop->getId() : 0;
        $id = 0;

        return PromoblockQuery::create()
                ->_if($id > 0)
                    ->addJoin("_promoblocks.domain_id","`shop_shops`.`domain_id`")
                    ->where("`shop_shops`.`id` = " . $id
                        )
                ->_endif()
                
                ;
        
    }

    /**
     * Поиск по имени
     * @param type $name
     * @return PromoblockEntity
     */
    public function findByCode($name, $url = null){
        return $this->buildQuery()
                ->filterByCode($name)
                ->_if($url)
                ->filterByPrmUrlMask($url)
                ->_endif()
                ->useDomainQuery()
                    ->orderById(\Propel\Runtime\ActiveQuery\Criteria::DESC)
                    ->filterByDomain(
                        sprintf("'%s' REGEXP `domain`",$this->request->getHost()), \Propel\Runtime\ActiveQuery\Criteria::CUSTOM)
                ->endUse()
                ->findOne();
    }
}
