<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Route;

/**
 * String operations helper.
 * 
 */
class Utils
{

    public static function redirect($route = null)
    {
        if ($url = request('_redirect')) {
            return redirect($url);
        }
        return redirect($route);
    }

    public static function storageUrl($namespace, $filename)
    {
        $config = config('paths.' . $namespace);
        return asset('storage/' . ($config ? $config : $namespace) . '/' . $filename);
    }

    // @quikfix
    public static function getActiveClass($section, $current_section, $classname = 'active') {
        if ($section === $current_section) {
            return $classname;
        }
        return '';
    }

    public static function getActiveRouteClass($route, $classname = 'active')
    {
        $current_route = Route::getCurrentRoute();
        if (!$current_route) {
            return '';
        }
        // check exact route
        if ($current_route->getName() == $route) {
            return $classname;
        }

        // check by prefix
        if ($current_route->getPrefix() == $route) {
            return $classname;
        }
        return '';
    }

    /**
     * Replace the locale from the URL.
     * Useful when we want to get the current page but in different locale!
     * 
     * @param type $new_locale
     * @return type
     */
    public static function urlReplaceLocale($new_locale)
    {
        if ($new_locale === config('app.locale')) {
            return url()->current();
        }
        $root = request()->root();
        $path = request()->path();
        $query = request()->getQueryString();
        $full_url = ($path !== '/' ? $path : '') . ($query ? '?' . $query : '');
        $full_url = preg_replace('#^[a-z]{2}#', $new_locale, $full_url);
        return implode('/', [$root, $full_url]);
    }

}
