<?php

/**
 * Class Helper
 */
class Helper
{
    public static $pageNumber = '';
    public static $currentPath = '';

    public static function setCurrentPath($url)
    {
        self::$currentPath = $url;
    }

    public static function getCurrentPath()
    {
        return self::$currentPath;
    }

    public static function getCurrentURL()
    {
        return PA::getURL().self::$currentPath;
    }

    public static function userHasPostalcode()
    {
        if (Session::get('search_plz')) {
            return true;
        } else {
            return false;
        }
    }

    public static function getTotalNumberByType($type)
    {
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "SELECT COUNT(id) AS number
                FROM ".$prefix."offers
                WHERE type = :type
                  AND status > 0";
        $query = $database->prepare($sql);
        $query->bindParam(':type', $type, PDO::PARAM_INT);
        $query->execute();
        $offer = $query->fetch();
        return $offer->number;
    }

    public static function getTotalNumberOfUsers()
    {
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "SELECT COUNT(user_id) AS number
                FROM ".$prefix."users
                WHERE user_active = 1";
        $query = $database->prepare($sql);
        $query->execute();
        $users = $query->fetch();
        return $users->number;
    }

    public static function getTotalNumberOfConnections()
    {
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "SELECT COUNT(id) AS number
                FROM ".$prefix."platforms
                WHERE status > 1";
        $query = $database->prepare($sql);
        $query->execute();
        $connections = $query->fetch();
        return $connections->number;
    }

    public static function getTotalNumberOfSearches()
    {
        $prefix = Config::get('DB_PREFIX');
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "SELECT COUNT(id) AS number
                FROM ".$prefix."searches";
        $query = $database->prepare($sql);
        $query->execute();
        $searches = $query->fetch();
        return $searches->number;
    }

    public static function cleanForOutput($text)
    {
        return nl2br(htmlentities(str_replace('\\r\\n', "\r\n", $text),ENT_COMPAT,'UTF-8'));
    }

    public static function convertPrice($price, $currency, $unit, $format)
    {
        $output = array();
        $price = self::cleanForOutput($price);
        $currencies = Text::get('CURRENCY');
        $units = Text::get('UNITS');
        switch ($currency) {
            case 0:
                $price = '';
                break;
            case 2:
                if ($format == 'edit') {
                    $price = $price;
                } else {
                    $price = strpos($price,'.') !== false ? rtrim(rtrim($price,'0'),'.') : $price;
                }
                break;
            default:
                $price = number_format($price,
                                       $currencies[$currency][3],
                                       $currencies[$currency][4],
                                       $currencies[$currency][5]);
                break;
        }

        switch ($unit) {
            case 'x':
            case 0:
                $output['price'] = Text::get('NOT_AVAILABLE_SHORT');
                $output['currency'] = '';
                $output['unit'] = '';
                break;
            case 1:
            case 2:
                $output['price'] = $units[$unit][0];
                $output['currency'] = '';
                $output['unit'] = '';
                break;
            default:
                $output['price'] = $price;
                $output['currency'] = ' '.$currencies[$currency][2].' / ';
                switch ($format) {
                    case 'long':
                        $output['unit'] = $units[$unit][0].' ('.$units[$unit][1].')';
                        break;
                    case 'short':
                    default:
                        $output['unit'] = $units[$unit][1];
                        break;
                }
                break;
        }
        return $output;
    }

    public static function convertPriceForDB($price, $dec = ',')
    {
        switch ($dec) {
            case ',':
                $locale = 'de_DE';
                break;
            default:
                $locale = 'en_US';
                break;
        }
        if (class_exists('NumberFormatter')) {
            $fmt = new NumberFormatter( $locale, NumberFormatter::DECIMAL );
            return $fmt->parse($price);
        } else {
            return self::numberFormatterLight($price, $dec);
        }
    }

    public static function numberFormatterLight($price, $dec)
    {
        $output     = str_replace(' ', '', $price);
        $rest       = substr($output, strpos($output, $dec) + 1);
        $rest_count = strlen($rest);

        if ($dec == '.') {
            $output = str_replace(',', '', $output);
        } elseif ($dec == ',') {
            $output = str_replace('.', '', $output);
            $output = str_replace(',', '.', $output);
        }

        if ($rest_count > 2 && $dec != '.') {
            $output = str_replace('.', '', $output);
            $output = str_replace(',', '', $output);
        }

        if ($rest_count == 0) {
            $output = $output.'.';
        }

        if (substr_count($output,'.') == 0) {
            $output = $output.'.';
            $rest_count = 0;
        }

        $a = 0;
        $fill = 8 - $rest_count;
        while ($a < $fill) {
            $output = $output.'0';
            $a++;
        }

        return $output;
    }

    public static function compressHTML($buffer)
    {
        $search = array(
            '/\>[^\S]+/s',      // strip whitespaces after tags
            '/[^\S]+\</s',      // strip whitespaces before tags
            '/(\s)+/s',         // shorten multiple whitespace sequences
            '/<!--(.|\s)*?-->/' // Remove HTML comments
        );

        $replace = array('>','<','\\1','');

        $buffer = preg_replace($search, $replace, $buffer);

        //BLÖDSINN AB HIER ;-)

        $parts  = explode(">", $buffer);
        $cpl    = 200;
        $c      = 0;
        foreach ($parts as $part) {
            $length = strlen($part);
            $c = $c + $length;
            $return .= $part.'>';
            if ($c >= $cpl) {
                $return .= '
';
                $c = 0;
            }
        }
        $buffer = substr($return, 0, -1);

        //BLÖDSINN ENDE

        return $buffer;
    }

    public static function slugify($str, $delimiter = '-')
    {
        $umlauts = array("ä","ö","ü","ß","&");
        $replace = array("ae","oe","ue","ss","und");
        $text =  str_ireplace($umlauts, $replace, $str);
        // replace non letter or digits by -
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);
        // transliterate
        $text = iconv('utf-8', 'ASCII//TRANSLIT', $text);
        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);
        // trim
        $text = trim($text, '-');
        // remove duplicate -
        $text = preg_replace('~-+~', '-', $text);
        // lowercase
        $text = strtolower($text);

        return $text;
    }
}
