<?php
/*
 * Copyright (c) 2023.
 *
 * A.Сапаргалиев
 * ТОО "Дизайн лаборатория А7"
 * Астана
 */

namespace App\components;

use A7kz\Platform\Modules\Platform\Acl\Facades\Acl;
use A7kz\Platform\Modules\Platform\Core\Facades\Logic;
use A7kz\Platform\Modules\Platform\Core\Services\Base\Component;

class HeadActions extends Component
{
    const TYPE_LOGIC = 'logic';
    const TYPE_ACTION = 'action';
    const ACCESS_HANDLER_KEY = 'access_handler';

    public array $actions = [];
    public function __construct(array $params = [])
    {
        parent::__construct($params, $module = '');
        $this->template = "components.head_actions";

        if ($this->app->action['head'] ?? false) {
            $this->prepareHeadActions();
        }
        $this->setParam('actions', $this->actions);
    }

    public function render(){
        return view($this->template, $this->params)->render();
    }

    protected function prepareHeadActions(): void
    {
        $this->actions = $this->app->action['head'];

        foreach ($this->actions as $action => $property) {
            $this->actions[$action]->show = false;

            if((!$this->app->isReadonly() || !isset($property->readonly) || !$property->readonly) && $this->app->isReadonly()) {
                continue;
            }

            switch ($property?->type) {
                case self::TYPE_LOGIC:
                    $this->handleLogic($action, $property);
                    break;
                case self::TYPE_ACTION:
                default:
                    $this->handleAction($action, $property);
                    break;
            }
        }
    }

    protected function handleLogic(string $action, $property): void
    {
        if (isset($property->{self::ACCESS_HANDLER_KEY})) {
            $show = $this->handleActionAccess($action, $property->{self::ACCESS_HANDLER_KEY});
        } else {
            $show = Acl::isInRoleArray($property->access ?? []);
        }

        $this->actions[$action]->url = $this->app->getPath() . '?logic=' . $action;
        $this->actions[$action]->show = $show;

    }

    public function handleAction(string $action, $property): void
    {
        if (isset($property->{self::ACCESS_HANDLER_KEY})) {
            $show = $this->handleActionAccess($action, $property->{self::ACCESS_HANDLER_KEY});
        } else {
            $show = true;
        }

        $this->actions[$action]->url = $this->app->getPath() . '/' . $action;
        $this->actions[$action]->show = $show;
    }

    protected function handleActionAccess(string $action, string $handler): bool
    {
        $processorResult = Logic::handle($handler, $this->app, ['action' => $action]);
        return $processorResult->getStatus();
    }
}
