<?

// Определение количества задач
function count_task($type, $val){
	global $baseT;
	if (file_exists($baseT)) {
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseT);
		$xpath 	= 	new DOMXPath($dom);
		if($type == 'type' 			and $val !='') {
			$tasks	= 	$xpath->query('/tasks/task[@type="'.$val.'"]');
		} elseif($type == 'status' 	and $val !='') {
			$tasks	= 	$xpath->query('/tasks/task[@status="'.$val.'"]');
		} elseif($type == 'user' 	and $val !='') {
			$tasks	= 	$xpath->query('/tasks/task[@deligated="'.$val.'"]');
		} elseif($type == 'supv' 	and $val !='') {
			$tasks	= 	$xpath->query('/tasks/task[supervisor="'.$val.'"]');
		} elseif($type == 'deal' 	and $val !='') {
			$tasks	= 	$xpath->query('/tasks/task[@deal="'.$val.'"]');
		} elseif($type == 'prior' 	and $val !='') {
			$tasks	= 	$xpath->query('/tasks/task[@priority="'.$val.'"]');
		} else {
			$tasks	= 	$xpath->query('/tasks/task');
		}
		return $tasks->length;
	}
}

// Определение количества клиентов
function count_dir_files($val){
	global $aliases_arr;
	$files = count(glob('crmdata/upload/' . $aliases_arr[1] . '_' . $val . '/*.*'));
	return $files;
}

// Определение количества задач / мультивыбор
function multi_count_task($type, $status, $user, $supv, $deal, $prior){
	global $baseT;
	$dom 	= 	new DOMDocument;
	$dom	->	load($baseT);
	$xpath 	= 	new DOMXPath($dom);
	if($type == 'all' or $type == ''){
		$sel_type = '@type';
	} else {
		$sel_type = '@type="'.$type.'"';
	}
	if($status == 'all' or $status == ''){
		$sel_status = '@status';
	} else {
		$sel_status = '@status="'.$status.'"';
	}
	if($user == 'all' or $user == ''){
		$sel_user = '@deligated';
	} else {
		$sel_user = '@deligated="'.$user.'"';
	}
	if($supv == 'all' or $supv == ''){
		$sel_supv = 'supervisor';
	} else {
		$sel_supv = 'supervisor="'.$supv.'"';
	}
	if($deal == 'all'){
		$sel_deal = '@deal';
	} elseif($deal == ''){
		$sel_deal = '@deal=""';
	} else {
		$sel_deal = '@deal="'.$deal.'"';
	}
	if($prior == 'all' or $prior == ''){
		$sel_prior = '@priority';
	} else {
		$sel_prior = '@priority="'.$prior.'"';
	}
	$tasks	= $xpath->query('/tasks/task['.$sel_type.' and  '.$sel_status.' and  '.$sel_user.' and  '.$sel_supv.' and  '.$sel_deal.' and  '.$sel_prior.']');
	return $tasks->length;
}

function count_vacation($type, $val){
	global $baseV;
	if (file_exists($baseV)) {
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseV);
		$xpath 	= 	new DOMXPath($dom);
		if($type == 'type' 			and $val !='') {
			$vacations	= 	$xpath->query('/vacations/vacation[@type="'.$val.'"]');
		} elseif($type == 'status' 	and $val !='') {
			$vacations	= 	$xpath->query('/vacations/vacation[@status="'.$val.'"]');
		} elseif($type == 'user' 	and $val !='') {
			$vacations	= 	$xpath->query('/vacations/vacation[@user="'.$val.'"]');
		} elseif($type == 'agreed' 	and $val !='') {
			$vacations	= 	$xpath->query('/vacations/vacation[@agreed="'.$val.'"]');
		} elseif($type == 'datey' 	and $val !='') {
			$vacations	= 	$xpath->query('/vacations/vacation[datey="'.$val.'"]');
		} else {
			$vacations	= 	$xpath->query('/vacations/vacation');
		}
		return $vacations->length;
	}
}

function multi_count_vacation($type, $status, $user, $agreed, $datey){
	global $baseV;
	$dom 	= 	new DOMDocument;
	$dom	->	load($baseV);
	$xpath 	= 	new DOMXPath($dom);
	if($type == 'all' or $type == ''){
		$sel_type = '@type';
	} else {
		$sel_type = '@type="'.$type.'"';
	}
	if($status == 'all' or $status == ''){
		$sel_status = '@status';
	} else {
		$sel_status = '@status="'.$status.'"';
	}
	if($user == 'all' or $user == ''){
		$sel_user = '@user';
	} else {
		$sel_user = '@user="'.$user.'"';
	}
	if($agreed == 'all' or $agreed == ''){
		$sel_agreed = '@agreed';
	} else {
		$sel_agreed = '@agreed="'.$agreed.'"';
	}
	if($datey == 'all' or $datey == ''){
		$sel_datey = 'datey';
	} else {
		$sel_datey = 'datey="'.$datey.'"';
	}
	$vacations	= $xpath->query('/vacations/vacation['.$sel_type.' and  '.$sel_status.' and  '.$sel_user.' and  '.$sel_agreed.' and  '.$sel_datey.']');
	return $vacations->length;
}

// Определение количества клиентов
function count_client($type, $val){
	global $baseC;
	if (file_exists($baseC)) {
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseC);
		$xpath 	= 	new DOMXPath($dom);
		if($type == 'type' 			and $val !='') {
			$clients	= 	$xpath->query('/clients/client[@type="'.$val.'"]');
		} elseif($type == 'fined' 	and $val !='') {
			$clients	= 	$xpath->query('/clients/client[clientfined="'.$val.'"]');
		} elseif($type == 'prior' 	and $val !='') {
			$clients	= 	$xpath->query('/clients/client[@priority="'.$val.'"]');
		} else {
			$clients	= 	$xpath->query('/clients/client');
		}
		return $clients->length;
	}
}

