<?php include 'telegrambotlib.php'; include 'logger.php'; // imports

// handler.php
// Unicon * t.me/unicon_studio
// baddev * t.me/baddev

header('Content-Type: text/html;charset=UTF-8'); // fix russian text
libxml_use_internal_errors(TRUE);

$bot = new TelegramBot('867104266:AAHal8i9HUy7tlWJ3b-qgwqpD43kzpzD1ts');

$db     = json_decode(file_get_contents('./db.json')     , TRUE); // quests database
//$users  = json_decode(file_get_contents('./users.json')   , TRUE); // users database
$array  = json_decode(file_get_contents('php://input')    , TRUE);

$message = $array['message']['text'];
$message_id = $array['message']['message_id'];
$chat_id = $array['message']['chat']['id'];
$chat_username = $array['message']['chat']['username'];
$chat_type = $array['message']['chat']['type'];
$from = $array['message']['from']['username'];
$from_id = $array['message']['from']['id'];
$reply_message_id = $array['message']['reply_to_message']['message_id'];
$reply_id = $array['message']['reply_to_message']['from']['id'];
$reply_username = $array['message']['reply_to_message']['from']['username'];

if(isset($array['callback_query'])){ // is button
    $message = $array['callback_query']['data'];
	$message_id = $array['callback_query']['message']['message_id'];
	$from_id = $array['callback_query']['from']['id'];
	$chat_id = $array['callback_query']['message']['chat']['id'];
	$is_button = true;
	$from = $array['callback_query']['from']['username'];
}

if(is_player($from) == false){
   makenew($from , $from_id);
}

$logger = new Logger(); // logger

$line = str_replace("@fenixofbot" , "" , trim(mb_strtolower($message))); // filter
$cm = explode(' ' , $line , 2); // split command
$cmm = explode(' ' , $line); // split command all args

