<?php
namespace twa\htmlhelpers\helpers;

use twa\ecomgeneral\models\EcomStoreModel;
use twa\ecomprofile\models\EcomCountriesModel;
use function Symfony\Component\Translation\t;

class urlHelper
{

    function __construct(){
    }

    public function getCurrent(){
        return url()->current();
    }
    public function getCurrentFull(){
        return request()->fullUrl();
    }
    public function removeParameter($url,$params = false){
        if(!$params){
            $params = $url;
            $url = self::getCurrentFull();
        }
        if(!is_array($params)){
            $params = [ $params ];
        }
        foreach ($params AS $param){
            $url = self::removeParam($url, $param);
        }
        return $url;
    }


    public function addParameter($url,$params = false){
        if(!$params){
            $params = $url;
            $url = self::getCurrentFull();
        }

        if(!is_array($params)){
            $params = [ $params ];
        }
        foreach ($params AS $key => $param){
            $url = self::removeParam($url, $key);
        }
        foreach ($params AS $key => $param){
            if(is_array($param)){
                foreach ($param AS $pararm_row){
                    $url .= (parse_url($url, PHP_URL_QUERY) ? '&' : '?') . $key.'[]='.$pararm_row;
                }
            }else{
                $url .= (parse_url($url, PHP_URL_QUERY) ? '&' : '?') . $key.'='.$param;
            }
        }
        $url = str_replace('??','?',$url);
        return $url;
    }


    private function removeParam($url, $param)
    {

        $pieces = parse_url($url);
        $query = [];
        if (isset($pieces['query'])) {
            parse_str($pieces['query'], $query);
            unset($query[$param]);
        }
        $url = $pieces['scheme'].'://'.$pieces['host'].$pieces['path'].'?'.http_build_query($query);
        return $url;
    }


}
