<?php

namespace Shop\Modules\AdminContractors;

use ActiveTable\ColumnTable;
use ActiveTable\DataTableEngine;
use Diamond\Helpers\Form;
use Shop\Domain\Customer\Contracts\CustomerEntityInterface;
use Shop\Domain\CustomerGroup\CustomerGroupCollection;
use Shop\Modules\AdminClients\AdminClients;
use Shop\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('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
    {
        return \Diamond\Helpers\Formatter::formatYN($customerEntity->getBlocked(), [
            'Y' => 'color-alert'
        ]);
    }

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

}