// Определение количества задач / мультивыбор
function multi_count_client($type, $fined, $prior){
	global $baseC;
	$dom 	= 	new DOMDocument;
	$dom	->	load($baseC);
	$xpath 	= 	new DOMXPath($dom);
	if($type == 'all' or $type == ''){
		$sel_type = '@type';
	} else {
		$sel_type = '@type="'.$type.'"';
	}
	if($fined == 'all' or $fined == ''){
		$sel_fined = 'clientfined';
	} else {
		$sel_fined = 'clientfined="'.$fined.'"';
	}
	if($prior == 'all' or $prior == ''){
		$sel_prior = '@priority';
	} else {
		$sel_prior = '@priority="'.$prior.'"';
	}
	$clients	= $xpath->query('/clients/client['.$sel_type.' and  '.$sel_fined.' and  '.$sel_prior.']');
	return $clients->length;
}

// Определение количества сделок
function count_deal($type, $val){
	global $baseD;
	if (file_exists($baseD)) {
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseD);
		$xpath 	= 	new DOMXPath($dom);
		if($type == 'type' 			and $val !='') {
			$deals	= 	$xpath->query('/deals/deal[@type="'.$val.'"]');
		} elseif($type == 'client' 	and $val !='') {
			$deals	= 	$xpath->query('/deals/deal[@client="'.$val.'"]');
		} elseif($type == 'datey' 	and $val !='') {
			$deals	= 	$xpath->query('/deals/deal[datey="'.$val.'"]');
		} else {
			$deals	= 	$xpath->query('/deals/deal');
		}
		return $deals->length;
	}
}

// Определение количества шаблонов
function count_templs($mod){
	global $baseTMPL;
	if (file_exists($baseTMPL)) {
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseTMPL);
		$xpath 	= 	new DOMXPath($dom);
		$templs	= 	$xpath->query('/templs/templ[mod="'.$mod.'"]');
		return $templs->length;
	}
}

// Определение количества сделок / мультивыбор
function multi_count_deal($type, $client, $year, $priceS, $priceE){
	global $baseD;
	$dom 	= 	new DOMDocument;
	$dom	->	load($baseD);
	$xpath 	= 	new DOMXPath($dom);
	if($type == 'all' or $type == ''){
		$sel_type = '@type';
	} else {
		$sel_type = '@type="'.$type.'"';
	}
	if($client == 'all' or $client == ''){
		$sel_client = '@client';
	} else {
		$sel_client = '@client="'.$client.'"';
	}
	if($year == 'all' or $year == ''){
		$sel_year = 'datey';
	} else {
		$sel_year = 'datey="'.$year.'"';
	}
	if($priceS == 'all' or $priceS == '' or $priceE == 'all' or $priceE == ''){
		$sel_price = ' and price';
	} else {
		if($priceS == 'all' or $priceS == ''){
			$sel_priceS = ' and price>="'.$priceS.'"';
		}
		if($priceE == 'all' or $priceE == ''){
			$sel_priceE = ' and price<"'.$priceE.'"';
		}
		$sel_price = $sel_priceS.$sel_priceE;
	}
	$deals	= $xpath->query('/deals/deal['.$sel_type.' and  '.$sel_client.' and  '.$sel_year.$sel_price.']');
	return $deals->length;
}

// Определение количества платежей
function count_payment($type, $val){
	global $baseP;
	if (file_exists($baseP)) {
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseP);
		$xpath 	= 	new DOMXPath($dom);
		if($type == 'type' 			and $val !='') {
			$payments	= 	$xpath->query('/payments/payment[@type="'.$val.'"]');
		} elseif($type == 'deal' 	and $val !='') {
			$payments	= 	$xpath->query('/payments/payment[@did="'.$val.'"]');
		} elseif($type == 'datey' 	and $val !='') {
			$payments	= 	$xpath->query('/payments/payment[datey="'.$val.'"]');
		} else {
			$payments	= 	$xpath->query('/payments/payment');
		}
		return $payments->length;
	}
}

// Определение количества платежей / мультивыбор
function multi_count_payment($type, $status, $deal, $year){
	global $baseP;
	$dom 	= 	new DOMDocument;
	$dom	->	load($baseP);
	$xpath 	= 	new DOMXPath($dom);
	if($type == 'all' or $type == ''){
		$sel_type = '@type';
	} else {
		$sel_type = '@type="'.$type.'"';
	}
	if($status == 'all' or $status == ''){
		$sel_status = '@status';
	} else {
		$sel_status = '@status="'.$status.'"';
	}
	if($deal == 'all' or $deal == ''){
		$sel_deal = 'deal';
	} else {
		$sel_deal = 'deal="'.$deal.'"';
	}
	if($year == 'all' or $year == ''){
		$sel_year = 'datey';
	} else {
		$sel_year = 'datey="'.$year.'"';
	}
	$payments	= $xpath->query('/payments/payment['.$sel_type.' and  '.$sel_status.' and  '.$sel_deal.' and  '.$sel_year.']');
	return $payments->length;
}

// Определение количества событий
function count_event($type, $val){
	global $baseE;
	if (file_exists($baseE)) {
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseE);
		$xpath 	= 	new DOMXPath($dom);
		if($type == 'user' 			and $val !='') {
			$events	= 	$xpath->query('/events/event[@user="'.$val.'"]');
		} elseif($type == 'client' 	and $val !='') {
			$events	= 	$xpath->query('/events/event[@client="'.$val.'"]');
		} elseif($type == 'repeat' 	and $val !='') {
			$events	= 	$xpath->query('/events/event[repeat="'.$val.'"]');
		} elseif($type == 'prior' 	and $val !='') {
			$events	= 	$xpath->query('/events/event[@priority="'.$val.'"]');
		} else {
			$events	= 	$xpath->query('/events/event');
		}
		return $events->length;
	}
}

