<?php 

session_start();

$message = '';
$error = 'no';

if(!$_SESSION['login']){
	header("Location: login.php");
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
	
	$errorArray = array();
	$message = '';
	$error = 'no';
	
	$web_username= $_POST["web_username"];
	$web_password = $_POST["web_password"];
	$web_password_old = $_POST["web_password_old"];
	$web_password_confirm = $_POST["web_password_confirm"];
	$device_type = $_POST["device_type"];
	$server = $_POST["server"];
	$account_username= $_POST["account_username"];
	$account_password = $_POST["account_password"];
	$account_password_old = $_POST["account_password_old"];
	$account_password_confirm = $_POST["account_password_confirm"];
	$account_id = 'sip:'.$account_username.'@'.$server;
	$account_uri= 'sip:'.$server;
	$local_port = $_POST["local_port"];
	$emergency_all_call_ip = $_POST["emergency_all_call_ip"];
	$emergency_all_call_port = $_POST["emergency_all_call_port"];
	$emergency_all_call_volume = $_POST["emergency_all_call_volume"];
	$all_call_ip = $_POST["all_call_ip"];
	$all_call_port = $_POST["all_call_port"];
	$all_call_volume = $_POST["all_call_volume"];
	$audio_distribution_ip = $_POST["audio_distribution_ip"];
	$audio_distribution_port = $_POST["audio_distribution_port"];
	$audio_distribution_volume = $_POST["audio_distribution_volume"];
	$multicast_list = $_POST["multicast_list"];
	$multicast_indexes = $_POST["multicast_indexes"];
	$multicasts = $_POST["multicasts"];
	$additional_multicasts =$_POST["additional_multicasts"];
	$master_volume = $_POST["master_volume"];
	$vlan_id = $_POST["vlan_id"];
	$priority_802_1p = $_POST["priority_802_1p"];
	
	if (empty($_POST["web_username"])) {
    	$errorArray[] = "Web username is required.";
  	}
	if ($_POST["web_password"] != $_POST["web_password_confirm"]) {
		$errorArray[] = "Web passwords do not match.";
	}
	
	if($_SESSION['device_id']=='nq-voip' || $_SESSION['device_id']=='nq-s810v2' || $_SESSION['device_id']=='nq-wbc' || $_SESSION['device_id']=='nq-dsc01'){
		// check sip login fields for voip speaker

		if (empty($_POST["account_username"])) {
    	$errorArray[] = "Account username is required.";
  		}
		if ($_POST["account_password"] != $_POST["account_password_confirm"]) {
			$errorArray[] = "Account passwords do not match.";
		}
	}
	
	if (empty($_POST["server"])) {
    	$errorArray[] = "Server address is required.";
  	}
	if(!filter_var($_POST["server"], FILTER_VALIDATE_IP)) {
   		$errorArray[] = "Server address is not formatted as an IP Address.";
	}
	if ((!empty($_POST["local_port"]) && !is_numeric($_POST["local_port"])) || (!empty($_POST["local_port"]) && $_POST["local_port"]<1)) {
    	$errorArray[] = "Local port needs to be a positive integer.";
  	}
		
	if(count($errorArray)>0){
		
		$error = 'yes';
		
		// show error messages
		$message = '<div class="isa_error"><i class="fa fa-times-circle"></i><div class="message_content">';
		foreach($errorArray as $error){
			$message .= $error . '<br>';
		}
		$message .= '</div></div>';

		// load the multicasts
		$indexArray = explode(",", $multicast_indexes);
		$x=1;
		foreach($indexArray as $item){
			if($item>0){
				$ip = 'multicast_ip' . $item;
				$port = 'multicast_port' . $item;
				$volume = 'multicast_volume' . $item;
			 	$html .= '
						<tr>
							<td><strong>Multicast '.$item.':</strong></td>
							<td><input type="text" class="form-control" name="multicast_ip'.$item.'" placeholder="" style="width:100px;" value="'.$_POST[$ip].'"></td>
							<td><input type="text" class="form-control" name="multicast_port'.$item.'" placeholder="" style="width:100px;" value="'.$_POST[$port].'"></td>
							<td><input type="text" class="form-control" name="multicast_volume'.$item.'" placeholder="" style="width:100px;" value="'.$_POST[$volume].'"></td>
							<td>&nbsp;</td>
						</tr>';
			}
			$x++;
		}
		
	} else {
		
		// only update passwords if changed
		if(empty($_POST["account_password"]) && empty($_POST["account_password_confirm"])){
			
			$account_password = $account_password_old;
		}
		
		if(empty($_POST["web_password"]) && empty($_POST["web_password_confirm"])){
			
			$web_password = $web_password_old;
		}
		
		
			// read the current file
			$config_file = fopen("/etc/nyquist/SIP.config", "r");
			$config_file_array = array();
			if(!$config_file){
			  // show error message
			  $message = '<div class="isa_error"><i class="fa fa-times-circle"></i><div class="message_content">';
			  $message .= 'There was a problem reading the SIP Configuration file.';
			  $message .= '</div></div>';
			 } else { 
				// go through the config file one line at a time
				while(!feof($config_file)) {
					$line_text = fgets($config_file);
					array_push($config_file_array,$line_text  );
				}
				fclose($config_file);
			}
		    
			// search through rows and insert changes
			$edited_array = array();
			foreach($config_file_array as $key => $row){
				
				if(strpos($row, 'WEB_USERNAME =') !== FALSE){
					$new_row = 'WEB_USERNAME = '. $web_username . '' . PHP_EOL;
					array_push($edited_array, $new_row);
					
				} else if(strpos($row, 'WEB_PASSWORD =') !== FALSE){
					$new_row = 'WEB_PASSWORD = '. $web_password . '' . PHP_EOL;
					array_push($edited_array, $new_row);
				
				} else if(strpos($row, 'ACCOUNT_USERNAME =') !== FALSE){
					$new_row = 'ACCOUNT_USERNAME = '. $account_username. '' . PHP_EOL;
					array_push($edited_array, $new_row);
					
				} else if(strpos($row, 'ACCOUNT_PASSWORD =') !== FALSE){
					$new_row = 'ACCOUNT_PASSWORD = '. $account_password . '' . PHP_EOL;
					array_push($edited_array, $new_row);
					
				} else if(strpos($row, 'ACCOUNT_ID =') !== FALSE){
					$new_row = 'ACCOUNT_ID = '. $account_id . '' . PHP_EOL;
					array_push($edited_array, $new_row);
					
				} else if(strpos($row, 'ACCOUNT_REG_URI =') !== FALSE){
					$new_row = 'ACCOUNT_REG_URI = '. $account_uri . '' . PHP_EOL;
					array_push($edited_array, $new_row);
					
				} else if(strpos($row, 'LOCAL_PORT =') !== FALSE){
					$new_row = 'LOCAL_PORT = '. $local_port. '' . PHP_EOL;
					array_push($edited_array, $new_row);	
				} else {
					array_push($edited_array, $row);
				}
			}
		
			// create new file
			$new_config_file = '';
			foreach($edited_array as $row){
				$new_config_file .= $row;
			}
		
			// write the file
			$config_file = fopen("/etc/nyquist/SIP.config", "w");
			
			if(!$config_file){
				
				$error = 'yes';
				
				// show error message
				$message = '<div class="isa_error"><i class="fa fa-times-circle"></i><div class="message_content">';
				$message .= 'Save failed. There was a problem writing to the SIP Configuration file.';
				$message .= '</div></div>';
				
			} else {
				// complete write
				fwrite($config_file, $new_config_file);
				fclose($config_file);	
			}
	} 
	} else {
		
	  // set up the form variables
	  $web_username = '';
	  $web_password = '';
	  $web_password_confirm = '';
	  $device_type = '';
	  $account_id = '';
	  $account_uri = '';
	  $server = '';
	  $account_username = '';
	  $account_password = '';
	  $account_password_confirm = '';
	  $local_port = '';
	  $emergency_all_call = '';
	  $emergency_all_call_ip = '';
	  $emergency_all_call_port = '';
	  $emergency_all_call_volume = '';
	  $emergency_all_call_station_list = '';
	  $all_call = '';
	  $all_call_ip = '';
	  $all_call_port = '';
	  $all_call_volume = '';
	  $all_call_station_list = '';
	  $audio_distribution = '';
	  $audio_distribution_ip = '';
	  $audio_distribution_port = '';
	  $audio_distribution_volume = '';
	  $audio_distribution_station_list= '';
	  $multicast_list = '';
	  $multicasts = 0;
	  $multicast_indexes = '';
	  $additional_multicasts = 0;
	  $multicast_list_add = '';
	  $master_volume = 0;
	  $vlan_id = '';
	  $priority_802_1p = '';
	  $html = '';
	  $html2 = '';
	  $config_file_text = '';
	  $port_type = '';
	
	if($_SESSION['device_id']=='nq-asb'){ // Bridge Device Only
		for($x = 1; $x < 25; ++$x) {
			${'port_type_' .$x } ='';
			${'account_id_' .$x } ='';
			${'local_port_' .$x } ='';
			${'account_username_' .$x } ='';
			${'account_password_' .$x } ='';
			${'dcs_entries' .$x } ='';
			${'intercom_volume_' .$x } ='';
		}
	}
	
	if($_SESSION['device_id']=='nq-ga400p'){ // GA400P
		for($x = 1; $x < 3; ++$x) {
			${'port_type_' .$x } ='';
			${'account_id_' .$x } ='';
			${'local_port_' .$x } ='';
			${'account_username_' .$x } ='';
			${'account_password_' .$x } ='';
			${'dcs_entries' .$x } ='';
			${'intercom_volume_' .$x } ='';
		}
	}
	
	  // load config file and read in data
		  
	  $config_file = fopen("/etc/nyquist/SIP.config", "r");
	  
	  if(!$config_file){
		  // show error message
		  $message = '<div class="isa_error"><i class="fa fa-times-circle"></i><div class="message_content">';
		  $message .= 'There was a problem reading the SIP Configuration file.';
		  $message .= '</div></div>';
	  } else { 
	  	 // go through the config file one line at a time
		while(!feof($config_file)) {
			
			$line_text = fgets($config_file);
			
			if(strpos($line_text, 'WEB_USERNAME =') !== FALSE){
				$web_username = str_replace("WEB_USERNAME = ","",$line_text);
				$web_username = trim($web_username);
			}
			if(strpos($line_text, 'WEB_PASSWORD =') !== FALSE){
				$web_password = str_replace("WEB_PASSWORD = ","",$line_text);
				$web_password = trim($web_password);
				$web_password_confirm = $web_password;
			}
			if(strpos($line_text, 'DEVICE_TYPE =') !== FALSE){
				$device_type = str_replace("DEVICE_TYPE = ","",$line_text);
				$device_type = trim($device_type);
			} else {
				// grab the device_type name from the environmental variable if it's not in the config file
				$device_type = trim($_ENV['APPLIANCE_BOARD']);
				$device_type = str_replace('"','', $device_type);
			}
			if(strpos($line_text, 'ACCOUNT_ID =') !== FALSE){
				$account_id = str_replace("ACCOUNT_ID = ","",$line_text);
				$account_id = trim($account_id);
			}
			if(strpos($line_text, 'ACCOUNT_REG_URI =') !== FALSE){
				$account_uri = str_replace("ACCOUNT_REG_URI = ","",$line_text);
				$account_uri = trim($account_uri);
				
				$server = str_replace("ACCOUNT_REG_URI = ","",$line_text);
				$server = str_replace("sip:","",$server);
			}
			if(strpos($line_text, 'LOCAL_PORT =') !== FALSE){
				$local_port = str_replace("LOCAL_PORT = ","",$line_text);
				$local_port = trim($local_port);
			}
			if(strpos($line_text, 'ACCOUNT_USERNAME =') !== FALSE){
				$account_username = str_replace("ACCOUNT_USERNAME = ","",$line_text);
				$account_username = trim($account_username);
			}
			if(strpos($line_text, 'ACCOUNT_PASSWORD =') !== FALSE){
				$account_password = str_replace("ACCOUNT_PASSWORD = ","",$line_text);
				$account_password = trim($account_password);
				$account_password_confirm = $account_password;
			}
			if(strpos($line_text, 'MASTER_VOLUME =') !== FALSE){
				$master_volume = str_replace("MASTER_VOLUME = ","",$line_text);
				$master_volume = trim($master_volume);
			}
			if(strpos($line_text, 'VLAN_ID =') !== FALSE){
				$vlan_id = str_replace("VLAN_ID = ","",$line_text);
				$vlan_id = trim($vlan_id);
			}
			if(strpos($line_text, 'PRIORITY_802_1P =') !== FALSE){
				$priority_802_1p = str_replace("PRIORITY_802_1P = ","",$line_text);
				$priority_802_1p = trim($priority_802_1p);
			}
			if(strpos($line_text, 'PORT_TYPE =') !== FALSE){
				$port_type = str_replace("PORT_TYPE = ","",$line_text);
				$port_type = trim($port_type);
			}
			if(strpos($line_text, 'MULTICAST_E_ALL_CALL =') !== FALSE){
				$emergency_all_call = str_replace("MULTICAST_E_ALL_CALL = ","",$line_text);
				$emergency_all_call = trim($emergency_all_call);
				$emergency_all_call_array = explode(":", $emergency_all_call );
				if(count($emergency_all_call_array )>0){
					$emergency_all_call_ip = $emergency_all_call_array[0]; 
					$emergency_all_call_array2 = explode("[", $emergency_all_call_array[1]);
					$emergency_all_call_port = $emergency_all_call_array2[0]; 
					$emergency_all_call_array3 = explode("]", $emergency_all_call_array2[1]);
					$emergency_all_call_volume = $emergency_all_call_array3[0];
					$emergency_all_call_station_list = str_replace("{","",$emergency_all_call_array3[1]);
					$emergency_all_call_station_list = str_replace("}","",$emergency_all_call_station_list);
				}
			}
			if(strpos($line_text, 'MULTICAST_ALL_CALL =') !== FALSE){
				$all_call = str_replace("MULTICAST_ALL_CALL = ","",$line_text);
				$all_call = trim($all_call);
				$all_call_array = explode(":", $all_call );
				if(count($all_call_array )>0){
					$all_call_ip = $all_call_array[0]; 
					$all_call_array2 = explode("[", $all_call_array[1]);
					$all_call_port = $all_call_array2[0]; 
					$all_call_array3 = explode("]", $all_call_array2[1]);
					$all_call_volume = $all_call_array3[0];
					$all_call_station_list = str_replace("{","",$all_call_array3[1]);
					$all_call_station_list = str_replace("}","",$all_call_station_list);
				}
			}
			if(strpos($line_text, 'MULTICAST_AUDIO_DIST =') !== FALSE){
				$audio_distribution = str_replace("MULTICAST_AUDIO_DIST = ","",$line_text);
				$audio_distribution = trim($audio_distribution);
				$audio_distribution_array = explode(":", $audio_distribution );
				if(count($audio_distribution_array )>0){
					$audio_distribution_ip = $audio_distribution_array[0]; 
					$audio_distribution_array2 = explode("[", $audio_distribution_array[1]);
					$audio_distribution_port = $audio_distribution_array2[0]; 
					$audio_distribution_array3 = explode("]", $audio_distribution_array2[1]);
					$audio_distribution_volume = $audio_distribution_array3[0];
					$audio_distribution_station_list = str_replace("{","",$audio_distribution_array3[1]);
					$audio_distribution_station_list = str_replace("}","",$audio_distribution_station_list);
				}
			}
			if(strpos($line_text, 'MULTICAST_LIST =') !== FALSE){
				$multicast_list = str_replace("MULTICAST_LIST = ","",$line_text);
				$multicast_list = trim($multicast_list);
				$multicast_list = str_replace(";","",$multicast_list);
				$multicast_list_array = explode(",", $multicast_list);
				if(count($multicast_list_array)>0 && strlen($multicast_list)>0){
					$multicasts = count($multicast_list_array);
					$i = 1;
					foreach($multicast_list_array as $item){
						if($i>1){
							$multicast_indexes .= ',' . $i;
						} else {
							$multicast_indexes .= $i;
						}
						$item_array = explode(":", $item);
						$item_ip = $item_array[0];
						$item_array2 = explode("[", $item_array[1]);
						$item_port = $item_array2[0];
						$item_volume = str_replace("]","",$item_array2[1]);
						$item_volume = trim($item_volume);
						$html .= '
						<tr>
							<td><strong>Multicast '.$i.':</strong></td>
							<td><input type="text" class="form-control" name="multicast_ip'.$i.'" placeholder="" style="width:150px;" value="'.$item_ip.'" readonly></td>
							<td><input type="text" class="form-control" name="multicast_port'.$i.'" placeholder="" style="width:100px;" value="'.$item_port.'" readonly></td>
							<td><input type="text" class="form-control" name="multicast_volume'.$i.'" placeholder="" style="width:100px;" value="'.$item_volume.'" readonly></td>
							<td><input type="text" class="form-control" name="multicast_stations'.$i.'" placeholder="" style="width:450px;" value="1" readonly></td>
						</tr>';
						$i++;
					}
				}
			}
			
			if(in_array($_SESSION["device_id"],['nq-asb','nq-mix','nq-amp2c','nq-amp4c','nq-nqpaxxx','nq-amp2c-g2','nq-amp4c-g2','nq-ga400p'])){ // Bridge Device, Mixer, 2 Channel Amps, 4 Channel Amps, GA400P
				for($x = 1; $x < 25; ++$x) {
					
					if(strpos($line_text, 'MULTICAST_LIST_'.$x.' =') !== FALSE){
						
						$multicast_list = str_replace("MULTICAST_LIST_".$x." =","",$line_text);
						$multicast_list = trim($multicast_list);
						$explode1 = explode(":", $multicast_list);
						$item_ip = $explode1[0];
						$explode2 = explode("[", $explode1[1]);
						$item_port = $explode2[0];
						$explode3 = explode("]", $explode2[1]);
						$item_volume = $explode3[0];
						$item_stations = str_replace("{","",$explode3[1]);
						$item_stations = str_replace("}","",$item_stations);
						
						$html .= '
						<tr>
							<td><strong>Multicast '.$x.':</strong></td>
							<td><input type="text" class="form-control" name="multicast_ip'.$x.'" placeholder="" style="width:150px;" value="'.$item_ip.'" readonly></td>
							<td><input type="text" class="form-control" name="multicast_port'.$x.'" placeholder="" style="width:100px;" value="'.$item_port.'" readonly></td>
							<td><input type="text" class="form-control" name="multicast_volume'.$x.'" placeholder="" style="width:100px;" value="'.$item_volume.'" readonly></td>
							<td><input type="text" class="form-control" name="multicast_stations'.$x.'" placeholder="" style="width:450px;" value="'.$item_stations.'" readonly></td>
						</tr>';			
					}
				
					if(strpos($line_text, 'PORT_TYPE_'.$x.' =') !== FALSE){
						${'port_type_' .$x } = str_replace('PORT_TYPE_'.$x.' = ',"",$line_text);
						${'port_type_' .$x } = trim(${'port_type_' .$x });
					}
					if(strpos($line_text, 'ACCOUNT_ID_'.$x.' =') !== FALSE){
						${'account_id_' .$x } = str_replace('ACCOUNT_ID_'.$x.' = ',"",$line_text);
						${'account_id_' .$x } = trim(${'account_id_' .$x });
					}
					if(strpos($line_text, 'LOCAL_PORT_'.$x.' =') !== FALSE){
						${'local_port_' .$x }  = str_replace('LOCAL_PORT_'.$x.' = ',"",$line_text);
						${'local_port_' .$x } = trim(${'local_port_' .$x });
					}
					if(strpos($line_text, 'ACCOUNT_USERNAME_'.$x.' =') !== FALSE){
						${'account_username_' .$x }  = str_replace('ACCOUNT_USERNAME_'.$x.' = ',"",$line_text);
						${'account_username_' .$x } = trim(${'account_username_' .$x });
					}
					if(strpos($line_text, 'ACCOUNT_PASSWORD_'.$x.' =') !== FALSE){
						${'account_password_' .$x }  = str_replace('ACCOUNT_PASSWORD_'.$x.' = ',"",$line_text);
						${'account_password_' .$x } = trim(${'account_password_' .$x });
					}
					if(strpos($line_text, 'INTERCOM_VOLUME_'.$x.' =') !== FALSE){
						${'intercom_volume_' .$x }  = str_replace('INTERCOM_VOLUME_'.$x.' = ',"",$line_text);
						${'intercom_volume_' .$x } = trim(${'intercom_volume_' .$x });
					}
				}
			}
		}
		fclose($config_file);
		  
		  
	  if($_SESSION['device_id']=='nq-asb'){ // Bridge Device Only
		  	
		   // parse through xml data
			$filename = "/etc/nyquist/canconfig.xml";
		  
 			if(file_exists($filename)){
				
				$canconfig = fopen($filename, "r"); 
				
				$contents = fread ($canconfig, filesize ($filename)); 
				
				$dataArray = new SimpleXMLElement($contents);
				
				if($dataArray->Collection[0]){ // make sure the collection exists
					foreach($dataArray->Collection[0]->children() as $data){
					$port_number =  (string)$data->Member[0];
						$x=0;
						foreach($data->Collection->Class as $data2){
							$serial_number = (string)$data2->Member[0];
							$comma = '';
							if($x>0){
								$comma = ', ';
							}
							${'dcs_entries_' .$port_number } .= $comma . $serial_number;
							$x++;
						}
					}
				}
			}
		}
		  
		if(in_array($_SESSION["device_id"], ['nq-voip','nq-s810v2','nq-wbc','nq-ga10p','nq-ser20p2','nq-dsc01'])) {
					  	
		   // parse through xml data
			$filename = "/etc/nyquist/canconfig.xml";
		  
 			if(file_exists($filename) && filesize($filename)>0){
				
				$canconfig = fopen($filename, "r"); 
				
				$contents = fread ($canconfig, filesize ($filename)); 
				
				$dataArray = new SimpleXMLElement($contents);
				
				if($dataArray->Collection[0]){ // make sure the collection exists
					foreach($dataArray->Collection[0]->children() as $data){
						$port_number =  (string)$data->Member[0];
						$x1=0;
						$x6=0;
						foreach($data->Collection->Class as $data2){
							$serial_number = (string)$data2->Member[0];
							$device_number = (string)$data2->Member[1];
							$comma1 = '';
							$comma6 = '';
							if($x1>0){
								$comma1 = ', ';
							}
							if($x6>0){
								$comma6 = ', ';
							}
							if($device_number=='1'){
								${'dcs_serials'} .= $comma1 . $serial_number;
								$x1++;
							}
							if($device_number=='6'){
								${'vctrl_serials'} .= $comma6 . $serial_number;
								$x6++;
							}
							
						}
					}
				}
			}
		}
		  
		  
	  }
	}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="">
