<?php
class profile {

public static function showDate($date) // $date --> время в формате Unix time
{
	global $user;
    $diff = ((time()+$user['timeshift']*60*60)-$date);
 
    $seconds = array('секунда', 'секунды', 'секунд');
    $minutes = array('минута', 'минуты', 'минут');
    $hours = array('час', 'часа', 'часов');
    $days = array('день', 'дня', 'дней');
    $weeks = array('неделя', 'недели', 'недель');
    $months = array('месяц', 'месяца', 'месяцев');
    $years = array('год', 'года', 'лет');
    $decades = array('десятилетие', 'десятилетия', 'десятилетий');
 
    $phrase = array($seconds, $minutes, $hours, $days, $weeks, $months, $years, $decades);
    $length = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
 
    for ($i = sizeof($length) - 1; ($i >= 0) && (($no = $diff / $length[$i]) <= 1); $i--) ;
    if ($i < 0) $i = 0;
    $_time = $cur_time - ($diff % $length[$i]);
    $no = floor($no);
    $value = sprintf("%d %s ", $no, self::getPhrase($no, $phrase[$i]));
 
    if (($stf == 1) && ($i >= 1) && (($cur_time - $_time) > 0)) $value .= time_ago($_time);
 
    return $value /*. ' на сайте'*/;
}
public static function getPhrase($number, $titles)
{
    $cases = array (2, 0, 1, 1, 1, 2);
    return $titles[ ($number%100>4 && $number%100<20)? 2 : $cases[min($number%10, 5)] ];
}
public static function onlineTime($time){
    if($time < 60){ return $time.' '.self::getPhrase($time, array('секунду', 'секунды', 'секунд')); 
    } else if($time < 3600){ return round($time/60).' '.self::getPhrase(round($time/60), array('минуту', 'минуты', 'минут'));
    } else { return round($time/3600).' '.self::getPhrase(round($time/3600), array('час', 'часа', 'часов'));
    }
} 


public static function is_user($access) {
global $user;
if (isset($user) && $access == false) {
system::redirect(NULL, "/"); }
if (!isset($user) && $access == true) {
system::redirect(NULL, "/signup"); }
}

public static function age($year,$month,$day){
$age = date("Y")-$year;
if(date("n") < $month)$age = $age-1;
elseif (date("n") == $month && date("j") < $day)$age = $age-1;
return "{$age} ".self::getPhrase($age, array('год','года','лет'));
}
//Ф-ция вывода офф страницы  mini
	public static function vermini($d) {
	    return ($d['vertification'] == 0 ? "" : "<img src='/template/icons/verified.png' style='margin:0 2px -4px;'>");
	}

//Ф-ция вывода офф страницы 
	public static function ver($d) {
	    return ($d['vertification'] == 0 ? "" : "<img src='/template/icons/verified.png'>");
	}
//Ф-ция вывода пола
	public static function getSex($d) {
		return ($d['info_sex'] == 0 ? "Женский" : "Мужской");
	}
//Ф-ция линка на страницу
	public static function getLink($d) {
		return "/id".(int)@$d['id'];
	}
//ф-ция логина	
	public static function getName($d, $ico = false) {
		return ($ico === true ? self :: ico($d) : '' ).''.(isset($d['login']) ? $d['login'] : 'DELETED' ).''; 
	}
//Ф-ция полного имени и фамили
    public static function getfirstname($d) { #Имя
			return $d['info_first_name'] ? : 'Имя';
	}
 public static function getlastname($d) { #Фамилия
		return $d['info_last_name'] ? : '';
	}
public static function getFullName($d = [], $ico = false ) { #Имя и фамилия
			return "".($ico === true ? self :: ico($d) : '' )."".self :: getfirstname($d)." ".self :: getlastname($d)."";
		}
//Ф-ция возраста		
	public static function getAge($d) {
		if ($d['info_b_d'] != 0 && $d['info_b_m'] != 0 && $d['info_b_y'] != 0){
			$d['ank_age'] = (date("Y")-$d['info_b_y']);
			if (date("n") < $d['info_b_m']){ $d['ank_age'] = ($d['ank_age']-1); }
			else if (date("n") == $d['info_b_m'] && date("j") < $d['info_b_d']) { $d['ank_age'] = ($d['ank_age']-1); }
		} else {$d['ank_age'] = 0;}
		return $d['ank_age'];
	}
//Ф-ция назад для пк	
	public static function goPage($d, $ico = true) {
		return ($ico === true ? self :: ico($d) : '' )."<a href=\"".self :: getLink($d)."\">".self :: getFullName($d)."</a>";
	}

