<?php
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');

require_once('../settings.php');

$action = filter_input(INPUT_GET, 'do', FILTER_SANITIZE_STRING);

if ($action === 'reboot') {
    // echo shell_exec("systemctl halt -i");
    if (REBOOT_ENABLED) {
        echo $lang->translate('reboot_in_progress') . '<br>';
        echo shell_exec('sudo shutdown -r');
    } else {
        echo $lang->translate('reboot_prohibited') . '<br>';
    }
} else if ($action === 'shutdown') {
    if (SHUTDOWN_ENABLED) {
        echo $lang->translate('shutdown_in_progress') . '<br>';
        echo shell_exec('sudo halt -p');
    } else {
        echo $lang->translate('shutdown_prohibited') . '<br>';
    }
} else if ($action === 'setup') {
    $def_lang             = filter_input(INPUT_GET, 'default_language',          FILTER_SANITIZE_STRING);
    $dim_on_create        = filter_input(INPUT_GET, 'dim_on_create',             FILTER_SANITIZE_NUMBER_INT) == 1;
    $chk_f_rights         = filter_input(INPUT_GET, 'chk_files_rights',          FILTER_SANITIZE_NUMBER_INT) == 1;
    $max_hdd_temp         = filter_input(INPUT_GET, 'max_hdd_temp',              FILTER_SANITIZE_NUMBER_INT);
    $chk_hdd_temp_int     = filter_input(INPUT_GET, 'chk_temp_interval',         FILTER_SANITIZE_NUMBER_INT);
    $chk_smart_int        = filter_input(INPUT_GET, 'chk_smart_interval',        FILTER_SANITIZE_NUMBER_INT);
    $chk_users_online_int = filter_input(INPUT_GET, 'chk_users_online_interval', FILTER_SANITIZE_NUMBER_INT);

    $user_cfg->set_value('lang',                        $def_lang);
    $user_cfg->set_value('dim_on_create',               $dim_on_create);
    $user_cfg->set_value('check_files_rights',          $chk_f_rights);
    $user_cfg->set_value('max_hdd_temp',                $max_hdd_temp);
    $user_cfg->set_value('check_hdd_temp_interval',     $chk_hdd_temp_int);
    $user_cfg->set_value('check_smart_interval',        $chk_smart_int);
    $user_cfg->set_value('check_users_online_interval', $chk_users_online_int);

    $uc_saved = $user_cfg->save();
    
    /* Apps list */
    $enabled_apps = array();
    foreach ($_GET["app_caption"] as $item => $val) {
        if (isset($_GET["app_enabled"][$item]) && (bool)$_GET["app_enabled"][$item]) {
            $app_cap  = filter_var($_GET["app_caption"][$item], FILTER_SANITIZE_STRING);
            $app_name = filter_var($_GET["app_name"][$item],    FILTER_SANITIZE_STRING);
            $enabled_apps[$app_cap] = $app_name;
        }
    }
    $app = new \CAI\CAICP\Applications(CP_ROOT_REL);
    $app->set($enabled_apps);
    $apps_saved = $app->save();

    if ($uc_saved && $apps_saved) {
        echo 'true';
    } else {
        echo 'false';
    }
}