<meta name="author" content="Bogen Communications LLC">
<meta name="copyright" content="Bogen Communications LLC">
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
<link rel="shortcut icon" href="">
<link rel="stylesheet" href="/css/styles.css">
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css">
<link rel="icon" type="image/png" href="/favicon.png" />
<title><?php echo $_SESSION['device_type']; ?> (<?php echo $_SESSION['device_name']; ?>) - Configuration Settings</title>
</head>

<body>
<div class="container">

<?php include 'navbar.php';?>

<h4><strong><i class="fa fa-cogs"></i> Configuration Settings</strong>&nbsp;&nbsp;<a href="/help/<?php echo $_SESSION['device_id']; ?>/#t=<?php echo $_SESSION['help_configuration']; ?>" type="button" class="btn btn-xs btn-primary" target="_blank"><i class="fa fa-question-circle"></i></a></h4>
<button type="button" class="btn btn-xs btn-primary" style="margin-bottom:10px;" name="tftpButton" id="tftpButton" onclick="update_configuration()"><i class="fa fa-download"></i>&nbsp;&nbsp;Get Configuration From Server</button>
<div id="status"></div>
<form action="configuration.php" method="post">
<input type="hidden" name="account_id" value="<?php echo $account_id;?>">
<input type="hidden" name="account_uri" value="<?php echo $account_uri;?>">
<input type="hidden" name="reboot" value="yes">
<input type="hidden" name="multicast_list" id="multicast_list" value="<?php echo $multicast_list;?>">
<input type="hidden" name="multicast_list_add" id="multicast_list_add" value="<?php echo $multicast_list_add;?>">
<input type="hidden" name="multicasts" id="multicasts" value="<?php echo $multicasts;?>">
<input type="hidden" name="multicast_indexes" id="multicast_indexes" value="<?php echo $multicast_indexes;?>">
<input type="hidden" name="additional_multicasts" id="additional_multicasts" value="<? echo $additional_multicasts;?>">
<input type="hidden" name="master_volume" id="master_volume" value="<? echo $master_volume;?>">
<input type="hidden" name="vlan_id" id="vlan_id" value="<? echo $vlan_id;?>">
<input type="hidden" name="priority_802_1p" id="priority_802_1p" value="<? echo $priority_802_1p;?>">
<input type="hidden" name="account_password_old" id="account_password_old" value="<? echo $account_password;?>">
<input type="hidden" name="web_password_old" id="web_password_old" value="<? echo $web_password;?>">
<input type="hidden" name="bogen_default_password" id="bogen_default_password" value="<? echo $_SESSION['bogen_default_password']; ?>">	
	
