<?

namespace Shop\Presentation\Services;

use Diamond\Services\Notify;
use Diamond\Services\Report\ReportService;
use Shop\Presentation\Config\Main;
use Shop\Contracts\CustomerComplexInterface;
use Shop\DTO\CustomerRequest;
use Shop\Presentation\UseCases\SecurePolicy\SecurePolicy;

/**
 * Description of Customer
 * @deprecated
 * @author Admin
 */
class Customer #implements \Diamond\Contracts\CustomerEmailFinderInterface
{
    static $currentShop;
    
    static $currentCustomer;

    protected $customerRepo;
    protected $mainConfig;
    protected $reportService;
    protected $notifyService;
    protected $authService;
    protected $shopService;

    function __construct(\Shop\Infrastructure\Repositories\Customer $customerRepo, Main $mainConfig, ReportService $reportService,
                         Notify $notifyService, \Shop\Presentation\Services\Auth $authService, \Shop\Presentation\Services\Shop $shopService)
    {
        $this->customerRepo  = $customerRepo;
        $this->mainConfig    = $mainConfig;
        $this->reportService = $reportService;
        $this->notifyService = $notifyService;
        $this->authService   = $authService;
        $this->shopService   = $shopService;
    }
    

    

    


    



    
    /**
     * 
     * @param type $name
     * @param type $email
     * @param type $phone
     * @param type $cityId
     * @return \Shop\Infrastructure\Models\Customer\Customer
     * @deprecated
     * @see \Shop\Presentation\Services\Customer::regstration
     */
    public function regstrationCustomer($name, $email, $phone, $cityId): \Shop\Infrastructure\Models\Customer\Customer
    {

        $newCustomer = new \Shop\DTO\CustomerRequest(
                $name, $email, $this->mainConfig->getDefault_customer_category(), $phone, $cityId
        );

        return $this->registration($newCustomer);
    }

    /**
     * Получение офиса текущего клиента
     * @deprecated self::getCurrentShop
     * @return int
     */
    public function getCurrentShopId(): int
    {
        $shop = $this->getCurrentShop();

        return $shop->getId();
    }
    
    /**
     * @deprecated
     * @return int
     * @throws \RuntimeException
     */
    public function getCurrentShop(): \Shop\Infrastructure\Models\Shop\Shop
    {

        if(isset(self::$currentShop)){
            return self::$currentShop;
        }        
        
        if ($customer = $this->authService->getAuthCustomer()) {

            $shop = $customer->getManager()->getShop();
            
            self::$currentShop = $shop;
            
            return $shop;
        }

        self::$currentShop = $this->shopService->getCurrentOrDefaultShop();
        
        

        return self::$currentShop;
    }
    
    /**
     * @deprecated
     * @return \Shop\Infrastructure\Models\Manager\Manager
     */
    public function getCurrentManager(): \Shop\Infrastructure\Models\Manager\Manager
    {
        $shop = $this->getCurrentShop();
       
        return $shop->getManagers()->getFirst();
    }
    
    /**
     * Возращает тек пользователя или false
     * @return \Shop\Infrastructure\Models\Customer\Customer
     */
    public function getCurrentCustomer(){
        
        return $this->authService->getAuthCustomer();
    }
    
    /**
     * Заменить полностью на DTO
     * @return type
     */
    public function buildCurrentCustomer() : CustomerComplexInterface{

        if(is_a(self::$currentCustomer, CustomerComplexInterface::class)){
            return self::$currentCustomer;
        }
        
        $customerFind = $this->getCurrentCustomer();

        $customer = !$customerFind ? $this->buildDefaultComplexRate(): $customerFind;

        self::$currentCustomer = $customer;
        
        return $customer;
    }

