<?php

final class Util
{
    private function __construct()
    {
    }

    public static function printArr($dataArr)
    {
        echo '<pre>';
        print_r($dataArr);
        echo '</pre>';
    }

    public static function sendEmail($to, $toName, $from, $fromName, $subject, $mailContent, $sendBCC = 0)
    {
        ini_set('sendmail_from', $from);
        $headers = 'From: '.$fromName.'<'.$from.'>'.PHP_EOL;
        $headers .= 'Reply-To: '.FROM_NAME.'<'.FROM_EMAIL.'>'.PHP_EOL;
        $headers .= 'Return-Path: '.$from.PHP_EOL;
        $headers .= 'X-Mailer: BADHAI/'.phpversion().PHP_EOL;
        $headers .= 'MIME-Version: 1.0'.PHP_EOL;
        $headers .= 'Content-Type: text/html; utf-8 '.PHP_EOL;
        if ($sendBCC == 1) {
            $headers .= 'Bcc: '.SEND_BCC_EMAILS_TO_THIS_ID.PHP_EOL;
        }
        if (IS_REVERSE_LOOKUP_SET == 1) {
            return mail($to, $subject, $mailContent, $headers, '-r '.$from);
        } else {
            return mail($to, $subject, $mailContent, $headers);
        }
    }

    public static function isAjax()
    {
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            return true;
        }

