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

require_once ('../../settings.php');
require_once("../ClassLibs/ClassMessageAndLogs.php");
require_once 'ExportTOiR.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;
$securityKey = $_REQUEST['securityKey'];
/* $dateFrom = $_REQUEST['from'];
$dateTo =  $_REQUEST['to']; */

$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'");
/* 
$db3 = new mysqli ($dbset['DB']['DB_HOST'],$dbset['DB']['DB_USER'],$dbset['DB']['DB_PASS'],$dbset['DB']['DB_NAME']);
$db3->query("SET CHARSET SET utf8");
$db3->query("SET NAMES 'utf8'"); */
if (mysqli_connect_errno()) {
	echo "Error connecting to DB";
	exit;
}
$ObjLogsTOiR = new MessageAndLogs();    

if ($securityKey == 'e10adc3949ba59abbe56e057f20f883e') {

	$query = "SELECT `isConfirm`, `date_from`, `date_to`, `code`  FROM `toir_export_info` 
			WHERE `client_id`=$_REQUEST[client_id] ORDER BY id DESC LIMIT 1";
	$stmt = $db2->prepare($query);
	$stmt->execute();
	$stmt->bind_result($isConfirm, $dateFrom, $dateTo, $codeTransaction);
	$stmt->fetch();
	$stmt->close();
	if ($isConfirm) {
		$dateFrom = $dateTo;
		$code = time();
		$dateTo = date('Y-m-d H:i:s', $code);
		$query = "INSERT INTO  `toir_export_info` (`date_from`, `date_to`, `code`, `client_id`) 
				VALUES ('$dateFrom', '$dateTo', $code, $_REQUEST[client_id])";
		$stmt = $db2->prepare($query);
		$stmt->execute();		
		echo exportToir($dbset, $dateFrom, $dateTo, $_REQUEST['client_id'], $code);
	} else {
		echo 'У вас есть неподтвержденный импорт. Формирование нового, без подтверждения получения предудущего пакета невозможно.';
	}
	
	
} else {
	echo 'Неверный код допуска!';
}