    /**
     * создание дефолтного комплексного
     */
    protected function buildDefaultComplexRate(){
        $defaultCategory = $this->mainConfig->getDefault_customer_category();
        $curShop = $this->getCurrentShop();

        $pricesIds = [];
        
        $pricesQ = 
                \Shop\Infrastructure\Models\PricelistSheet\PricelistSheetQuery::create("s")
                  
                ->usePricelistFileQuery()
                    ->useProviderQuery()
                        ->filterByContractorId($curShop->getContractorId())
                    ->endUse()
                ->endUse()
                //->_if($_GET["test"]>0)
                
		->addAlias("ac", "shop_price_access")
                ->addJoin("s.id","ac.price_scheet_id")
                ->_if($defaultCategory > "")
                ->where($defaultCategory . " LIKE ac.customer_group_id")
                ->_endif()
               
                ;
                
     
          
         $prices = $pricesQ ->find();

    
        if($prices->count()){
            $pricesIds = array_keys($prices->toArray("id"));
        }
        
        
        return (new \Shop\DTO\CustomerComplex())
                ->setGroupId($defaultCategory)
                ->setAccessPriceListScheetIds($pricesIds);
    }







    /**
     * 
     * @param type $name
     * @param type $email
     * @param type $phone
     * @param type $cityId
     * @return \Shop\Infrastructure\Models\Customer\Customer
     * @deprecated
     * @see \Shop\Presentation\Services\Customer::registrationWithNotify
     */
    public function regstrationCustomerAndNotify($name, $email, $phone, $cityId): \Shop\Infrastructure\Models\Customer\Customer
    {
        $newCustomer = new \Shop\DTO\CustomerRequest();
        $newCustomer
                ->setName($name)
                ->setCityId($cityId)
                ->setEmail($email)
                ->setGroupId($this->mainConfig->getDefault_customer_category())
                ->setPhone($phone)
        ;

        return $this->registrationWithNotify($newCustomer);
    }

    
    
    /**
     * @deprecated
     * @see SecurePolicy::createCustomerWithNotify()
     * @param CustomerRequest $newCustomer
     * @return \Shop\Infrastructure\Models\Customer\Customer
     */
    public function registrationWithNotify(CustomerRequest $newCustomer): \Shop\Infrastructure\Models\Customer\Customer
    {

        $customer = $this->registration($newCustomer);

        //Формируем сообщение
        $data = $customer->toArray();
        $data["region"] = $customer->getCustomerCity()->getCityRegion()->getName();
        $data["city"] = $customer->getCustomerCity()->getName();
        $data["code"] = $customer->getRegisterCode();
        $data["registred"] = date(\Diamond\Helpers\Date::formatDisplay());
        $data["link"] = anchor('/personal/data', 'личном кабинете');
        $data["phone"] = $customer->getPhone();
        $data["group"] = $customer->getCustomerGroup()->getName();
        $data["address"] = $customer->getFullAddress();

        $message = $this->reportService->createMessageByReport("client_registration", $data);

        //отправляем уведомление
        if ($message) {
            $this->notifyService->sendToEmail($customer->getEmail(), $message);
        }

        $manager = $customer->getManager();
        $messageManager = $this->reportService->createMessageByReport("client_registration_manager", $data);

        if ($manager && $messageManager) {
            $this->notifyService->sendToEmail($manager->getEmail(), $messageManager);
        }

        return $customer;
    }

    /**
     * Регистрация клиента
     * @deprecated
     * @see SecurePolicy::createCustomer()
     * @param CustomerRequest $newCustomer
     * @return \Shop\Infrastructure\Models\Customer\Customer
     * @throws \Core\Exceptions\LogicException
     */
    public function registration(CustomerRequest $newCustomer): \Shop\Infrastructure\Models\Customer\Customer
    {

        $code = $this->generateCode();
        
        //если менеджер не определен автопоиск магазина и менеджера по адресу
        if(!$managerId = $newCustomer->getManagerId()){
            $managerId = $this->getManagerByCityId($newCustomer->getCityId())->getId();
        }
 
        $customer = $this->customerRepo->buildEntity()
                ->setName($newCustomer->getName())
                ->setEmail($newCustomer->getEmail())
                ->setPhone($newCustomer->getPhone())
                ->setCityId($newCustomer->getCityId())
                ->setManagerId($managerId)
                ->setPassword(md5($code))
                ->setRegisterCode($code)
                ->setGroupId($newCustomer->getGroupId())//новая группа
                ->setBlocked("N")
        ;

        if ( ! $customer->save()) {
            throw new \Core\Exceptions\LogicException("customer not save");
        }

        return $customer;
    }





}