<?php
/* ============================ */
/* (C) 2018 Vladislav Andreev   */
/*      SalesMan Project        */
/*        www.isaler.ru         */
/*          ver. 2018.3         */

/* ============================ */

use Salesman\Client;
use Salesman\Currency;
use Salesman\Deal;

function getTags($identity): array {

	$prefix = realpath( __DIR__.'/../../../' );

	require_once $prefix."/inc/config.php";
	require_once $prefix."/inc/dbconnector.php";
	require_once $prefix."/inc/func.php";

	$db       = $GLOBALS['db'];
	$identity = (!isset( $identity )) ? $GLOBALS['identity'] : $identity;
	$sqlname  = $GLOBALS['sqlname'];

	$fieldsNames = [];

	$result = $db -> query( "select fld_title,fld_tip,fld_name,fld_required from ".$sqlname."field where fld_on = 'yes' and identity = '$identity'" );
	while ($data = $db -> fetch( $result )) {

		$fieldsNames[ $data['fld_tip'] ][ $data['fld_name'] ] = $data['fld_title'];

	}

	//массив тэгов для шаблонов
	$alltags = [
		"client.expressadd"  => [
			"link"       => "Ссылка",
			"client"     => $fieldsNames['client']['title'],
			"category"   => $fieldsNames['client']['idcategory'],
			"clientpath" => $fieldsNames['client']['clientpath'],
			"territory"  => $fieldsNames['client']['territory'],
			"comment"    => "Комментарий",
			"phone"      => "Телефоны",
			"email"      => "Email",
			"relation"   => $fieldsNames['client']['tip_cmr'],
			"user"       => "Ответственный",
			"theme"      => "Тема сообщения"
		],
		"client.add"         => [
			"link"       => "Ссылка",
			"client"     => $fieldsNames['client']['title'],
			"category"   => $fieldsNames['client']['idcategory'],
			"clientpath" => $fieldsNames['client']['clientpath'],
			"territory"  => $fieldsNames['client']['territory'],
			/*"comment" => "Комментарий",*/
			"phone"      => "Телефоны",
			"email"      => "Email",
			"relation"   => $fieldsNames['client']['tip_cmr'],
			"user"       => "Ответственный",
			"autor"      => "Автор изменений",
			"theme"      => "Тема сообщения"
		],
		"client.edit"        => [
			"link"       => "Ссылка",
			"client"     => $fieldsNames['client']['title'],
			"category"   => $fieldsNames['client']['idcategory'],
			"clientpath" => $fieldsNames['client']['clientpath'],
			"territory"  => $fieldsNames['client']['territory'],
			"comment"    => "Комментарий",
			"phone"      => "Телефоны",
			"email"      => "Email",
			"relation"   => $fieldsNames['client']['tip_cmr'],
			"user"       => "Ответственный",
			"autor"      => "Автор изменений",
			"theme"      => "Тема сообщения"
		],
		"client.change.user" => [
			"link"    => "Ссылка",
			"client"  => $fieldsNames['client']['title'],
			"comment" => "Комментарий",
			"autor"   => "Автор изменений",
			"user"    => "Новый ответственный",
			"userold" => "Предыдущий ответственный",
			"theme"   => "Тема сообщения",
		],
		"client.change.recv" => [
			"link"    => "Ссылка",
			"client"  => $fieldsNames['client']['title'],
			"comment" => "Комментарий",
			"theme"   => "Тема сообщения"
		],
		"client.delete"      => [
			"client"  => $fieldsNames['client']['title'],
			"comment" => "Комментарий",
			"user"    => "Ответственный",
			"autor"   => "Автор",
			"theme"   => "Тема сообщения"
		],
		"person.add"         => [
			"link"     => "Ссылка",
			"person"   => $fieldsNames['person']['person'],
			"status"   => $fieldsNames['person']['ptitle'],
			"relation" => $fieldsNames['person']['loyalty'],
			"client"   => $fieldsNames['client']['title'],
			"phone"    => "Телефоны",
			"email"    => "Email",
			"user"     => "Ответственный",
			"theme"    => "Тема сообщения"
		],
		"person.edit"        => [
			"link"     => "Ссылка",
			"person"   => $fieldsNames['person']['person'],
			"status"   => $fieldsNames['person']['ptitle'],
			"relation" => $fieldsNames['person']['loyalty'],
			"client"   => $fieldsNames['client']['title'],
			"phone"    => "Телефоны",
			"email"    => "Email",
			"comment"  => "Комментарий",
			"user"     => "Ответственный",
			"theme"    => "Тема сообщения"
		],
		"person.change.user" => [
			"link"    => "Ссылка",
			"person"  => $fieldsNames['person']['person'],
			"status"  => $fieldsNames['person']['ptitle'],
			"client"  => $fieldsNames['client']['title'],
			"comment" => "Комментарий",
			"autor"   => "Автор изменений",
			"user"    => "Новый ответственный",
			"userold" => "Предыдущий ответственный",
			"theme"   => "Тема сообщения"
		],
		"deal.add"           => [
			"title"      => $fieldsNames['deal']['title'],
			"step"       => $fieldsNames['deal']['idcategory'],
			"datum_plan" => $fieldsNames['deal']['datum_plan'],
			"direction"  => $fieldsNames['deal']['direction'],
			"tip"        => $fieldsNames['deal']['tip'],
			"kol"        => $fieldsNames['deal']['kol'],
			"marga"      => $fieldsNames['deal']['marga'],
			"client"     => $fieldsNames['deal']['client'],
			"user"       => "Ответственный",
			"autor"      => "Автор",
			/*"comment" => "Комментарий",*/
			"theme"      => "Тема сообщения"
		],
		"deal.edit"          => [
			"title"      => $fieldsNames['deal']['title'],
			"step"       => $fieldsNames['deal']['idcategory'],
			"datum_plan" => $fieldsNames['deal']['datum_plan'],
			"direction"  => $fieldsNames['deal']['direction'],
			"tip"        => $fieldsNames['deal']['tip'],
			"kol"        => $fieldsNames['deal']['kol'],
			"marga"      => $fieldsNames['deal']['marga'],
			"client"     => $fieldsNames['deal']['client'],
			"user"       => "Ответственный",
			"autor"      => "Автор",
			"comment"    => "Комментарий",
			"theme"      => "Тема сообщения"
		],
		"deal.change.user"   => [
			"title"      => $fieldsNames['deal']['title'],
			"step"       => "Текущий ".$fieldsNames['deal']['idcategory'],
			"datum_plan" => $fieldsNames['deal']['datum_plan'],
			"direction"  => $fieldsNames['deal']['direction'],
			"tip"        => $fieldsNames['deal']['tip'],
			"kol"        => $fieldsNames['deal']['kol'],
			"marga"      => $fieldsNames['deal']['marga'],
			"client"     => $fieldsNames['deal']['client'],
			"autor"      => "Автор изменений",
			"user"       => "Новый ответственный",
			"userold"    => "Предыдущий ответственный",
			"comment"    => "Комментарий",
			"theme"      => "Тема сообщения"
		],
		"deal.change.step"   => [
			"title"      => $fieldsNames['deal']['title'],
			"step"       => $fieldsNames['deal']['idcategory'],
			"stepOld"    => "Предыдущий ".$fieldsNames['deal']['idcategory'],
			"datum_plan" => $fieldsNames['deal']['datum_plan'],
			"kol"        => $fieldsNames['deal']['kol'],
			"marga"      => $fieldsNames['deal']['marga'],
			"client"     => $fieldsNames['deal']['client'],
			"autor"      => "Автор изменений",
			"user"       => "Ответственный",
			"comment"    => "Комментарий",
			"theme"      => "Тема сообщения"
		],
		"deal.close"         => [
			"title"       => $fieldsNames['deal']['title'],
			"step"        => $fieldsNames['deal']['idcategory'],
			"datum_plan"  => $fieldsNames['deal']['datum_plan'],
			"kol"         => $fieldsNames['deal']['kol'],
			"marga"       => $fieldsNames['deal']['marga'],
			"status"      => "Статус закрытия",
			"datum_close" => $fieldsNames['deal']['datum_close'],
			"kol_fact"    => $fieldsNames['deal']['kol_fact'],
			"client"      => $fieldsNames['deal']['client'],
			"user"        => "Ответственный",
			"autor"       => "Автор",
			"comment"     => "Комментарий",
			"theme"       => "Тема сообщения"
		],
		"invoice.add"        => [
			"link"            => "Ссылка на сделку",
			"invoice"         => "Номер счета",
			"date"            => "Дата счета",
			"date_plan"       => "Ожидаемая дата оплаты",
			"summa"           => "Сумма счета",
			"nalog"           => "Налог по счету",
			"contract"        => "Номер договора",
			"rs"              => "Расчетный счет",
			"tip"             => "Тип счета",
			"client"          => $fieldsNames['client']['title'],
			"deal.title"      => $fieldsNames['deal']['title'],
			"deal.step"       => "Текущий ".$fieldsNames['deal']['idcategory'],
			"deal.datum_plan" => $fieldsNames['deal']['datum_plan'],
			"deal.direction"  => $fieldsNames['deal']['direction'],
			"deal.tip"        => $fieldsNames['deal']['tip'],
			"deal.kol"        => $fieldsNames['deal']['kol'],
			"deal.marga"      => $fieldsNames['deal']['marga'],
			"deal.client"     => $fieldsNames['deal']['client'],
			"deal.user"       => "Ответственный",
			"invoiceStatus"   => "Статусы счетов",
			"theme"           => "Тема сообщения"
		],
		"invoice.edit"       => [
			"link"            => "Ссылка на сделку",
			"invoice"         => "Номер счета",
			"date"            => "Дата счета",
			"date_plan"       => "Ожидаемая дата оплаты",
			"summa"           => "Сумма счета",
			"nalog"           => "Налог по счету",
			"contract"        => "Номер договора",
			"rs"              => "Расчетный счет",
			"tip"             => "Тип счета",
			"client"          => $fieldsNames['client']['title'],
			"deal.title"      => $fieldsNames['deal']['title'],
			"deal.step"       => "Текущий ".$fieldsNames['deal']['idcategory'],
			"deal.datum_plan" => $fieldsNames['deal']['datum_plan'],
			"deal.direction"  => $fieldsNames['deal']['direction'],
			"deal.tip"        => $fieldsNames['deal']['tip'],
			"deal.kol"        => $fieldsNames['deal']['kol'],
			"deal.marga"      => $fieldsNames['deal']['marga'],
			"deal.client"     => $fieldsNames['deal']['client'],
			"deal.user"       => "Ответственный",
			"invoiceStatus"   => "Статусы счетов",
			"theme"           => "Тема сообщения"
		],
		"invoice.doit"       => [
			"link"            => "Ссылка на сделку",
			"invoice"         => "Номер счета",
			"do"              => "Признак оплаты",
			"date_do"         => "Дата оплаты",
			"date"            => "Дата счета",
			"date_plan"       => "Ожидаемая дата оплаты",
			"summa"           => "Сумма оплаты",
			"summaCredit"     => "Сумма счета",
			"summaNew"        => "Сумма созданного платежа",
			"nalog"           => "Налог по счету",
			"contract"        => "Номер договора",
			"rs"              => "Расчетный счет",
			"tip"             => "Тип счета",
			"client"          => $fieldsNames['client']['title'],
			"deal.title"      => $fieldsNames['deal']['title'],
			"deal.step"       => "Текущий ".$fieldsNames['deal']['idcategory'],
			"deal.datum_plan" => $fieldsNames['deal']['datum_plan'],
			"deal.direction"  => $fieldsNames['deal']['direction'],
			"deal.tip"        => $fieldsNames['deal']['tip'],
			"deal.kol"        => $fieldsNames['deal']['kol'],
			"deal.marga"      => $fieldsNames['deal']['marga'],
			"deal.client"     => $fieldsNames['deal']['client'],
			"deal.user"       => "Ответственный",
			"invoiceStatus"   => "Статусы счетов",
			"theme"           => "Тема сообщения"
		],
		"invoice.expressadd" => [
			"link"            => "Ссылка на сделку",
			"invoice"         => "Номер счета",
			"do"              => "Признак оплаты",
			"date_do"         => "Дата оплаты",
			"date"            => "Дата счета",
			"date_plan"       => "Ожидаемая дата оплаты",
			"summa"           => "Сумма счета",
			"summaNew"        => "Сумма созданного платежа",
			"nalog"           => "Налог по счету",
			"contract"        => "Номер договора",
			"rs"              => "Расчетный счет",
			"tip"             => "Тип счета",
			"client"          => $fieldsNames['client']['title'],
			"deal.title"      => $fieldsNames['deal']['title'],
			"deal.step"       => "Текущий ".$fieldsNames['deal']['idcategory'],
			"deal.datum_plan" => $fieldsNames['deal']['datum_plan'],
			"deal.direction"  => $fieldsNames['deal']['direction'],
			"deal.tip"        => $fieldsNames['deal']['tip'],
			"deal.kol"        => $fieldsNames['deal']['kol'],
			"deal.marga"      => $fieldsNames['deal']['marga'],
			"deal.client"     => $fieldsNames['deal']['client'],
			"deal.user"       => "Ответственный",
			"invoiceStatus"   => "Статусы счетов",
			"theme"           => "Тема сообщения"
		],
		"lead.add"           => [
			"link"       => "Ссылка",
			"client"     => $fieldsNames['client']['title'],
			"person"     => $fieldsNames['person']['person'],
			"user"       => "Ответственный",
			"clientpath" => "Канал",
			"comment"    => "Комментарий",
			"theme"      => "Тема сообщения"
		],
		"lead.setuser"       => [
			"link"       => "Ссылка",
			"client"     => $fieldsNames['client']['title'],
			"person"     => $fieldsNames['person']['person'],
			"user"       => "Ответственный",
			"clientpath" => "Канал",
			"comment"    => "Комментарий",
			"theme"      => "Тема сообщения"
		],
		"lead.do"            => [
			"link"        => "Ссылка",
			"client"      => $fieldsNames['client']['title'],
			"person"      => $fieldsNames['person']['person'],
			"deal"        => $fieldsNames['dogovor']['title'],
			"user"        => "Ответственный",
			"clientpath"  => "Канал",
			"status"      => "Статус заявки",
			"statusClose" => "Причина отмены",
			"comment"     => "Комментарий",
			"theme"       => "Тема сообщения"
		],
		"entry.add"          => [
			"link"    => "Ссылка",
			"client"  => $fieldsNames['client']['title'],
			"person"  => $fieldsNames['person']['person'],
			"deal"    => $fieldsNames['dogovor']['title'],
			"user"    => "Ответственный",
			"autor"   => "Автор",
			"status"  => "Статус обращения",
			"comment" => "Комментарий",
			"theme"   => "Тема сообщения"
		],
		"entry.status"       => [
			"link"    => "Ссылка",
			"client"  => $fieldsNames['client']['title'],
			"person"  => $fieldsNames['person']['person'],
			"deal"    => $fieldsNames['dogovor']['title'],
			"user"    => "Ответственный",
			"status"  => "Статус обращения",
			"comment" => "Комментарий",
			"theme"   => "Тема сообщения"
		],
	];

	return $alltags;

}

