<?php

namespace App\Helpers;

class TextHelper
{
    public static function generateAcronym(string $str): string
    {
        $words = explode(' ', $str);
        $acronym = '';

        foreach ($words as $word) {
            $acronym .= $word[0];
        }

        return $acronym;
    }

    public static function checkString(string $string): string
    {
        return empty($string) ? "N/A" : $string;
    }

    public static function generateUsername(string $stringName, int $randomNumber = 100): string
    {
        $usernameParts = array_filter(explode(' ', strtolower($stringName)));
        $usernameParts = array_slice($usernameParts, 0, 2);

        $part1 = !empty($usernameParts[0]) ? substr($usernameParts[0], 0, 8) : '';
        $part2 = !empty($usernameParts[1]) ? substr($usernameParts[1], 0, 5) : '';
        $part3 = $randomNumber ? rand(0, $randomNumber) : '';

        $username = $part1 . str_shuffle($part2) . $part3;
        return $username;
    }

    public static function replaceText(string $body, array $array): string
    {
        return strtr($body, $array);
    }

    public static function generateCopyright(int|null $year = null): string
    {
        $currentYear = date('Y');
        if ($year === null) {
            return $currentYear;
        }
        if (intval($year) < $currentYear) {
            return intval($year) . ' - ' . $currentYear;
        }
        return $currentYear;
    }

    public static function removeCommas(string $text): string
    {
        $text = str_replace(",", "", $text);
        return $text;
    }

    public static function replaceSymbol($text, $symbol, $to): string
    {
        $text = str_replace($symbol, $to, $text);
        return $text;
    }

    public static function addDashes($text): string
    {
        $text = str_replace(" ", "-", $text);
        return $text;
    }

    public static function removeDashes($text): string
    {
        $text = str_replace("-", " ", $text);
        return $text;
    }

    /**
     * Limits string text to certain number
     * @param string $text
     * @param int $chars_limit
     *
     * @return string
     */
    public static function limit(string $text, int $chars_limit): string
    {
        if (strlen($text) > $chars_limit) {
            $new_text = substr($text, 0, $chars_limit);
            $new_text = trim($new_text);
            return $new_text . "...";
        } else {
            return $text;
        }
    }

    public static function breakText($longString, $len = 15, $separate = '\n\r'){
        return preg_replace("/(.{".$len."})/", "$1".$separate, $longString);
    }

    public static function readMore(string $string, int $max = 10, string $ending = "..."): string
    {
        // strip tags to avoid breaking any html
        $string = strip_tags($string);

        if (strlen($string) > $max) {
            // truncate string
            $stringCut = substr($string, 0, $max);

            //if the string doesn't contain any space then it will cut without word basis.
            $endPoint = strrpos($stringCut, ' ');
            $string = ($endPoint ? substr($stringCut, 0, $endPoint) : substr($stringCut, 0)) . $ending; 
        }

        return $string;
    }

    public static function empty_display($value): string
    {
        return $value ?: 'N/A';
    }

    public static function slugify($string): string
    {
        //Lower case everything
        $string = strtolower($string);
        $string = str_replace(['&amp;', '&', 'And', 'and'], '-', $string);
        $string = preg_replace("/[\s-_]+/", "-", $string);
        $string = preg_replace("/[^a-z0-9-]/", "", $string);
        return $string;
    }

    public static function maskEmail(string $email, int $shownChars = 2): string
    {
        [$username, $domain] = explode('@', $email);
        $hiddenChars = strlen($username) - $shownChars;
        $maskedUsername = substr_replace($username, str_repeat('*', $hiddenChars), $shownChars);
        return $maskedUsername . '@' . substr_replace($domain, str_repeat('*', $shownChars), 0, $shownChars);
    }

    /**
     * Places a mask on a string, useful for credit cards or other sensitive data that must be filtered
     *
     * @param string $string The string that needs to be masked
     * @param string $maskChar The character used for masking
     * @param int $unmaskAmount The number of characters that should remain unmasked
     * @param bool $maskFromEnd If true masking should start from the end of the string instead of the beginning
     * @return string
     */
    public static function maskString(string $string, string $maskChar = '*', int $unmaskAmount = 4, bool $maskFromEnd = false): string
    {
        $maskLength = strlen($string) - $unmaskAmount;
        return substr_replace($string, str_repeat($maskChar, $maskLength), $maskFromEnd ? -$maskLength : 0, $maskLength);
    }

    public static function position(int $number): string
    {
        $suffix = ['st', 'nd', 'rd'][$number % 10 - 1] ?? 'th';

        if ($number % 100 >= 11 && $number % 100 <= 13) {
            return "{$number}th";
        } else {
            return "{$number}{$suffix}";
        }
    }
}