// Определение количества событий / мультивыбор
function multi_count_event($user, $client, $repeat, $prior){
	global $baseE;
	$dom 	= 	new DOMDocument;
	$dom	->	load($baseE);
	$xpath 	= 	new DOMXPath($dom);
	if($user == 'all' or $user == ''){
		$sel_user = '@user';
	} else {
		$sel_user = '@user="'.$user.'"';
	}
	if($client == 'all' or $client == ''){
		$sel_client = '@client';
	} else {
		$sel_client = '@client="'.$client.'"';
	}
	if($repeat == 'all' or $repeat == ''){
		$sel_repeat = 'repeat';
	} else {
		$sel_repeat = 'repeat="'.$repeat.'"';
	}
	if($prior == 'all' or $prior == ''){
		$sel_prior = '@priority';
	} else {
		$sel_prior = '@priority="'.$prior.'"';
	}
	$events	= $xpath->query('/events/event['.$sel_user.' and  '.$sel_client.' and  '.$sel_repeat.' and  '.$sel_prior.']');
	return $events->length;
}

// Определение количества пользователей
function count_user($type, $val){
	global $baseU;
	if (file_exists($baseU)) {
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseU);
		$xpath 	= 	new DOMXPath($dom);
		if($type == 'group' and $val !='') {
			$users	= 	$xpath->query('/users/user[@group="'.$val.'"]');
		} else {
			$users	= 	$xpath->query('/users/user');
		}
		return $users->length;
	}
}

// Определение величины Активных сделок / Завершенных сделок / Предложений / Оплаченной суммы
function count_deals_price($d_type, $p_type, $client, $year, $month){
	global $baseD;
	if (file_exists($baseD)) {
		
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseD);
		$xpath 	= 	new DOMXPath($dom);
		
		if($d_type == 'all' or $d_type == ''){
			$sel_d_type = '@type';
		} else {
			$sel_d_type = '@type="'.$d_type.'"';
		}
		
		if($client == 'all' or $client == ''){
			$sel_client = '';
		} else {
			$sel_client = 'and @client="'.$client.'"';
		}
		
		if($year == 'all' or $year == ''){
			$sel_year = '';
		} elseif($year == 'curr') {
			$sel_year = 'and datey="'.date("Y").'"';
		} else {
			$sel_year = 'and datey="'.$year.'"';
		}
		
		if($month == 'all' or $month == ''){
			$sel_month = '';
		} else {
			$sel_month = 'and datem="'.$month.'"';
		}
		$deals	= 	$xpath->query('/deals/deal['.$sel_d_type.' '.$sel_client.' '.$sel_year.' '.$sel_month.']');
		if($deals->length > 0){
			$dealsValue = 0;
			for ($i = 0; $i < $deals->length; $i++) {
				$dealsValue	+= floatval($xpath->query('/deals/deal['.$sel_d_type.' '.$sel_client.' '.$sel_year.' '.$sel_month.']')->item($i)->getElementsByTagName($p_type)->item(0)->nodeValue);
			}
		} else {
			$dealsValue = '0';
		}
		return $dealsValue;
	}
}

// Определение величины прибыли Активных сделок / Завершенных сделок по Метке
function count_deals_paid($subject){
	global $baseD;
	if (file_exists($baseD)) {
		
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseD);
		$xpath 	= 	new DOMXPath($dom);
		
		$deals	= 	$xpath->query('/deals/deal[subject="'.$subject.'"]');
		if($deals->length > 0){
			$dealsValue = 0;
			for ($i = 0; $i < $deals->length; $i++) {
				$dealsValue	+= floatval($xpath->query('/deals/deal[subject="'.$subject.'"]')->item($i)->getElementsByTagName('paid')->item(0)->nodeValue);
			}
		} else {
			$dealsValue = '0';
		}
		return $dealsValue;
	}
}

// Определение величины расходов Активных сделок / Завершенных сделок по Метке
function count_deals_cost($subject){
	global $baseD;
	if (file_exists($baseD)) {
		
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseD);
		$xpath 	= 	new DOMXPath($dom);
		
		$deals	= 	$xpath->query('/deals/deal[subject="'.$subject.'"]');
		if($deals->length > 0){
			$dealsValue = 0;
			for ($i = 0; $i < $deals->length; $i++) {
				$dealsValue	+= floatval($xpath->query('/deals/deal[subject="'.$subject.'"]')->item($i)->getElementsByTagName('costs')->item(0)->nodeValue);
			}
		} else {
			$dealsValue = '0';
		}
		return $dealsValue;
	}
}

// Определение величины Платежей
function count_payments_val($p_type, $year, $month){
	global $baseP;
	if (file_exists($baseP)) {
		
		$dom 	= 	new DOMDocument;
		$dom	->	load($baseP);
		$xpath 	= 	new DOMXPath($dom);
		
		if($p_type == 'all' or $p_type == ''){
			$sel_p_type = '@type';
		} else {
			$sel_p_type = '@type="'.$p_type.'"';
		}
		
		if($year == 'all' or $year == ''){
			$sel_year = '';
		} elseif($year == 'curr') {
			$sel_year = 'and datey="'.date("Y").'"';
		} else {
			$sel_year = 'and datey="'.$year.'"';
		}
		
		if($month == 'all' or $month == ''){
			$sel_month = '';
		} else {
			$sel_month = 'and datem="'.$month.'"';
		}
		$payments	= 	$xpath->query('/payments/payment[@status="+" and '.$sel_p_type.' '.$sel_year.' '.$sel_month.']');
		if($payments->length > 0){
			$paymentsValue = 0;
			for ($i = 0; $i < $payments->length; $i++) {
				$paymentsValue	+= floatval($xpath->query('/payments/payment[@status="+" and '.$sel_p_type.' '.$sel_year.' '.$sel_month.']')->item($i)->getElementsByTagName('val')->item(0)->nodeValue);
			}
		} else {
			$paymentsValue = '0';
		}
		return $paymentsValue;
	}
}

// Определение суммы сделок
function count_deals_price_summ($d_type, $p_type, $client, $year, $month){
	if($d_type != ''){
		$deal 	= count_deals_price($d_type, $p_type, $client, $year, $month);
		$count 	= $deal;
	} else {
		$deal_a = count_deals_price('deal-a', $p_type, $client, $year, $month);
		$deal_c = count_deals_price('deal-c', $p_type, $client, $year, $month);
		$count 	= $deal_a + $deal_c;
	}
	return $count;
}

// Определение величины прибыли
function count_deals_profit_summ($d_type, $client, $year, $month){
	$price = count_deals_price_summ($d_type, 'paid', $client, $year, $month);
	$costs = count_deals_price_summ($d_type, 'costs', $client, $year, $month);
	$count = $price - $costs;
	return $count;
}

