<?php


/**
 * file: insight_json_settings.php
 *
 * Copyright Miller Electric Mfg. Co. as an unpublished work.
 * All rights reserved.
 *
 * The information contained herein is confidential property of
 * Miller Electric Mfg. Co.  The use of, copying, transfer or
 * disclosure of such information is prohibited except by express
 * written agreement with Miller Electric.
 */


session_start();


require_once('../lib/user_authentication.php');
require_once('../lib/utility.php');


if(!UserAuthentication::isUserLoggedIn()) {
	navigateToLoginPage();
}


$filePath = "/Insight/settings.json";
$settingsSavedResult = 0;
$insightApp = "InsightApp";

// Json keys.
$centerpoint = "Centerpoint";
$core = "Core";
// $externalIOApp = "ExternalIOApp";

// Json values.
// $externalIOAppValues = array(
//     "NONE",
//     "EIP",
//     "ADAM"
// );

// This array contains the keys that the settings.json file should contain.
$settingsJson = array(
    $centerpoint => 0,
    $core => 1
    // $externalIOApp => $externalIOAppValues[0]
);


// Utility functions.
/**
 * A function that maps values of a checkbox html element to integer values.
 * @param string $in Either on or off.
 * @return int 1 if $in is on, otherwise 0.
 */
$mapCheckBoxValueToInts = fn($in) => ($in == "on" ? 1 : 0);


/**
 * A function that returns the string if both values are equal (using == operator).
 * @param mixed $value1 The first value to use in the comparison. 
 * @param mixed $value2 The second value to use in the comparison. 
 * @param string $string The string to return if both values are equal.
 * @return string $string if both values are equal, otherwise the empty string. 
 */
$mapEqualsToString = fn($value1, $value2, $string) => ($value1 == $value2 ? $string : "");


$mapButtonDefaultOrWarningClassToInts = fn($in) => ($in == 1 ? "btn btn-warning" : "btn btn-default");


/**
 * Builds the associative array that is to contain the settings.json settings.
 * After this function is called, $settingsJson should contain the settings
 * that are inside the settings.json file.
 * If settings.json doesn't exist, create it with the default settings 
 * (Core enabled).
 */
function buildSettingsJsonData() {
    global $settingsJson;
    global $filePath;

	if (!file_exists($filePath)) {
		$jsonDataPut = json_encode($settingsJson, JSON_PRETTY_PRINT);
		file_put_contents($filePath, $jsonDataPut);
	}

    $json = file_get_contents($filePath);
    $jsonData = json_decode($json, true);
	if ($jsonData != null && $jsonData != false) {
		// Replace default values as defined in this file with the actual values from settings.json.
		$settingsJson = array_merge($settingsJson, $jsonData);
	}
}


/**
 * Builds the html form for editing the settings.json file.
 */
function buildForm() {
    global $settingsJson;
	global $insightApp;
    global $centerpoint;
    global $core;
    // global $externalIOApp;
    // global $externalIOAppValues;
    global $mapEqualsToString;
	global $mapButtonDefaultOrWarningClassToInts;

    $checkedFunction = fn($value) => $mapEqualsToString($value, 1, "checked");
    $selectedFunction = fn($value1, $value2) => $mapEqualsToString($value1, $value2, "selected");

    // $externalIOAppValue = $settingsJson[$externalIOApp];
    
    ?>
		<label for="insightappradiogroup"><h3>Enable Insight App:</h3></label>
		<fieldset id="insightappradiogroup">
			<div class="btn-group">
				<div class="btn-group btn-toggle" data-toggle="buttons">
					<label label-default="" class="<?php echo $mapButtonDefaultOrWarningClassToInts($settingsJson[$centerpoint]); ?>" id="<?php echo $centerpoint ?>" onclick="onInsightAppSelectionChanged('<?php echo $centerpoint ?>');">
					<?php echo $centerpoint ?>
					</label>
					<input type="radio" id="<?php echo "radio$centerpoint"; ?>" name="<?php echo $insightApp ?>" value="<?php echo $centerpoint ?>" <?php echo $checkedFunction($settingsJson[$centerpoint]); ?> style="opacity: 0.0"  >
					<label label-default="" class="<?php echo $mapButtonDefaultOrWarningClassToInts($settingsJson[$core]); ?>" id="<?php echo $core ?>" onclick="onInsightAppSelectionChanged('<?php echo $core ?>');">
					<?php echo $core ?>
					</label>
					<input type="radio" id="<?php echo "radio$core"; ?>" name="<?php echo $insightApp ?>" value="<?php echo $core ?>" <?php echo $checkedFunction($settingsJson[$core]); ?> style="opacity: 0.0" >
				</div>
			</div>
		</fieldset>
    <?php
}