<div id="message_container"><?php echo $message; ?></div>
<table id="config_table" class="table-condensed">
<tr>
<td><strong>Web Username:</strong></td>
<td><input type="text" class="form-control" name="web_username" placeholder="" style="width:200px;" value="<?php echo $web_username; ?>" readonly></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
<?php if(!in_array($_SESSION["device_id"], ['nq-io'])) {  // start  - do not show bottom table for IO Controller ?>
<table  class="table-condensed">
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<tr>
<td>&nbsp;</td>
<td><strong>IP Address</strong></td>
<td><strong>Port Number</strong></td>
<td><strong>Cut Level</strong></td>
<?php if(in_array($_SESSION["device_id"], ['nq-voip','nq-asb','nq-amp2c','nq-amp4c','nq-nqpaxxx','nq-amp2c-g2','nq-amp4c-g2','nq-mix','nq-s810v2','nq-wbc','nq-ga10p','nq-ga20p2','nq-ga400p','nq-ga40p3','nq-edp01','nq-ser20p2','nq-dsc01'])) {?>
<td><strong>Station List</strong></td>
<?php } ?>
</tr>
<tr>
<td><strong>Emergency-All-Call:</strong></td>
<td><input type="text" class="form-control" name="emergency_all_call_ip" placeholder="" style="width:150px;" value="<?php echo $emergency_all_call_ip; ?>" readonly></td>
<td><input type="text" class="form-control" name="emergency_all_call_port" placeholder="" style="width:100px;" value="<?php echo $emergency_all_call_port; ?>" readonly></td>
<td><input type="text" class="form-control" name="emergency_all_call_volume" placeholder="" style="width:100px;" value="<?php echo $emergency_all_call_volume; ?>" readonly></td>
<?php if(in_array($_SESSION["device_id"], ['nq-asb','nq-amp2c','nq-amp4c','nq-nqpaxxx','nq-amp2c-g2','nq-amp4c-g2','nq-ga400p'])) {?>
<td><input type="text" class="form-control" name="emergency_all_call_station_list" placeholder="" style="width:450px;" value="<?php echo $emergency_all_call_station_list; ?>" readonly></td>
<?php } ?>
<?php if(in_array($_SESSION["device_id"], ['nq-mix','nq-voip','nq-s810v2','nq-wbc','nq-ga10p','nq-ga20p2','nq-ga40p3','nq-edp01','nq-ser20p2','nq-dsc01'])) {?>
<td><input type="text" class="form-control" name="emergency_all_call_station_list" placeholder="" style="width:450px;" value="1" readonly></td>
<?php } ?>
</tr>
<tr>
<td><strong>All-Call:</strong></td>
<td><input type="text" class="form-control" name="all_call_ip" placeholder="" style="width:150px;" value="<?php echo $all_call_ip; ?>" readonly></td>
<td><input type="text" class="form-control" name="all_call_port" placeholder="" style="width:100px;" value="<?php echo $all_call_port; ?>" readonly></td>
<td><input type="text" class="form-control" name="all_call_volume" placeholder="" style="width:100px;" value="<?php echo $all_call_volume; ?>" readonly></td>
<?php if(in_array($_SESSION["device_id"], ['nq-asb','nq-amp2c','nq-amp4c','nq-nqpaxxx','nq-amp2c-g2','nq-amp4c-g2','nq-ga400p'])) {?>
<td><input type="text" class="form-control" name="all_call_station_list" placeholder="" style="width:450px;" value="<?php echo $all_call_station_list; ?>" readonly></td>
<?php } ?>
<?php if(in_array($_SESSION["device_id"], ['nq-mix','nq-voip','nq-s810v2','nq-wbc','nq-ga10p','nq-ga20p2','nq-ga40p3','nq-edp01','nq-ser20p2','nq-dsc01'])) {?>
<td><input type="text" class="form-control" name="all_call_station_list" placeholder="" style="width:450px;" value="1" readonly></td>
<?php } ?>
</tr>
<tr>
<td><strong>Audio Distribution:</strong></td>
<td><input type="text" class="form-control" name="audio_distribution_ip" placeholder="" style="width:150px;" value="<?php echo $audio_distribution_ip; ?>" readonly></td>
<td><input type="text" class="form-control" name="audio_distribution_port" placeholder="" style="width:100px;" value="<?php echo $audio_distribution_port; ?>" readonly></td>
<td><input type="text" class="form-control" name="audio_distribution_volume" placeholder="" style="width:100px;" value="<?php echo $audio_distribution_volume; ?>" readonly></td>
<?php if(in_array($_SESSION["device_id"], ['nq-asb','nq-amp2c','nq-amp4c','nq-nqpaxxx','nq-amp2c-g2','nq-amp4c-g2','nq-ga400p'])) {?>
<td><input type="text" class="form-control" name="audio_distribution_station_list" placeholder="" style="width:450px;" value="<?php echo $audio_distribution_station_list; ?>" readonly></td>
<?php } ?>
<?php if(in_array($_SESSION["device_id"], ['nq-mix','nq-voip','nq-s810v2','nq-wbc','nq-ga10p','nq-ga20p2','nq-ga40p3','nq-edp01','nq-ser20p2','nq-dsc01'])) {?>
<td><input type="text" class="form-control" name="audio_distribution_station_list" placeholder="" style="width:450px;" value="1" readonly></td>
<?php } ?>
</tr>

<?php echo $html;?>
<span id="html2"></span>

</table><br>
<?php } // end  - do not show bottom table for IO Controller ?>
</form>
	
