<?php


declare(strict_types=1);

namespace App\Http\Controllers\Helpers\Permissions;

use App\Enums\UserTypes;
use Hypervel\Http\Request;
use App\Models\User;
use Hypervel\Support\Facades\Auth;
use App\Enums\UserActions;
use App\Http\Controllers\Helpers\QueryHelper;
use App\Models\Market\Product;
use App\Models\Market\Store;
use Exception;

class LibLegacy
{

    function endsWithSlash($path)
    {
        if (strlen($path) === 0) {
            return false;
        }
        $lastChar = substr($path, -1);
        return $lastChar === '/' || $lastChar === '\\';
    }

    function ArraytoHash($array)
    {
        if (!is_array($array) || empty($array)) {
            return false;
        }
        $jsonString = json_encode($array);
        $hash = hash('sha256', $jsonString);
        return $hash;
    }

    function SetNoCache()
    {
        header('Cache-Control: no-cache');
    }

    function SetCacheTime($seconds)
    {
        if ($seconds) {
            return false;
        }
        header('Cache-Control: max-age=' . $seconds . '');
    }
    function SetCacheTimeMinutes($minutes)
    {
        if ($minutes) {
            return false;
        }
        $seconds = $minutes * 60;
        header('Cache-Control: max-age=' . $seconds . '');
    }

    function SetCache1Year()
    {
        header('Cache-Control: max-age=31536000, public');
    }

    function json_array_echo($array)
    {
        jsonheader();
        echo json_encode($array);
    }
    function tryjsondecode($string, $arrayoutput = true)
    {
        if (is_array($string)) {
            return $string;
        }
        if (!$string) {
            return $string;
        }
        $json = json_decode($string, $arrayoutput);
        if ($json === null) {
            return $string;
        } else {
            return $json;
        }
    }

    function tryjsonencode($array)
    {
        if (!$array) {
            return json_encode([]);
        }
        if (is_array($array)) {
            $result = json_encode($array);
        } else {
            $result = json_encode([$array]);
        }
        return $result;
    }

    function filterArrayColumns($array, $columns)
    {
        return array_map(function ($item) use ($columns) {
            return array_intersect_key($item, array_flip($columns));
        }, $array);
    }

    function logmaker($filename, $nolog = false)
    {
        $main = new class ($filename, $nolog) {
            public $filename;
            public $loglistarray = [];

            public function __construct($filename, $nolog)
            {
                $this->filename = $filename;
                if ($nolog) {
                    return null;
                }
            }

            public function add($str)
            {
                $this->loglistarray[] = $str;
            }

            public function done()
            {
                file_put_contents($this->filename, implode("\r\n\r\n", $this->loglistarray));
            }

            function __destruct()
            {
                file_put_contents($this->filename, implode("\r\n\r\n", $this->loglistarray));
            }
        };
        return $main;
    }

    function createThumbnail($sourcePath, $destinationPath = null, $thumbWidth = 64, $thumbHeight = 64)
    {
        list($width, $height, $type) = getimagesize($sourcePath);
        $srcImage = null;

        switch ($type) {
            case IMAGETYPE_JPEG:
                $srcImage = imagecreatefromjpeg($sourcePath);
                break;
            case IMAGETYPE_PNG:
                $srcImage = imagecreatefrompng($sourcePath);
                break;
            case IMAGETYPE_GIF:
                $srcImage = imagecreatefromgif($sourcePath);
                break;
            default:
                throw new Exception('Unsupported image type');
        }

        $thumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);

        imagecopyresampled($thumbImage, $srcImage, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);

        if (!$destinationPath) {
            $basepath = dirname($sourcePath);
            $basenameWithoutExtension = pathinfo($sourcePath, PATHINFO_FILENAME);
            $extension = pathinfo($sourcePath, PATHINFO_EXTENSION) ?? '';
            if ($extension) {
                $extension = '.' + $extension;
            }
            $newfilename = $basenameWithoutExtension + '_thumbnail' + $extension;
            $destinationPath = $basepath + '/' + $newfilename;
        }

        switch ($type) {
            case IMAGETYPE_JPEG:
                imagejpeg($thumbImage, $destinationPath);
                break;
            case IMAGETYPE_PNG:
                imagepng($thumbImage, $destinationPath);
                break;
            case IMAGETYPE_GIF:
                imagegif($thumbImage, $destinationPath);
                break;
        }

