<?php

namespace Modules\Seo\Validators;

use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Route as FacadeRoute;
use Illuminate\Routing\Matching\UriValidator;

class CustomValidator extends UriValidator
{
    public function getUniqueSlugs() {
        $allRoutes = FacadeRoute::getRoutes();
        $uris = [];
        foreach ($allRoutes as $route) {
            preg_match("/(\.\w+)/", $route->uri, $matches);
            if (count($matches) == 0) {
                $uris[] = $route->uri;
            }
        }
        $uniqueSlugs = config('seo::default.ignore_slugs', []);
        $ignoreSlugs = [];
        $tranSlug = explode('/', trans('routes.frontend.brand'));
        if (count($tranSlug) > 1) {
            $ignoreSlugs[] = $tranSlug[1];
        }
        $tranSlug = explode('/', trans('routes.frontend.product-all'));
        if (count($tranSlug) > 1) {
            $ignoreSlugs[] = $tranSlug[1];
        }
        $tranSlug = explode('/', trans('routes.frontend.shop'));
        if (count($tranSlug) > 1) {
            $ignoreSlugs[] = $tranSlug[1];
        }
        foreach ($uris as $value) {
            $value = str_replace('{locale?}/', '', $value);
            $slugs = explode('/', $value);
            if (count($slugs) && $slugs[0] && !in_array($slugs[0], $ignoreSlugs)) {
                $uniqueSlugs[$slugs[0]] = $slugs[0];
            }
        }

        return $uniqueSlugs;
    }
    /**
     * Validate a given rule against a route and request.
     *
     * @param  \Illuminate\Routing\Route  $route
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    public function matches(Route $route, Request $request)
    {
        $retVal = parent::matches($route, $request);
        $action = $route->getAction();
        if (isset($action['useCustomValidator']) && $action['useCustomValidator']) {
            $locales = config('localization::module.locales', []);
            $locales = array_keys($locales);
            $path = $request->path() == '/' ? '/' : '/'. $request->path();
            foreach ($locales as $locale) {
                $path = str_replace("/$locale/", "/", $path);
            }
            $slugs = explode('/', $path);
            $uniqueSlugs = $this->getUniqueSlugs();
            if (count($slugs) > 1) {
                $retVal = !in_array($slugs[1], $uniqueSlugs);
            } else {
                $retVal = false;
            }
        }
        return $retVal;
    }
}