<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/


class TB_Server_Utils_Helper {

    public static function getDate( $unixTs = NULL ) {
        if ( is_null(( $unixTs ) ) ) {
            $unixTs = time();
        }
        return date( 'j.n.y', $unixTs );
    }

    public static function getTime( $unixTs = NULL ) {
        if ( is_null(( $unixTs ) ) ) {
            $unixTs = time();
        }
        return date( 'G:i', $unixTs );
    }

    /**
     * @param array $jsonDate
     * @throws Exception
     */
    public static function getDatetimeFromJsonDate( array $jsonDate )
    {
        if ( !isset( $jsonDate[ 'date' ] ))
        {
            throw new \Exception( 'Invalid json date' );
        }

        return new DateTime( $jsonDate[ 'date' ] );
    }

    /**
     * @param DateTime $dt
     * @return string
     */
    public static function getMySqlDateTimeStringFromPHPDateTime( DateTime $dt )
    {
        return $dt->format( 'Y-m-d H:i:s' );
    }

    public static function getUTCNowDateTime()
    {
        return new DateTime( "now", new \DateTimeZone( "UTC" ) );
    }

    public static function getFirstnameFromEmail( $email )
    {
        $firstname = NULL;
        $parts = explode("@", $email );
        if ( count( $parts) > 0 )
        {
            $name = $parts[ 0 ];
            $nameParts = explode( ".", $name );
            if ( count( $nameParts ) > 0 )
            {
                $firstname = ucfirst( $nameParts[ 0 ] );
            }
        }

        return $firstname;
    }

    public static function getLastnameFromEmail( $email )
    {
        $lastname = NULL;
        $parts = explode("@", $email );
        if ( count( $parts) > 0 )
        {
            $name = $parts[ 0 ];
            $nameParts = explode( ".", $name );
            if ( count( $nameParts ) > 1 )
            {
                $lastname = array_pop( $nameParts );
                $lastname = ucfirst( $lastname );
            }
        }

        return $lastname;
    }

    public static function crypto_rand_secure($min, $max)
    {
        $range = $max - $min;
        if ($range < 1) return $min; // not so random...
        $log = ceil(log($range, 2));
        $bytes = (int) ($log / 8) + 1; // length in bytes
        $bits = (int) $log + 1; // length in bits
        $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
            $rnd = $rnd & $filter; // discard irrelevant bits
        } while ($rnd > $range);
        return $min + $rnd;
    }

    public static function getToken($length)
    {
        $token = "";
        $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
        $codeAlphabet.= "0123456789";
        $max = strlen($codeAlphabet); // edited

        for ($i=0; $i < $length; $i++) {
            $token .= $codeAlphabet[ self::crypto_rand_secure( 0, $max-1 ) ];
        }

        return $token;
    }

    /**
     * Public Team token is a fixed 4-character lentgh token consisting of the following tokens
     * 2,3,4,5,6,7,8,9, B,D,F,G,J,K,L,M,P,R,S,T,V,W,X
     * @return string
     */
    public static function getPublicTeamToken( array $usedIds )
    {
        $currentTry = 0;
        $maxTries = 10000;
        $token = NULL;
        while ( is_null( $token ) )
        {
            $token = self::generateTeamId();
            if ( in_array( $token, $usedIds ) )
            {
                $token = NULL;
            }

            $currentTry++;
            if ( $currentTry > $maxTries )
            {
                throw new Exception( "Too many tries in finding public team id." );
            }
        }
        return $token;
    }

    private static function generateTeamId()
    {
        $length = 4;
        $token = "";
        $codeAlphabet = "23456789BDFGJKLMPRSTVWX";

        $max = strlen($codeAlphabet); // edited

        for ($i=0; $i < $length; $i++)
        {
            $token .= $codeAlphabet[ self::crypto_rand_secure( 0, $max-1 ) ];
        }

        return $token;
    }

}