<?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');
}

$_REQUEST['client_id'] = 67;
$securityKey = $_REQUEST['securityKey'];
$confirmCode = $_REQUEST['code'];
$confirm = $_REQUEST['confirm'];

$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;
}

if ($securityKey == 'e10adc3949ba59abbe56e057f20f883e') {
	if ($confirm == 'true') {
		$query = "SELECT `id`, `isConfirm` FROM `toir_export_info`
		WHERE `client_id`= $_REQUEST[client_id] AND  `code`=$confirmCode";
		$stmt = $db2->prepare($query);
		$stmt->execute();
		$stmt->bind_result($id, $isConfirm);
		$stmt->fetch();
		$stmt->close();
		if (!$isConfirm) {
			$query = "UPDATE `toir_export_info` SET `isConfirm`=1 WHERE `id`=$id";
			$stmt = $db2->prepare($query);
			$stmt->execute();
			$stmt->close();
			exit("Экспорт с кодом $confirmCode успешно закрыт");
		} else {
			exit('Данный экспорт уже закрыт');
		}
		
	} else {
		echo 'Повторная отправка данных <br />';
		$query = "SELECT  `date_from`, `date_to`  FROM `toir_export_info`
		WHERE `client_id`=$_REQUEST[client_id]  AND `code`=$confirmCode";
		$stmt = $db2->prepare($query);
		$stmt->execute();
		$stmt->bind_result($dateFrom, $dateTo);
		$stmt->fetch();
		$stmt->close();
		echo exportToir($dbset, $dateFrom, $dateTo, $_REQUEST['client_id'], $confirmCode);		
	}	
} else {
	echo 'Неверный код допуска!';
}