// Определение величины долга
function count_deals_debt_summ($d_type, $client, $year, $month){
	$price 	= count_deals_price_summ($d_type, 'price', $client, $year, $month);
	$paid 	= count_deals_price_summ($d_type, 'paid', $client, $year, $month);
	$diff 	= $price - $paid;
	if($d_type != 'offer'){
		if($diff < 0){
			$count 	= '0';
		} else {
			$count 	= $diff;
		}
	} else {
		$count = 0;
	}
	return 	$count;
}

// Пути к XML фалам системы
if (file_exists($baseT)) { $xmltask 	= simplexml_load_file($baseT); }
if (file_exists($baseU)) { $xmluser 	= simplexml_load_file($baseU); }
if (file_exists($baseC)) { $xmlclient  	= simplexml_load_file($baseC); }
if (file_exists($baseD)) { $xmldeal 	= simplexml_load_file($baseD); }
if (file_exists($baseQ)) { $xmlqchat 	= simplexml_load_file($baseQ); }
if (file_exists($baseE)) { $xmlevent 	= simplexml_load_file($baseE); }
if (file_exists($baseLT)){ $xmlletters 	= simplexml_load_file($baseLT); }
if (file_exists($baseV)) { $xmlvacations= simplexml_load_file($baseV); }
if (file_exists($baseP)) { $xmlpayment	= simplexml_load_file($baseP); }

// Счетчики по задачам
if (file_exists($baseT)) { 

	$countAllTask 					= count($xmltask->xpath('/tasks/task'));
	$countTaskStatusDone 			= count($xmltask->xpath('/tasks/task[@status="done"]'));
	$countIndexTaskStatusInWork 	= count($xmltask->xpath('/tasks/task[@status="inwork"]'));
	$countTaskPriorityHigh 			= count($xmltask->xpath('/tasks/task[@status="inwork" and @priority="high"]'));
	$countTaskPriorityMedium 		= count($xmltask->xpath('/tasks/task[@status="inwork" and @priority="medium"]'));
	$countTaskPriorityLow 			= count($xmltask->xpath('/tasks/task[@status="inwork" and @priority="low"]'));
	$countTaskPriorityNone 			= count($xmltask->xpath('/tasks/task[@status="inwork" and @priority="none"]'));
	$countTaskDonePriorityHigh 		= count($xmltask->xpath('/tasks/task[@status="done" and @priority="high"]'));
	$countTaskDonePriorityMedium 	= count($xmltask->xpath('/tasks/task[@status="done" and @priority="medium"]'));
	$countTaskDonePriorityLow 		= count($xmltask->xpath('/tasks/task[@status="done" and @priority="low"]'));
	$countTaskDonePriorityNone 		= count($xmltask->xpath('/tasks/task[@status="done" and @priority="none"]'));
	
	$countNoLogin 	= count($xmltask->xpath('/tasks/task[@status="inwork" and @deligated=""]'));
	
	$doc = new DOMDocument;
	$doc->load($baseT);
	$xpath = new DOMXPath($doc);
	$tasks = $xpath->query('/tasks/task[@status="done"]');
	$countTaskTimeInWork		= 0;
	for ($i = 0; $i < $tasks->length; $i++) {
		$countTaskTimeInWork 		+= floatval($xpath->query('/tasks/task[@status="done"]')->item($i)->getElementsByTagName("timeinwork")->item(0)->nodeValue);
	}
}

// Счетчики по пользователям
if (file_exists($baseU)) { 
	$countGroupAdmin 				= count($xmluser->xpath('/users/user[@group="admin"]'));
	$countGroupManager 				= count($xmluser->xpath('/users/user[@group="manager"]'));
	$countGroupUser 				= count($xmluser->xpath('/users/user[@group="user"]'));
	$countGroupGuest 				= count($xmluser->xpath('/users/user[@group="guest"]'));
	$countIndexUser 				= count($xmluser->xpath('/users/user'));
}

// Счетчики по событиям
if (file_exists($baseE)) { 
	$countIndexEvents 				= count($xmlevent->xpath('/events/event'));
	$countEventsPriorityHigh 		= count($xmlevent->xpath('/events/event[@priority="high"]'));
	$countEventsPriorityMedium 		= count($xmlevent->xpath('/events/event[@priority="medium"]'));
	$countEventsPriorityLow 		= count($xmlevent->xpath('/events/event[@priority="low"]'));
	$countEventsPriorityNone 		= count($xmlevent->xpath('/events/event[@priority="none"]'));
}

// Счетчики по клиентам
if (file_exists($baseC)) {
	$countClientPriorityHigh 		= count($xmlclient->xpath('/clients/client[@priority="high"]'));
	$countClientPriorityMedium 		= count($xmlclient->xpath('/clients/client[@priority="medium"]'));
	$countClientPriorityLow 		= count($xmlclient->xpath('/clients/client[@priority="low"]'));
	$countClientPriorityNone 		= count($xmlclient->xpath('/clients/client[@priority="none"]'));
	$countClientTypeUl 				= count($xmlclient->xpath('/clients/client[@type="UL"]'));
	$countClientTypeFl 				= count($xmlclient->xpath('/clients/client[@type="FL"]'));
	$countIndexClient 				= count($xmlclient->xpath('/clients/client'));
}

