<?
	$ENTspace = array("&nbsp;", "&nbsp"); // Замена неразрывных пробелов
	
	/* Добавление клиента */
	if( isset( $_POST['ClientAdd'] ) ) {
		$formClientId 		= newID('clients','clients','client');
	
		$formClientType 	= $_POST["selectType"];
		$formClientName 	= $_POST["inputName"];
		$formClientPhoto 	= $_POST["inputFile"];
		$formClientPriority	= $_POST["selectPriority"];
		$formClientAgent 	= $_POST["inputAgent"];
		if($_POST["inputEmail"] != ''){
			$formClientEmail 	= $_POST["inputEmail"];
		}else{
			$formClientEmail 	= 'noreply@'.$_SERVER['HTTP_HOST'];
		}
		$formClientPhoneW 	= $_POST["inputPhoneW"];
		$formClientPhone 	= $_POST["inputPhone"];
		$formClientSite 	= $_POST["inputSite"];
		$formClientStart 	= $_POST["inputDateStart"];
		$formClientAdress 	= $_POST["inputAdress"];
		$formClientFined	= $_POST["selectFined"];

		# Загрузка фотографии сотрудника #
		if($_FILES['inputFile']['tmp_name']) {
			$path = './crmdata/upload/_client-photo/';					// Путь загрузки файла
			$tmp_path = './tmp/';										// Путm загрузки временных файлов
			$types = array('image/gif', 'image/png', 'image/jpeg');		// Массив допустимых значений типа файла 'image/gif', 'image/png', 
			$size = 1048576; 											// Максимальный размер файла - 1 мб
			if($_SERVER['REQUEST_METHOD'] == 'POST' and $_FILES['inputFile']['size'] < $size and in_array($_FILES['inputFile']['type'], $types)) {
				require_once(ROOT . 'functions/func-upload-photo.php');
				$name 		= resize($_FILES['inputFile'], $_POST['file_type'], $_POST['file_rotate']);
				$newname 	= $aliases_arr[1] . '_' . $formClientId . '.' . $ext;
				if (!@copy($tmp_path . $name, $path . $newname)) 		// Загрузка файла и вывод сообщения
					echo '';
				else
					$newClientPhoto = $newname;
					echo ''; 											// <p>Загрузка прошла удачно <a href="' . $path . $newname . '">Посмотреть</a>.</p>
				unlink($tmp_path . $name);								// Удаляем временный файл
			}
		}

		$dom = new DOMDocument; 
		$dom->load($baseC);
		$xpath = new DOMXPath($dom);
		
		$clients=$xpath->query('/clients')->item(0);
		$client = $dom->createElement('client');
		$attribute1 = $dom->createAttribute("id");
		$attribute2 = $dom->createAttribute("type");
		$attribute3 = $dom->createAttribute("priority");
		$attribute1->value = $formClientId;
		$client->appendChild($attribute1);
		$attribute2->value = $formClientType;
		$client->appendChild($attribute2);
		$attribute3->value = $formClientPriority;
		$client->appendChild($attribute3);
		$client->appendChild($dom->createElement('clientphoto', $newClientPhoto));
		$client->appendChild($dom->createElement('clientname', $formClientName));
		$client->appendChild($dom->createElement('clientagent', $formClientAgent));
		$client->appendChild($dom->createElement('clientphonew', $formClientPhoneW));
		$client->appendChild($dom->createElement('clientphone', $formClientPhone));
		$client->appendChild($dom->createElement('clientsite', $formClientSite));
		$client->appendChild($dom->createElement('clientemail', $formClientEmail));
		$client->appendChild($dom->createElement('clientstart', $formClientStart));
		$client->appendChild($dom->createElement('clientadress', $formClientAdress));
		$client->appendChild($dom->createElement('clientfined', $formClientFined));
		$client->appendChild($dom->createElement('clientdeals', '0'));
		$client->appendChild($dom->createElement('clientdebt', '0'));
		$client->appendChild($dom->createElement('uip', $sessionIP));
		$clients->appendChild($client);
		$dom->save($baseC);
			
		// Добавление лога
		new_log("Добавление клиента: $formClientName");
		
		$notices[] = 'Клиент успешно добавлен';
	}
	
	/* Редактирование клиента */
	if( isset( $_POST['ClientEdit'] ) ) {
		$oldClientId 		= $_POST["inputId"];
		
		$newClientId 		= $_POST["inputId"];
		$newClientType 		= $_POST["selectType"];
		$newClientName 		= $_POST["inputName"];
		$newClientPriority	= $_POST["selectPriority"];
		$newClientAgent 	= $_POST["inputAgent"];
		if($_POST["inputEmail"] != ''){
			$newClientEmail 	= $_POST["inputEmail"];
		}else{
			$newClientEmail 	= 'noreply@'.$_SERVER['HTTP_HOST'];
		}
		$newClientPhoneW 	= $_POST["inputPhoneW"];
		$newClientPhone 	= $_POST["inputPhone"];
		$newClientSite 		= $_POST["inputSite"];
		$newClientStart 	= $_POST["inputDateStart"];
		$newClientAdress 	= $_POST["inputAdress"];
		$newClientFined		= $_POST["selectFined"];

		# Загрузка фотографии сотрудника #
		if($_FILES['inputFile']['tmp_name']) {
			
			$ClientPhotoFile 	=  ROOT . '/crmdata/upload/_client-photo/' . $_POST["inputPhoto"];
			if (file_exists($ClientPhotoFile) and $_POST["inputPhoto"] != '') {
				unlink($ClientPhotoFile);
			}
			
			$path = './crmdata/upload/_client-photo/';								// Путь загрузки файла
			$tmp_path = './tmp/';											// Путm загрузки временных файлов
			$types = array('image/gif', 'image/png', 'image/jpeg');				// Массив допустимых значений типа файла 'image/gif', 'image/png', 
			$size = 1048576; 	 							// Максимальный размер файла - 1 мб
			if($_SERVER['REQUEST_METHOD'] == 'POST' and $_FILES['inputFile']['size'] < $size and in_array($_FILES['inputFile']['type'], $types)) {
				require_once(ROOT . 'functions/func-upload-photo.php');
				$name 		= resize($_FILES['inputFile'], $_POST['file_type'], $_POST['file_rotate']);
				$newname 	= $aliases_arr[1] . '_' . $newClientId . '.' . $ext;
				if (!@copy($tmp_path . $name, $path . $newname)) 		// Загрузка файла и вывод сообщения
					echo '';
				else
					$newClientPhoto = $newname;
					echo ''; 											// <p>Загрузка прошла удачно <a href="' . $path . $newname . '">Посмотреть</a>.</p>
				unlink($tmp_path . $name);								// Удаляем временный файл
			}
		} else {
			$newClientPhoto = $_POST["inputPhoto"];
		}
		
		$parent = new DomDocument;
		$parent_node = $parent->createElement('client');
		$attribute1 = $parent->createAttribute("id");
		$attribute2 = $parent->createAttribute("type");
		$attribute3 = $parent->createAttribute("priority");
		$attribute1->value = $newClientId;
		$parent_node->appendChild($attribute1);
		$attribute2->value = $newClientType;
		$parent_node->appendChild($attribute2);
		$attribute3->value = $newClientPriority;
		$parent_node->appendChild($attribute3);
		$parent_node->appendChild($parent->createElement('clientphoto', $newClientPhoto));
		$parent_node->appendChild($parent->createElement('clientname', $newClientName));
		$parent_node->appendChild($parent->createElement('clientagent', $newClientAgent));
		$parent_node->appendChild($parent->createElement('clientphonew', $newClientPhoneW));
		$parent_node->appendChild($parent->createElement('clientphone', $newClientPhone));
		$parent_node->appendChild($parent->createElement('clientsite', $newClientSite));
		$parent_node->appendChild($parent->createElement('clientemail', $newClientEmail));
		$parent_node->appendChild($parent->createElement('clientstart', $newClientStart));
		$parent_node->appendChild($parent->createElement('clientadress', $newClientAdress));
		$parent_node->appendChild($parent->createElement('clientfined', $newClientFined));
		$parent_node->appendChild($parent->createElement('clientdeals', count_deals_price_summ('', 'price', $newClientId, '', '')));
		$parent_node->appendChild($parent->createElement('clientdebt', count_deals_debt_summ('', $newClientId, '', '')));
		$parent_node->appendChild($parent->createElement('uip', $sessionIP));
		$parent->appendChild($parent_node);
		$dom = new DomDocument;
		$dom->load($baseC);
		$xpath = new DOMXpath($dom);
		$nodelist = $xpath->query('/clients/client[@id="'.$oldClientId.'"]');
		$oldnode = $nodelist->item(0);
		$newnode = $dom->importNode($parent->documentElement, true);
		$oldnode->parentNode->replaceChild($newnode, $oldnode);
		$dom->save($baseC);	
			
		// Добавление лога
		new_log("Редактирование данных клиента: $newClientName");

		$notices[] = 'Данные клиента сохранены';
	}
	
	/* Удаление клиента */
	if( isset( $_POST['clientDelete'] ) ) {
		$dom = new DOMDocument; 
		$dom->load($baseC);
		$xpath = new DOMXPath($dom); 
		
		$id = $_POST["clientDelId"];
		$ClientName 		= $xpath->query('/clients/client[@id="'. $id .'"]')->item(0)->getElementsByTagName("clientname")->item(0)->nodeValue;
		$ClientPhoto 		= $xpath->query('/clients/client[@id="'. $id .'"]')->item(0)->getElementsByTagName("clientphoto")->item(0)->nodeValue;
		$ClientPhotoFile 	= ROOT . '/crmdata/upload/_client-photo/' . $aliases_arr[1] . '_' . $id;
		if (file_exists($ClientPhotoFile)) {
			unlink($ClientPhotoFile);
		}
		$clients = $xpath->query('/clients/client[@id="'.$id.'"]');
		$el = $clients->item(0);
		$el->parentNode->removeChild($el);
		$dom->save($baseC); 
		
		// Удаление Загрузок
		$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("Удаление клиента: $ClientName");
		
		$notices[] = 'Клиент успешно удален';
	}
	
	/* Удаление фото */
	if( isset( $_POST['DelPhoto'] ) ) {
		$dom = new DOMDocument; 
		$dom->load($baseC);
		$xpath = new DOMXPath($dom); 
		
		$id = $_POST["inputId"];
		$ClientPhoto 		= $xpath->query('/clients/client[@id="'. $id .'"]')->item(0)->getElementsByTagName("clientphoto")->item(0)->nodeValue='';
		$ClientPhotoFile 	= ROOT . '/crmdata/upload/_client-photo/' . $aliases_arr[1] . '_' . $id;
		if (file_exists($ClientPhotoFile)) {
			unlink($ClientPhotoFile);
		}

		$dom->save($baseC); 
		
		// Добавление лога
		new_log("Удаление фото клиента: $ClientName");
		
		$notices[] = 'Фото успешно удалено';
	}
	
	/* Изменение важности */
	if( isset( $_POST['ClientChangePrior'] ) ) {
		$dom = new DOMDocument;
		$dom->load($baseC);
		$xpath = new DOMXPath($dom);
		if(isset($_GET['view']) AND $_GET['view'] != ''){
			$clients = $xpath->query('/clients/client[@id="'.$_GET['view'].'"]');
		} elseif(isset($_GET['edit']) AND $_GET['edit'] != ''){
			$clients = $xpath->query('/clients/client[@id="'.$_GET['edit'].'"]');
		}
		if($_POST['ClientChangePrior'] == '3'){
			$ClientNewPriorTxt = 'high';
		} elseif($_POST['ClientChangePrior'] == '2'){
			$ClientNewPriorTxt = 'medium';
		} elseif($_POST['ClientChangePrior'] == '1'){
			$ClientNewPriorTxt = 'low';
		} elseif($_POST['ClientChangePrior'] == '0'){
			$ClientNewPriorTxt = 'none';
		}

		$ClientNewPrior	= $clients->item(0)->setAttribute('priority', $ClientNewPriorTxt);
		
		$dom->save($baseC);

		$notices[] = 'Важность изменена';
		
	}
	
	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 	= newDealNum();
		$formDealPrice		= $_POST["inputPrice"];
		$formDealCosts		= '';
		$formDealPaid		= '';
		$formDealDateStart 	= date("Y-m-d");
		$formDealDateSyear 	= mb_substr($formDealDateStart, 0, 4);
		$formDealDateSmonth = mb_substr($formDealDateStart, 5, 2);
		$formDealDateSday 	= mb_substr($formDealDateStart, 8, 2);
		$formDealDateEnd 	= '';
		$formDealComment 	= '';
		$formDealClient		= $_GET["view"];

		$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[] = 'Сделка успешно добавлена';
	}
?>