<?php

$structure = "";
if (isset($_SESSION['structure']))
	$structure = $_SESSION['structure'];
	
$struct = json_decode($structure);

$saveunder = FALSE;
if (isset($_REQUEST['saveunder']))
{
	$saveunder = $_REQUEST['saveunder'];
	
	$struct->name = $_REQUEST['newname'];
	$struct->origin = $saveunder;
	
	$structure = json_encode($struct);
	
	$dashrel = FALSE;
	$dashrelid = -1;
	require_once($installfolder.'/model/relationship.php');
	$allrels = Relationships::GetAllRelationships();
	foreach($allrels as $r)
	{
		if ($r->name == "Dashboard")
		{
			$dashrel = $r;
			$dashrelid = $r->id;
			break;
		}
	}
	
	if ($dashrel === FALSE)
	{
		//The dashboard relationship doesn't exist. We'll need to create one.
		
		//For now, assume this will be manually created.
	}
	
	if ($dashrelid == -1)
	{
		echo '{ "status": "ERROR", "message": "Custom dashboards can not be saved without a Dashboard hierachy" }';
		exit;
	}
	
	//Check to make sure asset is part of the dashboard hierarchy...
	$ass = new Asset($saveunder);
	if (!isset($asset[$ass->id]['relationships'][$dashrelid]))
	{
		echo 'Specified asset is not in the dashboard hierarchy.';
		exit;
	}
	
	//Check to see if there is already an asset with this name in the dashboard hierarchy...
	
	
	//Assume this is a new dashboard...
	$dashid = Asset::Create($struct->name,"A Data Explorer Dashboard");
	Relationships::Add($saveunder,$dashid,$dashrelid);
	
	$filename = "default.dash";
	$fn = sys_get_temp_dir().'/'.$filename;
	file_put_contents($fn,$structure);
	
	$counter = 0;
	while(!file_exists($fn))
	{
		//print("File Doesn't Exist (".$counter.")...");
		sleep(0.5);
		$counter++;
		if ($counter > 10) break;
	}
	
	//Add or replace media file...
	require_once($installfolder.'/model/media.php');
	$med = new AssetMedia();
	$med->Add($dashid,$filename,$fn);
	header('Location: '.$siteroot.'/dexplore/dash?id='.$dashid.'&board=Default');
	exit;
}

$alist = array();
foreach($struct->panels as $pan)
{
	foreach($pan->points as $pnt)
	{
		if (!in_array($pnt->asset,$alist))
		{
			$alist[] = $pnt->asset;
		}
	}
}

if (isset($_REQUEST['id']))
{
	$id = filter_var($_REQUEST['id'],FILTER_VALIDATE_INT);
	if ($id !== FALSE)
		$alist = array($id);
}

header("Content-Type: application/json");
//print_r($alist);

if (count($alist) == 1)
{
	$ass = new Asset($alist[0]);
	//OK - all samples are from one asset. This is promising!
	
	if ($struct->name == $ass->name)
	{
		//This is the default dashboard...
		$filename = "default.dash";
	}
	else
	{
		$filename = $struct->name.".dash";
	}
	
	$fn = sys_get_temp_dir().'/'.$filename;
	file_put_contents($fn,$structure);
	
	$counter = 0;
	while(!file_exists($fn))
	{
		//print("File Doesn't Exist (".$counter.")...");
		sleep(0.5);
		$counter++;
		if ($counter > 10) break;
	}
	
	//echo $structure;
	
	//print_r($ass->name.' = '.$filename);
	//exit();
	//Add or replace media file...
	require_once($installfolder.'/model/media.php');
	$med = new AssetMedia();
	$med->Add($alist[0],$filename,$fn);
	echo '{ "status": "OK" }';
}
else
{
	$boardname = FALSE;
	if (isset($_REQUEST['board']))
	{
		$filename = $_REQUEST['board'].'.dash';
		$idno = filter_var($_REQUEST['id'],FILTER_VALIDATE_INT);
		if ($idno !== FALSE)
		{		
			$struct->origin = $saveunder;
	
			$structure = json_encode($struct);
	
			$fn = sys_get_temp_dir().'/'.$filename;
			file_put_contents($fn,$structure);
		
			require_once($installfolder.'/model/media.php');
			$med = new AssetMedia();
			$med->Add($idno,$filename,$fn);
			echo '{ "status": "OK" }';
			exit();
		}
	}
	//We probably need to save this as an ASSET.
	
	//First, determine if we have the needed hierarchy & base asset.
	$dashrel = FALSE;
	$dashrelid = -1;
	require_once($installfolder.'/model/relationship.php');
	$allrels = Relationships::GetAllRelationships();
	foreach($allrels as $r)
	{
		if ($r->name == "Dashboard")
		{
			$dashrel = $r;
			$dashrelid = $r->id;
			break;
		}
	}
	
	if ($dashrel === FALSE)
	{
		//The dashboard relationship doesn't exist. We'll need to create one.
		
		//For now, assume this will be manually created.
	}
	
	if ($dashrelid == -1)
	{
		echo '{ "status": "ERROR", "message": "Custom dashboards can not be saved without a Dashboard hierachy" }';
		exit;
	}
	
	//User needs to pick a place in that hierarchy...
	$pickplace = "";	
	$ra = $dashrel->GetRootAsset();
	$qry = "SELECT childasset,name FROM assetrelclosures JOIN assets ON (childasset = assets.id) WHERE relationship=".$dashrelid." AND parentasset=".$ra." ORDER BY name";
			
	$query = $db->query($qry);
	
	$lastname = "";
	while($row = $query->fetch(PDO::FETCH_ASSOC)) 
	{
		$pickplace = '<select name="saveunder">';
		$pickplace .= '<option value="'.$row['childasset'].'">'.$row['name'].'</option>';
		$pickplace .= '</select>';
	}
	echo '{ "status": "CHOICE", "content": "'.str_replace('"','\"',$pickplace).'" }';
	exit;
	
	
	echo '{ "status": "ERROR", "message": "Save Not Complete" }';
	
}
?>