<?php

namespace twa\htmlhelpers\middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\UrlGenerator;
use \twa\htmlhelpers\models\SEOByRouteModel;
use \twa\htmlhelpers\models\SEOSettingsModel;

class TWASEOMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

    private $url;

    public function __construct(UrlGenerator $url)
    {
        $this->url = $url;
    }


    public function handle(Request $request, Closure $next)
    {
        $request->seo = false;
        $request->seo_settings = SEOSettingsModel::where('cancelled',0)->orderBy('orders')->first();
        $Routes = SEOByRouteModel::where('cancelled',0)->orderByRaw('CHAR_LENGTH(`route`) DESC')->get();
        foreach($Routes AS $route){
            if($request->is($route->route)){
                $seo = [];
                foreach (lang()->list() AS $lang){
                    $seo[$lang->prefix] = [ "title" => $route["title_".$lang->prefix], "keywords" => $route["keywords_".$lang->prefix], "description" => $route["description_".$lang->prefix]  ];
                }
                $request->seo = json_encode($seo);
                break;
            }
        }
        return $next($request);
    }
}
