<?php

namespace Modules\Seo\Middlewares;

use Closure;
use DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Config;

class SeoRedirectMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */

    const IGNORE_CHECK_REDIRECT = [".css", ".js", ".svg", ".woff"];

    public function handle($request, Closure $next, $guard = null)
    {
        $parseUrl = parse_url($_SERVER['REQUEST_URI']);
        $route = \Route::getRoutes()->match($request);
        if (
            auth()->check() ||
            empty($route->action['middleware']) || 
            !is_array($route->action['middleware']) || 
            in_array('system', $route->action['middleware'])) {
            return $next($request);
        }
        foreach (self::IGNORE_CHECK_REDIRECT as $value) {
            if (!empty($parseUrl['path']) && strpos($parseUrl['path'], $value) !== false) {
                return $next($request);
            }
        }

        if (Config::get('seo::default.allow_redirect', true) && $request->isMethod('get')) {
            if (!empty($parseUrl['path']) && Redis::exists($parseUrl['path'])) {
                $parseRedirect = parse_url(Redis::get($parseUrl['path']));
                $queryParams = [];
                if (isset($parseRedirect['query'])) {
                    parse_str($parseRedirect['query'], $queryParams);
                }
                $input = $request->all();
                if (!empty($input)) {
                    $queryParams = array_merge($queryParams, $input);
                }
                $newUrl = $parseRedirect['path'];
                if (!empty($queryParams)) {
                    $newUrl .= '?' . http_build_query($queryParams);
                }
                return redirect($newUrl, 301);
            }
    
            $redirecRoutes = [
                '{slug}-t{id}.html',
                '{slug}-c{id}.html'
            ];
            $uri = $route->uri;
            if (env('LOCALIZATION')) {
                $uri = str_replace('{locale?}/', '', $uri);
            }
            if (in_array($uri, $redirecRoutes) && \Route::has('categoryOrTag')) {
                $params = $this->buildParams($route->parameters, $request);
                return redirect(route('categoryOrTag', $params), 301);
            }
            if ($uri == '{slug}-s{id}.html' && \Route::has('seller')) {
                $params = $this->buildParams($route->parameters, $request);
                $params['slug2'] = $params['slug'];
                $params['slug'] = substr(trans('routes.frontend.shop'), 1);
                return redirect(route('categoryOrTag', $params), 301);
            }
        }
        return $next($request);
    }

    public function buildParams($parameters , $request) {
        $params = $request->all();
        if (isset($parameters['id'])) {
            unset($parameters['id']);
        }
        if (isset($params['category'])) {
            $cate = DB::table('category')->where('id', $params['category'])->select('id', 'slug')->first();
            if ($cate) {
                $params['category'] = $cate->slug;
            }
        }
        $params = $parameters + $params;


        $locale = env('APP_LOCALE');
        if ($locale && isset($params['slug']) && strpos($params['slug'], $locale . '/') === 0) {
            $params['slug'] = substr($params['slug'], strlen($locale) + 1);
            $params['locale'] = $locale;
        }

        return $params;
    }
}
