<?php
// запрет прямого доступа
defined('_JEXEC') or die('Restricted access');

require_once __DIR__.'/lib/dbclass.php';
require_once __DIR__.'/lib/slack.php';
require_once __DIR__.'/lib/mailclass.php';
require_once('views/view.php');

date_default_timezone_set('Europe/Moscow'); 

ini_set('session.gc_maxlifetime', 10800);

class ui_controller{
	var $access	= false;
	var $html	= '';
	var $title	= 'EMX bot';
	
	function __construct(){
		session_start();
		if (isset($_SESSION['access']))
		if ($_SESSION['access'] == 'true'){
			$this->access = true;
			
		}
	}
	
	function login(){
		if ($this->access){
			header('Location: index.php');
		}
		$u_login	= isset($_POST['username']) ? $_POST['username'] : false;
		$u_password	= isset($_POST['password']) ? $_POST['password'] : false;
		
		if ($u_password && $u_login){
			$_SESSION['access'] = 'false';
			
			if ($u_login == 'emx' && $u_password == '31415926535'){
				$_SESSION['access'] 	= 'true';
				$this->access = true;
				header('Location: index.php');
			}else{
				return array('error' => 1);
			}
		}
	}
	
	function logout(){
		session_unset();
		header('Location: index.php');
	}
	
	function view(){
		if ($this->access){
			$db 	= new db_controller();
			$rows 	= $db->query("select * from `mess` order by `id` ASC");
			
			return $rows;
		}
	}
	
	function edit(){
		if ($this->access){
			
			$id			= intval($_REQUEST['id']);
			$type		= $_POST['type'];
			$time		= $_REQUEST['time'];
			$condition	= $_REQUEST['condition'];
			$exception	= $_REQUEST['exception'];
			$state		= intval($_REQUEST['state']);
			$mess		= $_REQUEST['mess'];
			$sm_title	= $_REQUEST['sm_title'];
			$attachment	= $_REQUEST['attachment'];
			
			if (!is_array($condition)){
				$condition = explode(" ", $condition);
			}
			
			switch($type) {
			  case 'regular_wd':
			    $array = array(
					"type" => $type,
					"w_days" => $condition,
					"time" => $time
				);
			    break;

			  case 'regular_md':
			    $array = array(
					"type" => $type,
					"m_days" => $condition,
					"time" => $time
				);
			    break;

			  case 'regular_date':
			  case 'single':
			    $array = array(
					"type" => $type,
					"date" => $condition[0],
					"time" => $condition[1]
				);
			    break;
			  case 'birthday':
			    $array = array(
					"type" => $type,
					"date" => $condition[0],
					"time" => $time
				);
			    break;	

			  default:
       			echo "Тип не определён";
			}

			$json_data = json_encode($array);

			$item 			= new stdClass();
			$item->condition= $json_data;
			$item->state	= $state;
			$item->mess		= $mess;
			$item->exception= $exception;
			$item->id		= $id;
			$item->sm_title	= $sm_title;
			
			$item->attachment = $attachment;
			$db 	= new db_controller();
			//print_r($item);

			if ($id > 0){
				$db->update($item, 'mess', 'id');
			}else{
				$item->id = NULL;
				$db->insert($item, 'mess');
				/*echo "insert";*/
			}
			
			if ($_GET['type'] != 'json')
				header('Location: index.php');
			return true;
		}
	}

	function delete(){

		if ($this->access){

			$id		= intval($_REQUEST['id']);
			$db 	= new db_controller();
			
			$db->delete($id, 'mess', 'id');
			
			//header('Location: index.php');
			return true;
		}
	}
	
