<?
	$ENTspace = array("&nbsp;", "&nbsp"); // Замена неразрывных пробелов
	
	function newDealNum(){
		global $baseD;
		
		$dom 	= new DOMDocument;
		$dom	->load($baseD);
		$xpath 	= new DOMXPath($dom);
		
		$num = $xpath->query('/deals/deal[dates="'.date("Y-m-d").'"]');
		if($num->length > 0){
			$lastID = $xpath->query('/deals/deal[position()=last()]')->item(0)->getElementsByTagName("num")->item(0)->nodeValue;
		} else {
			$lastID = date("ymd") . '0';
		}
		return $lastID + 1;
	}
	
	/* Добавление сделки */
	if( isset( $_POST['DealAdd'] ) ) {
		
		$formDealId 		= newID('deals','deals','deal');
		$formDealType 		= $_POST["selectType"];
		$formDealSubject	= $_POST["inputSubject"];
		$formDealNumber 	= $_POST["inputNumber"];
		$formDealPrice		= $_POST["inputPrice"];
		$formDealCosts		= $_POST["inputCosts"];
		$formDealPaid		= $_POST["inputPaid"];
		$formDealDateStart 	= $_POST["inputDateStart"];
		$formDealDateSyear 	= mb_substr($formDealDateStart, 0, 4);
		$formDealDateSmonth = mb_substr($formDealDateStart, 5, 2);
		$formDealDateSday 	= mb_substr($formDealDateStart, 8, 2);
		$formDealDateEnd 	= $_POST["inputDateEnd"];
		$formDealComment 	= $_POST["inputComment"];
		
		if(isset($_POST["NewTempl"])){
		
			new_templ($formDealSubject, $formDealComment);
			$notices[] = 'Шаблон успешно создан';
			new_log("Создан шаблон: $formDealSubject");
			
		} else {
		
			/* Добавление нового клиента */
			$dox = new DOMDocument; 
			$dox->load($baseC);
			$xpathx = new DOMXPath($dox); 
			$formDealClientName = $_POST["selectClient"];
			$clientCount = $xpathx->query('/clients/client[clientname="'. $formDealClientName .'"]');
			if($clientCount -> length > 0){
				$clientID = $xpathx->query('/clients/client[clientname="'. $formDealClientName .'"]')->item(0)->getAttribute('id');
				$formDealClient 	= $clientID;
			} else {
				$formDealClient 	= newID('clients','clients','client');
				$clients=$xpathx->query('/clients')->item(0);
				$client = $dox->createElement('client');
				$attribute1 = $dox->createAttribute("id");
				$attribute2 = $dox->createAttribute("type");
				$attribute3 = $dox->createAttribute("priority");
				$attribute1->value = $formDealClient;
				$client->appendChild($attribute1);
				$attribute2->value = '';
				$client->appendChild($attribute2);
				$attribute3->value = '';
				$client->appendChild($attribute3);
				$client->appendChild($dox->createElement('clientphoto', ''));
				$client->appendChild($dox->createElement('clientname', $formDealClientName));
				$client->appendChild($dox->createElement('clientagent', ''));
				$client->appendChild($dox->createElement('clientphonew', ''));
				$client->appendChild($dox->createElement('clientphone', ''));
				$client->appendChild($dox->createElement('clientsite', ''));
				$client->appendChild($dox->createElement('clientemail', ''));
				$client->appendChild($dox->createElement('clientstart', date("Y-m-d")));
				$client->appendChild($dox->createElement('clientadress', ''));
				$client->appendChild($dox->createElement('clientfined', ''));
				$client->appendChild($dox->createElement('clientdeals', '0'));
				$client->appendChild($dox->createElement('clientdebt', '0'));
				$client->appendChild($dox->createElement('uip', $sessionIP));
				$clients->appendChild($client);
				$dox->save($baseC);
					
				// Добавление лога
				new_log("Добавление клиента: $formDealClientName");
				
				$notices[] = 'Клиент успешно добавлен';
			}
			/* * */

			$dom = new DOMDocument; 
			$dom->load($baseD);
			$xpath = new DOMXPath($dom);

			$deals=$xpath->query('/deals')->item(0);
			$deal = $dom->createElement('deal');
			$attribute1 = $dom->createAttribute("id");
			$attribute2 = $dom->createAttribute("type");
			$attribute3 = $dom->createAttribute("client");
			$attribute1->value = $formDealId;
			$deal->appendChild($attribute1);
			$attribute2->value = $formDealType;
			$deal->appendChild($attribute2);
			$attribute3->value = $formDealClient;
			$deal->appendChild($attribute3);
			$deal->appendChild($dom->createElement('subject', $formDealSubject));
			$deal->appendChild($dom->createElement('num', $formDealNumber));
			$deal->appendChild($dom->createElement('price', $formDealPrice));
			$deal->appendChild($dom->createElement('costs', $formDealCosts));
			$deal->appendChild($dom->createElement('paid', $formDealPaid));
			$deal->appendChild($dom->createElement('dates', $formDealDateStart));
			$deal->appendChild($dom->createElement('datey', $formDealDateSyear));
			$deal->appendChild($dom->createElement('datem', $formDealDateSmonth));
			$deal->appendChild($dom->createElement('dated', $formDealDateSday));
			$deal->appendChild($dom->createElement('datee', $formDealDateEnd));
			$deal->appendChild($dom->createElement('comment', mb_substr(strip_tags(str_replace($ENTspace, "&amp;#160;", $formDealComment)), 0, 50, 'UTF-8') . '...'));
			$deal->appendChild($dom->createElement('uip', $sessionIP));
			$deals->appendChild($deal);
			$dom->save($baseD);
				
			// Добавление файла с комментарием
			$dealDir = ROOT . 'crmdata/upload/deals_'.$formDealId;
			$dealFile = $dealDir . '/page_description.xml';
			if (!is_dir($dealDir)){
				mkdir($dealDir);
				file_put_contents($dealFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
			} else {
				file_put_contents($dealFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
			}
			if (file_exists($dealFile)){
				$dom = new DOMDocument; 
				$dom->load($dealFile);
				$xpath = new DOMXPath($dom);
				$nText = $xpath->query('/item')->item(0)->getElementsByTagName("text")->item(0)->nodeValue = str_replace($ENTspace, "&amp;#160;", $formDealComment);
				$dom->save($dealFile);
			}
				
			// Добавление лога
			new_log("Добавление сделки:  $formDealNumber");

			/* Обновление данных клиента */
			$dom = new DOMDocument;
			$dom->load($baseC);
			$xpath = new DOMXPath($dom);
			$clientCount = $xpath->query('/clients/client[@id="'.$formDealClient.'"]');
			if($clientCount -> length > 0){
				$clientDeals	= $xpath->query('/clients/client[@id="'.$formDealClient.'"]')->item(0)->getElementsByTagName("clientdeals")->item(0)->nodeValue = count_deals_price_summ('', 'price', $formDealClient, '', '');
				$clientDebt		= $xpath->query('/clients/client[@id="'.$formDealClient.'"]')->item(0)->getElementsByTagName("clientdebt")->item(0)->nodeValue = count_deals_debt_summ('', $formDealClient, '', '');
			}
			$dom->save($baseC);
			/* Обновление данных клиента */

			$notices[] = 'Сделка успешно добавлена';
		}
	}
	
	/* Редактирование сделки */
	if( isset( $_POST['DealEdit'] ) ) {
		
		$oldDealId 			= $_POST["inputId"];
		
		$newDealId 			= $_POST["inputId"];
		$newDealType 		= $_POST["selectType"];
		$newDealSubject		= $_POST["inputSubject"];
		$newDealNumber 		= $_POST["inputNumber"];
		$newDealPrice		= $_POST["inputPrice"];
		$newDealCosts		= $_POST["inputCosts"];
		$newDealPaid		= $_POST["inputPaid"];
		$newDealDateStart 	= $_POST["inputDateStart"];
		$newDealDateSyear 	= mb_substr($newDealDateStart, 0, 4);
		$newDealDateSmonth 	= mb_substr($newDealDateStart, 5, 2);
		$newDealDateSday 	= mb_substr($newDealDateStart, 8, 2);
		$newDealDateEnd 	= $_POST["inputDateEnd"];
		$newDealComment 	= $_POST["inputComment"];
		$newDealClient 		= $_POST["selectClient"];
		
		if(isset($_POST["NewTempl"])){
			new_templ($newDealSubject, $newDealComment);
			$notices[] = 'Шаблон успешно создан';
			new_log("Создан шаблон: $newDealSubject");
			
		} else {
			/* Добавление нового клиента */
			$dox = new DOMDocument; 
			$dox->load($baseC);
			$xpathx = new DOMXPath($dox); 
			$newDealClientName = $_POST["selectClient"];
			$clientCount = $xpathx->query('/clients/client[clientname="'. $newDealClientName .'"]');
			if($clientCount -> length > 0){
				$clientID = $xpathx->query('/clients/client[clientname="'. $newDealClientName .'"]')->item(0)->getAttribute('id');
				$newDealClient 	= $clientID;
			} else {
				$newDealClient 	= '';
			}
			/* * */
			
			$parent = new DomDocument;
			$parent_node = $parent->createElement('deal');
			$attribute1 = $parent->createAttribute("id");
			$attribute2 = $parent->createAttribute("type");
			$attribute3 = $parent->createAttribute("client");
			$attribute1->value = $newDealId;
			$parent_node->appendChild($attribute1);
			$attribute2->value = $newDealType;
			$parent_node->appendChild($attribute2);
			$attribute3->value = $newDealClient;
			$parent_node->appendChild($attribute3);
			$parent_node->appendChild($parent->createElement('subject', $newDealSubject));
			$parent_node->appendChild($parent->createElement('num', $newDealNumber));
			$parent_node->appendChild($parent->createElement('price', $newDealPrice));
			$parent_node->appendChild($parent->createElement('costs', $newDealCosts));
			$parent_node->appendChild($parent->createElement('paid', $newDealPaid));
			$parent_node->appendChild($parent->createElement('dates', $newDealDateStart));
			$parent_node->appendChild($parent->createElement('datey', $newDealDateSyear));
			$parent_node->appendChild($parent->createElement('datem', $newDealDateSmonth));
			$parent_node->appendChild($parent->createElement('dated', $newDealDateSday));
			$parent_node->appendChild($parent->createElement('datee', $newDealDateEnd));
			$parent_node->appendChild($parent->createElement('comment', mb_substr(strip_tags(str_replace($ENTspace, "&amp;#160;", $newDealComment)), 0, 50, 'UTF-8') . '...'));
			$parent_node->appendChild($parent->createElement('uip', $sessionIP));
			$parent->appendChild($parent_node);
			$dom = new DomDocument;
			$dom->load($baseD);
			$xpath = new DOMXpath($dom);
			$nodelist = $xpath->query('/deals/deal[@id="'.$oldDealId.'"]');
			$oldnode = $nodelist->item(0);
			$newnode = $dom->importNode($parent->documentElement, true);
			$oldnode->parentNode->replaceChild($newnode, $oldnode);
			$dom->save($baseD);
			
			// Добавление файла с комментарием
			$dealDir = ROOT . 'crmdata/upload/deals_'.$newDealId;
			$dealFile = $dealDir . '/page_description.xml';
			if (!is_dir($dealDir)){
				mkdir($dealDir);
				file_put_contents($dealFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
			} else {
				file_put_contents($dealFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
			}
			if (file_exists($dealFile)){
				$dom = new DOMDocument; 
				$dom->load($dealFile);
				$xpath = new DOMXPath($dom);
				$nText = $xpath->query('/item')->item(0)->getElementsByTagName("text")->item(0)->nodeValue = str_replace($ENTspace, "&amp;#160;", $newDealComment);
				$dom->save($dealFile);
			}
				
			// Добавление лога
			new_log("Редактирование сделки:  $newDealNumber");

			/* Обновление данных клиента */
			$dom = new DOMDocument;
			$dom->load($baseC);
			$xpath = new DOMXPath($dom);
			$clientCount = $xpath->query('/clients/client[@id="'.$newDealClient.'"]');
			if($clientCount -> length > 0){
				$clientDeals	= $xpath->query('/clients/client[@id="'.$newDealClient.'"]')->item(0)->getElementsByTagName("clientdeals")->item(0)->nodeValue = count_deals_price_summ('', 'price', $newDealClient, '', '');
				$clientDebt		= $xpath->query('/clients/client[@id="'.$newDealClient.'"]')->item(0)->getElementsByTagName("clientdebt")->item(0)->nodeValue = count_deals_debt_summ('', $newDealClient, '', '');
			}
			$dom->save($baseC);
			/* Обновление данных клиента */

			$notices[] = 'Сделка успешно сохранена';
		}
	}
	
	/* Редактирование сделки */
	if( isset( $_POST['SaveDescription'] ) ) {
		$dom 	= new DomDocument;
		$dom	->load($baseD);
		$xpath 	= new DOMXpath($dom);
		$dealslist 		= $xpath->query('/deals/deal[@id="'.$_GET["view"].'"]');
		$deals_num 		= $xpath->query('/deals/deal[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("num")->item(0)->nodeValue;
		$deals_descr 	= $xpath->query('/deals/deal[@id="'.$_GET["view"].'"]')->item(0)->getElementsByTagName("comment")->item(0)->nodeValue=mb_substr(strip_tags(str_replace($ENTspace, "&amp;#160;", $_POST["inputComment"])), 0, 50, 'UTF-8') . '...';
		$dom	->save($baseD);
		
		$dealDir 	= ROOT . 'crmdata/upload/deals_'.$_GET["view"];
		$dealFile 	= $dealDir . '/page_description.xml';
		if (!is_dir($dealDir)){
			mkdir($dealDir);
			file_put_contents($dealFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		} else {
			file_put_contents($dealFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		}
		if (file_exists($dealFile)){
			$dom = new DOMDocument; 
			$dom->load($dealFile);
			$xpath = new DOMXPath($dom);
			$nText = $xpath->query('/item')->item(0)->getElementsByTagName("text")->item(0)->nodeValue = str_replace($ENTspace, "&amp;#160;", $_POST["inputComment"]);
			$dom->save($dealFile);
		}
		
		// Добавление лога
		new_log("Редактирование сделки $deals_num");
		
		$notices[] = 'Описание успешно сохранено';
	}
	
	/* Удаление сделки */
	if( isset( $_POST['DealDelete'] ) ) {
		$dom = new DOMDocument; 
		$dom->load($baseD);
		$xpath = new DOMXPath($dom); 
		
		$id = $_POST["DealDelId"];
		$DealNumber = $xpath->query('/deals/deal[@id="'. $id .'"]')->item(0)->getElementsByTagName("num")->item(0)->nodeValue;
		$DealClient = $xpath->query('/deals/deal[@id="'. $id .'"]')->item(0)->getAttribute('client');

		$deals = $xpath->query('/deals/deal[@id="'.$id.'"]');
		$el = $deals->item(0);
		$el->parentNode->removeChild($el);
		$dom->save($baseD); 
			
		// Удаление Загрузок
		$dir 	= 	ROOT . 'crmdata/upload/' . $aliases_arr[1] . '_'.$id;
		if (is_dir($dir)) {
			$files = glob($dir."/*");
			foreach ($files as $file) {      
				if (file_exists($file)) {
					unlink($file);
				}   
			}
			rmdir($dir);
		}
			
		// Добавление лога
		new_log("Удаление сделки:  $DealNumber");

		/* Обновление данных клиента */
		$dom = new DOMDocument;
		$dom->load($baseC);
		$xpath = new DOMXPath($dom);
		$clientCount = $xpath->query('/clients/client[@id="'. $DealClient .'"]');
		if($clientCount -> length > 0){
			$clientDeals	= $xpath->query('/clients/client[@id="'.$DealClient.'"]')->item(0)->getElementsByTagName("clientdeals")->item(0)->nodeValue = count_deals_price_summ('', 'price', $DealClient, '', '');
			$clientDebt		= $xpath->query('/clients/client[@id="'.$DealClient.'"]')->item(0)->getElementsByTagName("clientdebt")->item(0)->nodeValue = count_deals_debt_summ('', $DealClient, '', '');
		}
		$dom->save($baseC);
		/* Обновление данных клиента */

		$notices[] = 'Сделка успешно удалена';
	}
	
	/* Перевод из предложения в активную сделку */
	if( isset( $_POST['DealActive'] ) ) {
		$DealActiveId 	= $_POST["DealActiveId"];
		$date			= date("Y-m-d");
		$DealDateSyear 	= mb_substr($date, 0, 4);
		$DealDateSmonth = mb_substr($date, 5, 2);
		$DealDateSday 	= mb_substr($date, 8, 2);
		
		$doc = new DOMDocument;
		$doc->load($baseD);
		$xpath = new DOMXPath($doc);
		
		$DealNumber 	= $xpath->query('/deals/deal[@id="'. $DealActiveId .'"]')->item(0)->getElementsByTagName("num")->item(0)->nodeValue;
		$DealClient 	= $xpath->query('/deals/deal[@id="'. $DealActiveId .'"]')->item(0)->getAttribute('client');
		$deals 			= $xpath->query('/deals/deal[@id="'.$DealActiveId.'"]');
		$dealType		= $xpath->query('/deals/deal[@id="'.$DealActiveId.'"]')->item(0)->setAttribute('type', 'deal-a');
		$dealDate		= $xpath->query('/deals/deal[@id="'.$DealActiveId.'"]')->item(0)->getElementsByTagName("dates")->item(0)->nodeValue=$date;
		
		$dealYear 		= $xpath->query('/deals/deal[@id="'.$DealActiveId.'"]')->item(0)->getElementsByTagName("datey")->item(0)->nodeValue=$DealDateSyear;
		$dealMonth 		= $xpath->query('/deals/deal[@id="'.$DealActiveId.'"]')->item(0)->getElementsByTagName("datem")->item(0)->nodeValue=$DealDateSmonth;
		$dealDay 		= $xpath->query('/deals/deal[@id="'.$DealActiveId.'"]')->item(0)->getElementsByTagName("dated")->item(0)->nodeValue=$DealDateSday;
		$doc->save($baseD);
			
		// Добавление лога
		new_log("Перевод предложения в активную сделку:  $DealNumber");

		/* Обновление данных клиента */
		$dom = new DOMDocument;
		$dom->load($baseC);
		$xpath = new DOMXPath($dom);
		$clientCount = $xpath->query('/clients/client[@id="'. $DealClient .'"]');
		if($clientCount -> length > 0){
			$clientDeals	= $xpath->query('/clients/client[@id="'.$DealClient.'"]')->item(0)->getElementsByTagName("clientdeals")->item(0)->nodeValue = count_deals_price_summ('', 'price', $DealClient, '', '');
			$clientDebt		= $xpath->query('/clients/client[@id="'.$DealClient.'"]')->item(0)->getElementsByTagName("clientdebt")->item(0)->nodeValue = count_deals_debt_summ('', $DealClient, '', '');
		}
		$dom->save($baseC);
		/* Обновление данных клиента */

		$notices[] = 'Сделка успешно заключена';
	}
	/* Завершение сделки */
	if( isset( $_POST['DealDone'] ) ) {
		$DealDoneId 	= $_POST["DealDoneId"];

		$doc = new DOMDocument;
		$doc->load($baseD);
		$xpathD = new DOMXPath($doc);
		
		$DealNumber 	= $xpathD->query('/deals/deal[@id="'. $DealDoneId .'"]')->item(0)->getElementsByTagName("num")->item(0)->nodeValue;
		$DealClient 	= $xpathD->query('/deals/deal[@id="'. $DealDoneId .'"]')->item(0)->getAttribute('client');
		$DealPrice 		= floatval($xpathD->query('/deals/deal[@id="'. $DealDoneId .'"]')->item(0)->getElementsByTagName("price")->item(0)->nodeValue);
		$DealPaid 		= floatval($xpathD->query('/deals/deal[@id="'. $DealDoneId .'"]')->item(0)->getElementsByTagName("paid")->item(0)->nodeValue);
		$DealLastPay 	= floatval($DealPrice - $DealPaid);
		
		if($DealLastPay != '' AND $DealLastPay != 0 AND $DealPrice > $DealPaid){
			$formPaymentDate 		= date("Y-m-d H:i:s");
			$formPaymentDateYear 	= date("Y", strtotime($formPaymentDate));
			$formPaymentDateMonth   = date("m", strtotime($formPaymentDate));
			$paymentDealNum 		= get_deal_num($DealDoneId);
			
			if($DealLastPay > 0){
				$paymentType	= 'profit';
				$paymentValue = '+' . $DealLastPay;
			} elseif($DealLastPay < 0){
				$paymentType	= 'cost';
				$paymentValue = '-' . $DealLastPay;
			}

			$dom = new DOMDocument; 
			$dom->load($baseP);
			$xpath = new DOMXPath($dom);
			
			$payments=$xpath->query('/payments')->item(0);
			$payment = $dom->createElement('payment');
			$attribute1 = $dom->createAttribute("id");
			$attribute2 = $dom->createAttribute("did");
			$attribute3 = $dom->createAttribute("type");
			$attribute4 = $dom->createAttribute("status");
			$attribute1->value = newID('payments','payments','payment');
			$payment->appendChild($attribute1);
			$attribute2->value = $DealDoneId;
			$payment->appendChild($attribute2);
			$attribute3->value = $paymentType;
			$payment->appendChild($attribute3);
			$attribute4->value = '+';
			$payment->appendChild($attribute4);
			$payment->appendChild($dom->createElement('deal', $paymentDealNum));
			$payment->appendChild($dom->createElement('val', $paymentValue));
			$payment->appendChild($dom->createElement('date', $formPaymentDate));
			$payment->appendChild($dom->createElement('datey', $formPaymentDateYear));
			$payment->appendChild($dom->createElement('datem', $formPaymentDateMonth));
			$payment->appendChild($dom->createElement('com', str_replace($ENTspace, "&amp;#160;", 'Последний платеж')));
			$payments->appendChild($payment);
			$dom->save($baseP);
			
			if($DealDoneId != '-'){
				if($paymentType == 'profit'){
					$dealPaid 	= floatval($xpathD->query('/deals/deal[@id="'. $DealDoneId .'"]')->item(0)->getElementsByTagName("paid")->item(0)->nodeValue);
					$NdealPaid 	= floatval($xpathD->query('/deals/deal[@id="'.$DealDoneId.'"]')->item(0)->getElementsByTagName("paid")->item(0)->nodeValue = $dealPaid + $DealLastPay);
				} elseif($paymentType == 'cost'){
					$dealCosts 	= floatval($xpathD->query('/deals/deal[@id="'. $DealDoneId .'"]')->item(0)->getElementsByTagName("costs")->item(0)->nodeValue);
					$NdealCosts = floatval($xpathD->query('/deals/deal[@id="'.$DealDoneId.'"]')->item(0)->getElementsByTagName("costs")->item(0)->nodeValue = $dealCosts + $DealLastPay);
				}
			}
		}	
			
		$dealType		= $xpathD->query('/deals/deal[@id="'.$DealDoneId.'"]')->item(0)->setAttribute('type', 'deal-c');
		$dealDate		= $xpathD->query('/deals/deal[@id="'.$DealDoneId.'"]')->item(0)->getElementsByTagName("datee")->item(0)->nodeValue=date("Y-m-d");
		$doc->save($baseD); 
				
		// Добавление лога
		new_log("Завершение сделки:  $DealNumber");
		/* Обновление данных клиента */
		$dom = new DOMDocument;
		$dom->load($baseC);
		$xpath = new DOMXPath($dom);
		$clientCount = $xpath->query('/clients/client[@id="'. $DealClient .'"]');
		if($clientCount -> length > 0){
			$clientDeals	= $xpath->query('/clients/client[@id="'.$DealClient.'"]')->item(0)->getElementsByTagName("clientdeals")->item(0)->nodeValue = count_deals_price_summ('', 'price', $DealClient, '', '');
			$clientDebt		= $xpath->query('/clients/client[@id="'.$DealClient.'"]')->item(0)->getElementsByTagName("clientdebt")->item(0)->nodeValue = count_deals_debt_summ('', $DealClient, '', '');
		}
		$dom->save($baseC);
		/* Обновление данных клиента */
		$notices[] = 'Сделка завершена';
	}
	/* Изменить оплаченную сумму */
	function set_paid_size($dealID){
		global $baseD;
		$doc = new DOMDocument;
		$doc->load($baseD);
		$xpath = new DOMXPath($doc);
		
		$price = $xpath->query('/deals/deal[@id="'. $dealID .'"]')->item(0)->getElementsByTagName("price")->item(0)->nodeValue;
		 
		if( isset( $_POST['SetPaidSize'] ) ) {
			$dom = new DOMDocument;
			$dom->load($baseD);
			$xpath = new DOMXPath($dom);
			$dealPaid 	= $xpath->query('/deals/deal[@id="'.$dealID.'"]')->item(0)->getElementsByTagName("paid")->item(0)->nodeValue = $_POST['NewPaid'];
			$dom->save($baseD);
			$notices[] = 'Успешно изменено';
		}
		if( isset( $_POST['ClearPaidSize'] ) ) {
			$dom = new DOMDocument;
			$dom->load($baseD);
			$xpath = new DOMXPath($dom);
			$dealPaid 	= $xpath->query('/deals/deal[@id="'.$dealID.'"]')->item(0)->getElementsByTagName("paid")->item(0)->nodeValue = "0";
			$dom->save($baseD);
			$notices[] = 'Успешно изменено';
		}
		return '
			<form method="POST">
				<div class="input-group">
					<span class="input-group-addon"><i class="fa fa-fw fa-rub" style="display:inline-block;" aria-hidden="true"></i></span>
					<input type="number" class="form-control" style="width:auto;" name="NewPaid" value="0" min="0" max="'.$price.'">
					<div class="input-group-btn" style="float:left;">
						<button type="submit" name="SetPaidSize" class="btn btn-primary" style="color:#fff;" onclick="return confirm(\'Вы уверены что хотите изменить оплаченную сумму?\')">Изменить</button>
						<button type="submit" name="ClearPaidSize" class="btn btn-default" style="color:#333;" onclick="return confirm(\'Вы уверены что хотите удалить оплаченную сумму?\')"><i class="fa fa-fw fa-times" style="display:inline-block;" aria-hidden="true"></i></button>
					</div>
				</div>
			</form>
		';
	}
	
	/* Добавление задачи */
	if( isset( $_POST['TaskAdd'] ) ) {
		$formTaskId 		= newID('tasks','tasks','task');
		$formTaskParent 	= '';
		$formTaskName 		= $_POST["inputName"];
		$formTaskType 		= $_POST["selectType"];
		$formTaskComment 	= '';
		$formTaskDeal 		= $_GET["view"];
		$formTaskUser 		= $_POST["selectUser"];
		if($_POST["selectUser"] == $LoginCheck){
			$formTaskUserS 		= '';
		} else {
			$formTaskUserS 		= $LoginCheck;
		}
		$formTaskDateStart 	= date("Y-m-d");
		$formTaskDateEnd 	= $_POST["inputDateEnd"];
		$formTaskPriority 	= '';
		$formTaskLink 		= '';
		$formTaskStatus 	= 'inwork';
		$formTaskPercent 	= '0';
		
		$dom = new DOMDocument; 
		$dom->load($baseT);
		$xpath = new DOMXPath($dom);
		$tasks=$xpath->query('/tasks')->item(0);
		$task = $dom->createElement('task');
		$attribute1 = $dom->createAttribute("id");
		$attribute2 = $dom->createAttribute("parent");
		$attribute3 = $dom->createAttribute("status");
		$attribute4 = $dom->createAttribute("deligated");
		$attribute5 = $dom->createAttribute("deal");
		$attribute6 = $dom->createAttribute("priority");
		$attribute7 = $dom->createAttribute("percent");
		$attribute8 = $dom->createAttribute("type");
		$attribute1->value = $formTaskId;
		$task->appendChild($attribute1);
		$attribute2->value = $formTaskParent;
		$task->appendChild($attribute2);
		$attribute3->value = $formTaskStatus;
		$task->appendChild($attribute3);
		$attribute4->value = $formTaskUser;
		$task->appendChild($attribute4);
		$attribute5->value = $formTaskDeal;
		$task->appendChild($attribute5);
		$attribute6->value = $formTaskPriority;
		$task->appendChild($attribute6);
		$attribute7->value = $formTaskPercent;
		$task->appendChild($attribute7);
		$attribute8->value = $formTaskType;
		$task->appendChild($attribute8);
		$task->appendChild($dom->createElement('taskname', $formTaskName));
		$task->appendChild($dom->createElement('supervisor', $formTaskUserS));
		$task->appendChild($dom->createElement('comment', ''));
		$task->appendChild($dom->createElement('datestart', $formTaskDateStart));
		$task->appendChild($dom->createElement('dateend', $formTaskDateEnd));
		$task->appendChild($dom->createElement('link', $formTaskLink));
		$task->appendChild($dom->createElement('timeinwork', ''));
		$task->appendChild($dom->createElement('uip', $sessionIP));
		$tasks->appendChild($task);
		$dom->save($baseT);
		
		// Добавление файла с комментарием
		$taskDir = ROOT . 'crmdata/upload/tasks_'.$formTaskId;
		$taskFile = $taskDir . '/page_description.xml';
		if (!is_dir($taskDir)){
			mkdir($taskDir);
			file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		} else {
			file_put_contents($taskFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		}
		
		// Добавление лога
		new_log("Добавление задачи: $formTaskName");
		
		if( $_POST["selectUser"] != '' and $auth->getLogin() != $_POST["selectUser"]) {
			# Отправка уведомления о новой задаче #
			$doc = new DOMDocument;
			$doc->load($baseU);
			$xpath = new DOMXPath($doc);
			$UserEmail = $xpath->query('/users/user[@login="'. $formTaskUser .'"]')->item(0)->getElementsByTagName("useremail")->item(0)->nodeValue;
			$UserName = $xpath->query('/users/user[@login="'. $formTaskUser .'"]')->item(0)->getElementsByTagName("username")->item(0)->nodeValue;
			
			if (file_exists($baseD) and file_exists($fileD)) {
				$doc = new DOMDocument;
				$doc->load($baseD);
				$xpath = new DOMXPath($doc);
				$deals = $xpath->query('/deals/deal[@id="'. $formTaskDeal .'"]');
				for ($i = 0; $i < $deals->length; $i++) {
					$formTaskDealN = $xpath->query('/deals/deal[@id="'. $formTaskDeal .'"]')->item($i)->getElementsByTagName("dealnumber")->item(0)->nodeValue;
				}
			}
			if($formTaskDeal != ''){$taskDeal = $formTaskDealN;} else {$taskDeal = '- не указана -';}
			if($formTaskDateEnd != ''){$taskDateEnd = 'до ' . $formTaskDateEnd;} else {$taskDateEnd = '- не указан -';}
			if($formTaskPriority == 'none'){$taskPriority = 'отсутствует';}  elseif($formTaskPriority == 'low'){$taskPriority = 'низкая';} elseif($formTaskPriority == 'medium'){$taskPriority = 'средняя';} else {$taskPriority = 'высокая';}
			$subject 	= "CRM система. Вам делегирована задача";
			$message 	= '
				<h2>Здравствуйте, '. $UserName .'!</h2>
				<p>Вам делегирована задача "<b>'. $formTaskName .'</b>" (важность: <b>'. $taskPriority .'</b>)</p>
				<p>Срок выполнения: <b>'. $taskDateEnd .'</b>. Подробная информация доступна по <a href="http://'. $_SERVER["SERVER_NAME"] .'/'. $folder . '/tasks/?view=' . $formTaskId . '" target="_blank">ссылке</a></p>
				<p><b>Комментарий:</b></p>'. $formTaskComment .'<br/>
				<p>CRM система <a href="http://'. $_SERVER["SERVER_NAME"] .'/'. $folder . '/" target="_blank">'. $_SERVER["SERVER_NAME"] .'/'. $folder . '/</a></p>
				<br/>
				<p>Хорошего дня и отличного настроения!</p>
			';
			send_email($UserEmail, "CRM система", $subject, $message);
		}
		$notices[] = 'Задача успешно добавлена';
	}
	
	
	/* Добавление платежа */
	if( isset( $_POST['AddPayment'] ) AND $_POST["NewPayment"] > 0) {
		
		
		if(isset($_POST["inputDateStart"]) AND $_POST["inputDateStart"] != '' OR isset($_POST["inputDateStart"]) AND $_POST["inputDateStart"] != date("Y-m-d")){
			$formPaymentDate = date("Y-m-d H:i:s", strtotime($_POST["inputDateStart"]));
		} else {
			$formPaymentDate = date("Y-m-d H:i:s");
		}
		
		$formPaymentDateYear 	= date("Y", strtotime($formPaymentDate));
		$formPaymentDateMonth   = date("m", strtotime($formPaymentDate));
		
		if($_POST["NewPaymentType"] == 'profit'){
			$paymentValue = '+' . $_POST["NewPayment"];
		} elseif($_POST["NewPaymentType"] == 'cost'){
			$paymentValue = '-' . $_POST["NewPayment"];
		}
		
		if(isset($_POST['checkConfirm']) AND $_POST['checkConfirm'] == 'yes'){
			$paymentStatus = '+';
		} else {
			$paymentStatus = '-';
		}
		
		if(isset($_GET['view']) AND $_GET['view'] != ''  OR $_POST["NewPaymentDeal"] != '-'){
			if(isset($_POST["NewPaymentDeal"])){
				$paymentDid = $_POST["NewPaymentDeal"];
			} else {
				$paymentDid = $_GET['view'];
			}
			$paymentDealNum = get_deal_num($paymentDid);
		} else{
			$paymentDid 	= '-';
			$paymentDealNum = '-';
		}

		$dom = new DOMDocument; 
		$dom->load($baseP);
		$xpath = new DOMXPath($dom);
		
		$payments=$xpath->query('/payments')->item(0);
		$payment = $dom->createElement('payment');
		$attribute1 = $dom->createAttribute("id");
		$attribute2 = $dom->createAttribute("did");
		$attribute3 = $dom->createAttribute("type");
		$attribute4 = $dom->createAttribute("status");
		$attribute1->value = newID('payments','payments','payment');
		$payment->appendChild($attribute1);
		$attribute2->value = $paymentDid;
		$payment->appendChild($attribute2);
		$attribute3->value = $_POST["NewPaymentType"];
		$payment->appendChild($attribute3);
		$attribute4->value = $paymentStatus;
		$payment->appendChild($attribute4);
		$payment->appendChild($dom->createElement('deal', $paymentDealNum));
		$payment->appendChild($dom->createElement('val', $paymentValue));
		$payment->appendChild($dom->createElement('date', $formPaymentDate));
		$payment->appendChild($dom->createElement('datey', $formPaymentDateYear));
		$payment->appendChild($dom->createElement('datem', $formPaymentDateMonth));
		$payment->appendChild($dom->createElement('com', str_replace($ENTspace, "&amp;#160;", $_POST["NewPaymentComm"])));
		$payments->appendChild($payment);
		$dom->save($baseP);
		
		if($paymentDid != '-'){
			$dox = new DOMDocument;
			$dox->load($baseD);
			$xpathx = new DOMXPath($dox);
			
			if($_POST["NewPaymentType"] == 'profit' AND $paymentStatus == '+'){
				$dealPaid 	= floatval($xpathx->query('/deals/deal[@id="'. $paymentDid .'"]')->item(0)->getElementsByTagName("paid")->item(0)->nodeValue);
				$NdealPaid 	= floatval($xpathx->query('/deals/deal[@id="'.$paymentDid.'"]')->item(0)->getElementsByTagName("paid")->item(0)->nodeValue = $dealPaid + $_POST["NewPayment"]);
			} elseif($_POST["NewPaymentType"] == 'cost' AND $paymentStatus == '+'){
				$dealCosts 	= floatval($xpathx->query('/deals/deal[@id="'. $paymentDid .'"]')->item(0)->getElementsByTagName("costs")->item(0)->nodeValue);
				$NdealCosts = floatval($xpathx->query('/deals/deal[@id="'.$paymentDid.'"]')->item(0)->getElementsByTagName("costs")->item(0)->nodeValue = $dealCosts + $_POST["NewPayment"]);
			}
			$dox->save($baseD);
		}
		/* Обновление данных клиента */
		$dom = new DOMDocument;
		$dom->load($baseC);
		$xpath = new DOMXPath($dom);
		$clientCount = $xpath->query('/clients/client[@id="'.get_deal_client($paymentDid).'"]');
		if($clientCount -> length > 0){
			$clientDeals	= $xpath->query('/clients/client[@id="'.get_deal_client($paymentDid).'"]')->item(0)->getElementsByTagName("clientdeals")->item(0)->nodeValue = count_deals_price_summ('', 'price', get_deal_client($paymentDid), '', '');
			$clientDebt		= $xpath->query('/clients/client[@id="'.get_deal_client($paymentDid).'"]')->item(0)->getElementsByTagName("clientdebt")->item(0)->nodeValue = count_deals_debt_summ('', get_deal_client($paymentDid), '', '');
		}
		$dom->save($baseC);
		/* Обновление данных клиента */
		$notices[] = 'Платеж успешно добавлен';
	}
/* Удаление платежа */
	if( isset( $_POST['PaymentDelete'] ) ) {
		$dom = new DOMDocument; 
		$dom->load($baseP);
		$xpath = new DOMXPath($dom); 
		
		$payments 		= $xpath->query('/payments/payment[@id="'.$_POST["PaymentDelId"].'"]');
		$paymentType 	= $xpath->query('/payments/payment[@id="'.$_POST["PaymentDelId"].'"]')->item(0)->getAttribute('type');
		$paymentStatus 	= $xpath->query('/payments/payment[@id="'.$_POST["PaymentDelId"].'"]')->item(0)->getAttribute('status');
		$paymentDid 	= $xpath->query('/payments/payment[@id="'.$_POST["PaymentDelId"].'"]')->item(0)->getAttribute('did');
		$paymentVal 	= $xpath->query('/payments/payment[@id="'.$_POST["PaymentDelId"].'"]')->item(0)->getElementsByTagName("val")->item(0)->nodeValue;
		
		$el = $payments->item(0);
		$el->parentNode->removeChild($el);
		$dom->save($baseP); 
			
		if($paymentDid != '-'){
			$dox = new DOMDocument;
			$dox->load($baseD);
			$xpathx = new DOMXPath($dox);
			
			$deal = $xpathx->query('/deals/deal[@id="'. $paymentDid .'"]');
			if($deal -> length > 0){
				if($paymentType == 'profit' AND $paymentStatus == '+'){
					$dealPaid 	= floatval($xpathx->query('/deals/deal[@id="'. $paymentDid .'"]')->item(0)->getElementsByTagName("paid")->item(0)->nodeValue);
					$NdealPaid 	= floatval($xpathx->query('/deals/deal[@id="'.$paymentDid.'"]')->item(0)->getElementsByTagName("paid")->item(0)->nodeValue = $dealPaid - substr($paymentVal,1));
				} elseif($paymentType == 'cost' AND $paymentStatus == '+'){
					$dealCosts 	= floatval($xpathx->query('/deals/deal[@id="'. $paymentDid .'"]')->item(0)->getElementsByTagName("costs")->item(0)->nodeValue);
					$NdealCosts = floatval($xpathx->query('/deals/deal[@id="'.$paymentDid.'"]')->item(0)->getElementsByTagName("costs")->item(0)->nodeValue = $dealCosts - substr($paymentVal,1));
				}
				$dox->save($baseD);
			}
		}
		/* Обновление данных клиента */
		$dom = new DOMDocument;
		$dom->load($baseC);
		$xpath = new DOMXPath($dom);
		$clientCount = $xpath->query('/clients/client[@id="'.get_deal_client($paymentDid).'"]');
		if($clientCount -> length > 0){
			$clientDeals	= $xpath->query('/clients/client[@id="'.get_deal_client($paymentDid).'"]')->item(0)->getElementsByTagName("clientdeals")->item(0)->nodeValue = count_deals_price_summ('', 'price', get_deal_client($paymentDid), '', '');
			$clientDebt		= $xpath->query('/clients/client[@id="'.get_deal_client($paymentDid).'"]')->item(0)->getElementsByTagName("clientdebt")->item(0)->nodeValue = count_deals_debt_summ('', get_deal_client($paymentDid), '', '');
		}
		$dom->save($baseC);
		/* Обновление данных клиента */
		$notices[] = 'Платеж успешно удален';
	}
	
	if( isset( $_POST['PaymentConfirm'] ) ) {
		$dom = new DOMDocument; 
		$dom->load($baseP);
		$xpath = new DOMXPath($dom); 

		$nPaymentStatus = $xpath->query('/payments/payment[@id="'.$_POST["PaymentConfirmId"].'"]')->item(0)->setAttribute('status', '+');
		$nPaymentDate 	= $xpath->query('/payments/payment[@id="'.$_POST["PaymentConfirmId"].'"]')->item(0)->getElementsByTagName("date")->item(0)->nodeValue = date("Y-m-d H:i:s");
		$dom->save($baseP);
		
		$paymentType 	= $xpath->query('/payments/payment[@id="'.$_POST["PaymentConfirmId"].'"]')->item(0)->getAttribute('type');
		$paymentStatus 	= $xpath->query('/payments/payment[@id="'.$_POST["PaymentConfirmId"].'"]')->item(0)->getAttribute('status');
		$paymentDid 	= $xpath->query('/payments/payment[@id="'.$_POST["PaymentConfirmId"].'"]')->item(0)->getAttribute('did');
		$paymentVal 	= $xpath->query('/payments/payment[@id="'.$_POST["PaymentConfirmId"].'"]')->item(0)->getElementsByTagName("val")->item(0)->nodeValue;
		
		if($paymentDid != '-'){
			$dox = new DOMDocument;
			$dox->load($baseD);
			$xpathx = new DOMXPath($dox);
			
			if($paymentType == 'profit' AND $paymentStatus == '+'){
				$dealPaid 	= floatval($xpathx->query('/deals/deal[@id="'. $paymentDid .'"]')->item(0)->getElementsByTagName("paid")->item(0)->nodeValue);
				$NdealPaid 	= floatval($xpathx->query('/deals/deal[@id="'.$paymentDid.'"]')->item(0)->getElementsByTagName("paid")->item(0)->nodeValue = $dealPaid + substr($paymentVal,1));
			} elseif($paymentType == 'cost' AND $paymentStatus == '+'){
				$dealCosts 	= floatval($xpathx->query('/deals/deal[@id="'. $paymentDid .'"]')->item(0)->getElementsByTagName("costs")->item(0)->nodeValue);
				$NdealCosts = floatval($xpathx->query('/deals/deal[@id="'.$paymentDid.'"]')->item(0)->getElementsByTagName("costs")->item(0)->nodeValue = $dealCosts + substr($paymentVal,1));
			}
			$dox->save($baseD);
		}
		/* Обновление данных клиента */
		$dom = new DOMDocument;
		$dom->load($baseC);
		$xpath = new DOMXPath($dom);
		$clientCount = $xpath->query('/clients/client[@id="'.get_deal_client($paymentDid).'"]');
		if($clientCount -> length > 0){
			$clientDeals	= $xpath->query('/clients/client[@id="'.get_deal_client($paymentDid).'"]')->item(0)->getElementsByTagName("clientdeals")->item(0)->nodeValue = count_deals_price_summ('', 'price', get_deal_client($paymentDid), '', '');
			$clientDebt		= $xpath->query('/clients/client[@id="'.get_deal_client($paymentDid).'"]')->item(0)->getElementsByTagName("clientdebt")->item(0)->nodeValue = count_deals_debt_summ('', get_deal_client($paymentDid), '', '');
		}
		$dom->save($baseC);
		/* Обновление данных клиента */
		$notices[] = 'Платеж успешно подтвержден';
	}
	if( isset( $_POST['SaveComment'] ) ) {
		$dom = new DOMDocument; 
		$dom->load($baseP);
		$xpath = new DOMXPath($dom); 

		$nPaymentComment = $xpath->query('/payments/payment[@id="'.$_POST["id"].'"]')->item(0)->getElementsByTagName("com")->item(0)->nodeValue = $_POST["comment"];
		$dom->save($baseP);
		
		/* Обновление данных клиента */
		$notices[] = 'Комментарий сохранен';
	}
if(isset($_GET['view']) AND $_GET['view'] != ''){
	$deal_debt 		= deals_sum($_GET['view'], 'price') - deals_sum($_GET['view'], 'paid');
	$deal_profit 	= deals_sum($_GET['view'], 'price') - deals_sum($_GET['view'], 'costs');
	$deal_sprofit 	= deals_sum($_GET['view'], 'paid') - deals_sum($_GET['view'], 'price');
}
?>