<?php

namespace App\Http\Controllers\Utils;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Laravolt\Avatar\Avatar;

class UtilController extends Controller
{
    /**
     * Slug function, creates a user readable slug from a provided string (title)
     * @param string $string
     * @return string;
     */
    public static function generateSlugFromString($string): string
    {
        return Str::slug($string);
    }

    /**
     * Generate token from a provided email
     * @param string $email
     * @return string
     */
    public static function generateToken(string $email = ''): string
    {
        return substr(md5(rand(0, 9) . $email . time()), 0, 32);
    }

    /**
     * Check if string is base64 encoded
     * @param string $data
     * @return boolean;
     */
    public static function isBase64Encoded($data): bool
    {
        if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * Replace the X occurrences of a character/ string in a string
     * @param string $from
     * @param string $to
     * @param string $content
     * @param int $number
     * @return string;
     */
    public static function replaceFirstString($from, $to, $content, $number): string
    {
        $from = '/'.preg_quote($from, '/').'/';

        return preg_replace($from, $to, $content, $number);
    }

    /**
     * Count occurances of a particular character/ string in a string
     * @param string $string
     * @param string $substring
     *
     */
    public static function countOccurrencesInString ($string, $substring): int
    {
        return substr_count($string, $substring);
    }

    /**
     * Generate avatar image from name, and save it to a specific path
     * @param string $image_name
     * @param string $name
     * @param string $path
     */
    public static function saveAvatarImage(string $image_name, string $name = 'user', string $path = 'app/public/users/')
    {
        $storage_path = storage_path($path);
        if (!file_exists($path)) {
            mkdir($path, 666, true);
        }

        (new Avatar)->create(strtoupper($name))->save($storage_path . $image_name);
    }
}
