<?php

namespace Shop\Modules\LastClientsWidget;

use Shop\Config\Main;
use Shop\Repositories\Customer\CustomerCriteria;
use Shop\Repositories\Customer\CustomerRepository;
use Shop\Repositories\CustomerGroup\CustomerGroupCriteria;
use Shop\Repositories\CustomerGroup\CustomerGroupRepository;

/**
 * Description of LastClientsWidget
 *
 * @author Diamond Code Generator
 */
class LastClientsWidget extends \Core\ModuleController
{

    public $limit = 3;

    protected $customerRepo;
    protected $mainConf;
    protected $customerGroupRepository;

    public function __construct(
        CustomerRepository $customerRepo,
        Main $mainConf,
        CustomerGroupRepository $customerGroupRepository
    )
    {
        $this->customerRepo = $customerRepo;
        $this->mainConf = $mainConf;
        $this->customerGroupRepository = $customerGroupRepository;
    }


    /**
     * @return string
     * @throws \ReflectionException
     * @throws \Repo\Concrete\Exceptions\Collection
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function process(): string
    {

        $groups =  $this->customerGroupRepository->findByCriteria(
          CustomerGroupCriteria::create()
        );

        $ids = [];
        foreach ($groups as $group){
            if(in_array($group->getId(), [
                $this->mainConf->getDefaultContractorGroup(),
                $this->mainConf->getDefaultGuestGroup()
            ], true)){
                continue;
            }
            $ids[]=$group->getId();
        }


        $clients = $this->customerRepo->findByCriteria(
            CustomerCriteria::create()
                ->setSortByRegistred('desc')
                ->setFilterByGroupIds($ids)->setLimit($this->limit)
        );

        return $this->render([
            'clients' => $clients
        ]);
    }

}               