<?php


namespace Diamond\Controllers;


use Core\BaseController;
use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Diamond\Domain\Menu\Contracts\MenuEntityInterface;
use Diamond\Infrastructure\Models\Menu\Menu;
use Diamond\Repositories\Menu\MenuCriteria;
use Diamond\Repositories\Menu\MenuRepository;
use Symfony\Component\HttpFoundation\JsonResponse;

class MenuController extends BaseController implements RequestAwareInterface
{

    use RequestAwareTrait;

    protected $menuRepository;

    public function __construct(MenuRepository $menuRepository)
    {
        $this->menuRepository = $menuRepository;
    }


    public function index(): JsonResponse
    {
        $search = $this->request->query->get('search_by_name');
        $res = [];
        if ($search) {

            $mainItems = $this->menuRepository->findByCriteria(
                MenuCriteria::create()
                    ->setSearchByName('admin-main')
                    ->setFilterByActive(true)
            );

            $items = $this->menuRepository->findByCriteria(
                MenuCriteria::create()
                    ->setSearchByTitle($search)
                    ->setSearchByName('admin-')
                    ->setFilterByActive(true)
            );

            /**
             * @var MenuEntityInterface|Menu $item
             */
            foreach ($items as $item) {

                $label = $item->getTitle();

                if(!$item->getUrl()){
                    continue;
                }

                if ($item->getParentId() > 0) {
                    $parent = $this->menuRepository->findById($item->getParentId());
                    $label = $parent->getTitle() . ' -> ' . $label;
                }

                foreach ($mainItems as $mainItem){
                    if(stripos($mainItem->getUrl(),preg_replace('~(.*)\/.*?$~','$1',$item->getUrl())) !== false){
                        $label = $mainItem->getTitle() . ' -> ' . $label;
                        break;
                    }
                }

                $res[] = [
                    'value' => $item->getUrl(),
                    'label' => $label
                ];
            }
        }

        return new JsonResponse([
            'items' => $res
        ]);
    }

}