<?php
	$ENTspace = array("&nbsp;", "&nbsp"); // Замена неразрывных пробелов
	
	/* Отпрвка письма */
	if( isset( $_POST['LetterSend'] ) ) {
		$formLetterId 			= newID('letters','letters','letter');
		$formLetterSubject 		= $_POST["inputSubject"];
		$formLetterUserTo 		= $_POST["selectUserTo"];
		$formLetterUserFrom 	= $_SESSION["userid"];
		$formLetterUserCoppy 	= $_POST["selectUserCoppy"]; 
		$formLetterText 		= $_POST["inputComment"];
		$formLetterTags 		= $_POST["inputTags"];
		$formLetterPriority 	= $_POST["selectPriority"];
		
		$formLetterTask 		= $_POST["selectTask"];
		$formLetterClient 		= $_POST["selectClient"];
		$formLetterDeal 		= $_POST["selectDeal"];
		$formLetterEvent 		= $_POST["selectEvent"];
		
		if(isset($_POST["LetterTempl"])){
		
			new_templ($formLetterSubject, $formLetterText);
			$notices[] = 'Шаблон успешно создан';
			new_log("Создан шаблон: $formLetterSubject");
			
		} else {

			$dom = new DOMDocument; 
			$dom->load($baseLT);
			$xpath = new DOMXPath($dom);
			
			$letters=$xpath->query('/letters')->item(0);
			$letter = $dom->createElement('letter');
			$attribute1 = $dom->createAttribute("id");
			$attribute2 = $dom->createAttribute("parentid");
			$attribute3 = $dom->createAttribute("status");
			$attribute1->value = $formLetterId;
			$letter->appendChild($attribute1);
			$attribute2->value = '';
			$letter->appendChild($attribute2);
			$attribute3->value = 'notread';
			$letter->appendChild($attribute3);
			$letter->appendChild($dom->createElement('fromid', $formLetterUserFrom));
			$letter->appendChild($dom->createElement('fromname', get_user_name($formLetterUserFrom, '')));
			$letter->appendChild($dom->createElement('toid', $formLetterUserTo));
			$letter->appendChild($dom->createElement('toname', get_user_name($formLetterUserTo, '')));
			$letter->appendChild($dom->createElement('coppyid', $formLetterUserCoppy));
			$letter->appendChild($dom->createElement('coppyname', get_user_name($formLetterUserCoppy, '')));
			$letter->appendChild($dom->createElement('subject', $formLetterSubject));
			$letter->appendChild($dom->createElement('text', mb_substr(strip_tags(str_replace($ENTspace, "&amp;#160;", $formLetterText)), 0, 100, 'UTF-8') . '...'));
			$letter->appendChild($dom->createElement('priority', $formLetterPriority));
			$letter->appendChild($dom->createElement('date', date("Y-m-d H:i:s")));
			$letter->appendChild($dom->createElement('tags', $formLetterTags));
			$letter->appendChild($dom->createElement('taskid', $formLetterTask));
			$letter->appendChild($dom->createElement('taskname', get_task_name($formLetterTask, '')));
			$letter->appendChild($dom->createElement('clientid', $formLetterClient));
			$letter->appendChild($dom->createElement('clientname', get_client_name($formLetterClient)));
			$letter->appendChild($dom->createElement('dealid', $formLetterDeal));
			$letter->appendChild($dom->createElement('dealnum', get_deal_num($formLetterDeal)));
			$letter->appendChild($dom->createElement('eventid', $formLetterEvent));
			$letter->appendChild($dom->createElement('eventname', get_event_name($formLetterEvent)));

			$letters->appendChild($letter);
			$dom->save($baseLT);
			
			// Добавление файла с комментарием
			$letterDir = ROOT . 'crmdata/upload/letters_'.$formLetterId;
			$letterFile = $letterDir . '/page_description.xml';
			if (!is_dir($letterDir)){
				mkdir($letterDir);
				file_put_contents($letterFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
			} else {
				file_put_contents($letterFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
			}
			if (file_exists($letterFile)){
				$dom = new DOMDocument; 
				$dom->load($letterFile);
				$xpath = new DOMXPath($dom);
				$nText = $xpath->query('/item')->item(0)->getElementsByTagName("text")->item(0)->nodeValue = str_replace($ENTspace, "&amp;#160;", $formLetterText);
				$dom->save($letterFile);
			}

			if( $_POST["selectUserTo"] != '') {
				# Отправка уведомления о сообщении #
				$doc = new DOMDocument;
				$doc->load($baseU);
				$xpath = new DOMXPath($doc);
				$UserEmail = $xpath->query('/users/user[@id="'. $formLetterUserTo .'"]')->item(0)->getElementsByTagName("useremail")->item(0)->nodeValue;
				$UserName = $xpath->query('/users/user[@id="'. $formLetterUserTo .'"]')->item(0)->getElementsByTagName("username")->item(0)->nodeValue;
				
				$subject 	= "CRM система. Новое личное сообщение";
				$message 	= '
					<h2>Здравствуйте, '. $UserName .'!</h2>
					<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);
			}
			
			if( $_POST["selectUserCoppy"] != '') {
				# Отправка уведомления о сообщении #
				$doc = new DOMDocument;
				$doc->load($baseU);
				$xpath = new DOMXPath($doc);
				$UserEmail = $xpath->query('/users/user[@id="'. $formLetterUserCoppy .'"]')->item(0)->getElementsByTagName("useremail")->item(0)->nodeValue;
				$UserName = $xpath->query('/users/user[@id="'. $formLetterUserCoppy .'"]')->item(0)->getElementsByTagName("username")->item(0)->nodeValue;
				
				$subject 	= "CRM система. Новое личное сообщение";
				$message 	= '
					<h2>Здравствуйте, '. $UserName .'!</h2>
					<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['AnswerSend'] ) ) {
		$formLetterId 			= newID('letters','letters','letter');
		$formLetterSubject 		= $_POST["inputSubject"];
		$formLetterUserTo 		= $_POST["selectUserTo"];
		$formLetterUserFrom 	= $_SESSION["userid"];
		$formLetterUserCoppy 	= $_POST["selectUserCoppy"]; 
		$formLetterText 		= $_POST["inputComment"];
		$formLetterTags 		= $_POST["inputTags"];
		$formLetterPriority 	= $_POST["selectPriority"];
		
		$formLetterTask 		= $_POST["selectTask"];
		$formLetterClient 		= $_POST["selectClient"];
		$formLetterDeal 		= $_POST["selectDeal"];
		$formLetterEvent 		= $_POST["selectEvent"];

		$dom = new DOMDocument; 
		$dom->load($baseLT);
		$xpath = new DOMXPath($dom);
		
		$letters=$xpath->query('/letters')->item(0);
		$letter = $dom->createElement('letter');
		$attribute1 = $dom->createAttribute("id");
		$attribute2 = $dom->createAttribute("parentid");
		$attribute3 = $dom->createAttribute("status");
		$attribute1->value = $formLetterId;
		$letter->appendChild($attribute1);
		$attribute2->value = $_GET['view'];
		$letter->appendChild($attribute2);
		$attribute3->value = 'notread';
		$letter->appendChild($attribute3);
		$letter->appendChild($dom->createElement('fromid', $formLetterUserFrom));
		$letter->appendChild($dom->createElement('fromname', get_user_name($formLetterUserFrom, '')));
		$letter->appendChild($dom->createElement('toid', $formLetterUserTo));
		$letter->appendChild($dom->createElement('toname', get_user_name($formLetterUserTo, '')));
		$letter->appendChild($dom->createElement('coppyid', $formLetterUserCoppy));
		$letter->appendChild($dom->createElement('coppyname', get_user_name($formLetterUserCoppy, '')));
		$letter->appendChild($dom->createElement('subject', $formLetterSubject));
		$letter->appendChild($dom->createElement('text', mb_substr(strip_tags(str_replace($ENTspace, "&amp;#160;", $formLetterText)), 0, 100, 'UTF-8') . '...'));
		$letter->appendChild($dom->createElement('priority', $formLetterPriority));
		$letter->appendChild($dom->createElement('date', date("Y-m-d H:i:s")));
		$letter->appendChild($dom->createElement('tags', $formLetterTags));
		$letter->appendChild($dom->createElement('taskid', $formLetterTask));
		$letter->appendChild($dom->createElement('taskname', get_task_name($formLetterTask, '')));
		$letter->appendChild($dom->createElement('clientid', $formLetterClient));
		$letter->appendChild($dom->createElement('clientname', get_client_name($formLetterClient)));
		$letter->appendChild($dom->createElement('dealid', $formLetterDeal));
		$letter->appendChild($dom->createElement('dealnum', get_deal_num($formLetterDeal)));
		$letter->appendChild($dom->createElement('eventid', $formLetterEvent));
		$letter->appendChild($dom->createElement('eventname', get_event_name($formLetterEvent)));

		$letters->appendChild($letter);
		$dom->save($baseLT);

		// Добавление файла с комментарием
		$letterDir = ROOT . 'crmdata/upload/letters_'.$formLetterId;
		$letterFile = $letterDir . '/page_description.xml';
		if (!is_dir($letterDir)){
			mkdir($letterDir);
			file_put_contents($letterFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		} else {
			file_put_contents($letterFile,'<?xml version="1.0" encoding="utf-8"?><item type="documentary"><text></text></item>');
		}
		if (file_exists($letterFile)){
			$dom = new DOMDocument; 
			$dom->load($letterFile);
			$xpath = new DOMXPath($dom);
			$nText = $xpath->query('/item')->item(0)->getElementsByTagName("text")->item(0)->nodeValue = str_replace($ENTspace, "&amp;#160;", $formLetterText);
			$dom->save($letterFile);
		}
		
		if( $_POST["selectUserTo"] != '') {
			# Отправка уведомления о сообщении #
			$doc = new DOMDocument;
			$doc->load($baseU);
			$xpath = new DOMXPath($doc);
			$UserEmail = $xpath->query('/users/user[@id="'. $formLetterUserTo .'"]')->item(0)->getElementsByTagName("useremail")->item(0)->nodeValue;
			$UserName = $xpath->query('/users/user[@id="'. $formLetterUserTo .'"]')->item(0)->getElementsByTagName("username")->item(0)->nodeValue;
			
			$subject 	= "CRM система. Новое личное сообщение";
			$message 	= '
				<h2>Здравствуйте, '. $UserName .'!</h2>
				<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['LetterDelete'] ) ) {
		$dom = new DOMDocument; 
		$dom->load($baseLT);
		$xpath = new DOMXPath($dom); 
		
		$id = $_POST["LetterDelId"];

		$letters = $xpath->query('/letters/letter[@id="'.$id.'"]');
		$el = $letters->item(0);
		$el->parentNode->removeChild($el);
		$dom->save($baseLT);
		
		// Удаление Загрузок
		$dir 	= 	ROOT . 'crmdata/upload/letters_'.$id;
		if (is_dir($dir)) {
			$files = glob($dir."/*");
			foreach ($files as $file) {      
				if (file_exists($file)) {
					unlink($file);
				}   
			}
			rmdir($dir);
		}

		// Добавление лога
		$sessionID = newID('logs','logs','log');
		$sessionIP = GET_IP();
		$sessionTime = date("Y-m-d").' '.date("H:i:s");
		$dom = new DOMDocument; 
		$dom->load($baseL);
		$xpath = new DOMXPath($dom);
		$logs=$xpath->query('/logs')->item(0);
		$log = $dom->createElement('log');
		$attribute1 = $dom->createAttribute("id");
		$attribute1->value = $sessionID;
		$log->appendChild($attribute1);
		$log->appendChild($dom->createElement('login', $LoginCheck));
		$log->appendChild($dom->createElement('action', 'Удаление задачи: ' . $TaskName));
		$log->appendChild($dom->createElement('userip', $sessionIP));
		$log->appendChild($dom->createElement('sessiontime', $sessionTime));
		$logs->appendChild($log);
		$dom->save($baseL);
		$xmllogs 	= simplexml_load_file($baseL);
		$countLogs 	= count($xmllogs->xpath('/logs/log'));
		if($countLogs > $numLogs) {
			$dom = new DOMDocument; 
			$dom->load($baseL);
			$xpath = new DOMXPath($dom); 
			$logs = $xpath->query('/logs/log[1]');
			$el = $logs->item(0);
			$el->parentNode->removeChild($el);
			$dom->save($baseL); 
		}
		$notices[] = 'Письмо успешно удалено';
	}
	
	/* Прочитать все письма */
	if( isset( $_POST['ReadAllLetters'] ) ) {
		$dom = new DOMDocument; 
		$dom->load($baseLT);
		$xpath = new DOMXPath($dom);
		
		$letters = $xpath->query('/letters/letter[toid="'.$_SESSION["userid"].'"]');
		
		for ($i = 0; $i < $letters->length; $i++) {
			$el = $letters->item($i)->setAttribute('status', 'read');
		}
		$dom->save($baseLT);
		$notices[] = 'Все письма помечены как прочтенные';
	}
	
	/* Прочитать все письма */
	if( isset( $_POST['DelAllNot'] ) ) {
		$dom = new DOMDocument; 
		$dom->load($baseLT);
		$xpath = new DOMXPath($dom);
		
		$letters = $xpath->query('/letters/letter[toid="'.$_SESSION["userid"].'" and contains(fromname,"WORKBox CRM")]');
		
		for ($i = 0; $i < $letters->length; $i++) {
			$el = $letters->item($i);
			$el->parentNode->removeChild($el);
		}
		$dom->save($baseLT);
		$notices[] = 'Все уведомления удалены';
	}
?>