<h4><strong>Nyquist Control Password</strong></h4>
<input type="password" class="form-control" id="mqtt_password" name="mqtt_password" placeholder="" style="width:200px;" value="" maxlength="20">
<button type="button" class="btn btn-xs btn-success" style="margin-top:10px;margin-bottom:10px;" name="mqttBumqttSaveButtontton" id="mqttSaveButton" onclick="save_mqtt_password()"><i class="fa fa-save"></i>&nbsp;&nbsp;Save Password</button> <span id="nyquist_control_password_text"></span>
	
<?php if(in_array($_SESSION["device_id"], ['nq-asb','nq-amp2c','nq-amp4c','nq-nqpaxxx','nq-amp2c-g2','nq-amp4c-g2','nq-mix','nq-voip','nq-s810v2','nq-wbc','nq-ga10p','nq-io','nq-ga20p2','nq-ga400p','nq-ga40p3','nq-edp01','nq-ser20p2','nq-dsc01'])) {?>
		
<h4><strong>Device Stations</strong></h4>
<table class="table-condensed">
<tr>
<td><strong>Port Number</strong></td>
<td><strong>Port Type</strong></td>
<td><strong>Account Id</strong></td>
<td><strong>Local Port</strong></td>
<td><strong>Username</strong></td>
<?php if($_SESSION["device_id"]=='nq-asb'){ ?>
<td><strong>Intercom<br>Cut Level (dB)</strong></td>
<td><strong>Digital Call Switches&nbsp;&nbsp;<a href="dcs.php"  type="button" class="btn btn-xs btn-primary"><i class="fa fa-cogs"></i>&nbsp;&nbsp;Manage</a></strong></td>
<?php } ?>
	</tr>
<?php 
$device_rows_limit = 25;																   
if($_SESSION["device_id"]=='nq-amp2c' || $_SESSION["device_id"]=='nq-amp2c-g2'){$device_rows_limit = 3; }
if($_SESSION["device_id"]=='nq-amp4c' || $_SESSION["device_id"]=='nq-amp4c-g2'){$device_rows_limit = 5; }
if($_SESSION["device_id"]=='nq-nqpaxxx'){$device_rows_limit = 3; } 
if($_SESSION["device_id"]=='nq-mix'){
	$device_rows_limit = 2; 
	$port_type_1 = 'Matrix Mixer Pre-Amp';
	$account_id_1 = $account_id;
	$local_port_1 = $local_port;
	$account_username_1 = $account_username;
} 
if($_SESSION["device_id"]=='nq-io'){
	$device_rows_limit = 2; 
	$port_type_1 = 'I/O Controller';
	$account_id_1 = $account_id;
	$local_port_1 = $local_port;
	$account_username_1 = $account_username;
} 
if(in_array($_SESSION["device_id"], ['nq-ga20p2','nq-ga40p3','nq-ser20p2'])) {
	$device_rows_limit = 2; 
	$port_type_1 = 'Paging-Audio Amp';
	$account_id_1 = $account_id;
	$local_port_1 = $local_port;
	$account_username_1 = $account_username;
} 
if(in_array($_SESSION["device_id"], ['nq-voip','nq-s810v2','nq-wbc','nq-ga10p','nq-edp01','nq-dsc01'])) {
	$device_rows_limit = 2; 
	$port_type_1 = $port_type;
	$account_id_1 = $account_id;
	$local_port_1 = $local_port;
	$account_username_1 = $account_username;
}
if($_SESSION["device_id"]=='nq-ga400p'){$device_rows_limit = 3;}
?>
	

<?php for($x = 1; $x < $device_rows_limit; ++$x) { ?>
	<tr>
	<td><input type="text" class="form-control" name="audio_distribution_volume" placeholder="" style="width:50px;" value="<?php echo $x ?>" readonly></td>
	<td><input type="text" class="form-control" name="audio_distribution_volume" placeholder="" style="width:300px;" value="<?php echo ${'port_type_' .$x } ?>" readonly></td>
	<td><input type="text" class="form-control" name="audio_distribution_volume" placeholder="" style="width:200px;" value="<?php echo ${'account_id_' .$x } ?>" readonly></td>
	<td><input type="text" class="form-control" name="audio_distribution_volume" placeholder="" style="width:100px;" value="<?php echo ${'local_port_' .$x } ?>" readonly></td>
	<td><input type="text" class="form-control" name="audio_distribution_volume" placeholder="" style="width:200px;" value="<?php echo ${'account_username_' .$x } ?>" readonly></td>
	<?php if($_SESSION["device_id"]=='nq-asb'){ ?>
	<td><input type="text" class="form-control" name="audio_distribution_volume" placeholder="" style="width:100px;" value="<?php echo ${'intercom_volume_' .$x } ?>" readonly></td>
	<td><input type="text" class="form-control" name="audio_distribution_volume" placeholder="" style="width:400px;" value="<?php echo ${'dcs_entries_' .$x } ?>" readonly></td>
	<?php } ?>
	</tr>
	
<?php } ?>
</table>
<?php } ?>
	