function URL2slack($string): array {

	$str = preg_match_all( "#<a.*href=[\"'](.*)[\"'].*>(.*)</a>#isU", $string, $matchs, PREG_SET_ORDER );

	return [
		"url"  => $matchs[0][1],
		"text" => $matchs[0][2]
	];

}

function outSender($url, $params) {

	$ch = curl_init();// Устанавливаем соединение
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	//curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
	curl_setopt( $ch, CURLOPT_POST, 1 );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params ) );
	curl_setopt( $ch, CURLOPT_TIMEOUT, 5 );
	curl_setopt( $ch, CURLOPT_URL, $url );

	$result = curl_exec( $ch );

	if ( $result === false ) {
		return curl_error( $ch );
	}
	else {
		return $result;
	}

}

function outSenderJson($url, $params) {

	$string = json_encode( $params );

	$ch = curl_init();// Устанавливаем соединение
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	//curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
	curl_setopt( $ch, CURLOPT_POST, 1 );
	curl_setopt( $ch, CURLOPT_POSTFIELDS, $string );
	curl_setopt( $ch, CURLOPT_TIMEOUT, 5 );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_HTTPHEADER, [
		'Content-Type: application/json',
		'Content-Length: '.strlen( $string ),
	] );

	$result = curl_exec( $ch );

	if ( $result === false ) {
		return curl_error( $ch );
	}
	else {
		return $result;
	}

}

function outSenderViber($url, $params, $token) {

	$string = json_encode( $params );

	$ch = curl_init();// Устанавливаем соединение
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	//curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
	curl_setopt( $ch, CURLOPT_POST, 1 );
	if ( !empty( $params ) ) {
		curl_setopt( $ch, CURLOPT_POSTFIELDS, $string );
	}
	curl_setopt( $ch, CURLOPT_TIMEOUT, 5 );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_HTTPHEADER, [
		'X-Viber-Auth-Token: '.$token
	] );

	$result = curl_exec( $ch );

	if ( $result === false ) {
		return curl_error( $ch );
	}
	else {
		return $result;
	}

}