	function event(){
		$slack = new slack();
		
		if($_SERVER['REQUEST_METHOD'] == 'POST') {
			$data 		= file_get_contents("php://input");
			$request	= json_decode($data);
		}
		
		if ($request->event->type == 'message' && !isset($request->event->bot_id)){
			
			$user = $request->event->user;
			$text = $request->event->text;
			
			$channel_type = $request->event->channel_type;
			
			$slack = new slack();
			$userData = $slack->get_members_by_id($user);
			$userNick = '';
			
			if (isset($userData[0]->profile->display_name)){
				$userNick = $userData[0]->profile->display_name;
			}else{
				$userNick = $userData[0]->name;
			}
			
			//$userNick = 'ike';
			
			if ($userNick && $channel_type == 'im'){
				if ($request->authed_users[0] == 'U56Q2JUNP' || $request->authed_users[1] == 'U56Q2JUNP'){
					file_put_contents('replyes.txt', $userNick.': '.$text."\n\n", FILE_APPEND);
					
					$db 	= new db_controller();
					$rows 	= $db->query("select * from `dialogs` as a 
					WHERE a.user = '$userNick' and a.answer = '' and (TO_DAYS(NOW()) - TO_DAYS(a.date) < 1) 
					order by a.id
					DESC limit 1");
					
					if (count($rows)){
						$row = $rows[0];
						
						$pollRow 	= $db->query("select * from `mess` as a WHERE a.id = ".$row->messid);
						$poll = $pollRow[0];
						$pollQArr = explode("\n", $poll->mess);
						
						$item 			= new stdClass();
						$item->id		= $row->id;
						$item->answer	= $text; 
						$r = $db->update($item, 'dialogs', 'id');  

						$Q = '';
						$nextQ = false;
						foreach($pollQArr as $question){ // выбираем следующий вопрос
							$question = str_replace("<br />","<br/>",$question);
							$question = str_replace("<br>","<br/>",$question);
							$Q_sm = $question;
							if (!(strpos($question, '<br/>') === false)){
								$QArr = explode("<br/>", $question);
								$Q_sm = $QArr[1];
							}
							
							if ($nextQ){
								$Q = $question;
								$nextQ = false;
							}
							if (trim($question) == trim($row->question) || trim($Q_sm) == trim($row->question)){
								$nextQ = true;
							}
						}
						
						//$slack->send($userData, print_r($pollQArr, true));
						
						if ($Q){ // Если задали не все вопросы, то добавляем следующий в базу
							$item 			= new stdClass();
							$item->question	= $Q;
							$item->user		= $userNick;
							$item->date		= date('Y-m-d H:i:s');
							$item->messid	= $row->messid;
							
							$db->insert($item, 'dialogs');
							
							$slack->send($userData, $Q);
						}else{
							$slack->send($userData, 'Супер! Спасибо тебе за ответы.');
							
							$rows 	= $db->query("select * from `dialogs` as a 
							WHERE a.user = '$userNick' and (TO_DAYS(NOW()) - TO_DAYS(a.date) < 1)  and a.messid = ".$row->messid."
							order by a.id ASC");
							
							$weekday = date('w') - 1;
							if ($weekday < 0) $weekday = 6;
							
							$week_begin = strtotime("-".($weekday+7)." day");
							$week_end	= strtotime("-".($weekday+1)." day");
							

							if ($poll->sm_title{0} == '#'){
								$report = ' @'.$userNick.' рассказал о работе своей команды на неделе '.date('d.m.Y', $week_begin).'-'.date('d.m.Y', $week_end)."\n";
								$poll->sm_title = substr($poll->sm_title, 1);
								$teamleads = $slack->get_chanel('reports_teamleads');
								$teamleads[0]->deleted = 0;
							}else{
								$report = ' @'.$userNick.' ответил на твой опрос:'."\n";
								//$row->sm_title = substr($row->sm_title, 1);
								$teamleads = $slack->get_members(array($poll->sm_title));
							}
							
							foreach($rows as $row){
								$report .= '>'.$row->question."\n".$row->answer."\n";
							}
							
							$slack->send($teamleads, $report);
							
						}
					}else{
						$slack->send($userData, 'Хм. Что-то я не пойму, о чем это ты. напиши @tod');
					}
				}	
			}else{
				//file_put_contents('data.txt', print_r($request, true), FILE_APPEND);
			}
		}
		
		return array('challenge' => $request->challenge);
	}
	
	private function poll_init($poll){
		$pollQArr = explode("\n", $poll->mess);
		$Q = $pollQArr[0];
		
		$db	= new db_controller();
		
		$exception = str_replace(" ","",$poll->exception);
		$exceptionArr = explode(",", $exception); // Формируем массив получателей
		
		$Q = str_replace("<br />","<br/>",$Q);
		$Q = str_replace("<br>","<br/>",$Q);
		$Q_sm = $Q;
		if (!(strpos($Q, '<br/>') === false)){
			$QArr = explode("<br/>", $Q);
			$Q_sm = $QArr[1];
		}
		
		$Q = str_replace("<br/>","\n\n",$Q); 
		
		
		/************/ 
		$usersTosend = array();
		require_once 'lib/googleSheetClass.php';
		$GSheet = new gSheet('https://docs.google.com/spreadsheets/d/1pXVvz-GbvMmMjv5y6XbwOcVqKIuWs316oWEQNndvi8w/edit?usp=sharing');
		$sheet_title = 'отпуск '.date('Y');	
		$nicks = $GSheet->read($sheet_title.'!B3:B38');
		$nicksArr = array();
		$i = 3;
		foreach($nicks as $nickrow){
			$nicksArr[mb_strtolower($nickrow[0])] = $i;
			$i++;
		}
		
		$ColNum = get_date_col(date('d.m.Y', time()), $GSheet);
		
		foreach($exceptionArr as $nick){
			$RowNum = isset($nicksArr[$nick])?$nicksArr[$nick]:0;
			if ($RowNum){
				$bg = strip_tags($GSheet->readBackground($sheet_title.'!'.getCols($ColNum).$RowNum));	
				if (!in_array($bg, array('#b6d7a8', '#fbd4b4', '#a4c2f4', '#c161ca', '#dd7e6b'))){
					$usersTosend[] = $nick;
				}
			}else{
				$usersTosend[] = $nick;
			}
		}
		
		echo '<pre>'.print_r($usersTosend, true).'</pre>';
		/************/ 
		
		if (count($usersTosend)){
			foreach($usersTosend as $user){
				$item 			= new stdClass();
				$item->question	= $Q_sm;
				$item->user		= $user;
				$item->date		= date('Y-m-d H:i:s');
				$item->messid	= $poll->id;
				
				$db->insert($item, 'dialogs');
			}				
			$slack = new slack();
			$userData = $slack->get_members($usersTosend);
			$slack->send($userData, $Q);
		}
	}
	
	private function poll_remind($row, $cancel = false){
		$db	= new db_controller();
		
		$exception = str_replace(" ","",$row->exception);
		$exceptionArr = explode(",", $exception); // Формируем массив получателей
		
		foreach($exceptionArr as $userNick){
			$rows 	= $db->query("select * from `dialogs` as a 
				WHERE a.user = '$userNick' and a.answer = '' and (TO_DAYS(NOW()) - TO_DAYS(a.date) < 1) 
				order by a.id
				DESC limit 1");
			
			if (count($rows)){
				$slack = new slack();
				if (!$cancel){
					$userData = $slack->get_members(array($userNick));
					$mess = 'Mail-e всё ещё надеется, что ты, как тимлид, проявишь ответственность и расскажешь об успехах твоей команды на прошлой неделе.';
					$attachment = array(
						"fallback"	=> "Еженедельный отчет",
						"color"		=> "#cccccc",
						"attachment_type" => "default",
						"callback_id" => $row->id,
						"actions"	=> array(
							array(
								"name"	=> "leadreport_no",
								"text"	=> "Не хочу",
								"style"	=> "danger",
								"type"	=> "button"
							),
							array(
								"name"	=> "leadreport_yes",
								"text"	=> "Да, сейчас",
								"style"	=> "primary",
								"type"	=> "button"
							)								
						)
					);
				}else{
					$userData = $slack->get_chanel('reports_teamleads');
					$userData[0]->deleted = 0;
					$attachment = null;
					
					$weekday = date('w') - 1;
					if ($weekday < 0) $weekday = 6;
					
					$week_begin = strtotime("-".($weekday+7)." day");
					$week_end	= strtotime("-".($weekday+1)." day");
					
					$mess = ' @'.$userNick.' нечего рассказать о работе своей команды на неделе '.date('d.m.Y', $week_begin).'-'.date('d.m.Y', $week_end)."\n";

				}
				
				$result = $slack->send($userData, $mess, $attachment);
			}
		}
	}
	
	function schedule(){
		$db 	= new db_controller();
		$rows 	= $db->query("select * from `mess` WHERE state = 1 order by `id` ASC");
		
		foreach($rows as $row){
			$send = false;
			$cond = json_decode($row->condition);
			if ($cond && json_last_error() == 0) {
				switch ($cond->type) {
					case 'regular_wd': // Еженедельное
						$days = $cond->w_days;
						$today = date('w');
						if ($today == 0) $today = 7;
						
						if (in_array($today, $days)){ // Если сегодня отправляем
							$send = true;
						}
						break;
					case 'regular_md': // Ежемесячное
						$days = $cond->m_days;
						$today = date('j');
						if (in_array($today, $days)){ // Если сегодня отправляем
							$send = true;
						}
						break;
					case 'single': // Разовое
						$day = $cond->date;
						$today = date('Y-m-d');
						if ($day == $today){ // Если сегодня отправляем
							$send = true;
						}
						break;
					case 'regular_date': // Ежегодное
						$day = date('m-d', strtotime($cond->date));
						$today = date('m-d');
						if ($day == $today){ // Если сегодня отправляем
							$send = true;
						}
						break;
					case 'birthday': // Напоминание о ДР
						$day = strtotime($cond->date) - 12*60*60;
						$weekbyday = $day - 20*24*60*60;
						$today = time();
						if ($today < $day && $today >= $weekbyday){ // Если сегодня отправляем
							$send = true; 
						}
						if (date('w', $today) == 0 || date('w', $today) == 6){
							$send = false; 
						}
						
						break;
				}
			}
			
			if ($send){
				//echo date('H:i').' != '.$cond->time;
				$timePlus2Arr = explode(":", $cond->time);
				$timePlus2H = intval($timePlus2Arr[0])+2;
				$timePlus2 = (($timePlus2H<10)?'0':'').$timePlus2H.':'.$timePlus2Arr[1];
				
				if ($cond->time == date('H:i') || ($row->attachment == 'poll' && ($timePlus2 == date('H:i') || date('H:i')== '20:00'))){ // Если сейчас отправляем
					if ($row->attachment == 'poll'){
						if ($cond->time == date('H:i')){
							$this->poll_init($row);
						}else{
							if ($timePlus2 == date('H:i') && $row->sm_title == '#reports_teamleads'){
								$this->poll_remind($row);
							}else{
							//	$this->poll_remind($row, true);
							}
						}
					}else{
						$exception = str_replace(" ","",$row->exception);
						$exceptionArr = explode(",", $exception); // Формируем массив исключений
						
						if (!$row->attachment){
							$mess = $row->mess;
							$attachment = null;
						}else{
							$mess = '';
							$attachment = str_replace("\r","",$row->attachment);
							$attachment = str_replace("\n","",$attachment);
							//$data_json = utf8_encode($attachment);
							$attachment = json_decode($attachment);
						}
						
						echo '<pre>'.print_r($attachment, true).'</pre>';
						
						$slack = new slack();
						//$users = $slack->get_members(array('lariler', 'tod'));
						$users = $slack->get_members($exceptionArr, true, true);
						
						
						if ($cond->type == 'birthday'){
							$mess = $row->mess;
							$attachment = array(
								"fallback"	=> "Собираем на подарочки",
								"color"		=> "#cccccc",
								"attachment_type" => "default",
								"callback_id" => $row->id,
								"actions"	=> array(
									array(
										"name"	=> "present_yes",
										"text"	=> "Cдал наличными",
										"style"	=> "primary",
										"type"	=> "button",
										"value"	=> "cancel"
									),
									/*array(
										"name"	=> "present_psb",
										"text"	=> "Cдал через псб",
										"style"	=> "primary",
										"type"	=> "button",
										"value"	=> "cancel"
									),*/
									array(
										"name"	=> "present_sber",
										"text"	=> "Перевел на карту",
										"style"	=> "primary",
										"type"	=> "button",
										"value"	=> "cancel"
									),
									array(
										"name"	=> "present_no",
										"text"	=> "Не буду сдавать",
										"style"	=> "danger",
										"type"	=> "button",
										"value"	=> "cancel"
									),								
								)
							);
						}
						
						// test
						$result = $slack->send($users, $mess, $attachment);
					}
					echo 'sended';
				}
			}
			
		}
		return true;
	}
	
	function test(){
		$resArr = array(
		//	'https://www.likeni.ru/rss/news/',
		//	'https://www.seonews.ru/rss/events/',
		//	'https://rusability.ru/research/feed/',
		//	'https://texterra.ru/blog/rss/',
		//	'https://searchengines.guru/ru/news/mobile/rss',
		//	'https://searchengines.guru/ru/news/ecommerce/rss',
		//	'https://adindex.ru/news/news.rss',
		//	'https://news.pressfeed.ru/category/pr/feed/',
		//	'https://news.pressfeed.ru/category/kontent-marketing/feed/',
		//	'https://www.thinkwithgoogle.com/intl/ru-ru/rss.xml',
		//	'https://sproutsocial.com/insights/social-trends/feed/',
		//	'https://www.litmus.com/resources/feed/',
		//	'https://www.sostav.ru/rss'
			array('http://fetchrss.com/rss/601d1d93532fe3183630a5f2601d1df2266b530211210282.xml', 3)
		);
		
		
		
		$slack = new slack();
		$users = $slack->get_members(array('tod'));
		
		
		foreach($resArr as $res){
			$txt = $this->rssget($res, 58000);
			if ($txt)
				$result = $slack->send($users, $txt);
		}
		
		/*$token = 'bd975cdbbd975cdbbd975cdbe7bdc6ebb3bbd97bd975cdbe6d3c9ff3bf40fbde0749abe';
		$groupid = '-160906852';		
		$url = 'https://api.vk.com/method/wall.get?owner_id='.$groupid.'&count=20&extended=1&v=5.120&access_token='.$token;
		
		$data = $this->curlget($url);
		
		//echo '<pre>'.print_r($mess).'</pre>';
		
		$link = 'https://vk.com/emailmatrix?w=wall'.$groupid.'_'.$data->response->items[0]->id;

		$time = $data->response->items[0]->date;
		$timeDif = ((time() - $time)/60);
		
		echo $link.'<br />'.$timeDif;
		
		//Рассылаем
		if ($timeDif < 30){
			$mess = "У нас появился новый пост Вконтакте. Ему очень не хватает твоего лайка! \n".$link;
			$slack = new slack();
			$users = $slack->get_members(array('umka'), true, true);
			
			$result = $slack->send($users, $mess);
		}*/
		
		echo 'test';
	}
	
	function ideas(){
		$resArr = array(
			array('https://www.likeni.ru/rss/news/', 0),
			array('https://www.seonews.ru/rss/events/', 0),
			array('https://texterra.ru/blog/rss/', 0),
			array('https://searchengines.guru/ru/news/mobile/rss', 0),
			array('https://searchengines.guru/ru/news/ecommerce/rss', 0),
			array('https://adindex.ru/news/news.rss', 0),
			array('https://news.pressfeed.ru/category/pr/feed/', 0),
			array('https://news.pressfeed.ru/category/kontent-marketing/feed/', 0),
			array('https://news.pressfeed.ru/category/pr/feed/', 0),
			array('https://www.thinkwithgoogle.com/intl/ru-ru/rss.xml', 0),
			array('https://sproutsocial.com/insights/social-trends/feed/', 0),
			array('https://www.litmus.com/resources/feed/', 0),
			array('https://www.sostav.ru/rss', 0),
			array('https://blog.hubspot.com/marketing/rss.xml', 0),
			array('http://fetchrss.com/rss/601d1d93532fe3183630a5f2601d1c375848a067393a2b72.xml', 3), // Сбермаркетинг
			array('http://fetchrss.com/rss/601d1d93532fe3183630a5f2601d1df2266b530211210282.xml', 3), // DataInsight
			array('https://rb.ru/feeds/news/', 0),
			array('http://rss.marketingprofs.com/marketingprofs/daily', 0),
			array('https://blog.euromonitor.com/white_paper/feed/', 0),
			array('https://www.cossa.ru/news/', 0),
			array('https://ppc.world/feed/', 0),
			array('https://siteclinic.ru/blog/web-analytics/feed/', 0)
		);
		$slack = new slack();
		//$users = $slack->get_members(array('tod'));
		$users = $slack->get_chanel('marketing_news');
		$users[0]->deleted = 0;
		
		$txt ='';
		foreach($resArr as $res){
			$itemtxt = $this->rssget($res, 10);
			if ($itemtxt)
				$txt .= $itemtxt."\n"; 			
		}
		
		if ($txt)
			$result = $slack->send($users, $txt);
		
		//file_put_contents('cron_test.log', date('y-m-d H:i:s'));
		
		
		echo 'ok';
		
	}
	
	function mg_report_new(){
		if ($_SERVER["REMOTE_ADDR"] == '176.9.155.239' || $_SERVER["REMOTE_ADDR"] == '88.99.100.15'){
			$slack = new slack();
			$managers = $slack->get_pchanel('managers');
			
			echo '<pre>'.print_r($managers, true).'</pre>';
			$managers[0]->deleted = 0;
			
			$mess = 'У нас появились новые клиенты? Обязательно подключи их к <http://emailmatrix.ru/_tasks/reports/|сервису отчётов>. Как это сделать есть у нас в <https://rm.emailmatrix.ru/projects/emx_education/wiki/Start_new_clients|инструкции>';
			
			$result = $slack->send($managers, $mess);
		}
	}
	
	function mg_report_up(){
		if ($_SERVER["REMOTE_ADDR"] == '176.9.155.239' || $_SERVER["REMOTE_ADDR"] == '88.99.100.15'){
			$slack = new slack();
			$managers = $slack->get_pchanel('managers');
			
			echo '<pre>'.print_r($managers, true).'</pre>';
			$managers[0]->deleted = 0;
			
			$mess = 'Зайдите в <http://emailmatrix.ru/_tasks/reports/|сервис отчётов> и актуализируйте емейлы менеджеров с клиентской и нашей стороны. Проверьте, что отчёты включены и вы их регулярно получаете.';
			
			$result = $slack->send($managers, $mess);
		}
	}
	
	function fb_notification(){
		
		$link = $this->fbget('178153198877541', 30);
		
		//Рассылаем
		if ($link){
			$mess = "У нас появился новый пост в Facebook. Ему очень не хватает твоего лайка! \n".$link;
			$slack = new slack();
			$users = $slack->get_members(array('umka'), true, true);
			
			// отключили
			//$result = $slack->send($users, $mess);
		}
		//echo '<pre>'.print_r($mess).'</pre>';
		
		
		/* vk */
		//sleep(3);
		/*$token = 'bd975cdbbd975cdbbd975cdbe7bdc6ebb3bbd97bd975cdbe6d3c9ff3bf40fbde0749abe';
		$groupid = '-160906852';		
		$url = 'https://api.vk.com/method/wall.get?owner_id='.$groupid.'&count=20&extended=1&v=5.120&access_token='.$token;
		
		$data = $this->curlget($url);
		
		//echo '<pre>'.print_r($mess).'</pre>';
		
		$link = 'https://vk.com/emailmatrix?w=wall'.$groupid.'_'.$data->response->items[0]->id;

		$time = $data->response->items[0]->date;
		$timeDif = ((time() - $time)/60);
		
		//Рассылаем
		if ($timeDif < 30){
			$mess = "У нас появился новый пост Вконтакте. Ему очень не хватает твоего лайка! \n".$link;
			$slack = new slack();
			$users = $slack->get_members(array('umka'), true, true);
			
			$result = $slack->send($users, $mess);
		}*/

		return true;
	}
	
	function vk_notification(){
		$token = 'bd975cdbbd975cdbbd975cdbe7bdc6ebb3bbd97bd975cdbe6d3c9ff3bf40fbde0749abe';
		$groupid = '-160906852';		
		$url = 'https://api.vk.com/method/wall.get?owner_id='.$groupid.'&count=20&extended=1&v=5.120&access_token='.$token;
		
		$data = $this->curlget($url);
		
		//echo '<pre>'.print_r($mess).'</pre>';
		
		$link = 'https://vk.com/emailmatrix?w=wall'.$groupid.'_'.$data->response->items[0]->id;

		$time = $data->response->items[0]->date;
		$timeDif = ((time() - $time)/60);
		
		echo $link.'<br />'.$timeDif;
		
		//Рассылаем
		if ($timeDif < 30){
			$mess = "У нас появился новый пост Вконтакте. Ему очень не хватает твоего лайка! \n".$link;
			$slack = new slack();
			$users = $slack->get_members(array('umka'), true, true);
			//$users = $slack->get_members(array('tod'));
			
			// отключили
			//$result = $slack->send($users, $mess);
		}
	}
	
	private function rssget($url, $period){
		$res1 = $this->curlget($url[0], 'xml');
		$item = $res1->channel->item[0];
		$item->pubDate = preg_replace('/(.*) (\+.*)/', '$1', $item->pubDate);
		$time = strtotime($item->pubDate)+$url[1]*60*60;
		$timeDif = ((time() - $time)/60);
		
		echo date('Y-m-d H:i', $time).'<br />'; 
		echo date('Y-m-d H:i', time()).'<br />';
		echo $timeDif;
		//echo '<pre>'.print_r($timeDif, true).'</pre>';
		
		if ($timeDif <= $period && $timeDif > 0){
			return "<".$item->link."|".$item->title."> \n".mb_substr(trim(strip_tags($item->description)), 0, 255);;
		}else{
			//return '==';
		}
	}
	
	private function fbget($groupid, $period){
		$token = 'EAAb09sMCHqYBAOEYoN5ZCTZCT7fQ9PA3KIUDZCCzJkvQA89p0Ps0PhIKVv856LszhrhiV6xN3dZCVkOzEg1o26hUnQGYfvIa6fZBYVzkocZBtAZCPjncJ1hpW3iofQ08l0ZBJbkHAx0Y4jGfVDO3BftT0B2KxFp6lhbFDjye6tz5WQZDZD';
		$url = 'https://graph.facebook.com/'.$groupid.'/feed?limit=3&access_token='.$token;
		
		echo $url.'<br />';
		
		$data = $this->curlget($url);
		
		$mess_data = explode('_', $data->data[0]->id);		
		$link = 'https://www.facebook.com/'.$mess_data[0].'/posts/'.$mess_data[1];

		$time = strtotime($data->data[0]->created_time);
		$timeDif = ((time() - $time)/60);
		
		//Рассылаем
		if ($timeDif < $period){
			return $link;
		}else{
			return "";
		}
	}
	
	private function curlget($url, $type = 'json'){
		$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
        $content = curl_exec($ch); 
        curl_close($ch); 
		
		$result = $content;
		if ($type == 'json'){
			$result = json_decode($content);
		}elseif($type == 'xml'){
			$result = simplexml_load_string($content);
		}
		return $result;
	}
	
	function rm_mention(){
		require_once __DIR__.'/lib/redmine_load.php';
		$host = 'https://rm.emailmatrix.ru/';
		$key = '3cfe87a134c680b9897d9e98edb6ca175098141f';
		$client = new Redmine\Client($host, $key);
		
		$dif = 1;
		
		$my_issues = $client->issue->all([
			'offset' => 0,
			'limit' => 1000,
			'sort' => 'updated_on',
			'status_id' => 'open',
			'updated_on' => '='.date('Y-m-d')
		]);
		
		foreach($my_issues['issues'] as $issue){
			$min = (time() - strtotime($issue['updated_on']))/60;
			$min_cr = (time() - strtotime($issue['created_on']))/60;
			
			$members = array();
			if ($min < $dif || $min_cr < $dif){ // Если тикет обновили после последней проверки
				$cur_issue = $client->issue->show($issue['id'], array('include' => array('journals')));
				
				$noteid = 0;
				$mynoteid = 1;
				
				if ($min_cr < $dif){
					preg_match_all('/(\W|^)@\w+/',$issue['description'], $matches);
					
					if (count($matches[0])){
						foreach($matches[0] as $nick){
							$nick = substr($nick, 1);
							$nick = str_replace("@", "", $nick);
							
							if ($nick == 'vio') $nick = 'vio47';
							
							$members[] = $nick;
							$mynoteid = $noteid;
						}
					}
				}else{
					foreach ($cur_issue['issue']['journals'] as $note){
						$noteid++;
						$note_min = (time() - strtotime($note['created_on']))/60;
						if ($note_min < $dif){ // Если коммент оставили после последней проверки
							
							//$note['notes'] - здесь у нас текст для анализа
							if (isset($note['notes'])){
								preg_match_all('/(\W|^)@\w+/', $note['notes'], $matches);
								
								if (count($matches[0])){
									foreach($matches[0] as $nick){
										$nick = substr($nick, 1);
										$nick = str_replace("@", "", $nick);
										
										if ($nick == 'vio') $nick = 'vio47';
										
										$members[] = $nick;
										$mynoteid = $noteid;
									}
								}
							}
						}
					}
				}
				
				if (count($members)){
					foreach($members as $member){
						$text = "Тебя упомянули в тикете <https://rm.emailmatrix.ru/issues/".$issue['id']."#note-".$mynoteid."|#".$issue['id'].' - '.$issue['subject'].">. Загляни в него, там ждут твоего ответа";
						
						$slack = new slack();
						$sl_users = $slack->get_members(array($member));
						
						if(!count($sl_users)){
							if (in_array($member, array('office', 'remote', 'support'))){
								$sl_group = $slack->get_group($member, true);
								$u_group = array();
								foreach($sl_group[0]->users as $usergroup){
									$item			= new stdClass();
									$item->id		= $usergroup;
									$u_group[] 		= $item;
								}
								$sl_users = $u_group;
							}else{
								$sl_users = $slack->get_chanel('team_'.$member);
								$sl_users[0]->deleted = 0;
								
								$sl_group = $slack->get_group($member);
								$text = "<!subteam^".$sl_group[0]->id.">, вас упомянули в тикете <https://rm.emailmatrix.ru/issues/".$issue['id']."#note-".$mynoteid."|#".$issue['id'].' - '.$issue['subject'].">. Загляните в него, там ждут вашего ответа";
							}
						} 

						$slack->send($sl_users, $text);
					}
				}
			}
		}
		echo 'ok';
	}
	
	function redmine_new(){
		require_once __DIR__.'/lib/redmine_load.php';
		$host = 'https://rm.emailmatrix.ru/';
		$key = '3cfe87a134c680b9897d9e98edb6ca175098141f';
		
		$client = new Redmine\Client($host, $key);
		
		$my_issues = $client->issue->all([
			'offset' => 0,
			'limit' => 1000,
			'sort' => 'author',
			'status_id' => 'open',
			'due_date'	=> '<='.date('Y-m-d')
		]);
		
		//echo '<pre>'.print_r($my_issues['issues'], true).'</pre>';
		
		$users = array();
		foreach($my_issues['issues'] as $issue){
			// Я автор
			$name = $issue['author']['name'];
			if (!isset($users[$name])){
				$users[$name] = array(
					'overdue'	=> array(),
					'today'		=> array(),
					'overdueMe'	=> array(),
					'waitingMe'	=> array(),
					'overdueSum'=> array()
				);
			} 
			// Если дедлайн не сегодня
			if ($issue['due_date'] != date('Y-m-d')){
				$users[$name]['overdueMe'][] = $issue['id'];
				$users[$name]['overdueSum'][] = $issue['id'];
			}
			
			// Я исполнитель
			$name = $issue['assigned_to']['name'];
			
			if (!isset($users[$name])){
				$users[$name] = array(
					'overdue'	=> array(),
					'today'		=> array(),
					'overdueMe'	=> array(),
					'waitingMe'	=> array(),
					'overdueSum'=> array()
				);
			}
			
			// Если статус не Resolved(3) и не Feedback (4)
			if ($issue['status']['id'] != 3 && $issue['status']['id'] != 4){
				// Если дедлайн не сегодня
				if ($issue['due_date'] != date('Y-m-d')){
					$users[$name]['overdue'][] = $issue['id'];	
					$users[$name]['overdueSum'][] = $issue['id'];	
				}else{
					$users[$name]['today'][] = $issue['id'];
				}
			}
		}
		
		$slack = new slack();
		foreach($users as $key => $user){
			if (count($user['overdueMe']))
				foreach ($user['overdueMe'] as $issueid){
					$cur_issue = $client->issue->show($issueid, array('include' => array('journals')));
					
					$countcomments = count($cur_issue['issue']['journals']);
					if ($countcomments > 0){
						$lastcomment = end($cur_issue['issue']['journals']);
						
						if ($lastcomment['user']['name'] != $key){
							$users[$key]['waitingMe'][] = $issueid;
						}
					}					
				}
				
			// prepare text
			$count_overdue = array();
			if (count($users[$key]['overdueSum']))
				$count_overdue = array_unique($users[$key]['overdueSum']);
			
			$text = '';
			$attacharray = array();
			if (count($count_overdue)){
				$text .= "Просрочено (тобой или твои задачи) — ".count($count_overdue)."\n";
				$attacharray[] = array(
						"name"	=> "overdue",
						"text"	=> "Просроченные",
						"type"	=> "button",
					);
			}
			if (count($users[$key]['today'])){
				$text .= "Необходимо выполнить сегодня — ".count($users[$key]['today'])."\n";
				$attacharray[] = array(
						"type"	=> "button",
						"text"	=> "Задачи на сегодня",
						"url"	=> "https://rm.emailmatrix.ru/projects/p_emailmatrix/issues?utf8=%E2%9C%93&set_filter=1&f%5B%5D=status_id&op%5Bstatus_id%5D=o&f%5B%5D=assigned_to_id&op%5Bassigned_to_id%5D=%3D&v%5Bassigned_to_id%5D%5B%5D=me&f%5B%5D=due_date&op%5Bdue_date%5D=%3D&v%5Bdue_date%5D%5B%5D=".date('Y-m-d')."&f%5B%5D=&c%5B%5D=tracker&c%5B%5D=status&c%5B%5D=priority&c%5B%5D=subject&c%5B%5D=author&c%5B%5D=assigned_to&c%5B%5D=updated_on&c%5B%5D=due_date&group_by="
					);
			}
			if (count($users[$key]['waitingMe'])){
				$text .= "Ожидает твоей проверки — ".count($users[$key]['waitingMe'])."\n";
				
				$attacharray[] = array(
						"name"	=> "waitingMe",
						"text"	=> "Ожидают проверки",
						"type"	=> "button",
					);
			}
			
			if ($text) $text = "Привет! Я проанализировал все твои тикеты. Положение дел такое: \n".$text;
				
			// Рассылаем
			$attachment = array(
				"fallback"	=> "Проверяем просрочку",
				"color"		=> "#cccccc",
				"attachment_type" => "default",
				"callback_id" => 'overdue',
				"actions"	=> $attacharray
			);
			
			//echo '<pre>'.print_r($text, true).'</pre>';
			//echo '<pre>'.print_r($users['lariler'], true).'</pre>';
			
			$nickname = $key;
			if ($nickname == 'vio') $nickname = 'vio47';
			if ($nickname == 'vertex') $nickname = 'ver1ex';
			
			if ($text){
				$sl_users = $slack->get_members(array($nickname));
				$slack->send($sl_users, $text, $attachment);
			}
			
		}
	
		/* Проверка для групп, а не людей */
		$groups = $client->group->all();
		
		foreach($groups['groups'] as $group){
			
			//echo '<pre>'.print_r($group, true).'</pre>';

			$issues = $client->issue->all([
				'offset' => 0,
				'limit' => 1000,
				'status_id' => 'open',
				'assigned_to_id' => $group['id']
			]);
			
			//echo '<pre>'.print_r($issues['issues'], true).'</pre>';
			
			$txt = '';
			if (count($issues['issues'])){
				foreach($issues['issues'] as $issue){
					if (strtotime($issue['due_date']) < time()+24*60*60){
						if (!$txt){
							$sl_group = $slack->get_group($group['name']);
							
							$txt = "<!subteam^".$sl_group[0]->id.">, ниже общие задачи вашей команды на сегодня. Сделайте их. \n";
						}
						
						$txt .= "<https://rm.emailmatrix.ru/issues/".$issue['id']."|".$issue['id'].' - '.$issue['subject']."> дедлайн - ".$issue['due_date']." \n";

					}
				}
				
				if ($txt){
					$sl_users = $slack->get_chanel('team_'.$group['name']);
					if (count($sl_users)){
						$sl_users[0]->deleted = 0;
						$slack->send($sl_users, $txt);
					}						
				}
			}
		}
		echo 'ok';
	}
	
	function redmine_assigned(){
		if ($_SERVER["REMOTE_ADDR"] == '176.9.155.239' || $_SERVER["REMOTE_ADDR"] == '88.99.100.15'){
			require_once __DIR__.'/lib/redmine_load.php';
			$host = 'https://rm.emailmatrix.ru/';
			$key = '3cfe87a134c680b9897d9e98edb6ca175098141f';

			$client = new Redmine\Client($host, $key);
			
			$my_issues = $client->issue->all([
				'offset' => 0,
				'limit' => 1000,
				'sort' => 'assigned_to',
				'status_id' => 'open',
				'due_date'	=> '<='.date('Y-m-d', time()-24*60*60)
			]);
			
			$users = array();
			foreach($my_issues['issues'] as $issue){
				if (isset($issue['assigned_to'])){
					$name = $issue['assigned_to']['name'];
					if ($name == 'vio') $name = 'vio47';
					if ($name == 'vertex') $name = 'ver1ex';
					if ($name){
						if (!isset($users[$name])) $users[$name] = array();
						$users[$name][] = $issue['id'];
					}
				}
			}
			
			$slack = new slack();
			foreach($users as $key => $value){
				$text = '';
				
				$attachment = array(
					'pretext'	=> 'Привет, у тебя просрочено несколько тикетов, а именно '.count($value).'. Если они выполнены, напомни менеджеру. Ну а если задача ещё не выполнена — приложи максимум усилий для её выполнения и сообщи реальные сроки автору задачи.',
					'title'	=> 'ПОСМОТРЕТЬ ТИКЕТЫ',
					'title_link' => 'https://rm.emailmatrix.ru/issues?c%5B%5D=project&c%5B%5D=tracker&c%5B%5D=status&c%5B%5D=priority&c%5B%5D=subject&c%5B%5D=author&c%5B%5D=assigned_to&c%5B%5D=updated_on&c%5B%5D=due_date&f%5B%5D=status_id&f%5B%5D=assigned_to_id&f%5B%5D=due_date&f%5B%5D=&group_by=&op%5Bassigned_to_id%5D=%3D&op%5Bdue_date%5D=%3C%3D&op%5Bstatus_id%5D=o&set_filter=1&sort=assigned_to%2Cpriority%3Adesc%2Cupdated_on%3Adesc&utf8=%E2%9C%93&v%5Bassigned_to_id%5D%5B%5D=me&v%5Bdue_date%5D%5B%5D='.date('Y-m-d', time()-24*60*60),
					'color'	=> "#dd0000",
				);
				
				$users = $slack->get_members(array($key));
				/*echo $key;
				echo '<pre>'.print_r($users, true).'</pre>';
				echo '<hr />';*/
				$slack->send($users, $text, $attachment);
			}
		}else{
			echo 'Restricted access';
		}
	}
	
	function redmine(){
		if ($_SERVER["REMOTE_ADDR"] == '176.9.155.239' || $_SERVER["REMOTE_ADDR"] == '88.99.100.15'){
			require_once __DIR__.'/lib/redmine_load.php';
			$host = 'https://rm.emailmatrix.ru/';
			$key = '3cfe87a134c680b9897d9e98edb6ca175098141f';

			$client = new Redmine\Client($host, $key);
			
			$my_issues = $client->issue->all([
				'offset' => 0,
				'limit' => 1000,
				'sort' => 'author',
				'status_id' => 'open',
				'due_date'	=> '<='.date('Y-m-d', time()-24*60*60)
			]);
			
			//echo '<h1>'.count($my_issues['issues']).'</h1>';
			
			$users = array();
			foreach($my_issues['issues'] as $issue){
				$name = $issue['author']['name'];
				if (!isset($users[$name])) $users[$name] = array();
				$users[$name][] = $issue['id'];
			}
			
			$slack = new slack();
			foreach($users as $key => $value){
				$text = '';
				
				$attachment = array(
					'pretext'	=> 'Привет, я тут обнаружил немного просрочки. Актуализируй, пожалуйста, дедлайн:',
					'title'	=> 'ПОСМОТРЕТЬ ТИКЕТЫ',
					'title_link' => 'https://rm.emailmatrix.ru/projects/p_emailmatrix/issues?utf8=%E2%9C%93&set_filter=1&f%5B%5D=status_id&op%5Bstatus_id%5D=o&f%5B%5D=author_id&op%5Bauthor_id%5D=%3D&v%5Bauthor_id%5D%5B%5D=me&f%5B%5D=due_date&op%5Bdue_date%5D=%3C%3D&v%5Bdue_date%5D%5B%5D='.date('Y-m-d', time()-24*60*60).'&f%5B%5D=&c%5B%5D=tracker&c%5B%5D=status&c%5B%5D=priority&c%5B%5D=subject&c%5B%5D=author&c%5B%5D=assigned_to&c%5B%5D=updated_on&c%5B%5D=due_date',
					'color'	=> "#3AA3E3",
				);
				
				$users = $slack->get_members(array($key));
				$slack->send($users, $text, $attachment);
			}
		}else{
			echo 'Restricted access';
		}
	}

	function report_notify(){
		$mbox = imap_open ("{mta.emailmatrix.ru:993/imap/ssl}INBOX/repors", "slack-bot@emailmatrix.ru", "ZLzljj3K");
		$MC = imap_check($mbox);
		$overview = imap_fetch_overview($mbox,"1:{$MC->Nmsgs}",0);
		
		// получить список папок
		//echo '<pre>'.print_r(imap_list($mbox, "{mta.emailmatrix.ru:993/imap/ssl}", "*"), true).'</pre>';
		
		if(is_array($overview)) {
			reset($overview); 
			$emailsArr = array();
			$nickArr = array();
			while( list($key,$val) = each($overview)) {
				if ($val->seen < 1){
					//$messBodyOrig 	= imap_fetchbody($mbox, $val->msgno, '1', FT_PEEK);
					$messBodyOrig 	= imap_fetchbody($mbox, $val->msgno, '1');
					$structure 		= imap_fetchstructure($mbox, $val->msgno);
					$header 		= imap_headerinfo($mbox, $val->msgno);

					$emailsArr[] = $header->sender[0]->mailbox.'@'.$header->sender[0]->host;
					$emailsArr = array_unique($emailsArr);
					
					$subject = imap_mime_header_decode($val->subject)[0]->text;		
					$dataSubject = explode(' ', $subject);
					$nickArr[] = mb_strtolower($dataSubject[count($dataSubject)-1]);
					
				}
			}
			
			/*
			$slack = new slack();
			foreach($emailsArr as $email){
				$user = $slack->get_members_by_email($email);
				
				if (isset($user[0]->profile->display_name)){
					$nickArr[] = $user[0]->profile->display_name;
				}
			}*/
			$nickArr[] = 'mike';
			$nickArr[] = 'noty';
			$nickArr[] = 'lena';
			
			$users = $slack->get_members($nickArr, true, true);
			$mess = "Ничего не забыл? :wink: \n Я не получил от тебя еженедельный отчет. Очень жду его сегодня!";
			$result = $slack->send($users, $mess);
			echo 'ok';
		}
		imap_close($mbox);
	}
	
	function vacation_report(){
		if ($_SERVER["REMOTE_ADDR"] == '176.9.155.239' || $_SERVER["REMOTE_ADDR"] == '88.99.100.15' || $_SERVER["REMOTE_ADDR"] == '94.130.51.218' || true){
			$vac = isset($_GET['vac']) ? $_GET['vac'] : false;
			
			$slack = new slack();
			$absence = $slack->get_chanel('absence');
			$absence[0]->deleted = 0;
			
			//$absence = $slack->get_members(array('tod'));
				
			
			require_once 'lib/googleSheetClass.php';
			
			$data = new gSheet('https://docs.google.com/spreadsheets/d/1pXVvz-GbvMmMjv5y6XbwOcVqKIuWs316oWEQNndvi8w/edit?usp=sharing');
			
			$sheet_title = 'отпуск '.date('Y');	
			$nicks = $data->read($sheet_title.'!B3:B46');
			$ColNum = get_date_col(date('d.m.Y'), $data);
			$statInfo = $data->read($sheet_title.'!'.getCols($ColNum-1).'3:'.getCols($ColNum).'46');
			
			$Stvac = array();
			$Finvac = array();
			$i = 0;
			foreach($nicks as $nick){
				if (isset($statInfo[$i][0])){ // Если в отпуске
					if ($statInfo[$i][0] != 1){  // Если вчера был не в отпуске
						$uservac = $data->read($sheet_title.'!'.getCols($ColNum).($i+3).':'.getCols($ColNum+20).($i+3));					
						$vacFinTime = strtotime("+".(count($uservac[0]))." days");
						$Stvac[] = array('nick'=>$nick[0], 'end'=> $vacFinTime);
					}
					if ($statInfo[$i][0] == 1 && $statInfo[$i][1] != 1){  // Если вчера был в отпуске, а сегодня уже нет
						$Finvac[] = $nick[0];
					}
				}
				$i++;
			}
			
			
			echo '<pre>'.print_r(getCols($ColNum-1), true).'</pre>';
			echo '<pre>'.print_r($Stvac, true).'</pre>';
			echo '<pre>'.print_r($Finvac, true).'</pre>';
			
			if ($vac == 'start'){
					
				if (count($Stvac) > 0){
					$mess = 'С сегодняшнего дня ';
					$i = 0;
					$wasinlist = array();
					foreach($Stvac as $row){
						if (!in_array($row, $wasinlist)){
							if ($i > 0) $mess .= '; ';
							$mess .= '@'.$row['nick'].' в отпуске, вернется '.date('d.m.Y', $row['end']);
							$i++;
							$wasinlist[] = $row['nick'];
						}
					}
					if (count($Stvac) > 1){
						$mess .= ". Не беспокойте коллег!";
					}else{
						$mess .= ". Не беспокойте коллегу!";
					}
					$result = $slack->send($absence, $mess);
				}
				print_r($Stvac);
			}
			if ($vac == 'end'){
				
				if (count($Finvac) > 0){
					
					$mess = 'У ';
					if (count($Finvac) > 1){
						$nicks = array();
						foreach($Finvac as $row){
							$nicks[] = $row;
						}
						$nicks = array_unique($nicks);
						$mess .= implode(", ", $nicks);
						
					}else{
						$mess .= $Finvac[0];
					}
					$mess .= ' закончился отпуск. Обнимайте, спрашивайте о впечатлениях и ставьте много интересных задач!';
					
					$result = $slack->send($absence, $mess);
				}
				print_r($Finvac);
			}
		}
	}
	
	function vacations(){
		echo 'Устарело';
	}

	function slackactions(){
		if($_SERVER['REQUEST_METHOD'] == 'POST') {
			$data = json_decode($_POST['payload'], true);
		}		
		
		$slack = new slack();
		
		$field = $data['actions'][0]['name'];
		$nick = $data['user']['name'];
		$nickid = $data['user']['id'];
		
		$userData = $slack->get_members_by_id($nickid);
		if (isset($userData[0]->profile->display_name))
			if ($userData[0]->profile->display_name != '')
				$nick = $userData[0]->profile->display_name;
			
		//$users = $slack->get_members(array($nick));	
		//$slack->send($users, $nick, null);
		
		
		if ($nick == 'vio47') $nick = 'vio';
		
		if ($field == 'cancel'){
			echo 'Прости :(';
			return false;
		}
		
		// Это уже не про отпуска, а про ДР_ы
		if (in_array($field, array('present_no', 'present_yes', 'present_psb', 'present_sber'))){
			$variants = array(
				'present_no' => array(
					'answer'	=> 'ок :unamused:',
					'text'		=> 'Не будет сдавать'
				),
				'present_yes' => array(
					'answer'	=> 'отлично! :wink:',
					'text'		=> 'наличными'
				),
				'present_psb' => array(
					'answer'	=> 'отлично! :wink:',
					'text'		=> 'через псб'
				),
				'present_sber' => array(
					'answer'	=> 'отлично! :wink:',
					'text'		=> 'через сбер'
				)
			);
			
			if ($nick == 'vio') $nick = 'vio47';
			if ($nick == 'vertex') $nick = 'ver1ex';
			
			$callback_id = $data['callback_id'];
			$db 	= new db_controller();
			$rows 	= $db->query("select * from `mess` WHERE `id` = $callback_id");
			$row 	= $rows[0];
			
			require_once 'lib/googleSheetClass.php';
			
			$data1 = new gSheet('https://docs.google.com/spreadsheets/d/1fHOMFqPcc6A6M3h4JQeENtzi_IeP5RZ0o4mhZT5NGo4/edit?usp=sharing');
			
			$sheetTitle = $row->sm_title;
			if (!$sheetTitle){
				$d = json_decode($row->condition);
				$sheetTitle = $d->date; 
			}else{
				$sheetTitle.= date('Y');
			}
			$data1->findSheet($sheetTitle);
			
			$nextRow = count($data1->read($sheetTitle.'!A2:C'))+2;
			$data1->write(array(array($nick, date('d.m.Y H:i'), $variants[$field]['text'])), $nextRow, $sheetTitle);	
			
			
			if ($row->exception != ''){
				$row->exception .= ','.$nick;
			}else{
				$row->exception = $nick;
			}
			
			$item			= new stdClass();
			$item->exception= $row->exception;
			$item->id		= $callback_id;
			$db 	= new db_controller();
			$db->update($item, 'mess', 'id');
			
			echo $variants[$field]['answer'];
			
			die();
		}
		
		// Это уже про отчеты
		switch($field){
			case 'overdue':
				
				require_once __DIR__.'/lib/redmine_load.php';
				$host = 'https://rm.emailmatrix.ru/';
				$key = '3cfe87a134c680b9897d9e98edb6ca175098141f';
				
				$client = new Redmine\Client($host, $key);
				
				$my_issues = $client->issue->all([
					'offset' => 0,
					'limit' => 1000,
					'sort' => 'author',
					'status_id' => 'open',
					'due_date'	=> '<='.date('Y-m-d')
				]);
				
				$issuesArr = array();
				$users = array();
				foreach($my_issues['issues'] as $issue){
					$issuesArr[$issue['id']] =  array(
						'id'	=> $issue['id'],
						'subject'=> $issue['subject'],
						'due_date'=> $issue['due_date'],
						'tracker'=> $issue['tracker']['name'],
					);
					
					// Я автор
					$name = $issue['author']['name'];
					if (!isset($users[$name])){
						$users[$name] = array(
							'overdueSum'=> array()
						);
					} 
					// Если дедлайн не сегодня
					if ($issue['due_date'] != date('Y-m-d')){
						$users[$name]['overdueSum'][] = $issue['id'];
					}
					
					// Я исполнитель
					$name = $issue['assigned_to']['name'];
					
					if (!isset($users[$name])){
						$users[$name] = array(
							'overdueSum'=> array()
						);
					}
					
					// Если статус не Resolved(3) и не Feedback (4)
					if ($issue['status']['id'] != 3 && $issue['status']['id'] != 4){
						if ($issue['due_date'] != date('Y-m-d')){
							$users[$name]['overdueSum'][] = $issue['id'];	
						}
					}
				}
				
				if (count($users[$nick]['overdueSum']))
					$users[$nick]['overdueSum'] = array_unique($users[$nick]['overdueSum']);
				
				$text = "Просроченные тикеты: \n";
				
				if (count($users[$nick]['overdueSum'])){
					foreach($users[$nick]['overdueSum'] as $issue){
						$text .= "<https://rm.emailmatrix.ru/issues/".$issuesArr[$issue]['id']."|".$issuesArr[$issue]['id'].' ('.$issuesArr[$issue]['tracker'].') — '.$issuesArr[$issue]['subject']."> (".$issuesArr[$issue]['due_date'].") \n";
					}
				}else{
					$text = 'Уже нет просроченных задач.';
				}	
				$slack = new slack();
				
				if ($nick == 'vio') $nick = 'vio47';
				if ($nick == 'vertex') $nick = 'ver1ex';
				
				$users = $slack->get_members(array($nick));
				$slack->send($users, $text, null);
				
				die();
			break;
			case 'waitingMe':
				require_once __DIR__.'/lib/redmine_load.php';
				$host = 'https://rm.emailmatrix.ru/';
				$key = '3cfe87a134c680b9897d9e98edb6ca175098141f';
				
				$client = new Redmine\Client($host, $key);
				
				$my_issues = $client->issue->all([
					'offset' => 0,
					'limit' => 1000,
					'sort' => 'author',
					'status_id' => 'open',
					'due_date'	=> '<='.date('Y-m-d')
				]);
				
				$issuesArr = array();
				$users = array();
				foreach($my_issues['issues'] as $issue){
					$issuesArr[$issue['id']] =  array(
						'id'	=> $issue['id'],
						'subject'=> $issue['subject'],
						'due_date'=> $issue['due_date'],
					);
					
					
					// Я автор
					$name = $issue['author']['name'];
					if (!isset($users[$name])){
						$users[$name] = array(
							'overdueMe'	=> array(),
							'waitingMe'	=> array()
						);
					} 
					// Если дедлайн не сегодня
					if ($issue['due_date'] != date('Y-m-d')){
						$users[$name]['overdueMe'][] = $issue['id'];
					}
					
				}
				
				// !!!!!тут у Злты ошибка!!!!!
				$user = $users[$nick];
				
				if (count($user['overdueMe']))
				foreach ($user['overdueMe'] as $issueid){
					$cur_issue = $client->issue->show($issueid, array('include' => array('journals')));
					
					$countcomments = count($cur_issue['issue']['journals']);
					if ($countcomments > 0){
						$lastcomment = end($cur_issue['issue']['journals']);
						
						if ($lastcomment['user']['name'] != $nick){
							$users[$nick]['waitingMe'][] = $issueid;
						}
					}
				}
				if (count ($users[$nick]['waitingMe'])){
					$text = "Ожидают твоей проверки: \n";
					foreach($users[$nick]['waitingMe'] as $issue){
						$text .= "<https://rm.emailmatrix.ru/issues/".$issuesArr[$issue]['id']."|".$issuesArr[$issue]['id'].' - '.$issuesArr[$issue]['subject']."> (".$issuesArr[$issue]['due_date'].") \n";
					}
					$slack = new slack();
					
					if ($nick == 'vio') $nick = 'vio47';
					if ($nick == 'vertex') $nick = 'ver1ex';
					
					$users = $slack->get_members(array($nick));
					$slack->send($users, $text, null);
				}
				
				die();
			break;
		}
		
		// Тим лид отчеты
		if (in_array($field, array('leadreport_no', 'leadreport_yes'))){
			$db 	= new db_controller();
			
			if ($field == 'leadreport_no'){
				$weekday = date('w') - 1;
				if ($weekday < 0) $weekday = 6;
				
				$week_begin = strtotime("-".($weekday+7)." day");
				$week_end	= strtotime("-".($weekday+1)." day");
				
				$report = ' @'.$nick.' нечего рассказать о работе своей команды на неделе '.date('d.m.Y', $week_begin).'-'.date('d.m.Y', $week_end)."\n";

				$teamleads = $slack->get_chanel('reports_teamleads');
				$teamleads[0]->deleted = 0;
				$slack->send($teamleads, $report);
				
				$rows 	= $db->query("select * from `dialogs` as a 
				WHERE a.user = '$nick' and a.answer = '' and (TO_DAYS(NOW()) - TO_DAYS(a.date) < 1) 
				order by a.id
				DESC limit 1");
				
				$row = $rows[0];
				
				$item			= new stdClass();
				$item->id		= $row->id;
				$item->answer	= 'no';
				$db->update($item, 'dialogs', 'id');
				
				echo "ну, ок :-\ ";
				return false;
			}else{
				
				$rows 	= $db->query("select * from `dialogs` as a 
				WHERE a.user = '$nick' and a.answer = '' and (TO_DAYS(NOW()) - TO_DAYS(a.date) < 1) 
				order by a.id
				DESC limit 1");
				
				$users = $slack->get_members(array($nick));	
				$slack->send($users, $rows[0]->question, null);
				
				echo 'отлично, жду';
			}			
		}
		
		if (isset($data['actions'][0]['selected_options']))
			$value = $data['actions'][0]['selected_options'][0]['value'];
		else
			$value = 0;
		
		
		
		$user = $slack->get_members(array($nick));
		
		$attachment = null;
		
		/*$data = '';
		if ($field != 'st_day'){
			$data = file_get_contents($nick.'.txt');
			
		}*/
		
		print_r($value);
		
	}
}


function get_date_col($str, $gdoc){
	global $sheet_title;
	
	$strMonths = array('январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь');
	$colsArr = 
	$time	= getsttrDate($str);
	$month	= date('n', $time);
	$day	= date('j', $time);
	
	$monthPos = $gdoc->read($sheet_title.'!C1:NC1');
	
	$st = 1;
	foreach($monthPos[0] as $key => $col){
		if (mb_strtolower($col) == $strMonths[$month-1]){
			$st = $key;
		}
	}
	$colCords = $st+$day+1;
	
	return $colCords;
}

function getCols($index){
	$colsArr = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
	
	$result = base_convert($index, 10, 26);
	
	$resultStr = (string)$result;
	$resultArr = array();
	
	
	$letter1 = base_convert((string)$result[0], 26, 10);
	$str = $colsArr[$letter1-1];
	
	if (isset($result[1])){
		$letter2 = base_convert((string)$result[1], 26, 10);
		$str .= $colsArr[$letter2];
	}
	
	//echo '|-'.$index.'='.$result.'='.$str.' -|';
	
	return $str;
}
function getsttrDate($str){
	$mytime = 0;
	$newStr = '';
	$streArr = explode('.', $str);
	
	if (strlen($streArr[0]) == 1) $streArr[0] = '0'.$streArr[0];
	if (strlen($streArr[1]) == 1) $streArr[1] = '0'.$streArr[1];
	if (strlen($streArr[2]) == 2) $streArr[2] = '20'.$streArr[2];
	
	$newStr = $streArr[2].'-'.$streArr[1].'-'.$streArr[0];
	
	$mytime = strtotime($newStr);
	
	return $mytime;
}