<?php
ini_set('display_errors','0');
error_reporting(E_ALL);
session_start();
setlocale(LC_ALL, 'de_DE');
header('Content-Type: application/json; charset=utf-8');
include('backend.php');

if (empty($module)) $module = 'login';

if (!isset($_SESSION['backend'][$session_name]) || !$_SESSION['backend'][$session_name]){
	http_response_code(403);
	print json_encode(array('success' => false, 'message' => 'Nicht angemeldet.'));
	exit;
}

include_once('includes/function/modules_manager_update.php');

$action = isset($_POST['action']) ? preg_replace('/[^a-z_]/', '', $_POST['action']) : '';
$module_update = isset($_POST['module_update']) ? preg_replace('/[^a-zA-Z0-9_\-]/', '', $_POST['module_update']) : '';
$delay = isset($_POST['delay']) ? (int)$_POST['delay'] : 0;

if ($action == 'list'){
	print json_encode(array('success' => true, 'updates' => cmt_update_available_list(false)), JSON_UNESCAPED_SLASHES);
	exit;
}

if ($action == 'update' || $action == 'install'){
	print json_encode(cmt_update_execute($module_update, $action, array('delay' => $delay)), JSON_UNESCAPED_SLASHES);
	exit;
}

if ($action == 'update_all'){
	$updates = cmt_update_available_list(false);
	$log = array();
	foreach ($updates AS $item){
		$result = cmt_update_execute($item['module'], $item['action'], array('delay' => $delay));
		if (isset($result['log'])) foreach ($result['log'] AS $line) $log[] = '['.$item['module'].'] '.$line;
		if (empty($result['success'])){
			print json_encode(array('success' => false, 'message' => $result['message'], 'log' => $log), JSON_UNESCAPED_SLASHES);
			exit;
		}
	}
	print json_encode(array('success' => true, 'message' => 'Alle Updates abgeschlossen.', 'log' => $log), JSON_UNESCAPED_SLASHES);
	exit;
}

print json_encode(array('success' => false, 'message' => 'Ungültige Aktion.'));