	public static function getOnline($d) {
		global $config;
		return (($d['last_time'] + $config['TIME_ONLINE']) > time() ? true : false );
	}
//Функция иконок  офф и on	
	public static function ico($d) {
		global $config;
		$i = (($d['last_time'] + $config['TIME_ONLINE']) > time() ? "on" : "off" );
		return "<i class=\"our our-u_{$i}\" /></i> ";
	}

// Определение юзера.
	public static function getUser($id, $s = NULL, $r = true) {
		global $thisPage, $config;
		
		$db = DB :: $pdo -> queryFetch("SELECT ".($s == NULL ? "*" : $s )." FROM `users` WHERE `id` = ? LIMIT 1;", array($id));
		
		if($r == true && ( $db['id'] == $config['SYS_ID'] || empty($db['id']) ) && $thisPage != "profile") {
			header("Location: ".self :: getLink($db)); die();
		}
		return $db;
	}




// Функции аватара.
	public static function getLinkAvatar($d) {
		return "/photos{$d['id']}/view{$d['avatar']}";
	}

	public static function getAvatar($d, $s = '') {
		$c = array('_64x', '_150x', '_256x', '_64x', '_64x');
		$path = ($d['info_avatar'] != NULL ? "photos/".$d['info_avatar'].$c[$s] : ($d['id'] > 0 ? system :: photosGetLink(true,$d['id'],"") : system :: $photosDir).'0'.($c[$s] == "_64x" ? $c[$s] : '')).".jpg";
		return FILES_SERVER . $path . "?v=" .filemtime(FILES_PATH . $path);
	}
//Вывод аватара
	public static function userAvatar($d, $s = 0) {
		$wdata = array('64', '100', '200', '45', '30');
		$hdata = array('64', '100', '200', '45', '30');
		return "<img src=\"".self :: getAvatar($d, $s)."\" style=\"border-radius: 50%;display: block;background: #F5F5F5;".($s != 1 ? "width: ".$wdata[$s]."px;height: ".$hdata[$s]."px;" : '' )."\">";
	}

// Проверка на дружбу
	public static function getFriend($id_user, $id_friend, $q = false) {
		$id_user = (int)abs($id_user);
		$id_friend = (int)abs($id_friend);

		$queryFriend = DB :: $pdo -> querySingle("SELECT COUNT(`id`) FROM `".( $q == true ? "query_" : "" )."friends` WHERE `id_user` = ? AND `id_friend` = ?", array($id_user,$id_friend));

		return ( $queryFriend < 1 ? false : true );
	}	

// Создание  аватара с буквой
	public static function avatarCreate($nick,$id) {
		system :: createDir(system :: photosGetLink(true,$id,""));
		$nick = preg_replace("([_])", "", $nick); // Вырезаем символы
		$colors = [
            [142, 68, 173],
            [22, 160, 133],
            [41, 128, 185],
            [44, 62, 80],
            [192, 57, 43],
            [211, 84, 0],
            [39, 174, 96],
            [26, 188, 156],
            [142, 68, 173],
            [243, 156, 18],
            [231, 76, 60]
          ];

		$text_string    = mb_strtoupper(mb_substr($nick, 0, 1));
		$font_ttf        = ROOT.'/template/_Tahoma.ttf'; 
		$font_size        = 35; 
		$text_angle        = 0; 
		$text_padding    = 10; 

		$rect = imagettfbbox($font_size,$text_angle,$font_ttf,$text_string); 
		$minX = min(array($rect[0],$rect[2],$rect[4],$rect[6])); 
		$maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6])); 
		$minY = min(array($rect[1],$rect[3],$rect[5],$rect[7])); 
		$maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7])); 
		$the_box        = array( 
		     "left"   => abs($minX) - 1, 
		     "top"    => abs($minY) - 1, 
		     "width"  => $maxX - $minX, 
		     "height" => $maxY - $minY, 
		     "box"    => $rect 
		    );  

		$imgWidth    = 150; 
		$imgHeight    = 150; 
		$r = rand(0,count($colors)-1);
		$image = imagecreate($imgWidth,$imgHeight); 
		imagefill($image, 0,0, imagecolorallocate($image,$colors[$r][0], $colors[$r][1], $colors[$r][2])); 

		$color = imagecolorallocate($image,255,255,255); 
		imagettftext($image, 
		    $font_size, 
		    $text_angle, 
		    $the_box["left"] + ($imgWidth / 2) - ($the_box["width"] / 2), 
		    $the_box["top"] + ($imgHeight / 2) - ($the_box["height"] / 2), 
		    $color, 
		    $font_ttf, 
		    $text_string); 
		imagepng($image,FILES_PATH.system :: photosGetLink(true,$id,"")."0.jpg");
		
		imagesavealpha($image, true);
		$new_image = imagecreatetruecolor(64, 64);
		imagecopyresampled($new_image, $image, 0, 0, 0, 0, 64, 64, $imgWidth, $imgHeight);
		imagepng($new_image,FILES_PATH.system :: photosGetLink(true,$id,"")."0_64x.jpg");
		imagedestroy($image); imagedestroy($new_image);
	}
}