<?php if(in_array($_SESSION["device_id"], ['nq-voip','nq-s810v2','nq-wbc','nq-ga10p','nq-ser20p2','nq-dsc01'])) {?>
<table class="table-condensed" width="100%">
	<tr>
		<td><strong>Digital Call Switches</strong></td>
	</tr>
	<tr>
		<td><input type="text" class="form-control" id="dcs" name="dcs" placeholder="" style="width:85%;" value="<?php echo ${'dcs_serials'} ?>" readonly></td>
	</tr>
</table>
<table class="table-condensed" width="100%">
	<tr>
		<td><strong>Volume Control Switches</strong></td>
	</tr>
	<tr>
		<td><input type="text" class="form-control" id="vctrl" name="vctrl" placeholder="" style="width:85%;" value="<?php echo ${'vctrl_serials'} ?>" readonly></td>
	</tr>
</table>
<?php } ?>
<br><br><br><br>
</div>
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/bootstrap-growl.min.js"></script>
</body>
</html>
<script>

// run on page load
var reboot = '<?php echo $_POST["reboot"]; ?>';
var error = '<?php echo $error; ?>';

if(reboot=='yes' && error=='no'){
	
	// show message
	document.getElementById("message_container").innerHTML = '<div class="isa_success"><i class="fa fa-check"></i><div class="message_content"> Configuration settings saved.<br>Appliance application is restarting.<br></div></div>';
	
	var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				//alert(xmlhttp.responseText);
				
				window.location.href = 'configuration.php';
        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=restart_application",true);
   		xmlhttp.send();
}

