<?php
use Illuminate\Support\Facades\Storage;
use App\Models\Taxonomy;

/**
 * Get Categories and childs
 */
function getCategories(int $parent = 0, $return= 'slug')
{
    // dump('parent=> '. $parent);
    $allCategories = Taxonomy::category()->where('parent', $parent)->get();
    $slugs= [];
    $categories= [];
    foreach ($allCategories as $cat) {
        // dump($cat->parent);
        if ($cat->parent == $parent) {
            if ('slug' == $return) {
                $slugs[] = $cat->term->slug;
                $slugs= array_merge($slugs, getCategories($cat->term_id, $return));
            } else {
                $categories= array_merge($categories, [$cat], getCategories($cat->term_id, $return));
            }
            // echo $cat->parent ." == ". $cat->term_id ." == ". $cat->term->name.'<br/>';
        }
    }
    return 'slug' == $return ? $slugs : $categories;
}

/**
 * Add Params to URL
 */
function addParamsToURL(string $url, array $params)
{
    $url.= (parse_url($url, PHP_URL_QUERY) ? '&' : '?').http_build_query($params);
    return $url;
}


/**
 * Upload 64 file
 * @param $image file
 * @return string image url
 */
function uploadBase64( $base64_image, $disk= 'thumbs' ): ?string
{
    if(!$base64_image) {
        return null;
    }
    $matched= preg_match('/^data:image\/(\w+);base64,/', $base64_image, $matches);
    // dd($matches);
    if ($matched) {
        $newFileName = time().'.'.$matches[1];
        $destinationPath= Storage::disk($disk)->path('');
        if ('portal' != $disk) {
            $destinationPath = str_replace (public_path('').'/', '', Storage::disk($disk)->path(''));
        }
        // dd($destinationPath);
        $data = substr($base64_image, strpos($base64_image, ',') + 1);
    
        $data = base64_decode($data);
        // $stored= Storage::disk('thumbs')->put($newFileName, $data);
        $stored= Storage::disk($disk)->put($newFileName, $data);
        // dd($stored, $destinationPath.$newFileName);
        return $destinationPath.$newFileName;
    } else {
        return null;
    }
}
?>