<?php

namespace Shop\Presentation\Modules\AdminContractors;

use ActiveTable\ColumnTable;
use ActiveTable\DataTableEngine;
use Core\Form\Control\Switchery;
use Diamond\Helpers\Form;
use Shop\Domain\Customer\Contracts\CustomerEntityInterface;
use Shop\Domain\CustomerGroup\CustomerGroupCollection;
use Shop\Domain\Stock\Contracts\StockEntityInterface;
use Shop\Presentation\Modules\AdminClients\AdminClients;
use Shop\Infrastructure\Repositories\Customer\CustomerCriteria;
use Shop\Application\Office\Exceptions\OfficeException;

/**
 * Description of AdminClients
 *
 * @author Diamond Code Generator
 */
class AdminContractors extends AdminClients
{
    /**
     * @param CustomerGroupCollection $customerGroups
     * @param CustomerGroupCollection $customerGroupsCollection
     * @return CustomerCriteria
     */
    protected function prepareCustomerCriteria(CustomerGroupCollection $customerGroups,
                                               CustomerGroupCollection $customerGroupsCollection): CustomerCriteria
    {
        $filterGroupIds = [];
        foreach ($customerGroupsCollection as $group) {

            if ($group->getId() !== $this->mainConfig->getDefaultContractorGroup()) {

                $customerGroups->offsetUnset($group);
                continue;
            }
            $filterGroupIds[] = $group->getId();
        }
        return CustomerCriteria::create()->setFilterByGroupIds($filterGroupIds);
    }

    /**
     * @param DataTableEngine $table
     */
    protected function prepareActions(DataTableEngine $table): void
    {
    }

    public function process(): string
    {

        if(!$this->mainConfig->getDefaultContractorGroup()){
            return Form::buildErrorMessage(
                sprintf(
                    'Необходимо указать группу контрагента в %s',anchor(
                        '/admin/shop/customers/settings','настройках'
                    )
                )
            );
        }

        return parent::process(); // TODO: Change the autogenerated stub
    }


    protected function makeForm(DataTableEngine $table, CustomerGroupCollection $customerGroups)
    {


        parent::makeForm($table,$customerGroups);

        try{
            $stockMain = $this->officeService->getMainStock();
        }
        catch (OfficeException $ex){
            Form::addTableNotice(Form::buildErrorMessage(
                'Головной офис еще не найден, создайте его'
            ));
     
            return;
        }

        try{
            $manager = $this->officeService->getFirstManagerByStockId($stockMain->getId());
        }
        catch (OfficeException $ex){
            Form::addTableNotice(Form::buildErrorMessage(
                'Не найден менеджер Головного офиса'
            ));
            return;
        }


        $table
            ->removeFieldByName('notifyProducts')
            ->removeFieldByName('lastauth')
            ->removeFieldByName('scores')
            ->removeFieldByName('registred')
            ->removeFieldByName('notifyType')
            ->removeFieldByName('notifyOrder')
            ->removeFieldByName('notifyNews')
            ->removeFieldByName('notifyProduct')
            ->removeFieldByName('notify')
            ->removeFieldByName('discount')
            ->removeFieldByName('groupId')
            ->removeFieldByName('managerId')
            ->removeFieldByName('contacts')
            ->removeFieldByName('others')
            ->removeFieldByName('address')
            ->addField(
                $this->controlBuilder->buildHidden('notifyType')->setValue('sms_email')
            )
            ->addField(
                $this->controlBuilder->buildHidden('notifyType')->setValue('sms_email')
            )
            ->addField(
                $this->controlBuilder->buildHidden('groupId')->setValue($this->mainConfig->getDefaultContractorGroup())
            )
            ->addField(
                $this->controlBuilder->buildHidden('managerId')->setValue($manager->getId())
            )
            ->addField(
                $this->controlBuilder->buildHidden('managerId')->setValue($manager->getId())
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildInputSmall('email'), true, 'Email', null,['email']
            )
        ;

    }

    /**
     * @param DataTableEngine $table
     */
    protected function prepareColumns(DataTableEngine $table): void
    {
        $table
            ->addColumn(
                (new ColumnTable('id', '№'))
                    ->setSorted(true)
                    ->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('name', 'Название контрагента'))
            )
            ->addColumn(
                (new ColumnTable('email', 'E-mail/Логин'))
                    ->setSorted(true)

            )
            ->addColumn(
                (new ColumnTable('phone', 'Телефон'))
            )
            ->addColumn(
                (new ColumnTable('inn', 'ИНН'))
            )
            ->addColumn(
                (new ColumnTable('address', 'Адрес'))
                    ->setFormat($this, 'formatAddress')
            )
            ->addColumn(
                (new ColumnTable('blocked', 'Заблокирован'))
                    ->setFormat($this, 'formatBlocked')
            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setWidth(120)
                    ->setFormat($this, 'formatActions')
            );

    }

    /**
     * @param CustomerEntityInterface $customerEntity
     * @return string
     */
    public function formatBlocked(CustomerEntityInterface $customerEntity): string
    {
        $data = [
            'class' => self::class,
            'id' => $customerEntity->getId(),
            'fn' => 'changeBlocked'
        ];
        return (new Switchery($data, $customerEntity->getBlocked()==='Y'))->setColor('#e33a4b')->render();
    }


    public function changeBlocked(int $id, bool $checked): void
    {
        $model = $this->customerRepo->findById($id);
        $model->setBlocked($checked);
        $this->customerRepo->save($model);
    }

    public function formatActions(CustomerEntityInterface $customer, array $items = []): string
    {
        return $this->controlBuilder->buildActionMenuAdmin($items, $customer->getId())->render();
    }

}