<?php 

session_start();

$message = '';

if(!$_SESSION['login']){
	header("Location: login.php");
}
if($_SESSION['device_id']!='nq-asb'){
	header("Location: index.php");
}

$portsArray = array();
$dcsArray = array();
$availableArray = array();
$key = array();
$dcsPortNumbers = array();

// load SIP 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);

		for($x = 1; $x < 25; ++$x) {
				
			if(strpos($line_text, 'PORT_TYPE_'.$x.' =') !== FALSE){
				$port_type  = str_replace('PORT_TYPE_'.$x.' = ',"",$line_text);
				$port_type = trim($port_type);
				if($port_type=='Digital-Call-Switch-With-Speaker'){
					array_push($dcsPortNumbers,$x);
				}
			}	

			if(strpos($line_text, 'ACCOUNT_USERNAME_'.$x.' =') !== FALSE){
				$account_username  = str_replace('ACCOUNT_USERNAME_'.$x.' = ',"",$line_text);
				$account_username = trim($account_username);
				$newArray = array();
				if(in_array($x, $dcsPortNumbers)){  
					$newArray = array($x => $account_username);
				}
				
				$portsArray =  $portsArray + $newArray;
			}	
		}
	}
	fclose($config_file);
}

// load canconfig file and read in data
$filename = "/etc/nyquist/canconfig.xml";


if(file_exists($filename)){
				
	$canconfig = fopen($filename , "r"); 

	$contents = fread ($canconfig , filesize ($filename)); 

	$dataArray = new SimpleXMLElement($contents);

	
	// get assigned serial numbers
	if($dataArray->Collection[0]){ // make sure the collection exists
		foreach($dataArray->Collection[0]->children() as $data){
		$port_number =  (string)$data->Member[0];
			foreach($data->Collection->Class as $data2){
			
				$serial_number = (string)$data2->Member[0];
				$device_number = (string)$data2->Member[1];
				
				if($serial_number!=''){
					array_push($dcsArray, array($serial_number,$device_number,$port_number));
				}
			}
		}
	}
	
	// get available serial numbers
	if($dataArray->Collection[1]){ // make sure the collection exists
		foreach($dataArray->Collection[1]->children() as $data){

			$serial_number = (string)$data->Member[0];
			$device_number = (string)$data->Member[1];
			array_push($availableArray, array($serial_number,$device_number));
		}			
	}
	
	fclose ($canconfig);
}

sort($availableArray);
asort($portsArray);

if(count($portsArray)>0){ 
	$keys = array_keys($portsArray);
} 

  if($_SESSION['saved']=='yes'){
	  $message = '<div class="isa_success"><i class="fa fa-check"></i><div class="message_content">';
	  $message .='Digital Call Switch Management saved.<br>';
	  $message .= '</div></div>';
  }
  
  $_SESSION['saved'] = ''; // reset

?>

<!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 / Digital Call Switch Management</title>
</head>

<body>
<div class="container">

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

<h4><strong><i class="fa fa-cogs"></i> Configuration Settings / Digital Call Switch Management</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>

<div id="status"></div>
<div id="message_container"><?php echo $message; ?></div>
	
<input name="dcsArray" id="dcsArray" type="hidden" value='<?php echo json_encode($dcsArray); ?>'>
<input name="availableArray" id="availableArray" type="hidden" value='<?php echo json_encode($availableArray); ?>'>	
<input name="keysArray" id="keysArray" type="hidden" value='<?php echo json_encode($keys); ?>'>	
		
<h4>Manage ports:</h4>
<div class="row">
        <div class="col-md-4">
        <strong>Available Digital Call Switches</strong>
         <div id="source" class="list-group source">
			 <?php foreach($availableArray as $available){ ?>
			 	<div class="list-group-item move-handle cursor_move" data-id="<?php echo $available[0];?>" data-id2="<?php echo $available[1];?>">
					<span aria-hidden="true"></span><i class="fa fa-arrows"></i>&nbsp;&nbsp;&nbsp;<?php echo $available[0]; ?>
				</div>
			 <?php } ?>
         </div>
        </div>
         <div class="col-md-4">
		<?php if(count($portsArray)==0){ echo '<strong>No ports available</strong>'; } ?>
		<?php foreach($portsArray as $port_number => $extension){?>
			<strong>Port<?php echo $port_number;?> (<?php echo $extension;?>)</strong>
          <div id="port<?php echo $port_number;?>" class="list-group port">
                <?php foreach($dcsArray as $dcs){?>
			    <?php if($dcs[2]==$port_number){ ?>
						<div class="list-group-item move-handle cursor_move" data-id="<?php echo $dcs[0];?>" data-id2="<?php echo $dcs[1];?>">
							<span aria-hidden="true"></span><i class="fa fa-arrows"></i>&nbsp;&nbsp;&nbsp;<?php echo $dcs[0]; ?>
						</div>
			 	<?php } ?>
			 <?php } ?>
  			</div>
		<?php } ?>
        </div>
</div>
<button class="btn btn-xs btn-success" type="button" onClick="save_config_changes()"><i class="fa fa-floppy-o"></i>&nbsp;&nbsp;Save All Changes</button><br>
*Manage all the digital call swtiches on all ports then save once when done.
<br><br><br><br>
</div>
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/Sortable.min.js"></script>
</body>
</html>
<script>
$(document).ready(function() { // start ready function
	
	
}); // end ready function

	// Audio File Lists
