<?php


namespace Shop\Application\Office\CustomerRegistration;

use Core\Helpers\Text;
use Shop\Application\Office\OfficeService;
use Shop\Repositories\Customer\CustomerRepository;

/**
 * Class CustomerRegistrationHandler
 * @package Shop\UseCases\Registration
 */
class CustomerRegistrationHandler
{
    protected $officeService;
    protected $managerService;
    protected $customerRepository;


    /**
     * CustomerRegistrationHandler constructor.
     * @param OfficeService $officeService
     * @param CustomerRepository $customerRepository
     */
    public function __construct(OfficeService $officeService,
                                CustomerRepository $customerRepository)
    {
        $this->officeService = $officeService;
        $this->customerRepository = $customerRepository;

    }

    /**
     * @param CustomerRegistrationCommand $command
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function handle(CustomerRegistrationCommand $command): void
    {
        $newCustomer = $command->getCustomerRequest();

        if(!$codeHash = $command->getCustomerRequest()->getPasswordHash()){
            $code = Text::generatePassword();
            $codeHash = md5($code);
        }
        else{
            $code = $command->getCustomerRequest()->getPassword();
        }


        //если менеджер не определен автопоиск магазина и менеджера по адресу
        if (!$managerId = $newCustomer->getManagerId()) {
            $managerId = $this->officeService->getManagerByCityId($newCustomer->getCityId())->getId();
        }

        $customer = $this->customerRepository
            ->buildEntityFromArray([])
            ->setName($newCustomer->getName())
            ->setEmail($newCustomer->getEmail())
            ->setPhone($newCustomer->getPhone())
            ->setCityId($newCustomer->getCityId())
            ->setManagerId($managerId)
            ->setPassword($codeHash)
            ->setRegisterCode($code)
            ->setGroupId($newCustomer->getGroupId())//новая группа
            ->setBlocked('N');

        $this->customerRepository->save($customer);

        $command->getCustomerResult()->setCustomer($customer);
    }

}