// Счетчики по сделкам
if (file_exists($baseD)) {
	$countIndexAllDeal 				= count($xmldeal->xpath('/deals/deal'));
	$countIndexDealA 				= count($xmldeal->xpath('/deals/deal[@type="deal-a"]'));
	$countIndexDealC 				= count($xmldeal->xpath('/deals/deal[@type="deal-c"]'));
	$countIndexOffer 				= count($xmldeal->xpath('/deals/deal[@type="offer"]'));
	
	$doc = new DOMDocument;
	$doc->load($baseD);
	$xpath = new DOMXPath($doc);
	$deals = $xpath->query('/deals/deal[@type="deal-a" or @type="deal-c"]');
	$countAllDealsDate	= 0;
	$countDealPrice		= 0; 
	$countDealCosts		= 0;
	for ($i = 0; $i < $deals->length; $i++) {
		$allDealsDateS 	= $xpath->query('/deals/deal[@type="deal-a" or @type="deal-c"]')->item($i)->getElementsByTagName("dates")->item(0)->nodeValue;
		$allDealsDateE 	= $xpath->query('/deals/deal[@type="deal-a" or @type="deal-c"]')->item($i)->getElementsByTagName("datee")->item(0)->nodeValue;
		if ($allDealsDateS == '' or $allDealsDateE == '') {
			$allDealsDateSformat	= DateTime::createFromFormat( 'Y-m-d', date("Y-m-d") );
			$allDealsDateEformat	= DateTime::createFromFormat( 'Y-m-d', date("Y-m-d") );
		} else {
			$allDealsDateSformat	= DateTime::createFromFormat( 'Y-m-d', $allDealsDateS );
			$allDealsDateEformat	= DateTime::createFromFormat( 'Y-m-d', $allDealsDateE );
		}

		$countAllDealsDate			+= floatval($allDealsDateEformat->diff( $allDealsDateSformat )->format( '%a' ));
		$countDealPrice 			+= floatval($xpath->query('/deals/deal[@type="deal-a" or @type="deal-c"]')->item($i)->getElementsByTagName("price")->item(0)->nodeValue);
		$countDealCosts 			+= floatval($xpath->query('/deals/deal[@type="deal-a" or @type="deal-c"]')->item($i)->getElementsByTagName("costs")->item(0)->nodeValue);
		$countDealProfit 			= $countDealPrice - $countDealCosts;
		
		$countAllDealPrice 	= $countDealPrice;
		$countAllDealCosts 	= $countDealCosts;
		$countAllDealProfit = $countDealProfit;
	}
}

if (file_exists($baseD)) {
	if( isset( $_POST["checkYear"] ) ) {
		$selectYear 	= $_POST["selectYear"]; // порядок выбранного года
		$currentYear 	= date("Y",strtotime(".$selectYear.")); // год ввиде числа
	} else {
		$currentYear 	= date("Y"); // год ввиде числа
	}
	$doy = new DOMDocument;
	$doy->load($baseD);
	$xpathy = new DOMXPath($doy);
	$dealsyear 		= $xpathy->query('/deals/deal[@type="deal-c" and datey="'.$currentYear.'"]');
	$alldealsyear 	= count($xmldeal->xpath('/deals/deal[@type="deal-c" and datey="'.$currentYear.'" or @type="deal-a" and datey="'.$currentYear.'"]'));
	$countAllDealsDateY	= 0;
	$countDealPriceY	= 0;
	for ($i = 0; $i < $dealsyear->length; $i++) {
		$allDealsDateS 	= $xpath->query('/deals/deal[@type="deal-c" and datey="'.$currentYear.'"]')->item($i)->getElementsByTagName("dates")->item(0)->nodeValue;
		$allDealsDateE 	= $xpath->query('/deals/deal[@type="deal-c" and datey="'.$currentYear.'"]')->item($i)->getElementsByTagName("datee")->item(0)->nodeValue;
		if ($allDealsDateS == '' or $allDealsDateE == '') {
			$allDealsDateSformat	= DateTime::createFromFormat( 'Y-m-d', date("Y-m-d") );
			$allDealsDateEformat	= DateTime::createFromFormat( 'Y-m-d', date("Y-m-d") );
		} else {
			$allDealsDateSformat	= DateTime::createFromFormat( 'Y-m-d', $allDealsDateS );
			$allDealsDateEformat	= DateTime::createFromFormat( 'Y-m-d', $allDealsDateE );
		}
		$countAllDealsDateY			+= floatval($allDealsDateEformat->diff( $allDealsDateSformat )->format( '%a' ));
		$countDealPriceY 			+= floatval($xpath->query('/deals/deal[@type="deal-c" and datey="'.$currentYear.'"]')->item($i)->getElementsByTagName("price")->item(0)->nodeValue);
	}
	if ( $deals->length > 0 ) {
		$countDayPrice = round($countDealPriceY / ($countAllDealsDateY + 1), -1);
	} else {
		$countDayPrice = '0';
	}
}


// Сводная статистика системы

# Время выполнения задач
if($countTaskStatusDone > 0){ $statTaskTime = round($countTaskTimeInWork / $countTaskStatusDone, 0) . ' дней'; } else {$statTaskTime = '0 дней';}

#сумма сделок за текущий год
if( isset( $_POST["checkYear"] ) ) {
	$selectYear 	= $_POST["selectYear"]; // порядок выбранного года
	$currentYear 	= date("Y",strtotime(".$selectYear.")); // год ввиде числа
} else {
	$currentYear 	= date("Y"); // год ввиде числа
}
$dox = new DOMDocument;
$dox->load($baseD);
$xpath = new DOMXPath($dox);
$dealsPrY = $xpath->query('/deals/deal[@type="deal-a" and datey="'.$currentYear.'" or @type="deal-c" and datey="'.$currentYear.'"]');
$countDealYear	= count($xmldeal->xpath('/deals/deal[@type="deal-a" and datey="'.$currentYear.'" or @type="deal-c" and datey="'.$currentYear.'"]'));
$countDealM 	= 0;
$countDealMC 	= 0;
for ($i = 0; $i < $dealsPrY->length; $i++) {
	if($countDealYear 	> 0){
		$countDealM += floatval($xpath->query('/deals/deal[@type="deal-a" and datey="'.$currentYear.'" or @type="deal-c" and datey="'.$currentYear.'"]')->item($i)->getElementsByTagName("price")->item(0)->nodeValue);
		$countDealMC += floatval($xpath->query('/deals/deal[@type="deal-a" and datey="'.$currentYear.'" or @type="deal-c" and datey="'.$currentYear.'"]')->item($i)->getElementsByTagName("costs")->item(0)->nodeValue);
		$countAllDealNowYear = $countDealM;
		$countAllDealCostsNowYear = $countDealMC;
	}else{
		$countAllDealNowYear = '0';
	}
}