/**
 * Class CreateTemplateTag
 * Tags - получение тэгов для формирования уведомлений
 */
class CreateTemplateTag {

	public $response = [];

	public function Tags($tip, $params): array {

		$prefix = dirname( __DIR__, 3 );

		require_once $prefix."/inc/config.php";
		require_once $prefix."/inc/dbconnector.php";
		require_once $prefix."/inc/func.php";

		$db       = $GLOBALS['db'];
		$identity = $GLOBALS['identity'];
		$sqlname  = $GLOBALS['sqlname'];

		if ( $params['identity'] > 0 ) {
			$identity = $params['identity'];
		}

		$valuta = $db -> getOne( "select valuta from ".$sqlname."settings WHERE id = '$identity'" );

		$server = $_SERVER['HTTP_HOST'];
		$scheme = $_SERVER['HTTP_SCHEME'] ?? ((isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] != 'off') || 443 == $_SERVER['SERVER_PORT']) ? 'https://' : 'http://';

		$response = $cc = [];

		//формируем ссылку в зависимости от типа события
		switch ($tip) {

			case 'client.expressadd':

				$client = Client ::info( (int)$params['clid'] );

				$response['link']       = '<a href="'.$scheme.$server.'/card.client?clid='.$params['clid'].'">Ссылка</a>';
				$response['url']        = $scheme.$server.'/card.client?clid='.$params['clid'];
				$response['pid']        = (int)$params['pid'];
				$response['clid']       = (int)$params['clid'];
				$response['client']     = $client['title'];
				$response['category']   = $client['category'];
				$response['clientpath'] = $client['clientpath'];
				$response['territory']  = $client['territoryname'];
				$response['comment']    = $client['des'];
				$response['phone']      = $client['phone'];
				$response['email']      = $client['mail_url'];
				$response['relation']   = $client['tip_cmr'];
				$response['user']       = current_user( $params['iduser'], "yes" );
				$response['theme']      = "CRM. Создан новый Клиент";
				$response['color']      = "#e53935";
				$response['icon_emoji'] = ":sandwich:";

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[iduser]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

			break;
			case 'client.add':

				$client = Client ::info( $params['clid'] );

				$response['link']       = '<a href="'.$scheme.$server.'/card.client?clid='.$params['clid'].'">Ссылка</a>';
				$response['url']        = $scheme.$server.'/card.client?clid='.$params['clid'];
				$response['clid']       = (int)$params['clid'];
				$response['client']     = $client['client']['title'];
				$response['category']   = $client['client']['category'];
				$response['clientpath'] = $client['client']['clientpath'];
				$response['territory']  = $client['client']['territoryname'];
				$response['comment']    = $client['client']['des'];
				$response['phone']      = $client['client']['phone'];
				$response['email']      = $client['client']['mail_url'];
				$response['relation']   = $client['client']['tip_cmr'];
				$response['idautor']    = $params['autor'];
				$response['autor']      = current_user( $params['autor'], "yes" );
				$response['user']       = current_user( $params['user'], "yes" );
				$response['iduser']     = $params['newuser'];
				$response['theme']      = "CRM. Создан новый Клиент";
				$response['color']      = "#e53935";

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

			break;
			case 'client.edit':

				$client = Client ::info( $params['clid'] );

				$des = $this -> Changes( 'client', $params['newparam'] );

				$response['link']       = '<a href="'.$scheme.$server.'/card.client?clid='.$params['clid'].'">Ссылка</a>';
				$response['url']        = $scheme.$server.'/card.client?clid='.$params['clid'];
				$response['clid']       = $params['clid'];
				$response['client']     = $client['client']['title'];
				$response['category']   = $client['client']['category'];
				$response['clientpath'] = $client['client']['clientpath'];
				$response['territory']  = $client['client']['territoryname'];
				$response['phone']      = $client['client']['phone'];
				$response['email']      = $client['client']['mail_url'];
				$response['relation']   = $client['client']['tip_cmr'];
				$response['idautor']    = (int)$params['autor'];
				$response['autor']      = current_user( $params['autor'], "yes" );
				$response['user']       = current_user( $params['user'], "yes" );
				$response['iduser']     = (int)$params['user'];

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				if ( !empty( $des ) ) {
					$response['comment'] = yimplode( "\n", $des );
				}

				$response['theme'] = "CRM. Внесены изменения в карточку Клиента.";
				$response['color'] = "#2196F3";

			break;
			case 'client.change.user':

				$response['link']      = '<a href="'.$scheme.$server.'/card.client?clid='.$params['clid'].'">Ссылка</a>';
				$response['url']       = $scheme.$server.'/card.client?clid='.$params['clid'];
				$response['clid']      = (int)$params['clid'];
				$response['client']    = current_client( $params['clid'] );
				$response['idautor']   = (int)$params['autor'];
				$response['autor']     = current_user( $params['autor'], "yes" );
				$response['user']      = current_user( $params['newuser'], "yes" );
				$response['iduser']    = (int)$params['newuser'];
				$response['userold']   = current_user( $params['olduser'], "yes" );
				$response['iduserold'] = (int)$params['olduser'];

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				if ( $params['comment'] != '' ) {
					$response['comment'] = $params['comment'];
				}

				$response['theme'] = "CRM. Изменен ответственный за Клиента";
				$response['color'] = "#2196F3";

			break;
			//todo: откорректировать удаление клиента и передавать данные прямым текстом
			case 'client.delete':

				//$response['link'] = '<a href="'.$scheme.$server.'/card.client.php?clid='.$params['clid'].'">Ссылка</a>';
				$response['clid']   = (int)$params['clid'];
				$response['client'] = $params['client'];
				$response['autor']  = current_user( $params['autor'], "yes" );
				$response['user']   = current_user( $params['user'], "yes" );

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				if ( $params['comment'] != '' ) {
					$response['comment'] = $params['comment'];
				}

				$response['theme'] = "CRM. Удален клиент";

			break;

			case 'person.add':

				$person = get_person_info( $params['pid'], "yes" );

				$response['link']     = '<a href="'.$scheme.$server.'/card.person?pid='.$params['pid'].'">Ссылка</a>';
				$response['url']      = $scheme.$server.'/card.person?pid='.$params['pid'];
				$response['pid']      = (int)$person['pid'];
				$response['person']   = $person['person'];
				$response['status']   = $person['ptitle'];
				$response['relation'] = $person['relation'];
				$response['client']   = current_client( $person['clid'] );
				$response['phone']    = implode( ", ", getPersonWPhone( $params['pid'], false ) );
				$response['email']    = implode( ", ", getPersonWMail( $params['pid'], false ) );
				$response['iduser']   = (int)$person['iduser'];
				$response['user']     = current_user( $person['iduser'], "yes" );
				$response['idautor']  = (int)$params['autor'];
				$response['autor']    = current_user( $params['autor'], "yes" );

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				$response['theme'] = "CRM. Создан новый Контакт";
				$response['color'] = "#e53935";

			break;
			case 'person.edit':

				$person = get_person_info( $params['pid'], "yes" );

				$des = $this -> Changes( 'person', $params['newparam'] );

				$response['link']     = '<a href="'.$scheme.$server.'/card.person?pid='.$params['pid'].'">Ссылка</a>';
				$response['url']      = $scheme.$server.'/card.person?pid='.$params['pid'];
				$response['pid']      = (int)$person['pid'];
				$response['person']   = $person['person'];
				$response['status']   = $person['ptitle'];
				$response['relation'] = $person['relation'];
				$response['client']   = current_client( $person['clid'] );
				$response['phone']    = implode( ", ", getPersonWPhone( $params['pid'], false ) );
				$response['email']    = implode( ", ", getPersonWMail( $params['pid'], false ) );
				$response['iduser']   = $person['iduser'];
				$response['user']     = current_user( $person['iduser'], "yes" );
				$response['idautor']  = $params['autor'];
				$response['autor']    = current_user( $params['autor'], "yes" );

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				if ( !empty( $des ) ) {
					$response['comment'] = yimplode( "\n", $des );
				}

				$response['theme'] = "CRM. Внесены изменения в карточку Контакта";
				$response['color'] = "#2196F3";

			break;
			case 'person.change.user':

				$person = get_person_info( $params['pid'], "yes" );

				$response['link']      = '<a href="'.$scheme.$server.'/card.person?pid='.$params['pid'].'">Ссылка</a>';
				$response['url']       = $scheme.$server.'/card.person?pid='.$params['pid'];
				$response['person']    = $person['person'];
				$response['status']    = $person['ptitle'];
				$response['client']    = current_client( $person['clid'] );
				$response['idautor']   = $params['autor'];
				$response['autor']     = current_user( $params['autor'], "yes" );
				$response['user']      = current_user( $params['newuser'], "yes" );
				$response['iduser']    = $params['newuser'];
				$response['userold']   = current_user( $params['olduser'], "yes" );
				$response['iduserold'] = $params['olduser'];

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				if ( $params['comment'] != '' ) {
					$response['comment'] = $params['comment'];
				}

				$response['theme'] = "CRM. Изменен ответственный за Контакт";
				$response['color'] = "#2196F3";

			break;

			case 'deal.add':

				$response['link'] = '<a href="'.$scheme.$server.'/card.deal?did='.$params['did'].'">Ссылка</a>';
				$response['url']  = $scheme.$server.'/card.deal?did='.$params['did'];

				$deal = Deal ::info( $params['did'] );

				$response['did']        = $params['did'];
				$response['title']      = $deal['title'];
				$response['kol']        = num_format( (float)$deal['summa'] );
				$response['marga']      = num_format( (float)$deal['marga'] );
				$response['clid']       = (int)$deal['client']['clid'];
				$response['client']     = $deal['client']['title'];
				$response['pid']        = (int)$deal['person']['pid'];
				$response['person']     = $deal['person']['person'];
				$response['idstep']     = $deal['step']['stepid'];
				$response['step']       = $deal['step']['steptitle'];
				$response['datum_plan'] = format_date_rus( $deal['datum_plan'] );
				$response['iduser']     = (int)$deal['iduser'];
				$response['user']       = $deal['user'];
				$response['idautor']    = (int)$deal['autor'];
				$response['autor']      = $deal['autorName'];

				$response['tip']       = $deal['tipName'];
				$response['direction'] = $deal['directionName'];

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$deal[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				if ( $params['comment'] != '' ) {
					$response['comment'] = "<br>Комментарий: <b>".$params['comment']."</b><br>";
				}

				$response['theme'] = "CRM. Создана новая Сделка";
				$response['color'] = "#e53935";

			break;
			case 'deal.edit':

				$des  = $this -> Changes( 'deal', $params['newparam'] );
				$deal = Deal ::info( $params['did'] );

				$response['link']       = '<a href="'.$scheme.$server.'/card.deal?did='.$params['did'].'">Ссылка</a>';
				$response['url']        = $scheme.$server.'/card.deal?did='.$params['did'];
				$response['did']        = (int)$params['did'];
				$response['title']      = $deal['title'];
				$response['datum_plan'] = format_date_rus( $deal['datum_plan'] );
				$response['kol']        = num_format( (float)$deal['summa'] );
				$response['marga']      = num_format( (float)$deal['marga'] );
				$response['clid']       = (int)$deal['client']['clid'];
				$response['client']     = $deal['client']['title'];
				$response['pid']        = $deal['person']['pid'];
				$response['person']     = $deal['person']['person'];
				$response['idstep']     = $deal['step']['stepid'];
				$response['step']       = $deal['step']['steptitle'];
				$response['iduser']     = (int)$deal['iduser'];
				$response['user']       = $deal['user'];
				$response['idautor']    = (int)$params['autor'];
				$response['autor']      = current_user( $params['autor'], "yes" );

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				$response['tip']       = $deal['tipName'];
				$response['direction'] = $deal['directionName'];

				if ( $params['comment'] != '' ) {
					$response['comment'] = "Комментарий: <b>".$params['comment']."</b>\n";
				}

				if ( !empty( $des ) ) {
					$response['comment'] .= yimplode( "\n", $des );
				}

				$response['theme'] = "CRM. Изменена Сделка";
				$response['color'] = "#2196F3";

				//проверим доступы к сделке и передадим массив пользователей, которые должны получать уведомления по сделке
				$response['users'] = $db -> getCol( "SELECT iduser FROM ".$sqlname."dostup WHERE did = '$params[did]' and subscribe = 'on' and identity = '$identity'" );

			break;
			case 'deal.change.user':

				$response['link'] = '<a href="'.$scheme.$server.'/card.deal?did='.$params['did'].'">Ссылка</a>';
				$response['url']  = $scheme.$server.'/card.deal?did='.$params['did'];

				$deal = Deal ::info( $params['did'] );

				$response['did']        = (int)$params['did'];
				$response['title']      = $deal['title'];
				$response['datum_plan'] = format_date_rus( $deal['datum_plan'] );
				$response['kol']        = num_format( (float)$deal['kol'] );
				$response['marga']      = num_format( (float)$deal['marga'] );
				$response['clid']       = (int)$deal['client']['clid'];
				$response['client']     = $deal['client']['title'];
				$response['pid']        = (int)$deal['person']['pid'];
				$response['person']     = $deal['person']['person'];
				$response['step']       = $deal['step'];
				$response['stepName']   = $deal['stepName'];
				$response['idautor']    = (int)$params['autor'];
				$response['autor']      = current_user( $params['autor'], "yes" );
				$response['user']       = current_user( $params['newuser'], "yes" );
				$response['iduser']     = (int)$params['newuser'];
				$response['userold']    = current_user( $params['olduser'], "yes" );
				$response['iduserold']  = (int)$params['olduser'];

				$response['tip']       = $deal['tipName'];
				$response['direction'] = $deal['directionName'];

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				if ( $params['comment'] != '' ) {
					$response['comment'] = "Комментарий: <b>".$params['comment']."</b>\n";
				}

				$response['theme'] = "CRM. Вы назначены куратором Сделки";
				$response['color'] = "#2196F3";

				//проверим доступы к сделке и передадим массив пользователей, которые должны получать уведомления по сделке
				$response['users'] = $db -> getCol( "SELECT iduser FROM ".$sqlname."dostup WHERE did = '$params[did]' and subscribe = 'on' and identity = '$identity'" );

			break;
			case 'deal.change.step':

				$response['link'] = '<a href="'.$scheme.$server.'/card.deal?did='.$params['did'].'">Ссылка</a>';
				$response['url']  = $scheme.$server.'/card.deal?did='.$params['did'];

				$deal = Deal ::info( $params['did'] );

				$response['did']        = (int)$params['did'];
				$response['title']      = $deal['title'];
				$response['datum_plan'] = format_date_rus( $deal['datum_plan'] );
				$response['kol']        = num_format( (float)$deal['summa'] );
				$response['marga']      = num_format( (float)$deal['marga'] );
				$response['clid']       = (int)$deal['client']['clid'];
				$response['client']     = $deal['client']['title'];
				$response['pid']        = (int)$deal['person']['pid'];
				$response['person']     = $deal['person']['person'];
				$response['step']       = $params['stepNew'];
				$response['stepOld']    = $params['stepOld'];
				$response['idautor']    = $params['autor'];
				$response['autor']      = current_user( $params['autor'], "yes" );
				$response['user']       = current_user( $deal['iduser'], "yes" );
				$response['iduser']     = (int)$deal['iduser'];

				$response['tip']       = $deal['tipName'];
				$response['direction'] = $deal['directionName'];

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				$response['comment'] = "Текущий этап: ".$response['step']."%\nПредыдущий этап: ".$response['stepOld']."%\n";

				if ( $params['comment'] != '' ) {
					$response['comment'] .= "Комментарий: ".str_replace( "<br>", "\n", $params['comment'] )."\n";
				}

				$response['theme'] = "CRM. Изменен этап сделки Сделки";
				$response['color'] = "#2196F3";

				//проверим доступы к сделке и передадим массив пользователей, которые должны получать уведомления по сделке
				$response['users'] = $db -> getCol( "SELECT iduser FROM ".$sqlname."dostup WHERE did = '$params[did]' and subscribe = 'on' and identity = '$identity'" );

			break;
			case 'deal.close':

				$response['link'] = '<a href="'.$scheme.$server.'/card.deal?did='.$params['did'].'">Ссылка</a>';
				$response['url']  = $scheme.$server.'/card.deal?did='.$params['did'];

				$deal = Deal ::info( $params['did'] );

				$response['did']         = (int)$params['did'];
				$response['title']       = $deal['title'];
				$response['datum_plan']  = format_date_rus( $deal['datum_plan'] );
				$response['datum_close'] = format_date_rus( $deal['close']['date'] );
				$response['kol']         = num_format( (float)$deal['summa'] );
				$response['kol_fact']    = num_format( (float)$deal['close']['summa'] );
				$response['marga']       = num_format( (float)$deal['marga'] );
				$response['clid']        = (int)$deal['client']['clid'];
				$response['client']      = $deal['client']['title'];
				$response['pid']         = (int)$deal['person']['pid'];
				$response['person']      = $deal['person']['person'];
				$response['step']        = $deal['step']['steptitle'];
				$response['status']      = $deal['close']['status'];
				$response['iduser']      = (int)$deal['iduser'];
				$response['user']        = $deal['user'];
				$response['idautor']     = $params['autor'];
				$response['autor']       = current_user( $params['autor'], "yes" );

				$response['tip']       = $deal['tipName'];
				$response['direction'] = $deal['directionName'];

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				$response['comment'] = "Текущий этап: <b>".$response['step']."%</b>\nСтатус закрытия: <b>".$response['status']."</b>\nПлановая сумма: <b>".num_format( $deal['summa'] )."</b>\nФактическая сумма: <b>".num_format( $response['kol_fact'] )." ".$valuta."</b>\nФактическая маржа: <b>".num_format( $deal['marga'] )."</b>\nПлановая дата: <b>".$response['datum_plan']."</b>\nФактическая дата: <b>".$response['datum_close']."</b>\n";

				$response['theme'] = "CRM. Закрыта сделка";

				if ( $response['kol_fact'] <= 0 ) {
					$response['color'] = "#FF5722";
				}
				else {
					$response['color'] = "#4CAF50";
				}

				//формируем статус счетов по сделке
				$totalCredit = $totalCreditSumma = $doCredit = $doCreditSumma = 0;

				$re = $db -> getAll( "SELECT `do`, `summa_credit` FROM ".$sqlname."credit WHERE did = '".$params['did']."' and identity = '$identity'" );
				foreach ( $re as $data ) {

					$totalCredit++;
					$totalCreditSumma += $data['summa_credit'];

					if ( $data['do'] == 'on' ) {
						$doCreditSumma += $data['summa_credit'];
						$doCredit++;
					}

				}

				$persent   = $deal['close']['summa'] > 0 ? num_format( $totalCreditSumma / $deal['close']['summa'] * 100 ) : 0;
				$persentDo = $deal['close']['summa'] > 0 ? num_format( $doCreditSumma / $deal['close']['summa'] * 100 ) : 0;

				$response['comment'] .= "Всего: ".$totalCredit." счетов по сделке на сумму ".num_format( (float)$totalCreditSumma )." ".$valuta.". (".$persent."%). Оплачено ".$doCredit." счетов на сумму ".num_format( (float)$doCreditSumma )." ".$valuta." (".$persentDo."%). \r\n";
				$response['comment'] .= ($doCreditSumma < $response['kol_fact']) ? "Не полная оплата по сделке" : "Полная оплата";

				//проверим доступы к сделке и передадим массив пользователей, которые должны получать уведомления по сделке
				$response['users'] = $db -> getCol( "SELECT iduser FROM ".$sqlname."dostup WHERE did = '$params[did]' and subscribe = 'on' and identity = '$identity'" );

			break;

			case 'invoice.add':

				$invoice = $db -> getRow( "SELECT * FROM ".$sqlname."credit WHERE crid='".$params['id']."' and identity = '$identity'" );

				$invoice['rs'] = $db -> getOne( "SELECT title FROM ".$sqlname."mycomps_recv WHERE id='".$invoice['rs']."' and identity = '$identity'" );

				$response = [
					'invoice'   => $invoice['invoice'],
					'date'      => get_sfdate2( $invoice['datum'] ),
					'date_plan' => format_date_rus( $invoice['datum_credit'] ),
					'summa'     => num_format( (float)$invoice['summa_credit'] ),
					'nalog'     => num_format( (float)$invoice['nds_credit'] ),
					'contract'  => $invoice['invoice_chek'],
					'rs'        => $invoice['rs'],
					'tip'       => $invoice['tip'],
					//'did'       => $invoice['did'],
					//'clid'      => $invoice['clid'],
					'client'    => current_client( $invoice['clid'] ),
				];

				$response['did']     = (int)$invoice['did'];
				$response['clid']    = (int)$invoice['clid'];
				$response['pid']     = (int)$invoice['pid'];
				$response['iduser']  = (int)$invoice['iduser'];
				$response['user']    = current_user( $invoice['iduser'] );
				$response['idautor'] = (int)$params['autor'];
				$response['autor']   = current_user( $params['autor'], "yes" );

				$deal = Deal ::info( $params['did'] );

				$response['deal']['title']      = $deal['title'];
				$response['deal']['kol']        = num_format( (float)$deal['summa'] );
				$response['deal']['marga']      = num_format( (float)$deal['marga'] );
				$response['deal']['clid']       = (int)$deal['client']['clid'];
				$response['deal']['client']     = $deal['client']['title'];
				$response['deal']['idstep']     = $deal['step']['stepid'];
				$response['deal']['step']       = $deal['step']['steptitle'];
				$response['deal']['datum_plan'] = format_date_rus( $deal['datum_plan'] );
				$response['deal']['iduser']     = (int)$deal['iduser'];
				$response['deal']['user']       = $deal['user'];
				$response['deal']['tip']        = $deal['tipName'];
				$response['deal']['direction']  = $deal['directionName'];

				$response['link']  = '<a href="'.$scheme.$server.'/card.deal?did='.$params['did'].'#7">Ссылка</a>';
				$response['url']   = $scheme.$server.'/card.deal?did='.$params['did'].'#7';
				$response['theme'] = "CRM. Выставлен счет";
				$response['color'] = "#e53935";

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[iduser]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				//формируем статус счетов по сделке
				$totalCredit = $totalCreditSumma = $doCredit = $doCreditSumma = 0;

				$re = $db -> getAll( "SELECT `do`, `summa_credit` FROM ".$sqlname."credit WHERE did = '".$params['did']."' and identity = '$identity'" );
				foreach ( $re as $data ) {

					$totalCredit++;
					$totalCreditSumma += $data['summa_credit'];

					if ( $data['do'] == 'on' ) {
						$doCreditSumma += $data['summa_credit'];
						$doCredit++;
					}

				}

				$persent   = $deal['summa'] > 0 ? num_format( $totalCreditSumma / $deal['summa'] * 100 ) : 0;
				$persentDo = $deal['summa'] > 0 ? num_format( $doCreditSumma / $deal['summa'] * 100 ) : 0;

				$response['invoiceStatus'] = "Всего: ".$totalCredit." счетов по сделке на сумму ".num_format( (float)$totalCreditSumma )." ".$valuta.". (".$persent."%). Оплачено ".$doCredit." счетов на сумму ".num_format( (float)$doCreditSumma )." ".$valuta." (".$persentDo."%). \n";
				$response['invoiceStatus'] .= ($doCreditSumma < $deal['summa']) ? "Не полная оплата по сделке" : "Полная оплата";

				//проверим доступы к сделке и передадим массив пользователей, которые должны получать уведомления по сделке
				$response['users'] = $db -> getCol( "SELECT iduser FROM ".$sqlname."dostup WHERE did = '$params[did]' and subscribe = 'on' and identity = '$identity'" );

			break;
			case 'invoice.edit':

				$invoice = $db -> getRow( "SELECT * FROM ".$sqlname."credit WHERE crid='".$params['id']."' and identity = '$identity'" );

				$invoice['rs'] = $db -> getOne( "SELECT title FROM ".$sqlname."mycomps_recv WHERE id='".$invoice['rs']."' and identity = '$identity'" );

				$response = [
					'invoice'   => $invoice['invoice'],
					'date'      => get_sfdate2( $invoice['datum'] ),
					'date_plan' => format_date_rus( $invoice['datum_credit'] ),
					'summa'     => num_format( (float)$invoice['summa_credit'] ),
					'nalog'     => num_format( (float)$invoice['nds_credit'] ),
					'contract'  => $invoice['invoice_chek'],
					'rs'        => $invoice['rs'],
					'tip'       => $invoice['tip'],
					//'clid'      => $invoice['clid'],
					'client'    => current_client( $invoice['clid'] )
				];

				$response['did']     = (int)$invoice['did'];
				$response['clid']    = (int)$invoice['clid'];
				$response['pid']     = (int)$invoice['pid'];
				$response['iduser']  = (int)$invoice['iduser'];
				$response['user']    = current_user( $invoice['iduser'] );
				$response['idautor'] = $params['autor'];
				$response['autor']   = current_user( $params['autor'], "yes" );

				$deal = Deal ::info( $params['did'] );

				$response['deal']['title']      = $deal['title'];
				$response['deal']['kol']        = num_format( (float)$deal['summa'] );
				$response['deal']['marga']      = num_format( (float)$deal['marga'] );
				$response['deal']['clid']       = (int)$deal['client']['clid'];
				$response['deal']['client']     = $deal['client']['title'];
				$response['deal']['idstep']     = $deal['step']['stepid'];
				$response['deal']['step']       = $deal['step']['steptitle'];
				$response['deal']['datum_plan'] = format_date_rus( $deal['datum_plan'] );
				$response['deal']['iduser']     = (int)$deal['iduser'];
				$response['deal']['user']       = $deal['user'];
				$response['deal']['tip']        = $deal['tipName'];
				$response['deal']['direction']  = $deal['directionName'];

				$response['link']  = '<a href="'.$scheme.$server.'/card.deal?did='.$params['did'].'#7">Ссылка</a>';
				$response['url']   = $scheme.$server.'/card.deal?did='.$params['did'].'#7';
				$response['theme'] = "CRM. Изменен счет";
				$response['color'] = "#2196F3";

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				//формируем статус счетов по сделке
				$totalCredit = $totalCreditSumma = $doCredit = $doCreditSumma = 0;

				$re = $db -> getAll( "SELECT `do`, `summa_credit` FROM ".$sqlname."credit WHERE did = '".$params['did']."' and identity = '$identity'" );
				foreach ( $re as $data ) {

					$totalCredit++;
					$totalCreditSumma += $data['summa_credit'];

					if ( $data['do'] == 'on' ) {
						$doCreditSumma += $data['summa_credit'];
						$doCredit++;
					}

				}

				$persent   = $deal['summa'] > 0 ? num_format( $totalCreditSumma / $deal['summa'] * 100 ) : 0;
				$persentDo = $deal['summa'] > 0 ? num_format( $doCreditSumma / $deal['summa'] * 100 ) : 0;

				$response['invoiceStatus'] = "Всего: ".$totalCredit." счетов по сделке на сумму ".num_format( (float)$totalCreditSumma )." ".$valuta.". (".$persent."%). Оплачено ".$doCredit." счетов на сумму ".num_format( (float)$doCreditSumma )." ".$valuta." (".$persentDo."%). \n";
				$response['invoiceStatus'] .= ($doCreditSumma < $deal['summa']) ? "Не полная оплата по сделке" : "Полная оплата";

				//проверим доступы к сделке и передадим массив пользователей, которые должны получать уведомления по сделке
				$response['users'] = $db -> getCol( "SELECT iduser FROM ".$sqlname."dostup WHERE did = '$params[did]' and subscribe = 'on' and identity = '$identity'" );

			break;
			case 'invoice.doit':

				$invoice = $db -> getRow( "SELECT * FROM ".$sqlname."credit WHERE crid='".$params['id']."' and identity = '$identity'" );

				$invoice['rs'] = $db -> getOne( "SELECT title FROM ".$sqlname."mycomps_recv WHERE id='".$invoice['rs']."' and identity = '$identity'" );

				$invoice['do'] = ($invoice['do'] == 'on') ? "Оплачен" : "Не оплачен";

				$response = [
					'invoice'     => $invoice['invoice'],
					'date'        => get_sfdate2( $invoice['datum'] ),
					'date_plan'   => format_date_rus( $invoice['datum_credit'] ),
					'summaCredit' => num_format( (float)$invoice['summa_credit'] ),
					'summa'       => num_format( (float)$params['summa'] ),
					'summaNew'    => num_format( (float)$params['summaNew'] ),
					'nalog'       => $invoice['nds_credit'],
					'do'          => $invoice['do'],
					'date_do'     => format_date_rus( $invoice['invoice_date'] ),
					'contract'    => $invoice['invoice_chek'],
					'rs'          => $invoice['rs'],
					'tip'         => $invoice['tip'],
					//'clid'        => $invoice['clid'],
					'client'      => current_client( $invoice['clid'] )
				];

				$response['did']     = (int)$invoice['did'];
				$response['clid']    = (int)$invoice['clid'];
				$response['pid']     = (int)$invoice['pid'];
				$response['iduser']  = (int)$invoice['iduser'];
				$response['user']    = current_user( $invoice['iduser'] );
				$response['idautor'] = (int)$params['autor'];
				$response['autor']   = current_user( $params['autor'], "yes" );

				$deal = Deal ::info( $params['did'] );

				$response['deal']['title']      = $deal['title'];
				$response['deal']['kol']        = num_format( (float)$deal['summa'] );
				$response['deal']['marga']      = num_format( (float)$deal['marga'] );
				$response['deal']['clid']       = $deal['client']['clid'];
				$response['deal']['client']     = $deal['client']['title'];
				$response['deal']['idstep']     = $deal['step']['stepid'];
				$response['deal']['step']       = $deal['step']['steptitle'];
				$response['deal']['datum_plan'] = format_date_rus( $deal['datum_plan'] );
				$response['deal']['iduser']     = $deal['iduser'];
				$response['deal']['user']       = $deal['user'];
				$response['deal']['tip']        = $deal['tipName'];
				$response['deal']['direction']  = $deal['directionName'];

				$response['link']  = '<a href="'.$scheme.$server.'/card.deal?did='.$params['did'].'#7">Ссылка</a>';
				$response['url']   = $scheme.$server.'/card.deal?did='.$params['did'].'#7';
				$response['theme'] = "CRM. Оплачен счет";
				$response['color'] = "#4CAF50";

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[iduser]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				//формируем статус счетов по сделке
				$totalCredit = $totalCreditSumma = $doCredit = $doCreditSumma = 0;

				$re = $db -> getAll( "SELECT `do`, `summa_credit` FROM ".$sqlname."credit WHERE did = '".$params['did']."' and identity = '$identity'" );
				foreach ( $re as $data ) {

					$totalCredit++;
					$totalCreditSumma += $data['summa_credit'];

					if ( $data['do'] == 'on' ) {
						$doCreditSumma += $data['summa_credit'];
						$doCredit++;
					}

				}

				$persent   = num_format( $totalCreditSumma / $deal['summa'] * 100 );
				$persentDo = num_format( $doCreditSumma / $deal['summa'] * 100 );

				$response['invoiceStatus'] = "Всего: ".$totalCredit." счетов по сделке на сумму ".num_format( (float)$totalCreditSumma )." ".$valuta." (".$persent."%). Оплачено ".$doCredit." счетов на сумму ".num_format( (float)$doCreditSumma )." ".$valuta." (".$persentDo."%). \n";
				$response['invoiceStatus'] .= ($doCreditSumma < $deal['summa']) ? "Не полная оплата по сделке" : "Полная оплата";

				//проверим доступы к сделке и передадим массив пользователей, которые должны получать уведомления по сделке
				$response['users'] = $db -> getCol( "SELECT iduser FROM ".$sqlname."dostup WHERE did = '$params[did]' and subscribe = 'on' and identity = '$identity'" );

			break;
			case 'invoice.expressadd':

				$invoice = $db -> getRow( "SELECT * FROM ".$sqlname."credit WHERE crid='".$params['id']."' and identity = '$identity'" );

				$invoice['rs'] = $db -> getOne( "SELECT title FROM ".$sqlname."mycomps_recv WHERE id='".$invoice['rs']."' and identity = '$identity'" );

				$invoice['do'] = ($invoice['do'] == 'on') ? "Оплачен" : "Не оплачен";

				$response = [
					'invoice'   => $invoice['invoice'],
					'date'      => get_sfdate2( $invoice['datum'] ),
					'date_plan' => format_date_rus( $invoice['datum_credit'] ),
					'summa'     => num_format( (float)$params['summa'] ),
					'summaNew'  => num_format( (float)$params['summaNew'] ),
					'nalog'     => $invoice['nds_credit'],
					'do'        => $invoice['do'],
					'date_do'   => format_date_rus( $invoice['invoice_date'] ),
					'contract'  => $invoice['invoice_chek'],
					'rs'        => $invoice['rs'],
					'tip'       => $invoice['tip'],
					//'clid'      => $invoice['clid'],
					'client'    => current_dogovor( $invoice['clid'] )
				];

				$response['did']     = (int)$invoice['did'];
				$response['clid']    = (int)$invoice['clid'];
				$response['pid']     = (int)$invoice['pid'];
				$response['iduser']  = (int)$invoice['iduser'];
				$response['user']    = current_user( $invoice['iduser'] );
				$response['idautor'] = (int)$params['autor'];
				$response['autor']   = current_user( $params['autor'], "yes" );

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				$deal = Deal ::info( $params['did'] );

				$response['deal']['title']      = $deal['title'];
				$response['deal']['kol']        = num_format( (float)$deal['summa'] );
				$response['deal']['marga']      = num_format( (float)$deal['marga'] );
				$response['deal']['clid']       = (int)$deal['client']['clid'];
				$response['deal']['client']     = $deal['client']['title'];
				$response['deal']['idstep']     = $deal['step']['stepid'];
				$response['deal']['step']       = $deal['step']['steptitle'];
				$response['deal']['datum_plan'] = format_date_rus( $deal['datum_plan'] );
				$response['deal']['iduser']     = (int)$deal['iduser'];
				$response['deal']['user']       = $deal['user'];
				$response['deal']['tip']        = $deal['tipName'];
				$response['deal']['direction']  = $deal['directionName'];

				//формируем статус счетов по сделке
				$totalCredit = $totalCreditSumma = $doCredit = $doCreditSumma = 0;

				$re = $db -> getAll( "SELECT `do`, `summa_credit` FROM ".$sqlname."credit WHERE did = '".$params['did']."' and identity = '$identity'" );
				foreach ( $re as $data ) {

					$totalCredit++;
					$totalCreditSumma += $data['summa_credit'];

					if ( $data['do'] == 'on' ) {
						$doCreditSumma += $data['summa_credit'];
						$doCredit++;
					}

				}

				$persent   = num_format( $totalCreditSumma / $deal['summa'] * 100 );
				$persentDo = num_format( $doCreditSumma / $deal['summa'] * 100 );

				$response['invoiceStatus'] = "Всего: ".$totalCredit." счетов по сделке на сумму ".num_format( (float)$totalCreditSumma )." ".$valuta." (".$persent."%). Оплачено ".$doCredit." счетов на сумму ".num_format( (float)$doCreditSumma )." ".$valuta." (".$persentDo."%). \n";
				$response['invoiceStatus'] .= ($doCreditSumma < $response['deal']['kol']) ? "Не полная оплата по сделке" : "Полная оплата";

				$response['link']  = '<a href="'.$scheme.$server.'/card.deal?did='.$params['did'].'#7">Ссылка</a>';
				$response['url']   = $scheme.$server.'/card.deal?did='.$params['did'].'#7';
				$response['theme'] = "CRM. Внесена оплата по сделке";
				$response['color'] = "#4CAF50";

				//проверим доступы к сделке и передадим массив пользователей, которые должны получать уведомления по сделке
				$response['users'] = $db -> getCol( "SELECT iduser FROM ".$sqlname."dostup WHERE did = '$params[did]' and subscribe = 'on' and identity = '$identity'" );

			break;

			//todo: доработать events, webhook
			case 'lead.add':

				$lead = $db -> getRow( "SELECT * FROM ".$sqlname."leads WHERE id = '".$params['id']."'" );

				$response['iduser'] = (int)$params['iduser'];
				$response['user']   = current_user( $params['iduser'] );
				$response['link']   = '<a href="'.$scheme.$server.'/leads?id='.$params['id'].'">Ссылка</a>';
				$response['url']    = $scheme.$server.'/leads?id='.$params['id'];
				$response['client'] = ((int)$lead['clid'] > 0) ? current_client( $lead['clid'] ) : "--нет в базе--";
				$response['person'] = ((int)$lead['pid'] > 0) ? current_person( $lead['pid'] ) : "--нет в базе--";

				$response['idclientpath'] = $lead['clientpath'];
				$response['clientpath']   = ((int)$lead['clientpath'] > 0) ? current_clientpathbyid( $lead['clientpath'] ) : '--не определен--';

				if ( (int)$response['iduser'] == 0 ) {
					$response['user'] = 'Необходимо назначить';
				}

				$response['comment'] = "
					Дата получения: ".get_sfdate( $lead['datum'] )."
					Имя: ".$lead['title']."
					Email: ".$lead['email']."
					Телефон: ".formatPhone( $lead['phone'] )."
					Страна, Город: ".$lead['country'].", ".$lead['city'];

				if ( (int)$lead['clid'] > 0 ) {
					$response['comment'] .= "Клиент: ".$response['client']."\n";
				}
				if ( (int)$lead['pid'] > 0 ) {
					$response['comment'] .= "Контакт: ".$response['person']."\n";
				}

				$response['theme'] = "CRM. Новый Входящий интерес (Лид). ID = ".$params['id'];
				$response['color'] = "#e53935";

			break;
			case 'lead.setuser':

				$lead = $db -> getRow( "SELECT * FROM ".$sqlname."leads WHERE id = '".$params['id']."'" );

				$response['iduser'] = (int)$lead['iduser'];
				$response['user']   = current_user( $lead['iduser'] );
				$response['link']   = '<a href="'.$scheme.$server.'/leads?id='.$params['id'].'">Ссылка</a>';
				$response['url']    = $scheme.$server.'/leads?id='.$params['id'];
				$response['client'] = ((int)$lead['clid'] > 0) ? current_client( $lead['clid'] ) : "";
				$response['person'] = ((int)$lead['pid'] > 0) ? current_person( $lead['pid'] ) : "";

				$response['idclientpath'] = $lead['clientpath'];
				$response['clientpath']   = ((int)$lead['clientpath'] > 0) ? current_clientpathbyid( $lead['clientpath'] ) : '--не определен--';

				$response['comment'] = "
					Дата получения: ".get_sfdate( $lead['datum'] )."
					Имя: ".$lead['title']."
					Email: ".$lead['email']."
					Телефон: ".formatPhone( $lead['phone'] )."
					Страна, Город: ".$lead['country'].", ".$lead['city'];

				if ( (int)$lead['clid'] > 0 ) {
					$response['comment'] .= "Клиент: ".$response['client']."\n";
				}
				if ( (int)$lead['pid'] > 0 ) {
					$response['comment'] .= "Контакт: ".$response['person']."\n";
				}

				$response['users'][] = $params['coordinator'];

				$response['theme'] = "CRM. Назначен ответственный за обработку Входящего интереса (Лида)";
				$response['color'] = "#2196F3";

			break;
			case 'lead.do':

				$lead = $db -> getRow( "SELECT * FROM ".$sqlname."leads WHERE id = '".$params['id']."' AND identity = '".$identity."'" );

				$response['iduser'] = $lead['iduser'];
				$response['user']   = current_user( $lead['iduser'] );
				$response['link']   = '<a href="'.$scheme.$server.'/leads?id='.$params['id'].'">Ссылка</a>';
				$response['url']    = $scheme.$server.'/leads?id='.$params['id'];
				$response['client'] = ((int)$lead['clid'] > 0) ? current_client( $lead['clid'] ) : "";
				$response['person'] = ((int)$lead['pid'] > 0) ? current_person( $lead['pid'] ) : "";
				$response['deal']   = ((int)$lead['did'] > 0) ? current_dogovor( $lead['did'] ) : "";
				$rez                = (int)$lead['rezult'];
				$status             = (int)$lead['status'];

				$response['idclientpath'] = $lead['clientpath'];
				$response['clientpath']   = ((int)$lead['clientpath'] > 0) ? current_clientpathbyid( $lead['clientpath'] ) : '--не определен--';

				$rezult   = [
					1 => 'Спам',
					2 => 'Дубль',
					3 => 'Другое',
					4 => 'Не целевой'
				];
				$statuses = [
					0 => 'Открыт',
					1 => 'В работе',
					2 => 'Обработан',
					3 => 'Закрыт'
				];

				$response['comment'] = '';

				if ( $rez > 0 ) {
					$response['comment'] .= "Входящий интерес дисквалифицирован с результатом: ".strtr( $rez, $rezult )."\n";
				}
				else {

					$response['comment'] .= "Входящий интерес квалифицирован";
					if ( (int)$lead['did'] > 0 ) {
						$response['comment'] .= ': Создана сделка.';
					}
					$response['comment'] .= "\n";

				}

				$response['statusClose'] = strtr( $rez, $rezult );
				$response['status']      = strtr( $status, $statuses );

				if ( (int)$lead['clid'] > 0 ) {
					$response['comment'] .= "Клиент: ".$response['client']."\n";
				}
				if ( (int)$lead['pid'] > 0 ) {
					$response['comment'] .= "Контакт: ".$response['person']."\n";
				}
				if ( (int)$lead['did'] > 0 ) {
					$response['comment'] .= "Сделка: ".$response['deal']."\n";
				}

				$response['theme'] = "CRM. Обработан входящий интерес (Лид)";
				$response['color'] = "#4CAF50";

				$response['users'][] = $params['coordinator'];

			break;

			case 'entry.add':

				$response           = $db -> getRow( "SELECT * FROM ".$sqlname."entry WHERE ide = '".$params['id']."' AND identity = '".$identity."'" );
				$response['autor']  = current_user( $params['autor'] );
				$response['user']   = current_user( $response['iduser'] );
				$response['link']   = '<a href="'.$scheme.$server.'/entry?id='.$params['id'].'">Ссылка</a>';
				$response['url']    = $scheme.$server.'/entry?id='.$params['id'];
				$response['client'] = ((int)$response['clid'] > 0) ? current_client( $response['clid'] ) : "";
				$response['person'] = ((int)$response['pid'] > 0) ? current_person( $response['pid'] ) : "";
				$response['deal']   = ((int)$response['did'] > 0) ? current_dogovor( $response['did'] ) : "";
				$rez                = (int)$response['status'];

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				$rezult = [
					0 => 'Новое',
					1 => 'Обработано',
					2 => 'Отменено'
				];

				$response['comment'] = '';

				if ( $rez == 0 ) {
					$response['comment'] .= "Статус: создано\n";
				}
				elseif ( $rez == 2 ) {
					$response['comment'] .= "Статус: закрыто с результатом: ".strtr( $rez, $rezult )."\n";
				}
				elseif ( $rez == 1 ) {

					$response['comment'] .= "Статус: обработано";
					if ( (int)$response['did'] > 0 ) {
						$response['comment'] .= ': Создана сделка.';
					}
					$response['comment'] .= "\n";

				}

				$response['status'] = strtr( $rez, $rezult );

				if ( $response['client'] != '' ) {
					$response['comment'] .= 'Клиент: <a href="'.$scheme.$server.'/card.client?clid='.$response['clid'].'">'.$response['client'].'</a>';
					$response['comment'] .= "\n";
				}

				if ( $response['person'] != '' ) {
					$response['comment'] .= 'Контакт: <a href="'.$scheme.$server.'/card.person?pid='.$response['pid'].'">'.$response['person'].'</a>';
					$response['comment'] .= "\n";
				}
				if ( $response['did'] > 0 ) {
					$response['comment'] .= 'Сделка: <a href="'.$scheme.$server.'/card.deal?did='.$response['did'].'">'.$response['deal'].'</a>';
					$response['comment'] .= "\n";
				}

				$response['theme'] = "CRM. Добавлено обращение";
				$response['color'] = "#e53935";

			break;
			case 'entry.status':

				$response           = $db -> getRow( "SELECT * FROM ".$sqlname."entry WHERE ide = '".$params['id']."' AND identity = '".$identity."'" );
				$response['autor']  = current_user( $params['autor'] );
				$response['user']   = current_user( $response['iduser'] );
				$response['link']   = '<a href="'.$scheme.$server.'/entry?id='.$params['id'].'">Ссылка</a>';
				$response['url']    = $scheme.$server.'/entry?id='.$params['id'];
				$response['client'] = ((int)$response['clid'] > 0) ? current_client( $response['clid'] ) : "";
				$response['person'] = ((int)$response['pid'] > 0) ? current_person( $response['pid'] ) : "";
				$response['deal']   = ((int)$response['did'] > 0) ? current_dogovor( $response['did'] ) : "";
				$rez                = (int)$response['status'];

				$response['idboss'] = (int)$db -> getOne( "SELECT mid FROM ".$sqlname."user WHERE iduser = '$params[autor]' and identity = '$identity'" );
				$response['boss']   = current_user( $response['idboss'] );

				$rezult = [
					0 => 'Новое',
					1 => 'Обработано',
					2 => 'Отменено'
				];

				$response['comment'] = '';

				if ( $rez == 2 ) {
					$response['comment'] .= "Обращение закрыто с результатом: ".strtr( $rez, $rezult )."\n";
				}
				elseif ( $rez == 1 ) {

					$response['comment'] .= "Обращение обработано";
					if ( $response['did'] > 0 ) {
						$response['comment'] .= ': Создана сделка.';
					}
					$response['comment'] .= "\n";

				}

				$response['status'] = strtr( $rez, $rezult );

				if ( $response['client'] != '' ) {
					$response['client'] = '<a href="'.$scheme.$server.'/card.client?clid='.$response['clid'].'">'.$response['client'].'</a>';
					//$response['comment'] .= "\n";
				}

				if ( $response['pid'] > 0 ) {
					$response['person'] = '<a href="'.$scheme.$server.'/card.person?pid='.$response['pid'].'">'.$response['person'].'</a>';
					//$response['comment'] .= "\n";
				}

				if ( $response['did'] > 0 ) {
					$response['deal'] = '<a href="'.$scheme.$server.'/card.deal?did='.$response['did'].'">'.$response['deal'].'</a>';
				}

				$response['theme'] = "CRM. Закрыто обращение";
				$response['color'] = "#4CAF50";

			break;
		}

		return $response;

	}