        imagedestroy($srcImage);
        imagedestroy($thumbImage);
    }


    function trim_ending_hyphen($string)
    {
        if (substr($string, -1) === "-") {
            return substr($string, 0, -1);  // Remove the last character (hyphen)
        } else {
            return $string;  // Return the original string if it doesn't end with a hyphen
        }
    }

    function convertStringToSQLDateTime($stringDate)
    {
        $timestamp = strtotime($stringDate);
        $sqlDatetime = date("Y-m-d H:i:s", $timestamp);
        return $sqlDatetime;
    }


    function comparestringnumberstoarray($string, $comparearray, $inorder = false)
    {
        $mainarray = explode('-', $string);
        $mainarray = array_values($mainarray);

        $lastvaluemainarray = $mainarray[count($mainarray) - 1];
        if ($lastvaluemainarray === '') {
            array_pop($mainarray);
        }

        if (in_array('', $mainarray)) {
            return null;
        }

        if (!$inorder) {
            sort($mainarray);
            sort($comparearray);
        }

        return $mainarray == $comparearray;
    }


    function refreshpage()
    {
        return '<script>location.reload()</script>';
    }
    function refreshpagenopost()
    {

        return '<script>window.location = window.location.href</script>';
    }
    function refresh()
    {
        header('Location: .');
    }
    function jschangetopurl($url)
    {

        return '<script>top.location = "' . $url . '";</script>';
    }

    function jschangetopurlnoscripttag($url)
    {

        return "top.location = '" . $url . "';";
    }
    function jsopenmodal($modalname)
    {
        return '<script>
$(document).ready(function(){
    $("#' . $modalname . '").modal();
});
</script>';
    }

    function jsonheader()
    {
        header('Content-Type: application/json; charset=utf-8');
    }

    function simpleredirect($requesturl, $functiontoexecute, $reqtype = '', $fallbackfunction = NULL, $conditiontrue = NULL, $caching = false)
    {

        // sample url  = http://website.com/?u=name/{john}
        // sample function syntax simpleredirect('name/{}')

        if (file_exists('sim.txt')) {
            unlink('sim.txt');
        }
        $addlog = function ($str) {
            @file_put_contents('sim.txt', $str . "\r\n", FILE_APPEND);
        };



        $urlcheck = geturlparameters($requesturl);

        $addlog('chekingurl=' . getappendedurl() . '  requrl=' . $requesturl);

        if ($urlcheck === FALSE) {
            $addlog('urlcheck=false');
            return false;
        }
        $addlog('chekingurl success');
        if ($reqtype == '') {
            $reqtype = 'get';
            $addlog('reqtype unknown changing to get');
        } else {
            $reqtype = strtolower($reqtype);

            $addlog('reqtype = ' . $reqtype);
        }

        if ($reqtype !== 'post' and $reqtype !== 'get') {
            $reqtype = 'get';
            $addlog('reqtype not post or get changing to get');
        }

        if (strtolower($reqtype) !== strtolower($_SERVER['REQUEST_METHOD'])) {
            $addlog('reqtype not the same reqtype = ' . $reqtype . ' requestmethod = ' . $_SERVER['REQUEST_METHOD']);
            return FALSE;
        }

        $GLOBALS['urlparameters'] = $urlcheck;

        if ($conditiontrue !== NULL and !$conditiontrue) {
            $addlog('condition not true exiting');
            if ($fallbackfunction) {
                $fallbackfunction();
            }
            return FALSE;
        }

        if (!$caching) {
            $addlog('removing cache');
            removecaching();
        } elseif ($caching) {
            $addlog('adding cache');
            if ($caching === true) {
                SetCache1Year();
            } elseif (is_numeric($caching)) {
                SetCacheTimeMinutes($caching);
            } else {
                SetCache1Year();
            }
        }
        $addlog('executing function');
        $functiontoexecute($urlcheck);
    }


    function simpleredirectfile($requesturl, $file, $reqtype = '', $fallbackfunction = NULL, $conditiontrue = NULL, $caching = FALSE)
    {
        $filefunct = function () use ($file) {
            readfile($file);
        };
        simpleredirect($requesturl, $filefunct, $reqtype, $fallbackfunction, $conditiontrue, $caching);
    }


    function checkifstringisenclosedinbrackets($string)
    {
        // checks if string is enclosed in brackers ex {name}
        //returns string inside and returns false if there is no bracket
        if (substr($string, 0, 1) === "{" && substr($string, -1) === "}") {
            $string = substr($string, 1, -1);
        } else {
            $string = false;
        }
        return $string;
    }




    function geturlparameters($urlparam)
    {
        //urlparam = 'users/'
        if ($urlparam === '') {
            $urlparam = [];
        } else {
            $urlparam = explode('/', $urlparam);
        }
        $url = geturlarray();


        if (count($url) !== count($urlparam)) {
            return false;
        }


        $params = [];
        foreach ($urlparam as $key => $value) {
            if ($urlparam[$key] !== $url[$key]) {
                $enclosed = checkifstringisenclosedinbrackets($value);
                if ($enclosed) {
                    $params[$enclosed] = $url[$key];
                } else {
                    return false;
                }
            }
        }

        return $params;
    }

    function getLastDigitSegments($string, $n)
    {
        $parts = explode('-', $string);
        $lastSegments = array_slice($parts, -$n);
        return implode('-', $lastSegments);
    }
    function geturlarray()
    {
        $url = getappendedurl();

        if (substr($url, 0, 1) === "/") {
            $uri = substr($url, 1);
        } else {
            $uri = $url;
        }



        $uri = array_values(array_filter(explode('/', $uri)));
        unset($uri[0]);
        $uri = array_values($uri);
        if (empty($uri)) {
            return [];
        }
        if (substr($uri[0], 0, 1) === "?") {
            $uri[0] = substr($uri[0], 1);
        }

        return $uri;
    }

    function getappendedurl()
    {
        //get appended url sample url https:/google.com/aslkdfj/asdf/asdf
        //result 	aslkdfj/asdf/asdf
        return $_SERVER['REQUEST_URI'];
    }


    function removecaching()
    {
        if (headers_sent()) {
            return false;
        }
        header_remove('ETag');
        header_remove('Pragma');
        header_remove('Cache-Control');
        header_remove('Last-Modified');
        header_remove('Expires');

        // set header
        header('Expires: Thu, 1 Jan 1970 00:00:00 GMT');
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Cache-Control: post-check=0, pre-check=0', false);
        header('Pragma: no-cache');
    }


    function is_valid_var($var)
    {
        if (!isset($var)) {
            return null;
        }

        if (empty($var) || $var === false || is_null($var)) {
            return null;
        }

        return $var;
    }

    function ConvertDatetoMDYYYY($datestring)
    {
        //from YYYY-MM-DD to M/D/YYYY
        if (!$datestring) {
            return false;
        }

        $timestamp = strtotime($datestring);
        $formattedDate = date('n/j/Y', $timestamp);
        return $formattedDate;
    }

    function PNGtoJPGNN($filelocation, $newfilelocation)
    {
        $new_pic = imagecreatefrompng($filelocation);
        $w = imagesx($new_pic);
        $h = imagesy($new_pic);
        $white = imagecreatetruecolor($w, $h);
        $bg = imagecolorallocate($white, 255, 255, 255);
        imagefill($white, 0, 0, $bg);

        imagecopy($white, $new_pic, 0, 0, 0, 0, $w, $h);
        $success = imagejpeg($white, $newfilelocation);
        imagedestroy($new_pic);
        imagedestroy($white);


        return $success;
    }


    function PNGtoJPG($pngFilePath, $jpgFilePath, $maxWidth = false, $maxHeight = false, $quality = 100)
    {
        $pngImage = imagecreatefrompng($pngFilePath);
        if (!$pngImage) {
            return false;
        }

        $originalWidth = imagesx($pngImage);
        $originalHeight = imagesy($pngImage);
        if (!$maxWidth && !$maxHeight) {
            $maxWidth = $originalWidth;
            $maxHeight = $originalHeight;
        }

        $aspectRatio = $originalWidth / $originalHeight;

        if ($maxWidth / $maxHeight > $aspectRatio) {
            $newWidth = $maxHeight * $aspectRatio;
            $newHeight = $maxHeight;
        } else {
            $newWidth = $maxWidth;
            $newHeight = $maxWidth / $aspectRatio;
        }
        $newWidth = ceil($newWidth);
        $newHeight = ceil(num: $newHeight);

        $jpgImage = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($jpgImage, $pngImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
        $success = imagejpeg($jpgImage, $jpgFilePath, $quality);

        imagedestroy($pngImage);
        imagedestroy($jpgImage);
        return $success;
    }

    function PNGtoWebP($pngFilePath, $webpFilePath, $maxWidth = false, $maxHeight = false, $quality = 100)
    {
        $pngImage = imagecreatefrompng($pngFilePath);
        if (!$pngImage) {
            return false;
        }

        $originalWidth = imagesx($pngImage);
        $originalHeight = imagesy($pngImage);

        if (!$maxWidth && !$maxHeight) {
            $maxWidth = $originalWidth;
            $maxHeight = $originalHeight;
        }

        $aspectRatio = $originalWidth / $originalHeight;

        if ($maxWidth / $maxHeight > $aspectRatio) {
            $newWidth = $maxHeight * $aspectRatio;
            $newHeight = $maxHeight;
        } else {
            $newWidth = $maxWidth;
            $newHeight = $maxWidth / $aspectRatio;
        }
        $newWidth = ceil($newWidth);
        $newHeight = ceil(num: $newHeight);

        $webpImage = imagecreatetruecolor($newWidth, $newHeight);

        imagealphablending($webpImage, false);
        imagesavealpha($webpImage, true);
        $transparent = imagecolorallocatealpha($webpImage, 255, 255, 255, 127);
        imagefilledrectangle($webpImage, 0, 0, $newWidth, $newHeight, $transparent);

        imagecopyresampled($webpImage, $pngImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

        $success = imagewebp($webpImage, $webpFilePath, $quality);
        imagedestroy($pngImage);
        imagedestroy($webpImage);
        return $success;
    }

    function BatchConvertPNG($oldfolder, $newfolder, $newtype = 'webp', $maxWidth = false, $maxHeight = false, $quality = 100)
    {
        //filename from old folder to new folder is copied exactly even  the extensions are the same. 
        if (!$newtype) {
            $newtype = 'webp';
        }
        $oldfolder = AddSlashtoStrifNolastSlash($oldfolder);
        $newfolder = AddSlashtoStrifNolastSlash($newfolder);
        $processIMG = function ($oldfilename) use ($newfolder, $newtype, $maxWidth, $maxHeight, $quality) {
            if (!file_exists($oldfilename)) {
                echo $oldfilename . '<br>';
                return false;
            }
            $mimetype = mime_content_type($oldfilename);
            if (!str_contains($mimetype, 'png')) {
                return false;
            }
            $basefilename = basename($oldfilename);
            $newjpglocation = $newfolder . $basefilename;

            if (strtolower($newtype) === 'webp') {
                return PNGtoWebP($oldfilename, $newjpglocation, $maxWidth, $maxHeight, $quality);
            } elseif (strtolower($newtype) === 'jpg' || strtolower($newtype) === 'jpeg') {
                return PNGtoJPG($oldfilename, $newjpglocation, $maxWidth, $maxHeight, $quality);
            } else {
                return false;
            }
        };

        $dir = scandir($oldfolder);
        foreach ($dir as $keyy => $file) {
            if ($file === '..') {
                unset($dir[$keyy]);
                continue;
            }
            if ($file === '.') {
                unset($dir[$keyy]);
                continue;
            }
        }
        foreach ($dir as $file) {
            $oldfilename = $oldfolder . '/' . $file;
            $processIMG($oldfilename);
        }
    }


    function AddSlashtoStrifNolastSlash($str)
    {
        if (!$str) {
            return false;
        }
        $lastchar = substr($str, -1);
        if ($lastchar !== '/' && $lastchar !== '\\') {
            $str .= '/';
        }
        return $str;
    }


    function formatDateTimetoReadable($dateTimeString)
    {
        if (empty($dateTimeString)) {
            return '';
        }
        $date = new DateTime($dateTimeString);
        if (!$date) {
            return '';
        }
        $formattedDate = $date->format('F j, Y');
        $hours = (int) $date->format('g');
        $minutes = (int) $date->format('i');
        $ampm = $date->format('A');
        $formattedMinutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
        return strpos($dateTimeString, ' ') !== false
            ? "{$formattedDate} {$hours}:{$formattedMinutes}{$ampm}"
            : "{$formattedDate}";
    }

    function generateDatesOLD($daysArray, $months = 1, $sort = true)
    {
        if (!$daysArray) {
            return false;
        }
        if (!is_array($daysArray)) {
            $daysArray = tryjsondecode($daysArray);
        }
        if (!is_array($daysArray)) {
            return false;
        }

        $dates = [];

        // Iterate through each day in the array
        foreach ($daysArray as $day) {
            list($weekday, $time) = $day;

            $currentDate = new DateTime();
            $currentDate->modify("next $weekday");

            for ($i = 0; $i < $months; $i++) {
                // Add the time to the current date
                $dateWithTime = $currentDate->format('Y-m-d') . ' ' . $time;

                // Add the date to the array
                $dates[] = $dateWithTime;

                // Move to the next week (incrementing only the week part)
                $currentDate->modify('+1 week');
            }
        }

        // Sort the dates if specified
        if ($sort) {
            sort($dates);
        }

        return $dates;
    }



    function generateDatesNEW($daysArray, $months = 2, $sort = true)
    {
        if (!$daysArray) {
            return false;
        }
        if (!is_array($daysArray)) {
            $daysArray = tryjsondecode($daysArray);
        }
        if (!is_array($daysArray)) {
            return false;
        }

        $dates = [];

        // Iterate through each day in the array
        foreach ($daysArray as $day) {
            list($weekday, $time) = $day;

            $currentDate = new DateTime();

            // If today is the specified weekday, include it
            if (strtolower($currentDate->format('D')) === strtolower($weekday)) {
                $dateWithTime = $currentDate->format('Y-m-d') . ' ' . $time;
                $dates[] = $dateWithTime;
            }

            // Move to the next week (incrementing only the week part)
            $currentDate->modify("next $weekday");

            for ($i = 1; $i < $months; $i++) {
                // Add the time to the current date
                $dateWithTime = $currentDate->format('Y-m-d') . ' ' . $time;

                // Add the date to the array
                $dates[] = $dateWithTime;

                // Move to the next week (incrementing only the week part)
                $currentDate->modify('+1 week');
            }
        }

        // Sort the dates if specified
        if ($sort) {
            sort($dates);
        }

        return $dates;
    }

    function generateDates($daysArray, $days = 8, $sort = true)
    {
        $dates = generateDatesNEW($daysArray, $months = 4, $sort);
        unset($dates[0]);
        return array_splice($dates, 0, $days, []);
    }

    function GetTotalAmountfromArray($array)
    {
        if (!is_array($array)) {
            return false;
        }

        $total = 0;

        foreach ($array as $amount) {
            if (is_numeric($amount) && $amount !== '') {
                $total += $amount;
            }
        }
        return $total;
    }

    function removecolumnsfrom2Darray($array, $arraycolumnstoremove)
    {
        if (!is_array($array) or !is_array($arraycolumnstoremove)) {
            return false;
        }
        foreach ($array as $key => $value) {
            foreach ($value as $skey => $sval) {
                if (in_array($skey, $arraycolumnstoremove)) {
                    unset($array[$key][$skey]);
                }
            }
        }
    }

    function sqlarray_2dfilter($array, $columnname, string $stringtosearch, $exact = FALSE, $caseinsensitive = false, $simplesearchwith_strpos = false)
    {
        if ($columnname === '' or $columnname === null or $columnname === false) {
            return FALSE;
        }
        if (!$array) {
            return false;
        }
        $datatosearch = array_column($array, $columnname);
        if ($caseinsensitive) {
            $stringtosearch = strtolower($stringtosearch);
            foreach ($datatosearch as $key => $value) {
                $datatosearch[$key] = strtolower($value);
            }
        }

        if ($exact) {
            $keylist = array_keys($datatosearch, $stringtosearch);
        } else {
            if ($simplesearchwith_strpos) {
                $keylist = [];
                foreach ($datatosearch as $sskey => $ssvalue) {
                    if ($caseinsensitive) {
                        if (stripos($ssvalue, $stringtosearch)) {
                            $keylist[] = $sskey;
                        }
                    } elseif (!$caseinsensitive) {
                        if (strpos($ssvalue, $stringtosearch)) {
                            $keylist[] = $sskey;
                        }
                    }
                }
            } else {
                $stringtosearch = preg_quote($stringtosearch, '/'); // remove if an error is encountered
                $keylist = array_keys(preg_grep('/(?i)' . $stringtosearch . '/', $datatosearch));
            }
        }
        $res = [];
        foreach ($keylist as $value) {
            $res[] = $array[$value];
        }
        return $res;
    }

    function array2d_removeduplicate($array, $columnname, $reorder = FALSE)
    {
        $keylist = array_keys(array_unique(array_column($array, $columnname)));
        $newarray = [];
        foreach ($keylist as $value) {
            $newarray[$value] = $array[$value];
        }
        if ($reorder) {
            $newarray = array_values($newarray);
        }

        return $newarray;
    }


    /**
     * Searches a 2d array using a multiple words that match by separating by space.
     * 
     * This function takes a 2D array, a column name, and a search string as input.
     * It separates the search string by space and calls the sqlarray_2dfilter function
     * multiple times until all words are matched.
     * 
     * @param array $array The 2D array to search in.
     * @param string $columnname The name of the column to search in.
     * @param string $stringtosearch The search string to search for.
     * @param bool $exact Whether to search for exact matches or not. Defaults to FALSE.
     * @param bool $caseinsensitive Whether to perform a case-insensitive search or not. Defaults to FALSE.
     * @param bool $simplesearchwith_strpos Whether to use the strpos function for searching or not. Defaults to FALSE.
     * 
     * @return array The filtered data array where all words in the search string are present.
     */
    function sqlarray_2dfilter_multiple($array, $columnname, string $stringtosearch, $exact = FALSE, $caseinsensitive = false, $simplesearchwith_strpos = false)
    {
        if ($columnname === '' or $columnname === null or $columnname === false) {
            return FALSE;
        }
        if (!$array) {
            return false;
        }

        $words = explode(' ', $stringtosearch);
        $result = $array;

        foreach ($words as $word) {
            $result = sqlarray_2dfilter($result, $columnname, $word, $exact, $caseinsensitive, $simplesearchwith_strpos);
            if (empty($result)) {
                return [];
            }
        }

        return $result;
    }

    function sqlarray_2dfilterContinuos($array, $columnname, $stringarraytosearch, $exact = FALSE, $caseinsensitive = false)
    {
        $res = [];
        foreach ($stringarraytosearch as $key => $value) {
            $searchresult = sqlarray_2dfilter($array, $columnname, $value, $exact, $caseinsensitive);
            if (!$searchresult) {
                continue;
            }
            $res = [...$res, ...$searchresult];
        }
        return $res;
    }


    function encryptString($simple_string, $encryption_key)
    {
        $ciphering = "AES-128-CTR";
        $iv_length = openssl_cipher_iv_length($ciphering);
        $options = 0;
        $encryption_iv = '1218277893585121';
        $encryption = openssl_encrypt(
            $simple_string,
            $ciphering,
            $encryption_key,
            $options,
            $encryption_iv
        );
        return $encryption;

    }


    function decryptString($string, $decryption_key)
    {
        $ciphering = "AES-128-CTR";
        $decryption_iv = '1218277893585121';
        $options = 0;
        $decryption = openssl_decrypt(
            $string,
            $ciphering,
            $decryption_key,
            $options,
            $decryption_iv
        );
        return $decryption;
    }

    function objectToUrlSafeBase64($obj)
    {
        $jsonString = json_encode($obj);
        $base64String = base64_encode($jsonString);
        $urlSafeBase64 = str_replace(['+', '/', '='], ['-', '_', ''], $base64String);
        return $urlSafeBase64;
    }

    function urlSafeBase64ToObject($urlSafeBase64)
    {
        $base64String = str_replace(['-', '_'], ['+', '/'], $urlSafeBase64);
        $padding = strlen($base64String) % 4;
        if ($padding) {
            $base64String .= str_repeat('=', 4 - $padding);
        }
        $jsonString = base64_decode($base64String);
        return json_decode($jsonString);
    }

}