/* Подсчет количества сделок по годам */
function deals_year_count($type, $year){
	global $xmldeal;
	$count = 0;
	if ($type == 'all'){
		$count = count($xmldeal->xpath('/deals/deal[@type="deal-a" and datey="'.date("Y",strtotime("- $year years")).'" or @type="deal-c" and datey="'.date("Y",strtotime("- $year years")).'" or @type="offer" and datey="'.date("Y",strtotime("- $year years")).'"]'));
	} elseif ($type == 'ac'){
		$count = count($xmldeal->xpath('/deals/deal[@type="deal-a" and datey="'.date("Y",strtotime("- $year years")).'" or @type="deal-c" and datey="'.date("Y",strtotime("- $year years")).'"]'));
	} elseif ($type == 'a'){
		$count = count($xmldeal->xpath('/deals/deal[@type="deal-a" and datey="'.date("Y",strtotime("- $year years")).'"]'));
	} elseif ($type == 'c'){
		$count = count($xmldeal->xpath('/deals/deal[@type="deal-c" and datey="'.date("Y",strtotime("- $year years")).'"]'));
	} elseif ($type == 'o'){
		$count = count($xmldeal->xpath('/deals/deal[@type="offer" and datey="'.date("Y",strtotime("- $year years")).'"]'));
	}
	return $count;
}

/* Подсчет суммы сделок/расходов по годам */
function deals_year_sum($type, $deal, $year){
	global $xmldeal, $baseD;
	$dom 	= new DOMDocument;
	$dom	->load($baseD);
	$xpath 	= new DOMXPath($dom);
	if ($type == 'all'){
		$xml_req = '/deals/deal[@type="deal-a" and datey="'.date("Y",strtotime("- $year years")).'" or @type="deal-c" and datey="'.date("Y",strtotime("- $year years")).'" or @type="offer" and datey="'.date("Y",strtotime("- $year years")).'"]';
	} elseif ($type == 'ac'){
		$xml_req = '/deals/deal[@type="deal-a" and datey="'.date("Y",strtotime("- $year years")).'" or @type="deal-c" and datey="'.date("Y",strtotime("- $year years")).'"]';
	} elseif ($type == 'a'){
		$xml_req = '/deals/deal[@type="deal-a" and datey="'.date("Y",strtotime("- $year years")).'"]';
	} elseif ($type == 'c'){
		$xml_req = '/deals/deal[@type="deal-c" and datey="'.date("Y",strtotime("- $year years")).'"]';
	} elseif ($type == 'o'){
		$xml_req = '/deals/deal[@type="offer" and datey="'.date("Y",strtotime("- $year years")).'"]';
	}
	if ($deal == 'deal'){
		$xml_deal = 'price';
	} elseif ($deal == 'cost'){
		$xml_deal = 'costs';
	} elseif ($deal == 'paid'){
		$xml_deal = 'paid';
	}
	$sum = '0';
	$base = $xpath->query($xml_req);
	for ($i = 0; $i < $base->length; $i++) {
		if(deals_year_count($type, $year) > 0){
			$sum += floatval($xpath->query($xml_req)->item($i)->getElementsByTagName($xml_deal)->item(0)->nodeValue);
		} else { 
			$sum = '0';
		}
	}
	return $sum;
}

function deals_year_average($type, $year){
	$deals_sum 	= deals_year_sum('ac', $type, $year);
	$deals_count = deals_year_count('ac',  $year);
	if($deals_count > 0){
		if($year == 0){
			return round($deals_sum/date("n"),0);
		} else {
			return round($deals_sum/12,0);
		}
	} else {
		return 0;
	}
}

function deals_year_average2($type, $year){
	$deals_sum 	= deals_year_sum('ac', $type, $year);
	$deals_count = deals_year_count('ac',  $year);
	if($deals_count > 0){
		return round($deals_sum / $deals_count,0);
	} else {
		return 0;
	}
}


/* Подсчет суммы сделок/расходов по сделкам */
function deals_sum($id, $type){
	global $baseD;
	$dom 	= new DOMDocument;
	$dom	->load($baseD);
	$xpath 	= new DOMXPath($dom);
	
	$sum 	= 	$xpath->query('/deals/deal[@id="'.$id.'"]')->item(0)->getElementsByTagName($type)->item(0)->nodeValue;
	
	if($sum != ''){
		$val = $sum;
	} else { 
		$val = '0';
	}
	return $val;
}

/* Подсчет сумы прибыли по годам */
function deals_year_diff($type, $year){
	$diff = '0';
	$diff = deals_year_sum($type, 'paid', $year) - deals_year_sum($type, 'cost', $year);
	return $diff;
}

/* Подсчет сумы расходов по годам */
function profit_year($profit, $type, $year){
	$persent = '0';
	if($profit == 'deal'){
		if(deals_year_sum($type, 'deal', $year) != '0'){
			$persent = round((deals_year_sum($type, 'deal', $year) - deals_year_sum($type, 'cost', $year)) / deals_year_sum($type, 'deal', $year) * 100 , 1);
		} else {
			$persent = '0';
		}
	} elseif($profit == 'cost'){
		if(deals_year_sum($type, 'deal', $year) != '0'){
			$persent = round(deals_year_sum($type, 'cost', $year) / deals_year_sum($type, 'deal', $year) * 100 , 1);
		} else {
			$persent = '0';
		}
	}
	return $persent;
}

# Средняя цена сделки
if(($countIndexDealA + $countIndexDealC) > 0){
	$statDealPrice = round($countDealPrice / ($countIndexDealA + $countIndexDealC), -1);
} else {
	$statDealPrice = '0';
}

/* Подсчет количества клиентов по годам */
function clients_year_count($type, $year){
	global $xmlclient;
	$count 	= 0;
	if ($type == 'all'){
		$count = count($xmlclient->xpath('/clients/client[contains(translate(clientstart, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz"),"'.date("Y",strtotime("- $year years")).'-")]'));
	} elseif ($type == 'UL'){
		$count = count($xmlclient->xpath('/clients/client[@type="UL" and contains(translate(clientstart, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz"),"'.date("Y",strtotime("- $year years")).'-")]'));
	} elseif ($type == 'FL'){
		$count = count($xmlclient->xpath('/clients/client[@type="FL" and contains(translate(clientstart, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz"),"'.date("Y",strtotime("- $year years")).'-")]'));
	}
	return $count;
}