	public function Changes($tip, $params): array {

		$prefix = realpath( __DIR__.'/../../../' );

		require_once $prefix."/inc/config.php";
		require_once $prefix."/inc/dbconnector.php";
		require_once $prefix."/inc/func.php";

		$db       = $GLOBALS['db'];
		$identity = $GLOBALS['identity'];
		$sqlname  = $GLOBALS['sqlname'];

		if ( $params['identity'] > 0 ) {
			$identity = $params['identity'];
		}

		$des = [];

		switch ($tip) {

			case 'client':

				//массив имен полей
				$titles = $db -> getIndCol( 'fld_name', "select fld_title, fld_name from ".$sqlname."field where fld_tip='client' and fld_on='yes' and identity = '$identity' order by fld_order" );

				$titles['type'] = 'Тип записи';

				foreach ( $params as $key => $value ) {

					switch ($key) {

						case 'type':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.strtr( $value, [
									"client"     => "Клиент Юр.лицо",
									"person"     => "Клиент Физ.лицо",
									"partner"    => "Партнер",
									"contractor" => "Поставщик",
									"concurent"  => "Конкурент"
								] );

						break;
						case 'idcategory':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.get_client_category( $value );

						break;
						case 'clientpath':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.current_clientpathbyid( $value );

						break;
						case 'territory':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.current_territory( $value );

						break;
						case 'head_clid':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.current_client( $value );

						break;
						case 'pid':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.current_person( $value );

						break;
						default:

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.$value;

						break;
					}

				}

			break;
			case 'person':

				//массив имен полей
				$titles = $db -> getIndCol( 'fld_name', "select fld_title, fld_name from ".$sqlname."field where fld_tip='person' and fld_on='yes' and identity = '$identity' order by fld_order" );

				foreach ( $params as $key => $value ) {

					switch ($key) {
						case 'clientpath':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.current_clientpathbyid( $value );

						break;
						case 'loyalty':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.current_loyalty( $value );

						break;
						default:

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.$value;

						break;
					}

				}

			break;
			case 'deal':

				//массив имен полей
				$t1 = [
					"clid"        => "Клиент по сделке",
					"payer"       => "Плательщик по сделке",
					"title"       => "Название",
					"content"     => "Описание",
					"tip"         => "Тип сделки",
					"idcategory"  => "Этап сделки",
					"adres"       => "Адрес",
					"datum_plan"  => "Дата план",
					"datum_start" => "Период.Начало",
					"datum_end"   => "Период.Конец",
					"kol"         => "Оборот",
					"marg"        => "Маржа",
					"dog_num"     => "Договор",
					"pid_list"    => "Контакты сделки",
					"coid1"       => "Конкуренты по сделке",
					"idcourse"    => "Курс валюты",
					"idcurrency"  => "Валюта"
				];

				$t2 = $db -> getIndCol( 'fld_name', "select fld_title, fld_name from ".$sqlname."field where fld_tip='dogovor' and fld_name LIKE '%input%' and fld_on='yes' and identity = '$identity' order by fld_order" );

				$titles = array_merge( $t1, $t2 );

				foreach ( $params as $key => $value ) {

					switch ($key) {
						case 'payer':
						case 'clid':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.current_client( $value );

						break;
						case 'datum_plan':
						case 'datum_start':
						case 'datum_end':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.format_date_rus( $value );

						break;
						case 'tip':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.current_dogtype( (int)$value );

						break;
						case 'marg':
						case 'kol':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.num_format( $value );

						break;
						case 'dog_num':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.current_contract( $value );

						break;
						case 'idcategory':

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.current_dogstepname( $value ).'%';

						break;
						case 'idcurrency':

							$currency = (new Currency()) -> currencyInfo( $value );

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.$currency['name'];

						break;
						case 'idcourse':

							$course = (new Currency()) -> courseInfo( $value );

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.$course['course'];

						break;
						case 'pid_list':

							$pids = explode( ";", $value );
							$pn   = [];
							foreach ($pids as $pid) {
								$pn[] = current_person( $pid );
							}
							$pn = implode( ', ', $pn );

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.$pn;

						break;
						case 'coid1':

							$pids = explode( ";", $value );
							$pn   = [];
							foreach ($pids as $pid) {
								$pn[] = current_client( $pid );
							}
							$pn = implode( ', ', $pn );

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.$pn;

						break;
						default:

							$des[] = '<b>'.strtr( $key, $titles ).'</b>: '.$value;

						break;
					}

				}

			break;

		}

		return $des;

	}

}