switch($cm[0]){
	case '/qlist':
    $list = userList();
	$moneys = array();
	foreach($list as $user){
		$u = user($user);
		$moneys[$user] = $u['money'];
	}

	$mask = array();
	foreach ($moneys as $key => $row){
    $mask[$key]['money'] = $row['money'];
	}
	array_multisort($mask, SORT_DESC, $moneys);
	$moneys = array_reverse($moneys);

	$z = '';
	$o = 14;

	foreach($moneys as $user => $dr){
		if((int)$moneys[$user] > 0){
			if($user!='' or $user!=null){
	
	    $space = str_repeat(' ' , $o - strlen($user));
		$z .= "\n<code>" . $user . $space . $moneys[$user] . " монет</code>" ;
		
	
	}
}
	}
	$bot->sendReplyMessage($chat_id , $z, $message_id);
	break;
	case '/qmoney':
	if($reply_username == ''){
		$u = user($from);

	$bot->sendReplyMessage($chat_id , "У вас на счету " . $u['money'] . " монет." , $message_id);
	}else{
		$u = user($reply_username);
	$bot->sendReplyMessage($chat_id , "У пользователя <b>@" . $reply_username . "</b> на счету " . $u['money'] . " монет." , $message_id);
	}
	break;

	case '/qasino':
	$bot->sendMessage($chat_id , "Кручу рулетку ...");
	$bot->sendMessage($chat_id , "...");
	$r = randomb(0,20);
	if($r > 7){
		$bot->sendMessage($chat_id , "Пользователь <b>@" . $from . "</b> выиграл в рулетку 1 монету.");
		addmoney($from , 1);
	}else{
		$bot->sendMessage($chat_id , "Пользователь <b>@" . $from . "</b> проиграл в рулетку 1 монету.");
		removemoney($from , 1);
	}
	break;
	case '/qplay':
	$s = sizeof($db);
	$r = randomb(0 , $s - 1);

	$a = $db[$r]['btn1'] ." " . $r . " " . 1;
	$b = $db[$r]['btn2'] ." " . $r . " " . 2;
	$c = $db[$r]['btn3'] ." " . $r . " " . 3;

	$keyboard = ['inline_keyboard'=>[[
		['text'=> $db[$r]['btn1'],'callback_data'=>'/q '.$a]
		,
		['text'=> $db[$r]['btn2'],'callback_data'=>'/q '.$b]
		,
		['text'=> $db[$r]['btn3'],'callback_data'=>'/q '.$c]
		]]];
    $bot->sendMessage($chat_id , $db[$r]['quest'] , json_encode($keyboard));
	break;

		case '/qprofile':
		
		if($reply_id==''){
		$u = user($from);
		$o = "Имя пользователя: " . $from . "\nМонет: " . $u['money'] . "\nВступил(a) в игру: " . $u['reg'] ;
		}else{	
		$u = user($reply_username);
		$o = "Имя пользователя: " . $reply_username . "\nМонет: " . $u['money'] . "\nВступил(a) в игру: " . $u['reg'];
		}
		$bot->sendReplyMessage($chat_id , $o , $message_id);
		break;

		case '/qpay':
		$du = trim(str_replace("@" , "" , $cmm[1]));
		if(is_player($du)){ // is player
		if(sizeof($cmm) > 2){
		$a = user($from);
		
		$b = user($du);

        if($a['money'] >= $cmm[2]){
			
			addmoney($du , $cmm[2]);
			removemoney($from , $cmm[2]);

			$bot->sendReplyMessage($chat_id , "Удачно передано " . $cmm[2] . " монет , игроку " . $du , $message_id);

		}else{
			$bot->sendReplyMessage($chat_id , "Не достаточно монеток , что бы отправить их другому игроку!" , $message_id);
		}

		}else{
			$bot->sendReplyMessage($chat_id , "Ошибка синтаксиса команды!" , $message_id);
		}
	}else{ // is player
		$bot->sendReplyMessage($chat_id , "Ошибка , такого игрока не существует!" , $message_id);
	}
		break;



	// buttons
	case '/q':
	// 0 - /q
	// 1 - btnname
	// 2 - questid
	// 3 - btnid
	$i = $cmm[2];
	$ok = $cmm[3];
	if($is_button){
	if($db[$i]['result'] == $ok){
		$bot->editMessageText($chat_id , "Правильно! Пользователь <b>@" . $from . "</b> дал правильный ответ и получил 2 монеты." , $message_id);
		addmoney($from , 2);
	}else{
		$bot->editMessageText($chat_id , "Не правильно! Пользователь <b>@" . $from . "</b> дал не правильный ответ." , $message_id);
	}
	} // is_button
	break;
}



function is_player($user){
	$list = userList();
	if(in_arrayi($user , $list)) return true;
	return false;
}

function userList(){
	$r = scandir("players/");
	$r = array_diff($r , array('..', '.'));
	$l = array();
	foreach($r as $b){
		$l[] = $b;
	}
	return $l;
}

function makenew($user , $id){
	$array = array(
		"id" => $id,
		"money" => 0,
		"items" => array(),
		"like" => 0,
		"reg" => date("d.m.y")   
	);
	putUser($user , $array);
}

function addmoney($user , $count){
$u = user($user);
$u['money'] = (int) $u['money'] + (int) $count;
putUser($user , $u);
}

function removemoney($user , $count){
	$u = user($user);
	$u['money'] = (int) $u['money'] - (int) $count;
	putUser($user , $u);
}

function user($user){
	$r = file_get_contents("players/" . $user);
	$d = json_decode($r , TRUE);
return $d;
}

function putUser($user , $array){
	$e = json_encode($array);
	file_put_contents("players/" . $user , $e);
}

// other functions

function array_key_exists_r($needle, $haystack)
{
    $result = array_key_exists($needle, $haystack);
    if ($result) return $result;
    foreach ($haystack as $v) {
        if (is_array($v)) {
            $result = array_key_exists_r($needle, $v);
        }
        if ($result) return $result;
    }
    return $result;
}

function in_arrayi($needle, $haystack) {
    return in_array(strtolower($needle), array_map('strtolower', $haystack));
}

function randomb($min , $max){
	return (int) file_get_contents("https://www.random.org/integers/?num=1&min=" . $min . "&max=" . $max . "&col=1&base=10&format=plain&rnd=new");
}