/* Вывод динамики количества клиентов */
function clients_year_sum($type){
	$array = array();
	for($i=100; $i>-1; $i--){
		$array['item'.$i] = clients_year_count($type, $i);
	}
	$setItems 	= array();
	$previous 	= 0;
	$count_all 	= count($array);
	foreach($array as $key => $val){ 
		$setItems['item'.$i] = $val+$previous;
		$previous += $val; $i++;
	};
	$limit = 0;
	foreach($setItems as $key=>$value) if($limit++ > $count_all-6){
		echo $value . ', ';
	}
}

/* Подсчет количества задач по годам */
function tasks_year_count($year){
	global $xmltask;
	$count = 0;
	$count = count($xmltask->xpath('/tasks/task[@status="done" and contains(translate(datestart, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz"),"'.date("Y",strtotime("- $year years")).'-")]'));
	return $count;
}

/* Подсчет суммы времени выполнения задач по годам */
function tasks_time_year_sum($year){
	global $xmltask, $baseT;
	$dom 	= new DOMDocument;
	$dom	->load($baseT);
	$xpath 	= new DOMXPath($dom);
	$xml_req = '/tasks/task[@status="done" and contains(translate(datestart, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz"),"'.date("Y",strtotime("- $year years")).'-")]';
	$sum = '0';
	$base = $xpath->query($xml_req);
	for ($i = 0; $i < $base->length; $i++) {
		if(tasks_year_count($year) > 0){
			$sum += floatval($xpath->query($xml_req)->item($i)->getElementsByTagName("timeinwork")->item(0)->nodeValue);
		} else { 
			$sum = '0';
		}
	}
	return round($sum,1);
}

/* Подсчет суммы времени выполнения задач по годам */
function tasks_time_year_diff($year){
	$diff = '0';
	if(tasks_year_count($year) > 0){
		$diff = tasks_time_year_sum($year) / tasks_year_count($year);
	} else { 
		$diff = '0';
	}
	return round($diff,1);
}

/* Подсчет количества писем пользователя */
function count_letters($type){
	global $xmlletters;
	if($type == 'inbox'){
		return count($xmlletters->xpath('/letters/letter[toid="'.$_SESSION["userid"].'"]'));
	} elseif($type == 'outbox') {
		return count($xmlletters->xpath('/letters/letter[fromid="'.$_SESSION["userid"].'"]'));
	} elseif($type == 'important') {
		return count($xmlletters->xpath('/letters/letter[priority="high" and toid="'.$_SESSION["userid"].'"]'));
	} elseif($type == 'notread') {
		return count($xmlletters->xpath('/letters/letter[@status="notread" and toid="'.$_SESSION["userid"].'"]'));
	} elseif($type == 'all') {
		return count($xmlletters->xpath('/letters/letter[toid="'.$_SESSION["userid"].'" or fromid="'.$_SESSION["userid"].'"]'));
	} else {
		return false;
	}
}

#Диаграмма стоимости сделок
$statAllDealPrice500001 	= count($xmldeal->xpath('/deals/deal[@type="deal-a" and price>="500000" or @type="deal-c" and price>="500000"]'));
$statAllDealPrice500000 	= count($xmldeal->xpath('/deals/deal[@type="deal-a" and price<"500000" and price>="250000" or @type="deal-c" and price<"500000" and price>="250000"]'));
$statAllDealPrice250000 	= count($xmldeal->xpath('/deals/deal[@type="deal-a" and price<"250000" and price>="100000" or @type="deal-c" and price<"250000" and price>="100000"]'));
$statAllDealPrice100000 	= count($xmldeal->xpath('/deals/deal[@type="deal-a" and price<"100000" and price>="25000" or @type="deal-c" and price<"100000" and price>="25000"]'));
$statAllDealPrice25000 		= count($xmldeal->xpath('/deals/deal[@type="deal-a" and price<"25000" and price>="5000" or @type="deal-c" and price<"25000" and price>="5000"]'));
$statAllDealPrice5000 		= count($xmldeal->xpath('/deals/deal[@type="deal-a" and price<"5000" or @type="deal-c" and price<"5000"]'));

#Процент вернувшихся клиентов 
function return_clients(){
	global $baseC;
	$dom 		= new DOMDocument;
	$dom		->load($baseC);
	$xpath 		= new DOMXPath($dom);
	$clients 	= $xpath->query('/clients/client');
	$count = 0;
	foreach ($clients as $client) {
		$CID 		= $client->getAttribute('id');
		$CNAME		= $client->getElementsByTagName("clientname")->item(0)->nodeValue;
		if (count_deal('client', $CID) > 2){
			$count += 1;
		}
	}
	return round($count * 100 / count_client('', ''),0) . '%';
}

#Кол-во обращений
function clients_requests_count($type){
	global $baseC, $baseD;
	$dom 		= new DOMDocument;
	$dom		->load($baseC);
	$xpath 		= new DOMXPath($dom);
	$clients 	= $xpath->query('/clients/client');
	$count = 0;
	foreach ($clients as $client) {
		$CID 		= $client->getAttribute('id');
		$CNAME		= $client->getElementsByTagName("clientname")->item(0)->nodeValue;
		
		$dox 		= new DOMDocument;
		$dox		->load($baseD);
		$xpathx 	= new DOMXPath($dox);
		$deal_a 	= $xpathx->query('/deals/deal[@type="deal-a" and @client="'.$CID.'"]')->length;
		$deal_c 	= $xpathx->query('/deals/deal[@type="deal-c" and @client="'.$CID.'"]')->length;
		
		if($type == 'once'){
			if (($deal_a + $deal_c) == 1){
				$count += 1;
			}
		} elseif($type == 'return'){
			if (($deal_a + $deal_c) > 2){
				$count += 1;
			}
		} elseif ($type == 'nodeal'){
			if (($deal_a + $deal_c) < 1){
				$count += 1;
			}
		}
	}
	return $count;
}

