<?php

namespace Shop\Presentation\Modules\LastClientsWidget;

use Core\Helpers\Date;
use Diamond\Helpers\UserIconHelper;
use PartScanner\Presentation\Helpers\UserIcon;
use Shop\Presentation\Config\Main;
use Shop\Infrastructure\Models\Customer\Customer;
use Shop\Infrastructure\Repositories\Customer\CustomerCriteria;
use Shop\Infrastructure\Repositories\Customer\CustomerRepository;
use Shop\Infrastructure\Repositories\CustomerGroup\CustomerGroupCriteria;
use Shop\Infrastructure\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)
        );

        $items = [];
        
        /** @var Customer $client */
        foreach($clients as $client){
            $items[] = [
                'date' => Date::lastTime($client->getRegistred()->getTimestamp()),
                'avatar' => UserIconHelper::createIcon($client->getId()),
                'name' => $client->getName(),
                'desc' => 'email. '. $client->getEmail() . ($client->getPhone() > '' ? ' ,тел. ' . $client->getPhone() : '')
            ];
        }
        
        return $this->render([
            'clients' => $items
        ]);
    }

}               