/**
 * Writes the settings contained in $settingsJson array to settings.json file.
 */
function writeSettingsToJsonFile() {
    global $settingsJson;
    global $filePath;
	global $settingsSavedResult;
    $stringData = json_encode($settingsJson, JSON_PRETTY_PRINT);
    $settingsSavedResult = file_put_contents($filePath, $stringData);
}


/**
 * Validates the given data, returning it free of white space, slashes, and
 * html injection.
 * @param mixed $data The data to validate.
 * @return mixed The validated data.
 */
function validate($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}


// First function call in this file.
buildSettingsJsonData();


// Process the form data on submission.
if(isset($_POST['submit'])) {
	// print_r($_POST);
	if(array_key_exists($insightApp, $_POST)) {
        $settingsJson[validate($_POST[$insightApp])] = 1;

		if($_POST[$insightApp] != $centerpoint) {
			$settingsJson[$centerpoint] = 0;
		}

		if($_POST[$insightApp] != $core) {
			$settingsJson[$core] = 0;
		}
    }

    // if(array_key_exists($centerpoint, $_POST)) {
    //     $settingsJson[$centerpoint] = $mapCheckBoxValueToInts(validate($_POST[$centerpoint]));
    // } else {
    //     $settingsJson[$centerpoint] = 0;
    // }
    
    // if(array_key_exists($core, $_POST)) {
    //     $settingsJson[$core] = $mapCheckBoxValueToInts(validate($_POST[$core]));
    // } else {
    //     $settingsJson[$core] = 0;
    // }

    // if(array_key_exists($externalIOApp, $_POST)) {
    //     $settingsJson[$externalIOApp] = validate($_POST[$externalIOApp]);
    // } else {
    //     $settingsJson[$externalIOApp] = "";
    // }

    writeSettingsToJsonFile();
}


?>


<html lang="en">
	<script type="text/javascript" >
		function onInsightAppSelectionChanged(selection) {
			console.log(selection);

			let core_button = document.getElementById("Core");
			let centerpoint_button = document.getElementById("Centerpoint");
			let core_radio = document.getElementById("radioCore");
			let centerpoint_radio = document.getElementById("radioCenterpoint");
			console.log(core_radio);
			console.log(centerpoint_radio);

			if(selection == "Core")
			{
				centerpoint_button.classList.remove("btn-warning");
				centerpoint_button.classList.add("btn-default");
				core_button.classList.remove("btn-default");
				core_button.classList.add("btn-warning");
				core_radio.checked = true;
				centerpoint_radio.checked = false;
			}
			else
			{
				core_button.classList.remove("btn-warning");
				core_button.classList.add("btn-default");
				centerpoint_button.classList.remove("btn-default");
				centerpoint_button.classList.add("btn-warning");
				centerpoint_radio.checked = true;
				core_radio.checked = false;
			}

			console.log("after");
			console.log(core_radio);
			console.log(centerpoint_radio);
		}
	</script> 
    <?php require('head.php'); ?>
    <body>
        <div class="container">
            <div class="panel panel-primary">
				<div class="panel-body">
					<?php require('navbar_header.php'); ?>
					<div class="panel panel-primary">
						<div class="panel-heading">
							<h3 id="insight_json_header" class="panel-title"><span class="glyphicon glyphicon-cog"></span>Insight Setup</h3>
						</div>
						<div class="panel-body">
							<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" id="form">
							<?php buildForm(); ?>
								<ul class="pager">
									<li class="edit">
										<a href="#" onclick="document.getElementById('submit').click();">
											Save<span class="glyphicon glyphicon-save"></span>
										</a>
									</li>
								</ul>
								<input type="submit" name="submit" id="submit" hidden />
							</form>
							<div>
								<?php
									if(isset($_POST['submit'])) {
										if($settingsSavedResult != false && $settingsSavedResult > 0) {
											echo "Settings saved.";
										} else {
											echo "Something went wrong.";
										}
									}
								?>
							</div>
						</div>
                    </div>
                </div>
				<?php require('footer.php'); ?>
            </div>
        </div>
    </body>
    <?php require('js_footer.php'); ?>
</html>