<?php


namespace App\Providers;

use \Exception;

/**
*
*/
class Shared
{
    

    public static function Redirect(string $to)
    {
        header("Location:$to");
        return exit();
    }


    /**
     * Generate real uniq id
     *
     * @access public
     * @static
     * @param int $lenght
     * @return string
     */
    public static function UniqIdReal(int $lenght = 13):string
    {
        /* uniqid gives 13 chars, but you could adjust it to your needs. */
        if (function_exists("random_bytes")) {
            $bytes = random_bytes(ceil($lenght / 2));
        } elseif (function_exists("openssl_random_pseudo_bytes")) {
            $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
        } else {
            throw new Exception("No cryptographically secure random function available");
        }
        return substr(bin2hex($bytes), 0, $lenght);
    }


    /**
     * A proper way to scan a directory, without dots
     *
     * @access public
     * @static
     * @param string $path
     * @return array
     */
    public static function ProperScandir(string $path):array
    {
        return
            array_slice(
                scandir($path),
                2
            );
    }


    /**
     * Convert to some variable to string
     *
     * @access public
     * @static
     * @param string|numeric|bool|null $variable
     * @throws Exception UNAUTHORIZE_TYPE
     * @return string
     */
    public static function Stringify($variable):string
    {
        if (is_string($variable) || is_numeric($variable)) {
            return "$variable";
        }

        if (is_bool($variable)) {
            return $variable ? 'TRUE' : 'FALSE';
        }

        if (is_null($variable)) {
            return 'NULL';
        }

        throw new Exception("UNAUTHORIZE_TYPE", 1);
    }







    public static function getSolde($transactions)
    {

        $solde = 0;

        foreach ($transactions as $trans) {
            if ( $trans->trans_type == 'plus' ) {
                $solde += $trans->trans_amount;
            } else {
                $solde -= $trans->trans_amount;
            }
        }
        
        return $solde;

    }


    public static function code()
    {

        $p1 = "3DSECURE";

        $p2 = date('Y');

        $p3 = strtoupper( self::UniqIdReal(5) );
        
        return "$p1$p2$p3";

    }








}