var sortable_source = Sortable.create(source, {
		handle: '.move-handle',
  		animation: 150,
		sort: true,
		ghostClass: 'ghost',
		dataIdAttr: 'data-id',
		group: {
    		name: 'group1',
   		 	put: ['port1','port2','port3'],
  		},
		onUpdate: function (evt) {
			//console.log('onUpdate');
    	},
		onAdd: function (evt) {
			//console.log('onAdd');
			var itemEl = evt.item;  // dragged HTMLElement
			var serial_number = itemEl.getAttribute('data-id');
			var device_number = itemEl.getAttribute('data-id2');
			
			edit_xml('add_source',serial_number, device_number, '');
		},
		onRemove: function (evt) {
			//console.log('onRemove');
			var itemEl = evt.item;  // dragged HTMLElement
			var serial_number = itemEl.getAttribute('data-id');
			var device_number = itemEl.getAttribute('data-id2');
			
			edit_xml('remove_source',serial_number, device_number, '');
    	},
});
	
<?php foreach($portsArray as $number => $extension){?>
	
var sortable_port = Sortable.create(port<?php echo $number;?>, {
  		handle: '.move-handle',
  		animation: 150,
		sort: true,
		ghostClass: 'ghost',
		group: {
    		name: 'group1',
   		 	put: ['source','port1','port2','port3'],
  		},
		onUpdate: function (evt) {
			//console.log('onUpdate');
    	},
		onAdd: function (evt) {
			//console.log('onAdd');
			var itemEl = evt.item;  // dragged HTMLElement
			var serial_number = itemEl.getAttribute('data-id');
			var device_number = itemEl.getAttribute('data-id2');
			var port_number = '<?php echo $number;?>';
			
			edit_xml('add_port',serial_number, device_number, port_number);
		},
		onRemove: function (evt) {
			//console.log('onRemove');
			var itemEl = evt.item;  // dragged HTMLElement
			var serial_number = itemEl.getAttribute('data-id');
			var device_number = itemEl.getAttribute('data-id2');
			var port_number = '<?php echo $number;?>';
			
			edit_xml('remove_port',serial_number, device_number, port_number);
    	},
	}); 
<?php } ?>
// portData drop down
$(".port-action").click(function(){
	$(this).parents(".port-btn").find('.selection').text($(this).text());
	$(this).parents(".port-btn").find('.selection').val($(this).data('value'));
	document.getElementById("port_number").value = $(this).data('value');
	document.getElementById("port_name").value = $(this).text();
	document.getElementById("port_display_name").innerHTML = $(this).text();
	
	choose_port($(this).data('value'));
	
	$('.open').removeClass('open');
	return false;
});
	
function choose_port(port){
	
	document.getElementById("port_number").value = port;
	var dcsArray = JSON.parse(document.getElementById("dcsArray").value);
	if(dcsArray[port]){
	    var length = dcsArray[port].length;
		var html = '';

		for (var i=0; i< length; i++) {
			html += '<div class="list-group-item move-handle cursor_move" data-id="'+ dcsArray[port][i] +'"><span aria-hidden="true"></span><i class="fa fa-arrows"></i>&nbsp;&nbsp;&nbsp;'+ dcsArray[port][i] +'</div>';
		}
		document.getElementById("port").innerHTML = html;
	 }	else {
		 document.getElementById("port").innerHTML = '';
	 }	
}
function edit_xml(action,serial_number, device_number, port_number){
		
	var dcsArray = JSON.parse(document.getElementById("dcsArray").value);
	var availableArray = JSON.parse(document.getElementById("availableArray").value);
	
	if(action=='add_port'){
		// add to port
		  dcsArray.push([serial_number,device_number,port_number]);
	 }
	 if(action=='remove_port'){
		// remove from port
		 for(var i = 0; i < dcsArray.length; i++){
			 if(dcsArray[i]){
                 if(serial_number == dcsArray[i][0] && port_number==dcsArray[i][2]){
                    dcsArray.splice(i, 1);
                 }
			 }
		 }
	 }
	if(action=='add_source'){
		 // add to available
		availableArray.push([serial_number,device_number]);
	 }
	 if(action=='remove_source'){
		// remove from available
		 for(var i = 0; i < availableArray.length; i++){
			 if(serial_number == availableArray[i][0]){
				availableArray.splice(i, 1);
		     }
		 }
	 }
	document.getElementById("dcsArray").value = JSON.stringify(dcsArray);
	document.getElementById("availableArray").value = JSON.stringify(availableArray);
}
function save_config_changes(){
	
	var dcsArray = document.getElementById("dcsArray").value;
	var availableArray = document.getElementById("availableArray").value;
	var keysArray = document.getElementById("keysArray").value;
			
	var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				// console.log(xmlhttp.responseText);
				window.location.href = 'dcs.php';
        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=save_config_changes&d=" + dcsArray + '&a=' + availableArray + '&k=' + keysArray,true);
   		xmlhttp.send();
}
// clear message after 10 seconds
setTimeout(function(){ 
	document.getElementById("message_container").innerHTML = '';
}, 10000);

</script>