<?php
/**
 * @param $current
 * @param string $targets
 * @param string $class
 * @param bool $echo
 * @return string
 */
function selectMenu($current, $targets="", $class='active', $echo = true){
	$targets = explode('|', $targets);
	if(in_array(strtolower($current), $targets)){
		if($echo){
			echo $class;
		} else {
			return $class;
		}
	} 
	return '';
}

/**
 * @param $key
 * @param array $array
 * @param bool $arr
 * @return array|mixed|string
 */
function getValue($key, array $array, $arr = false){
	return array_key_exists($key, $array) ? $array[$key] : ($arr ? array() : '');
}

/**
 *  transId
 *  sellingCurrencyAmount
 *  accountingCurrencyAmount
 *  status
 *  Random Key (rKey)
 *  ResellBiz key
 *  array($transId, $sellingCurrencyAmount, $accountingCurrencyAmount, $status, $rKey, $key)
 * @param array $data
 * @return string
 */
function generateChecksum(array $data) {
    return md5(implode('|', $data));
}

/**
 *  array($paymentTypeId, $transId, $userId, $userType, $transactionType, $invoiceIds, $debitNoteIds, $description, $sellingCurrencyAmount, $accountingCurrencyAmount, $key)
 * @param $checksum
 * @param array $data
 * @return boolean
 */
function verifyChecksum($checksum, array $data){
    return md5(implode('|', $data))==$checksum;
}

/**
 * @return int
 */
function generateRkey() {
    srand((double)microtime()*1000000);
    return rand();
}

/**
 * @param $actual
 * @param $rate
 * @return float|int
 */
function currencyConvertToBDT($actual, $rate) {
    if( $rate>0 && $actual>0 ) {
        return $actual*$rate;
    }
    return 0;
}

/**
 * @param $actual
 * @param $rate
 * @return float|int
 */
function currencyConvertFromBDT($actual, $rate) {
    if( $rate>0 && $actual>0 ) {
        return $actual/$rate;
    }
    return 0;
}

/**
 * @param $amount
 * @param $percentage
 * @return float
 */
function calculateCharges($amount, $percentage) {
    $ac = ( $percentage / 100 ) * $amount;
    $mcr = ceil( $ac + $amount );
    return  ($mcr - ($amount + $ac)) + $ac;
}

/**
 * @param array $parameters
 * @return string
 */
function generateURLParameter(array $parameters){
    $p = array();
    foreach ($parameters as $k => $v) {
        $p[] = $k.'='.urlencode($v);
    }
    return implode('&', $p);
}

/**
 * @param array $errors
 * @param $key
 * @param bool $boolean
 * @param string $prev
 * @param string $next
 * @return bool|string
 */
function aclErrorBlock(array $errors, $key, $boolean = false, $prev='<label class="error">', $next='</label>') {
    return array_key_exists($key, $errors) ? ($boolean ? true : $prev.$errors[$key].$next) : ($boolean ? false : '');
}

/**
 * @param string $to
 * @return int|mixed
 */
function aclServerUploadMax($to='B') {
    static $ms = -1;

    if ($ms < 0) {
        $pms = __aclPS(ini_get('post_max_size'));
        if ($pms > 0) {
            $ms = $pms;
        }

        $um = __aclPS(ini_get('upload_max_filesize'));
        if ($um > 0 && $um < $ms) {
            $ms = $um;
        }
    }
    return $ms>0 ? __aclCB2O($ms, $to, 0) : 0;
}

/**
 * @param $s
 * @return float
 */
function __aclPS($s) {
    $u = preg_replace('/[^bkmgtpezy]/i', '', $s);
    $s = preg_replace('/[^0-9\.]/', '', $s);
    return $u ? round($s * pow(1024, stripos('bkmgtpezy', $u[0]))) : round($s);
}

/**
 * @param $bytes
 * @param $to
 * @param int $decimal_places
 * @return int|mixed
 */
function __aclCB2O($bytes, $to, $decimal_places = 1) {
    $formulas = array(
        'B' => $bytes,
        'K' => number_format($bytes / 1024, $decimal_places, '.', ''),
        'M' => number_format($bytes / 1048576, $decimal_places, '.', ''),
        'G' => number_format($bytes / 1073741824, $decimal_places, '.', '')
    );
    return isset($formulas[$to]) ? $formulas[$to] : 0;
}

/**
 * @return mixed
 */
function aclGetDomain() {
    return str_replace('www.', '', $_SERVER['HTTP_HOST']);
}

/**
 * @param $number
 * @return int
 */
function aclCalPLen($number) {
    if(is_numeric($number)) {
        $num = explode('.', $number);
        $num = end($num);
        return strlen($num);
    }
    return 1;
}

/**
 * @param $json
 * @return string
 */
function aclPretifyJson($json) {

    $result      = '';
    $pos         = 0;
    $strLen      = strlen($json);
    $indentStr   = '  ';
    $newLine     = "\n";
    $prevChar    = '';
    $outOfQuotes = true;

    for ($i=0; $i<=$strLen; $i++) {
        $char = substr($json, $i, 1);
        if ($char == '"' && $prevChar != '\\') {
            $outOfQuotes = !$outOfQuotes;
        } else if(($char == '}' || $char == ']') && $outOfQuotes) {
            $result .= $newLine;
            $pos --;
            for ($j=0; $j<$pos; $j++) {
                $result .= $indentStr;
            }
        }

        $result .= $char;

        if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
            $result .= $newLine;
            if ($char == '{' || $char == '[') {
                $pos ++;
            }

            for ($j = 0; $j < $pos; $j++) {
                $result .= $indentStr;
            }
        }

        $prevChar = $char;
    }

    return $result;
}

/**
 * @param $email
 * @param int $s
 * @param string $d
 * @param string $r
 * @param bool $img
 * @param array $atts
 * @return string
 */
function get_gravatar($email, $s = 80, $d = 'mp', $r = 'g', $img = false, $atts = array() ) {
    $url = 'https://www.gravatar.com/avatar/';
    $url .= md5( strtolower( trim( $email ) ) );
    $url .= "?s=$s&d=$d&r=$r";
    if ( $img ) {
        $url = '<img src="' . $url . '"';
        foreach ( $atts as $key => $val )
            $url .= ' ' . $key . '="' . $val . '"';
        $url .= ' />';
    }
    return $url;
}

/**
 * @param $n
 * @return string
 */
function aclOrdinal($n) {
    $e = array('th','st','nd','rd','th','th','th','th','th','th');
    return (($n % 100) >= 11) && (($n%100) <= 13) ? $n . 'th' : $n. $e[$n % 10];
}

/**
 * @param $actual
 * @param $part
 * @return string
 */
function aclCalculatePercentage($actual, $part) {
    return number_format( (($part/$actual) * 100), 2, '.', '' );
}

/**
 * @param $s
 * @param $e
 */
function aclGetWeek(&$s, &$e) {
    $ts = strtotime(date("Y-m-d"));
    $se = (date('w', $ts) == 0) ? $ts : strtotime('last saturday', $ts);
    $s = date('Y-m-d', $se);
    $e = date('Y-m-d', strtotime('next friday', $se));
}

/**
 * @param string $url
 * @param string $client
 * @return string
 */
function getReferrerHome($url="", $client="")
{
    switch ($client)
    {
        case 'customer' :
            $homeExt = '/CustomerIndexServlet';
            break;

        case 'reseller' :
            $homeExt = '/ResellerIndexServlet';
            break;

        default:
            $homeExt = '';
    }

    $pathInfo = pathinfo($url);

    return isset($pathInfo['dirname']) ? $pathInfo['dirname'] . $homeExt : '';
}