<?php

namespace Diamond\Modules\AdminUserGroups;

use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Core\Security\Access;
use Diamond\Infrastructure\Models\UserGroup\UserGroup;
use DiamondTable\Commands\CommandAbstract;
use Propel\Runtime\Collection\Collection;

class GroupSaveCommand extends CommandAbstract implements CommandInterface
{


    public function __construct(protected DataTableEngine $tableEngine, private Access $access)
    {
    }

    public function process(): void
    {
        $data = $this->getPostData();

        $repo = $this->tableEngine->getRepo();;

        /** @var UserGroup $entity */
        if (!$id = $this->getId()) {
            $entity = $repo->buildEntityFromArray($data);
        } else {
            $entity = $repo->buildEntityFromArray($data, $repo->findById($id));
        }

        if ($entity->getGrpCode() !== 'root') {
            foreach ($data['rule'] as $rules => $check) {
                $part = explode('.', $rules);
                if((int)$check===1){
                    $this->access->addPolicy($entity->getGrpCode(), $part[0] . '.' . $part[1], $part[2]);
                }
                else{
                    $this->access->removePolicy($entity->getGrpCode(), $part[0] . '.' . $part[1], $part[2]);
                }
            }
        }

        $this->saveEntity($entity);
        $this->addFormNotice('Ассортимент <strong>№' . $entity->getId() . '</strong> успешно сохранен!', true);
        $this->redirect();
    }
}