<?php

$accessControl = array('StreamFile' => true);
include_once '../../AccessControl.php';

#include Classes
include_once(logaholic_dir() . "includes/datamanager.php");

if(isset($_REQUEST["checkpath"])) {
	$dataManDir = $_REQUEST["checkpath"];
	if (is_writable($dataManDir)) {
		echo '{ "Status": "Success", "Message": "'. _PATH_IS_WRITABLE .'" }';
	} else {
		echo '{ "Status": "Error", "Message": "'. _PATH_NOT_WRITEABLE .'" }';
	}
}

if(isset($_REQUEST["saveDataManagerSettings"])) {
	setGlobalSetting("datamanagersettings", $_REQUEST["datamanagerMonthLimit"]);
	
	$reverse = strrev( $_REQUEST["datamanagerDir"] );
	if($reverse[0] != "/") {
		$_REQUEST["datamanagerDir"] .= "/";
	}
	
	setGlobalSetting("datamanagerDirectory", $_REQUEST["datamanagerDir"]);
	setGlobalSetting("datamanagerStorageSize", $_REQUEST["maxManagerStorage"]);
	echo '{ "Status": "Success", "Message": "'. _SETTINGS_SAVED .'" }';
}

if(isset($_REQUEST["GetDatamanagerLogList"])) {
	$dir = "{$profile->datamanagerDir}{$profile->profilename}/log";
	$logFiles = array();
	if (is_dir($dir)) {
		if ($dh = opendir($dir)) {
			$prev_dropdown = "";
			while (($file = readdir($dh)) !== false) {
				if($file !== "." && $file !== "..") {							
					$month = explode(".",$file);
					$month = $month[0];
					$month = mktime(0,0,0,substr($month,4,-2),substr($month,6,7),substr($month,0,4));
					$month = date("Y m (F)",$month);							
					$logFiles[$month][] = $file;
				}
			}
			closedir($dh);
		}
	}
	ksort($logFiles);
	echo '{ "Status": "Success", "Logs": '. json_encode($logFiles) .' }';
}

if(isset($_REQUEST["runDatamNow"]) && isset($_REQUEST["conf"])) {
	header('Content-Type: text/event-stream');
	header('Cache-Control: no-cache');

	$currentSetting = $profile->GetOtherSettings("datamanagersettings",getGlobalSetting("datamanagersettings",0));		
				
	$datamanager = new DataManager();
	$datamanager->print = 'stream';
	
	$datamanager->LogProcess(_STARTING_DATAM . "..");

	$datamanager->ClearDatabase($profile,$currentSetting,true, 'stream');

	$datamanager->LogProcess(_FINISHED_DATAM . "..");
}

if(!empty($_REQUEST["fromDate"])  && !empty($_REQUEST["toDate"])) {
	header('Content-Type: text/event-stream');
	header('Cache-Control: no-cache');

	$from = explode("-", $_REQUEST["fromDate"]);
	$to = explode("-", $_REQUEST["toDate"]);

	$from  = mktime(0,0,0,$from[1],$from[0],$from[2]);
	$to  = mktime(23,59,59,$to[1],$to[0],$to[2]);

	$datamanager = new DataManager();
	$datamanager->print = 'stream';

	if(!empty($_REQUEST["imp"])){
		$datamanager->Import($profile, $from, $to, 'stream');
	} else if(!empty($_REQUEST["exp"])){		
		$datamanager->Export($profile, $from, $to, 'stream');
	}
}
?>