<?php

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

    public static function filterArgs($args,$context = 'undefined')
    {
        switch ($context)
        {
            case 'offers':
                $prefix = 'O.';
                break;
            case 'details':
                $prefix = 'P.';
                break;
            case 'search':
                $prefix = 'O.';
                break;
            default:
                $prefix = '';
        }

        if (isset($args['page']) || (isset(self::$pageNumber) && self::$pageNumber != ''))
        {
            if (isset(self::$pageNumber) && self::$pageNumber != '')
            {
                $args['page'] = (int) self::$pageNumber;
            } else {
                $args['page'] = (int) $args['page'];
            }
        } else {
            $args['page'] = 1;
        }

        if (isset($args['howMany']))
        {
            $args['howMany'] = (int) $args['howMany'];
        } else {
            $args['howMany'] = 12;
        }

        if (isset($args['orderBy']) &&
            in_array($args['orderBy'],
            array('created','modified','company_name','distance','id','title','price','random')))
        {
            $args['orderBy'] = $args['orderBy'];
        } else {
            $args['orderBy'] = 'modified';
        }

        if (isset($args['order']) &&
            in_array($args['order'], array('ASC','DESC')))
        {
            $args['orderDir'] = $args['order'];
        } else {
            $args['orderDir'] = 'DESC';
        }

        $args['where'] = 'WHERE';
        if (isset($args['userFeatured']) &&
            $args['userFeatured'] == true)
        {
            $args['where'] .= ' user_featured = 1';
        }

        if (isset($args['adminFeatured']) &&
            $args['adminFeatured'] == true)
        {
            if ($args['where'] != 'WHERE')
            {
                $args['where'] .= ' AND';
            }
            $args['where'] .= ' '.$prefix.'admin_featured = 1';
        }

        if (isset($args['otherFeatured']) &&
            $args['otherFeatured'] == true)
        {
            if ($args['where'] != 'WHERE')
            {
                $args['where'] .= ' AND';
            }
            $args['where'] .= ' '.$prefix.'other_featured = 1';
        }

        if ($context != 'details')
        {
            if (isset($args['active']) &&
                $args['active'] == true)
            {
                if ($args['where'] != 'WHERE')
                {
                    $args['where'] .= ' AND';
                }
                $args['where'] .= ' '.$prefix.'status > 2';
            } else {
                if ($args['where'] != 'WHERE')
                {
                    $args['where'] .= ' AND';
                }
                $args['where'] .= ' '.$prefix.'status > 0';
            }
        } else {
            if ($args['where'] != 'WHERE')
            {
                $args['where'] .= ' AND';
            }
            $args['where'] .= ' '.$prefix.'company_name IS NOT NULL';
        }

        if (isset($args['profile']))
        {
            if ($args['where'] != 'WHERE')
            {
                $args['where'] .= ' AND';
            }
            $args['where'] .= ' '.$prefix.'profile_id = '.$args['profile'];
        }
        if (isset($args['type']))
        {
            if ($args['where'] != 'WHERE')
            {
                $args['where'] .= ' AND';
            }
            $args['where'] .= ' '.$prefix.'type = '.$args['type'];
        }
        if ($args['where'] == 'WHERE')
        {
            $args['where'] = '';
        }

        if ($args['orderBy'] == 'random')
        {
            $args['order'] = 'rand()';
            $args['page'] = 1;
        } else {
            if (self::getSortOrder())
            {
                if (in_array(self::getSortOrder(), array('title ASC','title DESC',
                                                         'modified ASC','modified DESC',
                                                         'price ASC','price DESC',
                                                         'distance ASC','distance DESC')))
                {
                    if (in_array(self::getSortOrder(), array('distance ASC','distance DESC')))
                    {
                        if (self::userHasPostalcode())
                        {
                            $args['order'] = self::getSortOrder();
                        } else {
                            $args['order'] = 'modified DESC';
                        }
                    } else {
                        $args['order'] = $prefix.self::getSortOrder();
                    }
                }
                if ($context == 'details' && in_array($args['order'], array('title ASC','title DESC',
                                                                            'price ASC','price DESC')))
                {
                    $args['order'] = $prefix.'modified DESC';
                }
            } else {
                $args['order'] = $prefix.$args['orderBy'] . ' ' . $args['orderDir'];
            }
        }

        if ($args['page'] == 1)
        {
            $args['start'] = 0;
        } else {
            $args['start'] = ($args['page']-1) * $args['howMany'];
        }

        if ($context == 'search')
        {
            $where = array();
            if (Session::get('search_offers') == 'y' &&
                Session::get('search_requests') == 'y')
            {
            } else {
                if (Session::get('search_offers') == 'y')
                {
                    $where[] = 'O.type = 1';
                }
                if (Session::get('search_requests') == 'y')
                {
                    $where[] = 'O.type = 2';
                }
            }
            if (Session::get('search_internal') == 'y' &&
                Session::get('search_external') == 'y')
            {
            } else {
                if (Session::get('search_internal') == 'y')
                {
                    $where[] = 'O.external = 0';
                }
                if (Session::get('search_external') == 'y')
                {
                    $where[] = 'O.external = 1';
                }
            }
            $where[] = 'O.status > 1';
            if (count($where) >= 1)
            {
                $args['where'] = implode(' AND ', $where);
            }
        }

        self::setPageNumber($args['page']);

        return $args;
    }

    public static function setPageNumber($page)
    {
        self::$pageNumber = $page;
    }

    public static function getPageNumber()
    {
        return self::$pageNumber;
    }

    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 setSortOrder($orderBy,$order)
    {
        $args['orderBy'] = $orderBy;
        $args['order'] = $order;
        $clean_args = self::filterArgs($args);
        Session::init();
        Session::set('sort', $clean_args['order']);
    }

    public static function getSortOrder()
    {
        if (Session::get('sort') != '')
        {
            return Session::get('sort');
        } else {
            return false;
        }
    }

    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'] = '[N/A]';
                $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;
    }
}