#Время выполнения задачи общее
function timeinwork($login){
	global $baseT;
	$dom = new DOMDocument;
	$dom->load($baseT);
	$xpath = new DOMXPath($dom);
	
	if($login == '' OR $login == 'all'){
		$tasks = $xpath->query('/tasks/task[@status="done"]');
	} else {
		$tasks = $xpath->query('/tasks/task[@deligated="'.$login.'" and @status="done"]');
	}
	$count 	= $tasks->length;
	$time 	= 0;
	for ($i = 0; $i < $count; $i++) {
		$time += floatval($tasks->item($i)->getElementsByTagName("timeinwork")->item(0)->nodeValue) + 1;
	}
	if($count > 0){
		//return round($time / $count, 0);
		return round($time, 0);
	} else {
		return 0;
	}
}

#Время выполнения задачи среднее
function timeinwork2($login){
	global $baseT;
	$dom = new DOMDocument;
	$dom->load($baseT);
	$xpath = new DOMXPath($dom);
	
	if($login == '' OR $login == 'all'){
		$tasks = $xpath->query('/tasks/task[@status="done"]');
	} else {
		$tasks = $xpath->query('/tasks/task[@deligated="'.$login.'" and @status="done"]');
	}
	$count 	= $tasks->length;
	$time 	= 0;
	for ($i = 0; $i < $count; $i++) {
		$time += floatval($tasks->item($i)->getElementsByTagName("timeinwork")->item(0)->nodeValue) + 1;
	}
	if($count > 0){
		return round($time / $count, 0);
	} else {
		return 0;
	}
}

function timediff($dateS, $dateE){
	$dateF 		= DateTime::createFromFormat( 'Y-m-d', $dateS );
	$dateT 		= DateTime::createFromFormat( 'Y-m-d', $dateE );
	if(isset($dateE) AND $dateE != '0' AND $dateE != ''){
		if($dateT < $dateF){
			$diff = '- ' . $dateF->diff( $dateT )->format( '%a' );
		} else {
			$diff = $dateF->diff( $dateT )->format( '%a' );
		}
		return $diff;
	} else {
		return '0';
	}
}

function timediff2($dateS, $dateE){
	$dateF 		= DateTime::createFromFormat( 'Y-m-d', $dateS );
	$dateT 		= DateTime::createFromFormat( 'Y-m-d', $dateE );
	if(isset($dateE) AND $dateE != '0' AND $dateE != ''){
		if($dateT < $dateF){
			$diff = '- ' . $dateF->diff( $dateT )->format( '%a' );
		} else {
			$diff = $dateF->diff( $dateT )->format( '%a' );
		}
		return (int)$diff + 1;
		
	} else {
		return '0';
	}
}

function timediffpercent($dateS, $dateE){
	$diffS = timediff($dateS, $dateE);
	$diffE = timediff($dateS, date("Y-m-d"));
	$diffT = timediff(date("Y-m-d"), $dateE);
	if($diffT > 0){
		return round(100 * $diffE / $diffS,0);
	} elseif($diffT < 1){
		return '100';
	} else {
		return '0';
	}
}

function percent($num1, $num2, $class){
	$persent = round(($num2 / $num1) * 100, 1);
	if($num1 > 0 AND $num2 > 0){
		if ($num2 < $num1) {
			return '<i class="fa fa-arrow-down '.$class.' clr_red" aria-hidden="true" title="-'.$persent.'%"></i>';
		} else {
			return '<i class="fa fa-arrow-up '.$class.' clr_green" aria-hidden="true" title="+'.$persent.'%"></i>';
		}
	} else {
		return '';
	}
}

function percent2($num1, $num2, $class){
	$persent = round((($num2 / $num1) * 100)-100, 1);
	if($num1 > 0 AND $num2 > 0){
		if ($num2 < $num1) {
			return '<i class="fa fa-arrow-down '.$class.' clr_red" aria-hidden="true" title="'.$persent.'%"></i>';
		} else {
			return '<i class="fa fa-arrow-up '.$class.' clr_green" aria-hidden="true" title="+'.$persent.'%"></i>';
		}
	} else {
		return '';
	}
}

function difference($num1, $num2, $class, $unit){
	$diff = round(($num2 - $num1), 1);
	if ($num2 < $num1) {
		return '<i class="fa fa-arrow-down '.$class.' clr_red" aria-hidden="true" title="'.$diff.$unit.'"></i>';
	} else {
		return '<i class="fa fa-arrow-up '.$class.' clr_green" aria-hidden="true" title="+'.$diff.$unit.'"></i>';
	}
}

#Производительность сотрудника
function performance($login){
	if(timeinwork($login) > 0){
		$performance = floatval((multi_count_task('all', 'done', $login, 'all', 'all', 'all')*timeinwork2('all'))/(timeinwork($login)*timeinwork('all')));
		return $performance;
	} else {
		return 0;
	}
	
}
function performanceAll(){
	global $baseU;
	$dom 	= new DOMDocument;
	$dom	->load($baseU);
	$xpath 	= new DOMXPath($dom);
	$users = $xpath->query('/users/user');
	$perfom_all = 0;
	foreach ($users as $user) {
		$Login 		= $user->getAttribute('login');
		$perfom_all += performance($Login);
	}
	return $perfom_all;
}
function performancePercent($login){
	if(performanceAll() > 0){
		$performance = floatval(performance($login)*100/performanceAll());
		return round($performance,0);
	} else {
		return 0;
	}
}
#Кол-во дней с последней сделки клиента
function days_last_deal($client){
	global $baseD;
	$dom 	= new DOMDocument;
	$dom	->load($baseD);
	$xpath 	= new DOMXPath($dom);
	$deals	= 	$xpath->query('/deals/deal[@client="'.$client.'" and @type!="deal-o" and last()]');
	$dealscount = $deals->length;
	$lastdealdate = $deals->item($dealscount-1)->getElementsByTagName("dates")->item(0)->nodeValue;
	return timediff($lastdealdate, date("Y-m-d"));
}
?>