<?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 PartScanner\Infrastructure\Models\Assortment\Assortment;
use PartScanner\Infrastructure\Models\Assortment\AutoloadSettings;
use PartScanner\Infrastructure\Models\AssortmentReplaceRel\AssortmentReplaceRel;
use PartScanner\Infrastructure\Models\AssortmentsExportFileRel\AssortmentsExportFileRel;
use PartScanner\Infrastructure\Models\AssortmentsExportSourceRel\AssortmentsExportSourceRel;
use PartScanner\Infrastructure\Models\AssortmentsFiltersRel\AssortmentsFiltersRel;
use PartScanner\Infrastructure\Models\AssortmentsGroupsRel\AssortmentsGroupsRel;
use PartScanner\Infrastructure\Models\AssortmentsReplacesRel\AssortmentsReplacesRel;
use PartScanner\Infrastructure\Models\AssortmentsSheetsRel\AssortmentsSheetsRel;
use Propel\Runtime\Collection\Collection;
use function PartScanner\Presentation\Modules\AdminAssortments\str_starts_with;

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();
    }
}