<?php

class Base {

    public static function view($view, array $data = array()) {
        Flight::view()->display($view.'.phtml', $data);
    }

    public static function admin() {

        $cookie = Flight::request()->cookies->admin_verify;

        if ($cookie) {
            if (md5(PASSWORD) === $cookie) return true;
            else return false;
        } else return false;

    }

    public static function named($name) {
        return mb_substr($name, 0, 60);
    }

    public static function data($obj) {
        return Flight::request()->data->$obj;
    }

    public static function files($obj) {
        return Flight::request()->files->$obj;
    }

    public static function isMethod($method) {
        if (Flight::request()->method == $method)
            return true;
        else
            return false;
    }

    public static function times($time = NULL) {
        if ($time) {
            $data = date('d.m.Y', $time);
            $time = date('H:i', $time);
            if ($data == date('d.m.Y')) return 'Сегодня в ' . $time;
            if ($data == date('d.m.Y', time() - 3600 * 24)) return 'Вчера в ' . $time;
            return $data . ' в ' . $time;
        }
    }

    public static function sec($sec) {
        $sec = abs(intval($sec));
        $time = new DateTime('@'.$sec);

        if ($time->format('H') != '00') {
            return $time->format('H:i:s');
        } else return $time->format('i:s');
    }

    public static function videoRand() {

        /*return Flight::db()
            ->query("SELECT * FROM `video` ORDER BY RAND() LIMIT ".RANDLIST)
            ->fetchAll();*/
            
        return Flight::db()
            ->query("
                    SELECT video.*, category.*, video.name AS vName, category.name AS cName, video.url AS vURL, category.url AS cURL
                    FROM video LEFT JOIN category ON category.id = video.catid ORDER BY RAND() LIMIT " . RANDLIST)
            ->fetchAll();

    }

    public static function videoRate() {

        /*return Flight::db()
            ->query("SELECT * FROM `video` WHERE `last_load` > 0 ORDER BY `last_load` DESC LIMIT ".RATEVIDEO)
            ->fetchAll();*/
            
        return Flight::db()
            ->query("
                    SELECT video.*, category.*, video.name AS vName, category.name AS cName, video.url AS vURL, category.url AS cURL
                    FROM video LEFT JOIN category ON category.id = video.catid WHERE video.last_load > 0 ORDER BY video.last_load DESC LIMIT " . RATEVIDEO)
            ->fetchAll();

    }

    public static function category($id, $url = false) {

        $q = Flight::db()
            ->query("SELECT `name`, `url` FROM `category` WHERE `id` = {$id}")
            ->fetch();

        if ( ! $url)
            return $q['name'];
        else
            return $q['url'];

    }

    public static function catcount($id, $url = false) {

        $q = Flight::db()
            ->query("SELECT COUNT(*) FROM `video` WHERE `catid` = {$id}")
            ->fetchColumn();

        return $q;

    }

    public static function size($num) {
        if ( ! $num) $num = 0;

        if ($num >= 1000000000000) {
            $num = round($num / 1099511627776, 1);
            $unit = 'Тб';
        }
        elseif ($num >= 1000000000) {
            $num = round($num / 1073741824, 1);
            $unit = 'Гб';
        }
        elseif ($num >= 1000000) {
            $num = round($num / 1048576, 1);
            $unit = 'Мб';
        }
        elseif ($num >= 1000) {
            $num = round($num / 1024, 1);
            $unit = 'Кб';
        }
        else {
            $unit = 'б';
            return number_format($num).' '.$unit;
        }

        return number_format($num, 1).' '.$unit;
    }

    public static function resize($path_to_file, $path_to_save, $width, $height = 0, $quality = 100) {
        // Проверка наличия изображения на сервере
        if ( ! file_exists($path_to_file)) return FALSE;
        // Получение информации о изображении
        $info = getimagesize($path_to_file);
        // Формат изображения
        $format = strtolower(substr($info['mime'], strpos($info['mime'], '/') + 1));
        // Выбор функции для изображения
        $picfunc = 'imagecreatefrom'. $format;
        // Старая ширина изображения
        $old_width = $info[0];
        // Старая высота изображения
        $old_height = $info[1];
        // Вычисление горизонтального соотношения
        $horizontal = $width / $old_width;
        // Вычисление вертикального соотношения
        $vertical = $height / $old_height;
        // Пропорциональное вычисление параметров
        if ($height == 0) {
            $vertical = $horizontal;
            $height = $vertical * $old_height;
        }
        elseif ($width == 0) {
            $horizontal = $vertical;
            $width = $horizontal * $old_width;
        }
        // Формирование размера изображения
        $ratio = min($horizontal, $vertical);
        // Необходимость пропорционального изменения
        if ($horizontal == $ratio) $use_horizontal = TRUE;
        else $use_horizontal = FALSE;

        $new_width = $use_horizontal ? $width : floor($old_width * $ratio);
        $new_height = ! $use_horizontal ? $height : floor($old_height * $ratio);
        $new_left = $use_horizontal ? 0 : floor(($width - $new_width) / 2);
        $new_top = ! $use_horizontal ? 0 : floor(($height - $new_height) / 2);
        $pic_to_src = $picfunc($path_to_file);
        // Создание изображения в памяти
        $pic_to_save = imagecreatetruecolor($width, $height);
        // Заполнение цветом
        $white = imagecolorallocate($pic_to_save, 0, 0, 0);
        imagefill($pic_to_save, 0, 0, $white);
        // Нанесение старого изображения на новое
        imagecopyresampled($pic_to_save, $pic_to_src, $new_left, $new_top, 0, 0, $new_width, $new_height, $old_width, $old_height);
        // Определение формата изображения на выходе
        $ext = @array_pop(explode('.', $path_to_save));

        switch($ext) {
            case 'jpg':
            case 'jpeg':
                imagejpeg($pic_to_save, $path_to_save, $quality);
                break;

            case 'gif':
                imagegif($pic_to_save, $path_to_save);
                break;

            case 'png':
                imagepng($pic_to_save, $path_to_save);
                break;

            default:
                imagepng($pic_to_save, $path_to_save);
                break;
        }

        // Очистка памяти
        imagedestroy($pic_to_src);
        imagedestroy($pic_to_save);

        return TRUE;
    }

    public static function watermark($source_image_path, $result_image_path){

        list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
        if ($source_image_type === NULL) {
            return false;
        }
        switch ($source_image_type) {
            case 1: // картинка *.gif
                $source_image = imagecreatefromgif($source_image_path);
                break;
            case 2: // картинка *.jpeg, *.jpg
                $source_image = imagecreatefromjpeg($source_image_path);
                break;
            case 3: // картинка *.png
                $source_image = imagecreatefrompng($source_image_path);
                break;
            default:
                return false;
        }
        $watermark_image = imagecreatefrompng($_SERVER['DOCUMENT_ROOT'].'/public/watermark.png');
        $watermark_width = imagesx($watermark_image);
        $watermark_height = imagesy($watermark_image);
        imagealphablending($source_image, true);
        imagesavealpha($source_image, true);
        imagecopy($source_image, $watermark_image, $source_image_width - $watermark_width, $source_image_height - $watermark_height, 0, 0, $watermark_width, $watermark_height);

        imagejpeg($source_image, $result_image_path, 100);
        imagedestroy($source_image);
        imagedestroy($watermark_image);
    }
    
    public static function gen_timer_start() {
        global $timer_start_time;
        $start_time = microtime();
        $start_array = explode(" ",$start_time);
        $timer_start_time = $start_array[1] + $start_array[0];
        return $timer_start_time;        
    }
    
    public static function gen_timer_stop() {
    	global $timer_start_time;
    	$end_time = microtime();
    	$end_array = explode(" ",$end_time);
    	$timer_stop_time = $end_array[1] + $end_array[0];
    	$time = $timer_stop_time - $timer_start_time;
    	$time = substr($time,0,5);
    	return "[$time сек.]";     
    }

    /* (OLD) public static function online() {

        $ip = $_SERVER['REMOTE_ADDR'];
        $time = time();

        Flight::db()
            ->query("DELETE FROM `online` WHERE `time` > {$time} - 15");

        $q = Flight::db()
            ->query("SELECT * FROM `online` WHERE `ip` = '{$ip}'")
            ->fetch();

        if ($q) {
            Flight::db()
                ->query("UPDATE `online` SET `time` = '{$time}'");
        } else {
            Flight::db()
                ->query("INSERT INTO `online` SET `time` = '{$time}', `ip` = '{$ip}'");
        }

        $online = Flight::db()
            ->query("SELECT COUNT(*) FROM `online`")
            ->fetchColumn();

        return 'Онлайн: '.$online;
        
    }*/
    
    public static function online() {

        $ip = $_SERVER['REMOTE_ADDR'];
        $uagent = trim(htmlspecialchars($_SERVER['HTTP_USER_AGENT']));
        $session_id = session_id();
        $time = time();
        $ontime = 300;
        
        Flight::db()
            ->query("DELETE FROM online 
            WHERE time < NOW() -  INTERVAL '5' MINUTE");

        $result = Flight::db()->prepare("SELECT * FROM `online` WHERE session_id = '{$session_id}' OR (ip = '{$ip}' && uagent = :uagent)");
        $result->bindValue(":uagent", $uagent, PDO::PARAM_STR);
        $result->execute(); 
        $q = $result->fetch(PDO::FETCH_ASSOC);  
            
        if ($q) {
            $result = Flight::db()->prepare("UPDATE `online` SET `time` = NOW() WHERE session_id = '{$session_id}' OR (ip = '{$ip}' && uagent = :uagent)");
            $result->bindValue(":uagent", $uagent, PDO::PARAM_STR);
            $result->execute(); 
        } else {
                
            $result = Flight::db()->prepare("INSERT INTO `online` SET `time` = NOW(), `ip` = '{$ip}', session_id = '{$session_id}', uagent = :uagent");
            $result->bindValue(":uagent", $uagent, PDO::PARAM_STR);
            $result->execute();
        }

        $online = Flight::db()
            ->query("SELECT COUNT(*) FROM `online`")
            ->fetchColumn();
            
        /* Статистика онлайна */
        $stat = Flight::db()
                ->query("SELECT * FROM `statistics`")
                ->fetch();
                
        $todate = date("Y-m-d"); // Текущая дата
        
        if ($stat['date'] != $todate) {
            // Записываем на ВЧЕРА
            Flight::db()
                ->query("UPDATE `statistics` SET 
                
                `views_yesterday` = '{$stat['views_today']}', 
                `views_today` = 0, 
                
                `loads_yesterday` = '{$stat['loads_today']}', 
                `loads_today` = 0, 
                
                `online_yesterday` = '{$stat['online_today']}', 
                `online_today` = 0, 
                
                 date = NOW()
                
                ");
        }
        
        //Максимальный онлайн за все время
        if ($online > $stat['online_max']) {
            Flight::db()
                ->query("UPDATE `statistics` SET `online_max` = '{$online}'");            
        }
        
        //Максимальный онлайн за сегодня
        if ($online > $stat['online_today']) {
            Flight::db()
                ->query("UPDATE `statistics` SET `online_today` = '{$online}'");            
        }
        
        $pagesize = round((ob_get_length()+200)/1024 ,1);
        return 'Online: '.$online . ' | ' . $pagesize . 'kb | ' . Base::gen_timer_stop();
    }
    
    public static function rus2translit($string) {
        $converter = array(
            'а' => 'a',   'б' => 'b',   'в' => 'v',
            'г' => 'g',   'д' => 'd',   'е' => 'e',
            'ё' => 'e',   'ж' => 'zh',  'з' => 'z',
            'и' => 'i',   'й' => 'y',   'к' => 'k',
            'л' => 'l',   'м' => 'm',   'н' => 'n',
            'о' => 'o',   'п' => 'p',   'р' => 'r',
            'с' => 's',   'т' => 't',   'у' => 'u',
            'ф' => 'f',   'х' => 'h',   'ц' => 'c',
            'ч' => 'ch',  'ш' => 'sh',  'щ' => 'sch',
            'ь' => '\'',  'ы' => 'y',   'ъ' => '\'',
            'э' => 'e',   'ю' => 'yu',  'я' => 'ya',
            
            'А' => 'A',   'Б' => 'B',   'В' => 'V',
            'Г' => 'G',   'Д' => 'D',   'Е' => 'E',
            'Ё' => 'E',   'Ж' => 'Zh',  'З' => 'Z',
            'И' => 'I',   'Й' => 'Y',   'К' => 'K',
            'Л' => 'L',   'М' => 'M',   'Н' => 'N',
            'О' => 'O',   'П' => 'P',   'Р' => 'R',
            'С' => 'S',   'Т' => 'T',   'У' => 'U',
            'Ф' => 'F',   'Х' => 'H',   'Ц' => 'C',
            'Ч' => 'Ch',  'Ш' => 'Sh',  'Щ' => 'Sch',
            'Ь' => '\'',  'Ы' => 'Y',   'Ъ' => '\'',
            'Э' => 'E',   'Ю' => 'Yu',  'Я' => 'Ya',
        );
        return strtr($string, $converter);
    }

    public static function str2url($str) {
        // переводим в транслит
        $str = Base::rus2translit($str);
        // в нижний регистр
        $str = strtolower($str);
        // заменям все ненужное нам на "-"
        $str = preg_replace('~[^-a-z0-9_]+~u', '-', $str);
        // удаляем начальные и конечные '-'
        $str = trim($str, "-");
        return $str;
    }
    
    public static function get_uniqu_alias($alias) {

        $result = Flight::db()->prepare("SELECT * FROM `fo_video` WHERE alias = :alias");
        $result->bindValue(":alias", $alias, PDO::PARAM_STR);
        $result->execute(); 
        $q = $result->fetch(PDO::FETCH_ASSOC);  
                    
        if (!empty($q)) {
            return true;
        } else {
            return false;
        }
    }
    
    /* Создаем уникальный алиас */
    public static function uniqu_alias($alias) {
        
        if (Base::get_uniqu_alias($alias)) {
            $alias = $alias .'_' . rand(1,20);
            return Base::uniqu_alias($alias);
            //return $alias;
        } else {
            return $alias;
        }
        
    }

}