function update_configuration(){
	
	document.getElementById("status").innerHTML = '<i class="fa fa-refresh fa-spin fa-fw"></i> <strong>Processing ... </strong>';
	
	var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				//alert(xmlhttp.responseText);
				
				//document.getElementById("status").innerHTML = '';
				//document.getElementById("message_container").innerHTML = '<div class="isa_success"><i class="fa fa-check"></i><div class="message_content">' + xmlhttp.responseText + '<br></div></div>';
				
			 	// clear message after 10 seconds
				//setTimeout(function(){ 
					//document.getElementById("message_container").innerHTML = '';
				//}, 10000);
				
				window.location.href = 'configuration.php';
				
        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=update_configuration",true);
   		xmlhttp.send();
}

function add_multicast(){
	
	var multicasts = document.getElementById('multicasts').value;
	var additional_multicasts = document.getElementById('additional_multicasts').value;
	var multicasts_new = +multicasts +1;
	var next_row = +multicasts + 14;
	var multicast_indexes = document.getElementById('multicast_indexes').value;
	
	var x=document.getElementById('config_table').insertRow(next_row);
    var c1=x.insertCell(0);
    var c2=x.insertCell(1);
	var c3=x.insertCell(2);
	var c4=x.insertCell(3);
    c1.innerHTML='<strong>Multicast ' + multicasts_new + ':</strong>';
    c2.innerHTML='<input type="text" class="form-control" name="multicast_ip' + multicasts_new + '" placeholder="" style="width:100px;" value="" readonly>';
	c3.innerHTML='<input type="text" class="form-control" name="multicast_port' + multicasts_new + '" placeholder="" style="width:100px;" value="" readonly>';
	c4.innerHTML='<input type="text" class="form-control" name="multicast_volume' + multicasts_new + '" placeholder="" style="width:100px;" value="" readonly>';
	
	// increment multicasts
	document.getElementById('multicasts').value = multicasts_new;
	document.getElementById('additional_multicasts').value = +additional_multicasts + 1;
	document.getElementById('multicast_indexes').value = multicast_indexes + ',' + multicasts_new;
}

