<?php

namespace Redtree\BooyahWebTemplate\Services\Views;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Fluent;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class BreadcrumbService
{
    /**
     *
     * @return array Returns the breadcrumbs array with field url and name
     */
    public function getBreadcrumbs($baseUrl = '/')
    {
        $segments = request()->segments();

        return $this->generateBreadcrumbs($segments, $baseUrl);
    }

    protected function generateBreadcrumbs($segments, $baseUrl)
    {
        $crumbs = [];
        $currentRoute = request()->route();
        $parameters = collect($currentRoute->parameters);

        foreach ($segments as $segment) {
            $name = null;
            try {
                $segment = decrypt($segment);
            } catch (\Exception $exception) {
            }
            $baseUrl .= '/' . $segment;

            if (is_numeric($segment)) {
                $object = $parameters->first(function ($item) use ($segment) {
                    if ($item instanceof Model) {
                        return $item->getAttribute($item->getRouteKeyName()) == $segment;
                    }
                });
                $name = $object->alias ?? $object->title ?? $object->name ?? $object->displayname ?? $object->displayName ?? $name;
            }
            try {
                $uri = app('router')->getRoutes()->match(app('request')->create($baseUrl));
                //Check if Route requires resource
                $routeParameters = ! empty($uri->parameters) && ! $parameters->isEmpty() ? $parameters->first(function ($item, $key) use ($uri) {
                    return array_first(array_keys($uri->parameters)) === $key;
                }) : null;
                $url = route($uri->getName(), $routeParameters);
                if ($this->isDetailsView($uri, $currentRoute) && ! $name) {
                    $name = __('texts.breadcrumbs.show');
                }
            } catch (NotFoundHttpException $e) {
                // URL Existiert nicht. Hierachie falsch
                $url = null;
            } catch (MethodNotAllowedHttpException $e) {
                // URL Existiert aber nicht als GET
                $url = $url ?? null;
            }

            $crumbs[] = new Fluent([
                'url' => $url,
                'name' => $name ?? __('texts.breadcrumbs.' . $segment),
            ]);
        }

        return $crumbs;
    }

    protected function isDetailsView($route, $currentRoute)
    {
        if ($route === $currentRoute) {
            return array_last(explode('.', $currentRoute->getName())) === 'show';
        }

        return false;
    }
}
