<?php
header('Content-Type: text/html; charset=utf-8');

require_once ('../settings.php');
require_once("ClassLibs/ClassMessageAndLogs.php");
$db = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME,$DB_PORT);
$db->query("SET CHARSET SET utf8");
$db->query("SET NAMES 'utf8'");
if (mysqli_connect_errno()) {	
	exit('Error connecting to DB');
}
set_time_limit(300);
$_REQUEST['client_id'] = 67;
$query = "SELECT `settings` FROM `clientapp` WHERE `id_client`=$_REQUEST[client_id]";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->bind_result($json);
$stmt->fetch();

$dbset = json_decode($json,true);

$db2 = new mysqli ($dbset['DB']['DB_HOST'],$dbset['DB']['DB_USER'],$dbset['DB']['DB_PASS'],$dbset['DB']['DB_NAME']);
$db2->query("SET CHARSET SET utf8");
$db2->query("SET NAMES 'utf8'");
if (mysqli_connect_errno()) {
	echo "Error connecting to DB";
	exit;
}
$ObjLogsTOiR = new MessageAndLogs();    
$xmlstr = $_REQUEST['spares'];
$ObjLogsTOiR->WriteLogAttendance("Toir Import Spares  ".$xmlstr,'Toir_Import_log','logs');
$ObjLogsTOiR->WriteLogAttendance("Test All  Import Spares ".json_encode($_REQUEST),'Toir_ImportAllRequest_log','logs');

$xmlstr =  str_replace ( '@@@' , '&amp;' ,  $xmlstr);
$ObjLogsTOiR->WriteLogAttendance("Toir Import Spares After replace  ".$xmlstr,'Toir_Import_log','logs');
$toir = new SimpleXMLElement($xmlstr);

$sparesAtWorkers = array();

foreach ($toir->Запчасть as $spares) {
	$external_id = (string) $spares->{'CatalogObject.Склады'}->Ref;
	$IsFolder = (string) $spares->{'CatalogObject.Номенклатура'}->IsFolder;
	if (!empty($external_id) && $IsFolder == 'false') {		
		$Description = (string) $spares->{'CatalogObject.Номенклатура'}->Description;
		$Article = (string) $spares->{'CatalogObject.Номенклатура'}->Артикул;
		$FullDescription = (string) $spares->{'CatalogObject.Номенклатура'}->НаименованиеПолное;
		//$Code = (string) $spares->{'CatalogObject.Номенклатура'}->Code;		
		$Date = (string) $spares->НаМомент;		
		$Count = (int) $spares->Количество;
		$spareRef = (string) $spares->{'CatalogObject.Номенклатура'}->Ref;		
		$sparesAtWorkers[$external_id][] = array(
			'IsFolder' => $IsFolder,
			'Description' => $Description,
			'Article' => $Article,
			'FullDescription' => $FullDescription,
			//'Code' => $Code,
			'Count' => $Count,
			'Date' =>	$Date,
			'spareRef'	=> $spareRef
		);
	}
}

/* print_r($sparesAtWorkers); exit;
foreach ($sparesAtWorkers as key=>$spareValue) {
	
}  */

$ObjLogsTOiR->WriteLogAttendance("Toir Import Spares  Data".json_encode($sparesAtWorkers),'Toir_Import_log','logs');
//print_r($sparesAtWorkers); exit;

$count = 0;
$query = "DELETE FROM `toir_spares` WHERE `client_id`=$_REQUEST[client_id]";
//echo $query; exit;
$stmt = $db2->prepare($query);
$stmt->execute();
$stmt->close();

foreach ($sparesAtWorkers as $key=>$spareValue ) {	
	/* $query = "DELETE FROM `toir_spares` WHERE `external_id` ='$key'";
	$stmt = $db2->prepare($query);
	$stmt->execute();
	$stmt->close(); */
	
	foreach ($spareValue as $spare) {
		//$spare[Description] = str_replace ( '@@@' , '&' ,  $xmlstr);
		$query = "INSERT INTO `toir_spares` (`client_id`, `external_id`,`users_id`,`spare`,`aticle`,`count`,`date`, `spareRef`) 
			VALUES ($_REQUEST[client_id], '$key', (SELECT `id` FROM `toir_users` WHERE `external_id` = '$key'), 
			'".addslashes($spare[Description])."', '$spare[Article]', '$spare[Count]', '$spare[Date]', '$spare[spareRef]')";		
		//$query = addslashes($query);
		//echo $query.'<br />';
		$ObjLogsTOiR->WriteLogAttendance("Toir Import Spares  INSERT Query ".$query,'Toir_Import_log','logs');
		$stmt = $db2->prepare($query);
		$stmt->execute();
		$stmt->close();	
		$count++;	
	}  	
}

if ($count) {
	echo "Заимпортировано $count едениц запчастей";
} else {
	echo 'Не заимпортировно ни одной еденицы';
}  