        return false;
    }

    public static function isGuid($guid)
    {
        return preg_match('/^\{?[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\}?$/i', $guid);
    }

    public static function validateEmail($email)
    {
        return preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", $email);
    }

    public static function validateMobile($number)
    {
        return preg_match('/^[0-9]{10}$/i', $number);
    }

    public static function br2nl($string)
    {
        return preg_replace('/<br\\s*?\/??>/i', '', $string);
    }

    public static function nonxmlcharreplace($str)
    {
        $string = preg_replace('/[^a-zA-Z0-9\-]/', '-', $str);
        $newstr = preg_replace('/\-\-+/', '-', strtolower($string));

        return $newstr;
    }

    public static function nonxmlcharreplaceTitle($str)
    {
        $string = preg_replace('/[^a-zA-Z0-9\[\]\(\)\'\-\/:,;!$@%&]/', ' ', $str);
        $newstr = preg_replace('/\s\s+/', ' ', $string);

        return $newstr;
    }

    public static function getHashKey($key)
    {
        if ($key == 0) {
            return 0;
        } else {
            return $key % HASH_KEY_SPLIT;
        }
    }

    public static function setCookie($cookieName, $cookieData, $validity = 0)
    {
        if ($validity > 0) {
            setcookie($cookieName, self::encryptData($cookieData), time() + $validity, '/');
        } else {
            setcookie($cookieName, self::encryptData($cookieData), 0, '/');
        }
    }

    public static function getCookie($cookieName)
    {
        if (Cookie::has($cookieName)) {
            return @self::decryptData(Cookie::get($cookieName));
        } else {
            return false;
        }
    }

    public static function encryptData($data)
    {
        return strrev(base64_encode($data));
    }

    public static function decryptData($data)
    {
        return base64_decode(strrev($data));
    }

    public static function generateXML2($aResult, $sMainTag = 'xml')
    {
        $data_xml = '<'.$sMainTag.'>';
        if (is_array($aResult)) {
            foreach ($aResult as $sKey => $sValue) {
                $sTag = strtolower($sKey);
                if (is_string($sValue)) {
                    $data_xml .= '<'.$sTag.'><![CDATA['.$sValue.']]></'.$sTag.'>';
                } else {
                    $data_xml .= '<'.$sTag.'>'.$sValue.'</'.$sTag.'>';
                }
            }
        }
        $data_xml .= '</'.$sMainTag.'>';

        return $data_xml;
    }

    public static function generateXML3($aResult, $sMainTag = 'xml', $sLoopTag = 'data')
    {
        $data_xml = '<'.$sMainTag.'>';
        if (is_array($aResult)) {
            foreach ($aResult as $Row => $aValue) {
                $data_xml .= '<'.$sLoopTag.'>';
                if (is_array($aValue)) {
                    foreach ($aValue as $sKey => $sValue) {
                        $sTag = strtolower($sKey);
                        if (is_string($sValue)) {
                            $data_xml .= '<'.$sTag.'><![CDATA['.$sValue.']]></'.$sTag.'>';
                        } else {
                            $data_xml .= '<'.$sTag.'>'.$sValue.'</'.$sTag.'>';
                        }
                    }
                }
                $data_xml .= '</'.$sLoopTag.'>';
            }
        }
        $data_xml .= '</'.$sMainTag.'>';

        return $data_xml;
    }

    public static function generateXML($aResult, $sMainTag = 'xml', $sLoopTag = 'data')
    {
        $data_xml = '<'.$sMainTag.'>';
        if (is_array($aResult)) {
            foreach ($aResult as $Row => $aValue) {
                $data_xml .= '<'.$sLoopTag.'>';
                if (is_array($aValue)) {
                    foreach ($aValue as $sKey => $sValue) {
                        $sTag = strtolower($sKey);
                        if (is_string($sValue)) {
                            $data_xml .= '<'.$sTag.'><![CDATA['.$sValue.']]></'.$sTag.'>';
                        } else {
                            $data_xml .= '<'.$sTag.'>'.$sValue.'</'.$sTag.'>';
                        }
                    }
                }
                $data_xml .= '</'.$sLoopTag.'>';
            }
        }
        $data_xml .= '</'.$sMainTag.'>';

        return $data_xml;
    }

    public static function toXml($array, $tag, $subTag)
    {
        return '<'.$tag.'>'.self::ia2xml($array, $subTag).'</'.$tag.'>';
    }

    public static function ia2xml($array, $subTag)
    {
        $xml = '';
        foreach ($array as $key => $value) {
            $key = is_string($key) ? $key : $subTag;
            $key = str_replace(' ', '_', $key);
            if (is_array($value)) {
                $xml .= '<'.$key.'>'.self::ia2xml($value, $subTag).'</'.$key.'>';
            } else {
                if (is_string($value)) {
                    $xml .= '<'.$key.'><![CDATA['.$value.']]></'.$key.'>';
                } else {
                    $xml .= '<'.$key.'>'.$value.'</'.$key.'>';
                }
            }
        }

        return $xml;
    }

    public static function getJson($arrValue)
    {
        return json_encode($arrValue);
    }

    public static function getDurationInDays($startDate, $endDate = '')
    {
        if ($endDate == '') {
            $endDate = date('Y-m-d');
        }

        return ceil((strtotime($endDate) - strtotime($startDate)) / 86400);
    }

    public static function convertFacebookDate($dateStr, $format = 'Y-m-d')
    {
        if ($dateStr != null) {
            $dateStr = str_replace('/', '-', $dateStr);
            if (strlen($dateStr) < 10) {
                $dateStr = '0000-'.$dateStr;
            } else {
                $dateStr = '0000'.'-'.substr($dateStr, 0, 5);
            }

            return $dateStr;
        } else {
            return;
        }
    }

    public static function convertFacebookDateReal($dateStr, $format = 'Y-m-d')
    {
        if ($dateStr != null) {
            $dateStr = str_replace('/', '-', $dateStr);
            if (strlen($dateStr) < 10) {
                $dateStr = '1801-'.$dateStr;
            } else {
                $dateArr = explode('-', $dateStr);
                $date = mktime(0, 0, 0, $dateArr[0], $dateArr[1], $dateArr[2]);
                $dateStr = date('Y-m-d', $date);
            }

            return $dateStr;
        } else {
            return;
        }
    }

    public static function getDate($dateStr, $format = '')
    {
        $dateStr = str_replace('/', '-', $dateStr);
        if ($format == '') {
            $format = 'd-m-Y';
        }
        try {
            return date_format(date_create($dateStr), $format);
        } catch (Exception $e1) {
            try {
                return date($format, strtotime($dateStr));
            } catch (Exception $e2) {
            }
        }

        return date($format);
    }

    public static function getNoOfdays($dateStr)
    { // $dateStr - Date I/P Format : Y-m-d h:m:s
        $validTill = strtotime($dateStr);
        $currDate = strtotime(date('d-m-Y 00:00:00'));
        if ($validTill > $currDate) {
            $noOfdyas = ceil(($validTill - $currDate) / 86400);
        } else {
            $noOfdyas = 0;
        }

        return $noOfdyas;
    }

    public static function getNoOfhours($dateStr)
    { // $dateStr - Date I/P Format : Y-m-d h:m:s
        $validTill = strtotime($dateStr);
        $currDate = time();
        if ($validTill > $currDate) {
            $noOfhours = ceil(($validTill - $currDate) / 3600);
        } else {
            $noOfhours = 0;
        }

        return $noOfhours;
    }

    public static function getNoOfminutes($dateStr)
    { // $dateStr - Date I/P Format : Y-m-d h:m:s
        $validTill = strtotime($dateStr);
        $currDate = time();
        if ($validTill > $currDate) {
            $noOfhours = ceil(($validTill - $currDate) / 60);
        } else {
            $noOfhours = 0;
        }

        return $noOfhours;
    }

    public static function getNoOfdaysInBirthday($dateStr)
    { // $dateStr - Date I/P Format : d-m
        $validTill = strtotime($dateStr.date('-Y'));
        $currDate = strtotime(date('d-m-Y 00:00:00'));
        $noOfdyas = ceil(($validTill - $currDate) / 86400);
        if ($noOfdyas < 0) {
            $noOfdyas = $noOfdyas + 365;
        }

        return $noOfdyas;
    }

    public static function getDateAdvanceDays($dateStr, $noOfDays, $format = '')
    {
        if ($format == '') {
            $format = 'd-m-Y';
        }

        return date($format, strtotime("+$noOfDays days", strtotime($dateStr)));
    }

    public static function getAdvanceDate($noOfDays, $dateStr = '01-01-1900', $format = '')
    { // $dateStr : d-m-Y
        $date = new DateTime('01-01-1900');
        $date->modify('+'.$noOfDays.' day');
        if ($format == '') {
            $format = 'd-m-Y';
        }

        return $date->format($format);
    }

    public static function getDateTime24($dateStr)
    {
        return date('d-m-Y H:i:s', strtotime($dateStr));
    }

    public static function getDateTime12($dateStr, $format = null)
    {
        if ($format == null) {
            return date('d-m-Y h:i:s a', strtotime($dateStr));
        } else {
            return date($format, strtotime($dateStr));
        }
    }

    public static function getTime12($dateStr)
    {
        return date('h:i A', strtotime($dateStr));
    }

    public static function getPreviousDayDate($date = '')
    {
        if ($date == '') {
            $date = date('Y-m-d');
        }

        return date('Y-m-d', mktime(0, 0, 0, date('m', strtotime($date)), date('d', strtotime($date)) - 1, date('Y', strtotime($date))));
    }

    public static function getNextDayDate($date = '')
    {
        if ($date == '') {
            $date = date('Y-m-d');
        }

        return date('Y-m-d', mktime(0, 0, 0, date('m', strtotime($date)), date('d', strtotime($date)) + 1, date('Y', strtotime($date))));
    }

    public static function dateToMysql($date)
    { // date to mysql date
        $date = str_replace('/', '-', $date);
        if (strlen($date) > 0) {
            try {
                // return date_format(date_create($date), 'Y-m-d H:i:s');
                return date_format(date_create($date), 'Y-m-d');
            } catch (Exception $e1) {
                try {
                    // return date('Y-m-d H:i:s', strtotime($date));
                    return date('Y-m-d', strtotime($date));
                } catch (Exception $e2) {
                }
            }
        }

        return '0000-00-00 00:00:00';
    }

    public static function mysqlToDateTime($date)
    { // mysql date to date
        $date = str_replace('/', '-', $date);
        if (strlen($date) > 0) {
            try {
                return date_format(date_create($date), 'd-m-Y H:i:s');
            } catch (Exception $e1) {
                try {
                    return date('d-m-Y H:i:s', strtotime($date));
                } catch (Exception $e2) {
                }
            }
        }

        return '';
    }

    public static function mysqlToDate($date)
    { // mysql date to date
        if (strlen($date) > 0 && $date != '0000-00-00 00:00:00') {
            try {
                return date_format(date_create($date), 'd-m-Y');
            } catch (Exception $e1) {
                try {
                    return date('d-m-Y', strtotime($date));
                } catch (Exception $e2) {
                }
            }
        }

        return '';
    }

    public static function getCurrentTimeInMillisecond()
    {
        list($timestamp, $sec) = explode(' ', microtime());
        $timestamp += $sec;
        $timestamp = str_replace('.', '', $timestamp);

        return $timestamp;
    }

    public static function repalceNonAscii($val)
    {
        $val = preg_replace('/[^(\x20-\x7F)]*/', '', $val);

        return $val;
    }

    //Sandeep
    public static function ArrayToXML($root_element_name, $ar)
    {
        $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
        $f = create_function('$f,$c,$a', '
            foreach($a as $k=>$v) {
                if(is_array($v)) {
                    $ch=$c->addChild($k);
                    $f($f,$ch,$v);
                } else {
                    $c->addChild($k,$v);
                }
            }');
        $f($f, $xml, $ar);

        return $xml->asXML();
    }

    public static function arrayToCSVSimple($array, $qut = '"', $col_sep = ',')
    {
        $output = '';
        $tmp = '';
        foreach ($array as $val) {

            //foreach ($val as $cell_key => $cell_val) {
            //Escaping quotes.
            //$cell_val = str_replace($qut, "$qut$qut", $cell_val);
            $tmp .= "$qut$val$qut".$col_sep;
            //}
        }
        $output = substr($tmp, 0, -1); // . $col_sep;
        return $output;
    }

    public static function array_to_csv($array, $header_row = true, $col_sep = ',', $row_sep = "\n", $qut = '"')
    {
        if (!is_array($array) or !is_array($array[0])) {
            return false;
        }

        $output = '';
        //Header row.
        if ($header_row) {
            foreach ($array[0] as $key => $val) {
                //Escaping quotes.
                $key = str_replace($qut, "$qut$qut", $key);
                $output .= "$col_sep$qut$key$qut";
            }
            $output = substr($output, 1)."\n";
        }
        //Data rows.
        foreach ($array as $key => $val) {
            $tmp = '';
            foreach ($val as $cell_key => $cell_val) {
                //Escaping quotes.
                $cell_val = str_replace($qut, "$qut$qut", $cell_val);
                $tmp .= "$col_sep$qut$cell_val$qut";
            }
            $output .= substr($tmp, 1).$row_sep;
        }

        return $output;
    }

    public static function cutDisplayName($displayName, $numChars = 12)
    {
        if (strlen($displayName) > $numChars + 3) {
            return substr($displayName, 0, $numChars).'...';
        }

        return $displayName;
    }

    public static function cutDisplayNameForGridView($displayName, $numChars = 30)
    {
        if (strlen($displayName) > $numChars + 3) {
            return substr($displayName, 0, $numChars).'...';
        }

        return $displayName;
    }

    public static function cutPhrase($displayName, $numChars = 12)
    {
        if (strlen($displayName) > $numChars + 3) {
            return substr($displayName, 0, $numChars).'..';
        }

        return $displayName;
    }

    public static function downloadCSV($fileName)
    {
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename='.$fileName);
        header('Pragma: no-cache');
        readfile(DEPLOY_PATH.'/images/downloads/'.$fileName);
        exit;
    }

    public static function downloadEXCEL($fileName)
    {
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename='.$fileName);
        header('Pragma: no-cache');
        readfile(DEPLOY_PATH.'/images/downloads/'.$fileName);
        exit;
    }

    public static function checkeventCustomdate($occasion_customdate, $occ_id)
    {
        $status_occasion_customdate = 0;
        foreach ($occasion_customdate as $id) {
            if (trim($occ_id) == trim($id)) {
                $status_occasion_customdate = 1;
            }
        }

        return $status_occasion_customdate;
    }

    public static function convertJsonString($inputString, $key, $endwith, $endreplacement)
    {
        $pattern = '|\"'.$key.'\"\:(\d+)'.$endwith.'|';
        $replace = '"'.$key.'":"$1"'.$endreplacement.'';

        return preg_replace($pattern, $replace, $inputString);
    }

    public static function escapeforJS($input)
    {
        if (is_string($input)) {
            return preg_replace("/\r?\n/", '\\n', addslashes($input));
        } else {
            return '';
        }
    }

    public static function getListofIds($list, $colName)
    {
        $strAllVals = null;
        if (is_array($list) && count($list) > 0) {
            $strAllVals = ',';
            foreach ($list as $val) {
                $strAllVals .= $val[$colName].',';
            }
        }

        return $strAllVals;
    }

    public static function getCountryFromIP($ipAddr)
    {
        //verify the IP address for the  
        ip2long($ipAddr) == -1 || ip2long($ipAddr) === false ? trigger_error('Invalid IP', E_USER_ERROR) : '';
        // This notice MUST stay intact for legal use
        $ipDetail = array(); //initialize a blank array
        //get the XML result from hostip.info
        $xml = file_get_contents('http://api.hostip.info/?ip='.$ipAddr);
        //get the country name inside the node <countryName> and </countryName>
        preg_match('@<countryName>(.*?)</countryName>@si', $xml, $matches);
        if (count($matches) > 0) {
            //assign the country name to the $ipDetail array   
            $ipDetail['country'] = isset($matches[1]) ? $matches[1] : '';

            return $ipDetail['country'];
        }

        return false;
    }

    public static function currency($amount, $from_Currency = 'USD', $to_Currency = 'INR')
    {
        $amount = urlencode($amount);
        $from_Currency = urlencode($from_Currency);
        $to_Currency = urlencode($to_Currency);
        $url = "https://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
        $ch = curl_init();
        $timeout = 0;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $rawdata = curl_exec($ch);
        curl_close($ch);
        print_r($rawdata);
        exit;
        $data = explode('"', $rawdata);
        $data = explode(' ', $data['3']);
        $var = $data['0'];
        // return round($var,3);
//            if(!is_int($var)){
//                $return[0] =  util::ceil_dec($data['0'], 2);                
//                $return[1] =  $data['0'];                
//            }else{
//                $return[0] = $return[1] = $data['0'];
//            } 
        return $data['0'];
    }

    public static function ceil_dec($number, $precision, $separator = '.')
    {
        $appendZero = false;
        $numberpart = explode($separator, $number);
        $numberpart[1] = substr_replace($numberpart[1], $separator, $precision, 0);
        if ($numberpart[1][0] == 0) {
            $appendZero = true;
        }
        if ($numberpart[0] >= 0) {
            $numberpart[1] = ceil($numberpart[1]);
        } else {
            $numberpart[1] = floor($numberpart[1]);
        }
        if ($appendZero) {
            $numberpart[1] = (int) '0'.$numberpart[1];
        }
        $ceil_number = array($numberpart[0], $numberpart[1]);

        return implode($separator, $ceil_number);
    }

    public static function startsWith($haystack, $needle)
    {
        return strpos($haystack, $needle) === 0;
    }

    public static function endsWith($haystack, $needle)
    {
        return substr($haystack, -strlen($needle)) == $needle;
    }

    public static function reverse_strrchr($haystack, $needle, $trail)
    {
        return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
    }

    public static function changenumberFormat($number)
    {
        if (strlen($number) > 10) {
            if (substr($number, 0, 2) == 91) {
                $number = substr($number, 2);
            }
        }

        return $number;
    }

    public static function convert_number_to_words($number)
    {
        $hyphen = '-';
        $conjunction = ' and ';
        $separator = ', ';
        $negative = 'negative ';
        $decimal = ' point ';
        $dictionary = array(
            0 => 'zero',
            1 => 'one',
            2 => 'two',
            3 => 'three',
            4 => 'four',
            5 => 'five',
            6 => 'six',
            7 => 'seven',
            8 => 'eight',
            9 => 'nine',
            10 => 'ten',
            11 => 'eleven',
            12 => 'twelve',
            13 => 'thirteen',
            14 => 'fourteen',
            15 => 'fifteen',
            16 => 'sixteen',
            17 => 'seventeen',
            18 => 'eighteen',
            19 => 'nineteen',
            20 => 'twenty',
            30 => 'thirty',
            40 => 'fourty',
            50 => 'fifty',
            60 => 'sixty',
            70 => 'seventy',
            80 => 'eighty',
            90 => 'ninety',
            100 => 'hundred',
            1000 => 'thousand',
            1000000 => 'million',
            1000000000 => 'billion',
            1000000000000 => 'trillion',
            1000000000000000 => 'quadrillion',
            1000000000000000000 => 'quintillion',
        );

        if (!is_numeric($number)) {
            return false;
        }

        if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {
            // overflow
            trigger_error(
                    'convert_number_to_words only accepts numbers between -'.PHP_INT_MAX.' and '.PHP_INT_MAX, E_USER_WARNING
            );

            return false;
        }

        if ($number < 0) {
            return $negative.self::convert_number_to_words(abs($number));
        }

        $string = $fraction = null;

        if (strpos($number, '.') !== false) {
            list($number, $fraction) = explode('.', $number);
        }

        switch (true) {
            case $number < 21:
                $string = $dictionary[$number];
                break;
            case $number < 100:
                $tens = ((int) ($number / 10)) * 10;
                $units = $number % 10;
                $string = $dictionary[$tens];
                if ($units) {
                    $string .= $hyphen.$dictionary[$units];
                }
                break;
            case $number < 1000:
                $hundreds = $number / 100;
                $remainder = $number % 100;
                $string = $dictionary[$hundreds].' '.$dictionary[100];
                if ($remainder) {
                    $string .= $conjunction.self::convert_number_to_words($remainder);
                }
                break;
            default:
                $baseUnit = pow(1000, floor(log($number, 1000)));
                $numBaseUnits = (int) ($number / $baseUnit);
                $remainder = $number % $baseUnit;
                $string = self::convert_number_to_words($numBaseUnits).' '.$dictionary[$baseUnit];
                if ($remainder) {
                    $string .= $remainder < 100 ? $conjunction : $separator;
                    $string .= self::convert_number_to_words($remainder);
                }
                break;
        }

        if (null !== $fraction && is_numeric($fraction)) {
            $string .= $decimal;
            $words = array();
            foreach (str_split((string) $fraction) as $number) {
                $words[] = $dictionary[$number];
            }
            $string .= implode(' ', $words);
        }

        return $string;
    }

    public static function toAlpha($curr_no)
    { // convert single number to letter -- a=0, b=1, ---,i=8,j=9
        $alphabet = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
        $char = '';
        for ($i = 0; $i < strlen($curr_no); ++$i) {
            $char .= $alphabet[substr($curr_no, $i, 1)];
        }

        return $char;
    }

    //Relative Date Function
    public static function RelativeDateString($time)
    {
        $today = strtotime(date('M j, Y'));
        $reldays = ($time - $today) / 86400;
        if ($reldays >= 0 && $reldays < 1) {
            return 'Today';
        } elseif ($reldays >= 1 && $reldays < 2) {
            return 'Tomorrow';
        } elseif ($reldays >= -1 && $reldays < 0) {
            return 'Yesterday';
        }
        if (abs($reldays) < 7) {
            if ($reldays > 0) {
                $reldays = floor($reldays);

                return 'In '.$reldays.' day'.($reldays != 1 ? 's' : '');
            } else {
                $reldays = abs(floor($reldays));

                return $reldays.' day'.($reldays != 1 ? 's' : '').' ago';
            }
        }
        if (abs($reldays) < 182) {
            //return date('l, j F',$time ? $time : time());
            return date('j F', $time ? $time : time());
        } else {
            //return date('l, j F, Y',$time ? $time : time());
            return date('j F, Y', $time ? $time : time());
        }
    }

    public static function setDomainCookie($cookieName, $cookieData, $domain, $rememberMe = 0)
    {
        if ($rememberMe == 1) {
            $validity = 2592000;
        } else {
            $validity = 0;
        }
        $validity = 0;
        if ($validity > 0) {
            //setcookie($cookieName, self::encryptData($cookieData), time() + $validity, '/', null, $domain);
            $cookie = Cookie::make($cookieName, $cookieData, time() + $validity);
        } else {
            //setcookie($cookieName, self::encryptData($cookieData), 0, '/', null, $domain);
            $cookie = Cookie::make($cookieName, self::encryptData($cookieData));
        }

        return $cookie;
    }

    public static function deleteCookie($cookieName)
    {
        $cookie = Cookie::forget($cookieName);

        return $cookie;
    }

//    public function bitwiseNot ($value){
//        if($value == 0){
//            return 1;
//        }else if(is_int($value)){
//            return 0;
//        }
//    }

    public static function encodeUrlPart($part)
    {
        if (isset($part) && count($part) > 0) {
            $part60 = str_replace('&', '-', $part);
            $part50 = str_replace(',', '-', $part60);
            $part40 = str_replace('\\', '-', $part50);
            $part30 = str_replace('/', '-', $part40);
            $part20 = str_replace('&amp;', '-', $part30);
            $part0 = str_replace('  ', '-', $part20);
            $part1 = str_replace(' ', '-', $part0);
            $part2 = str_replace('---', '-', $part1);
            $part3 = str_replace('--', '-', $part2);
            $part4 = urlencode($part3);

            return $part4;
        }
    }

    public function encodeToUtf8($string)
    {
        return mb_convert_encoding($string, 'UTF-8', mb_detect_encoding($string, 'UTF-8, ISO-8859-1, ISO-8859-15', true));
    }

    public function encodeToIso($string)
    {
        return mb_convert_encoding($string, 'ISO-8859-1', mb_detect_encoding($string, 'UTF-8, ISO-8859-1, ISO-8859-15', true));
    }

    /* for new login functionality ends */

    public static function getPostArrayFromPostString($str)
    {
        $arr = explode('&amp;', $str);
        $newArr = array();
        foreach ($arr as $key => $value) {
            $newKeyVal = explode('=', $value);
            $newArr[$newKeyVal[0]] = $newKeyVal[1];
        }

        return $newArr;
    }

    /* Functions for Rewards Recognitation system - RRS */

    public static function time_stamp($session_time)
    {
        $time_difference = time() - $session_time;
        $seconds = $time_difference;
        $minutes = round($time_difference / 60);
        $hours = round($time_difference / 3600);
        $days = round($time_difference / 86400);
        $weeks = round($time_difference / 604800);
        $months = round($time_difference / 2419200);
        $years = round($time_difference / 29030400);
        if ($seconds <= 60) {
            echo"$seconds seconds ago";
        } elseif ($minutes <= 60) {
            if ($minutes == 1) {
                echo'one minute ago';
            } else {
                echo"$minutes minutes ago";
            }
        } elseif ($hours <= 24) {
            if ($hours == 1) {
                echo'one hour ago';
            } else {
                echo"$hours hours ago";
            }
        } elseif ($days <= 7) {
            if ($days == 1) {
                echo'one day ago';
            } else {
                echo"$days days ago";
            }
        } elseif ($weeks <= 4) {
            if ($weeks == 1) {
                echo'one week ago';
            } else {
                echo"$weeks weeks ago";
            }
        } elseif ($months <= 12) {
            if ($months == 1) {
                echo'one month ago';
            } else {
                echo"$months months ago";
            }
        } else {
            if ($years == 1) {
                echo'one year ago';
            } else {
                echo"$years years ago";
            }
        }
    }

    public static function clear($text)
    {
        $final = stripslashes(stripslashes($text));

        return $final;
    }

    public static function textlink($text)
    {
        $text = html_entity_decode($text);
        $text = ' '.$text;
        if (preg_match('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', $text, $a)) {
        } elseif (preg_match('(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', $text, $a)) {
        } else {
            $a = false;
        }

        return $a[0];
    }

    public static function Expand_URL($url)
    {
        $returns = '';
        if (!empty($url)) {
            if (eregi('youtu', $url) or eregi('youtube', $url)) {
                if (eregi('v=', $url)) {
                    $splits = explode('=', $url);
                } else {
                    $splits = explode('be/', $url);
                }

                if (!empty($splits[1])) {
                    if (preg_match('/feature/i', $splits[1])) {
                        $splits[1] = str_replace('&feature', '', $splits[1]);
                    }
                    $returns = '<iframe width="410" height="200" src="http://www.youtube.com/embed/'.$splits[1].'" frameborder="0"></iframe>';
                }
            } elseif (eregi('vimeo', $url)) {
                $splits = explode('com/', $url);
                $returns = '<iframe src="http://player.vimeo.com/video/'.$splits[1].'?title=0&amp;byline=0&amp;portrait=0" width="410" height="200" frameborder="0"></iframe>';
            } elseif (eregi('dailymotion', $url)) {
                $splits = explode('video/', $url);
                $splits = explode('_', $splits[1]);
                $returns = '<iframe frameborder="0" width="410" height="200" src="http://www.dailymotion.com/embed/video/'.$splits[0].'"></iframe>';
            } elseif (eregi('collegehumor', $url)) {
                $splits = explode('video/', $url);
                $splits = explode('/', $splits[1]);
                $returns = '<iframe src="http://www.collegehumor.com/e/'.$splits[0].'" width="410" height="200" frameborder="0"></iframe>';
            } elseif (eregi('metacafe', $url)) {
                $splits = explode('watch/', $url);
                $splits = explode('/', $splits[1]);
                $key = "$splits[0]/$splits[1].swf";

                $returns = '<embed flashVars="playerVars=autoPlay=no" src="http://www.metacafe.com/fplayer/'.$key.'" width="410" height="200"></embed>';
            }
        }

        return $returns;
    }

    public static function htmlcode($text)
    {
        $stvarno = array('<', '>');
        $zamjenjeno = array('&lt;', '&gt;');
        $final = str_replace($stvarno, $zamjenjeno, $text);

        return $final;
    }

    public static function timeUniqueId()
    {
        $time = microtime(true);

        return str_replace('.', '', $time);
    }

    public static function randomString($length = 4)
    {
        $stringBag = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $randomString = '';
        for ($i = 0; $i < $length; ++$i) {
            $randomString .= $stringBag[rand(0, 60)];
        }

        return $randomString;
    }

    public static function stringToSlug($string)
    {
        return strtolower(str_replace(' ', '+', trim($string)));
    }

    public static function priceCalculation($priceValue, $percentLess)
    {
        $totalLess = ($percentLess / 100) * $priceValue;

        return round(($priceValue - $totalLess));
    }

    public static function getCountryName($index)
    {
        $countryList = Config::get('config.country_list');

        return $countryList[$index];
    }

    public static function getCountryList()
    {
        $countryList = Config::get('config.country_list');

        return $countryList;
    }

    public static function getCurlResult($url)
    {
        $ch = curl_init();
        // Disable SSL verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // Will return the response, if false it print the response
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // Set the url
        curl_setopt($ch, CURLOPT_URL, $url);
        // Execute
        $response = curl_exec($ch);
        // Closing
        curl_close($ch);

        return $response;
    }

    public static function getFacebookProfilePic($uid)
    {
        $array = get_headers('https://graph.facebook.com/'.$uid.'/picture?redirect=false', 1);

        return (isset($array['data']['url']) ? $array['data']['url'] : false);
        exit;
    }

    public static function exportCsvfile($headers, $data, $exceptions)
    {
        $output = implode(',', $headers)."\n";

        foreach ($data as $row) {
            $arr = array();
            foreach ($row as $key => $value) {
                if (in_array(strtolower($key), $exceptions)) {
                    continue;
                }
                $arr[$key] = $value;
            }
            $output .= implode(',', $arr)."\n";
        }

        return $output;
    }

    // Bootstrap class for progressbar 
    public static function getColor($param)
    {
        $class_item = 'progress-bar-warning';
        if ($param >= 0 && $param <= 20) {
            $class_item = 'progress-bar-info';
        } elseif ($param >= 21 && $param < 49) {
            $class_item = 'progress-bar-danger';
        } elseif ($param >= 50 && $param <= 80) {
            $class_item = 'progress-bar-info';
        }

        return $class_item;
    }

    /* Verify url exist or not */

    public static function verifyUrlExists($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        $response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return (!empty($response) && $response != 404);
    }

    public function generateUniqueToken($userid, $username)
    {
        $rand = mt_rand(100, 999);
        $md5 = md5($userid.'!(&^ 532567_465 ///'.$username);
        $md53 = substr($md5, 0, 3);
        $md5_remaining = substr($md5, 3);
        $md5 = $md53.$rand.$userid.$md5_remaining;

        return $md5;
    }

    /* Short code generator ,  
     * nonce_length = X 
     * change this variable 
     * for getting code length */

    protected static $nonce_length = 5;

    public static function getNonce()
    {
        $chars = array();
        for ($i = 0; $i < 10; ++$i) {
            $chars = array_merge($chars, range(0, 9), range('A', 'Z'), range('a', 'z'), array('*', '@', ''));
        }
        shuffle($chars);
        $start = mt_rand(0, count($chars) - self::$nonce_length);

        return substr(implode('', $chars), $start, self::$nonce_length);
    }

    public static function getFolderFiles($folder_path)
    {
        $file_name = array();
        $handle = opendir($folder_path);
        while ($file = readdir($handle)) {
            if ($file !== '.' && $file !== '..') {
                $file_name[] = $file;
            }
        }

        return $file_name;
    }

    public static function toAscii($str, $replace = array(), $delimiter = '-')
    {
        if (!empty($replace)) {
            $str = str_replace((array) $replace, ' ', $str);
        }
        //$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);

        $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $str);
        $clean = strtolower(trim($clean, '-'));
        $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

        return $clean;
    }

    public static function excerptText($string, $link = '')
    {
        $limit = 200;
        // strip tags to avoid breaking any html
        $string = strip_tags($string);
        if (strlen($string) > $limit) {
            // truncate string
            $stringCut = substr($string, 0, $limit);
            // make sure it ends in a word so assassinate doesn't become ass...
            $string = substr($stringCut, 0, strrpos($stringCut, ' ')).' <hr><b><a href="'.$link.'">Read More</a></b>';
        }

        return $string;
    }
}