function delete_multicast(row){
	
	var multicast_indexes = document.getElementById('multicast_indexes');
	var indexArray = multicast_indexes.value.split(",");
	indexArray.splice(+row-14,1);
	
	var index_string = indexArray.toString();
	
	document.getElementById('multicast_indexes').value = index_string;

	var delete_row = row;
	var multicasts = document.getElementById('multicasts').value;
	document.getElementById("config_table").deleteRow(delete_row);
	var new_multicasts = +multicasts - 1;
	document.getElementById('multicasts').value = new_multicasts;
}
function save_mqtt_password(){
	
	var mqtt_password = document.getElementById('mqtt_password').value;
	var match1 = mqtt_password.match(/^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z]).{20,}$/);
	var match2 = mqtt_password.match(/^[a-zA-Z0-9]+$/);
	var bogen_default_password = document.getElementById('bogen_default_password').value;
	
	if(bogen_default_password=='1'){
	   // send growl notification
        $.bootstrapGrowl("You can not update or display the saved Nyquist Control Password while the web interface password is still set to the default password.", {
          ele: 'body', // which element to append to
          type: 'danger', // (null, 'info', 'error', 'success')
          offset: {from: 'top', amount: 50}, // 'top', or 'bottom'
          align: 'right', // ('left', 'right', or 'center')
          width: 350, // (integer, or 'auto')
          delay: 10000,
          allow_dismiss: true,
          stackup_spacing: 10 // spacing between consecutively stacked growls.
        });
	} else if(mqtt_password.length<20){
	   // send growl notification
        $.bootstrapGrowl("The Nyquist Control Password must be 20 characters long.", {
          ele: 'body', // which element to append to
          type: 'danger', // (null, 'info', 'error', 'success')
          offset: {from: 'top', amount: 50}, // 'top', or 'bottom'
          align: 'right', // ('left', 'right', or 'center')
          width: 350, // (integer, or 'auto')
          delay: 10000,
          allow_dismiss: true,
          stackup_spacing: 10 // spacing between consecutively stacked growls.
        });
	   
	} else if(match1 && match2){
		
		// clear password field
		document.getElementById('mqtt_password').value = '';
		
			// ajax action to call api so screen does not refresh
            var xmlhttp=new XMLHttpRequest();
            xmlhttp.onreadystatechange=function() {
                if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                    // success 
                    // console.log(xmlhttp.responseText);
					if(xmlhttp.responseText=='1'){
					   	// send growl notification
                        $.bootstrapGrowl("Nyquist Control Password Saved.", {
                          ele: 'body', // which element to append to
                          type: 'success', // (null, 'info', 'error', 'success')
                          offset: {from: 'top', amount: 50}, // 'top', or 'bottom'
                          align: 'right', // ('left', 'right', or 'center')
                          width: 350, // (integer, or 'auto')
                          delay: 10000,
                          allow_dismiss: true,
                          stackup_spacing: 10 // spacing between consecutively stacked growls.
                        });	  	
					}
                }
            }
            xmlhttp.open("GET","/scripts.php?s=save_mqtt_password&p=" + mqtt_password,true);
            xmlhttp.send();	
			  
	} else {
		// send growl notification
        $.bootstrapGrowl("The Nyquist Control Password must include a combination of upper case, lower case, and numbers. No special characters allowed.", {
          ele: 'body', // which element to append to
          type: 'danger', // (null, 'info', 'error', 'success')
          offset: {from: 'top', amount: 50}, // 'top', or 'bottom'
          align: 'right', // ('left', 'right', or 'center')
          width: 350, // (integer, or 'auto')
          delay: 10000,
          allow_dismiss: true,
          stackup_spacing: 10 // spacing between consecutively stacked growls.
        });	  	  
	}
	
}
	
// clear message after 10 seconds
setTimeout(function(){ 
	document.getElementById("message_container").innerHTML = '';
}, 10000);

</script>
