<?php

	namespace Mocha\UI\Pages;
	
	use Mocha\Core\OmsContext;
	use Mocha\UI\Renderers\HTML\HTMLRenderer;
	use Phast\CancelEventArgs;
	use Phast\RenderingEventArgs;
	use Phast\System;
	use Phast\WebControls\TabContainer;
	use Phast\WebControls\TabPage;
	use Phast\WebControls\Window;
	use Phast\WebPage;
	use Phast\WebScript;

	global $pdo;
	global $basepath;

	$pdo = null;
	$pdoex = null;

	try
	{
		$pdo = new \PDO("mysql:host=" . System::$Configuration["Database.ServerName"] . ";port=" . System::$Configuration["Database.PortNumber"] . ";dbname=" . System::$Configuration["Database.DatabaseName"], System::$Configuration["Database.UserName"], System::$Configuration["Database.Password"]);
	}
	catch (\Exception $ex)
	{
		$pdoex = $ex;
		// echo($pdoex); die();
	}
	$basepath = $_SERVER["SERVER_NAME"];

	class SUVPage extends WebPage
	{

		private function getTenants() : array
		{
			$tenants = array();
			$use_dotnet = true;

			if ($use_dotnet)
			{
				// using .NET OMS
				$curl = curl_init("http://localhost:4436/tenants");
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
				if ($curl == false)
				{
				}
				else
				{
					$result = curl_exec($curl);
					$json = json_decode($result, true);
					if ($json["result"] == "success")
					{
						foreach ($json["tenants"] as $tenant)
						{
							$tenants[] = array
							(
								"name" => $tenant["name"],
								"status" => "Active",
								"tenantType" => "Development",
								"dataCenter" => "Local",
								"charge" => "No Charge",
								"initialTerm" => null,
								"renewalTerm" => null,
								"tenantStartDate" => null,
								"tenantExpirationDate" => null,
								"purpose" => ""
							);
						}
					}
				}
			}
			else
			{
				global $pdo;
				if ($pdo !== null)
				{
					global $basepath;

					$query = "SELECT * FROM mocha_tenants";
					$stmt = $pdo->prepare($query);
					try
					{
						$result = $stmt->execute();
						$rows = $stmt->fetchAll();
						foreach ($rows as $values)
						{
							if ($values["is_library"] != 0)
							{
								continue;
							}
							$tenants[] = array
							(
								"name" => $values["tenant_name"],
								"status" => "Active",
								"tenantType" => "Development",
								"dataCenter" => "Local",
								"charge" => "No Charge",
								"initialTerm" => null,
								"renewalTerm" => null,
								"tenantStartDate" => null,
								"tenantExpirationDate" => null,
								"purpose" => $values["tenant_purpose"]
							);
						}
					}
					catch (\Exception $ex)
					{
						// echo ("<tr><td colspan=\"10\">" . $ex . "</td></tr>");
					}
				}
				else
				{
					// FIXME : use mocha-dotnet
				}
			}

			return $tenants;
		}
		
		protected function OnPreRender(CancelEventArgs $e)
		{
			global $basepath;
			$oms = mocha_get_oms();
			
			$e->Cancel = true;

			if ($_POST["reset"] == "1")
			{
				global $pdo;
				if ($pdo !== null) {
					$stmt = $pdo->prepare("DELETE FROM mocha_attributes WHERE tenant_id > 2");
					$stmt->execute();

					$stmt = $pdo->prepare("DELETE FROM mocha_relationships WHERE tenant_id > 2");
					$stmt->execute();

					$stmt = $pdo->prepare("DELETE FROM mocha_instances WHERE tenant_id > 2");
					$stmt->execute();

					$stmt = $pdo->prepare("DELETE FROM mocha_tenant_references WHERE source_tenant_id > 2");
					$stmt->execute();

					$stmt = $pdo->prepare("DELETE FROM mocha_tenants WHERE id > 2");
					$stmt->execute();

					header("HTTP/1.1 302 Found");
					header("Location: /suv/suvinfo.html");
					exit();
				}
			}

			$path = System::GetVirtualPath();
			if ($path[1] == "phpinfo.html")
			{
				phpinfo();
				return;
			}
			else if ($path[1] == "suvinfo.json")
			{
				header("Content-Type: application/json");

				$suvtype_file = "/etc/mocha/suvtype";
				$backend = null;
				if (file_exists($suvtype_file))
				{
					$backend = file_get_contents($suvtype_file);
				}

				$json = array
				(
					"name" => "suv",
					"description" => "",
					"backend" => $backend,
					"hostName" => $_SERVER["SERVER_NAME"],
					"environmentVersion" => 58132,
					"confidenceLevel" => "prod",
					"status" => "completed",
					"tenants" => array
					(
						array
						(
							"name" => "super",
							"status" => "active",
							"tenantType" => "development",
							"dataCenter" => "local",
							"charge" => "noCharge",
							"initialTerm" => "",
							"renewalTerm" => "",
							"tenantStartDate" => "",
							"tenantExpirationDate" => "",
							"purpose" => ""
						)
					),
					"database" => array
					(
						"backend" => $oms->getBackendName(),
						// "userName" => System::GetConfigurationValue("Database.UserName"),
						"hostName" => $oms->ServerName, // System::GetConfigurationValue("Database.ServerName"),
						"portNumber" => $oms->PortNumber,
						// "portNumber" => intval(System::GetConfigurationValue("Database.PortNumber")),
						"status" => "running"
					)
				);
				echo (json_encode($json));
			
				$e->Handled = true;
				return;
			}

			$ctx = new OmsContext();
			
			$htmlRenderer = new HTMLRenderer($ctx, true);
			$htmlRenderer->Scripts[] = WebScript::FromContent(<<<EOF

			window.addEventListener("load", function()
			{
				var wndCreateTenant = document.getElementById("windowCreateTenant").NativeObject;
				wndCreateTenant.validate = function()
				{
					var txtTenantName = document.getElementById("txtTenantName");
					var cboTenantType = document.getElementById("cboTenantType").NativeObject;
					var retval = true;
					if (txtTenantName.value == "")
					{
						System.ClassList.Add(txtTenantName, "uwt-required");
						System.ClassList.Add(txtTenantName, "uwt-failed-validation");
						retval = false;
					}
					if (cboTenantType.SelectElement.value == "")
					{
						System.ClassList.Add(cboTenantType.InputElement, "uwt-required");
						System.ClassList.Add(cboTenantType.InputElement, "uwt-failed-validation");
						retval = false;
					}
					
					if (!retval)
						return retval;

					var cboTenantType = document.getElementById("cboTenantType");
					//alert("create tenant '" + txtTenantName.value + "' with type: " + cboTenantType.value + "!");
					return true;
				};
				wndCreateTenant.reset = function()
				{
					var txtTenantName = document.getElementById("txtTenantName");
					var cboTenantType = document.getElementById("cboTenantType").NativeObject;
					
					System.ClassList.Remove(txtTenantName, "uwt-required");
					System.ClassList.Remove(txtTenantName, "uwt-failed-validation");
					
					System.ClassList.Remove(cboTenantType.InputElement, "uwt-required");
					System.ClassList.Remove(cboTenantType.InputElement, "uwt-failed-validation");
				};

				var btnAddTenant = document.getElementById("btnAddTenant");
				btnAddTenant.addEventListener("click", function(e)
				{
					var windowCreateTenant = document.getElementById("windowCreateTenant").NativeObject;
					if (!windowCreateTenant.initialized)
					{
						var footer = windowCreateTenant.ParentElement.children[2];
						var btnCancel = footer.children[0];
						btnCancel.addEventListener("click", function(ee)
						{
							windowCreateTenant.Hide();
						});
						windowCreateTenant.initialized = true;
					}

					windowCreateTenant.reset();
					windowCreateTenant.ShowDialog();

					e.preventDefault();
					e.stopPropagation();
					return false;
				});

				var btnResetTenants = document.getElementById("btnResetTenants");
				btnResetTenants.addEventListener("click", function(e)
				{
					var hidResetTenantsConfirm = document.getElementById("hidResetTenantsConfirm");
					if (!confirm("Reset tenants: Are you sure?"))
					{
						e.preventDefault();
						e.stopPropagation();
						return false;
					}
					else
					{
						hidResetTenantsConfirm.value = "1";
					}
				});

				var wndCreateTenant_btnSaveChanges = document.getElementById("wndCreateTenant_btnSaveChanges");
				wndCreateTenant_btnSaveChanges.ni = wndCreateTenant;
				wndCreateTenant_btnSaveChanges.addEventListener("click", function(e)
				{
					if (!this.ni.validate())
					{
						return;
					}
				});
			});
			
EOF
, "text/javascript");
			
			$htmlRenderer->renderBeginPage("SUV Self Service");
			
			if ($path[1] == "suvinfo.html")
			{
				$htmlRenderer->renderPageHeader("SUV Self Service", "");
				$htmlRenderer->renderBeginContent();

				$windowCreateTenant = new Window();
				$windowCreateTenant->ID = "windowCreateTenant";
				$windowCreateTenant->Title = "Create Tenant";
				$windowCreateTenant->Content = function()
				{
					?>
					<div class="uwt-header">
						<span class="uwt-title">Create Tenant</span>
					</div>
					<div class="uwt-content">
						<div class="uwt-formview">
							<div class="uwt-formview-item mcx-editable mcx-required">
								<div class="uwt-formview-item-label"><label>Tenant Name</label></div>
								<div class="uwt-formview-item-content"><input id="txtTenantName" type="text" value="" style="width: 256px;" /></div>
							</div>
							<div class="uwt-formview-item mcx-editable mcx-required">
								<div class="uwt-formview-item-label"><label>Tenant Type</label></div>
								<div class="uwt-formview-item-content">
									<select id="cboTenantType">
										<option data-description="The primary tenant for your organization.">Production</option>
										<option data-description="The testing tenant for your organization. Automatically refreshes from Production weekly.">Sandbox</option>
										<option data-description="Test out new platform functionality before it releases to production.">Sandbox Preview</option>
										<option data-description="Additional testing tenants for developing custom application objects. Refreshes manually.">Implementation</option>
										<option data-description="Quality Assurance Preview">QA Preview</option>
									</select>
								</div>
							</div>
							<div class="uwt-formview-item">
								<div class="uwt-formview-item-label"><label>Purpose</label></div>
								<div class="uwt-formview-item-content"><textarea style="width: 256px; height: 100px;"></textarea></div>
							</div>
						</div>
					</div>
					<div class="uwt-footer">
						<a class="uwt-button" href="#">Cancel</a>
						<a id="wndCreateTenant_btnSaveChanges" class="uwt-button uwt-color-primary" href="#">Save Changes</a>
					</div>
					<?php
				};
				$windowCreateTenant->Render();
				
				$tabContainer = new TabContainer();
				$page = new TabPage();
				$page->Title = "General";
				$page->Content = function()
				{
					?>
					<table class="uwt-listview">
						<thead>
							<tr>
								<th>Property</th>
								<th>Value</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>Name</td>
								<td>suv</td>
							</tr>
							<tr>
								<td>Description</td>
								<td><?php
								$suvtype_file = "/etc/mocha/suvdesc";
								if (file_exists($suvtype_file))
								{
									echo (file_get_contents($suvtype_file));
								}
								?></td>
							</tr>
							<tr>
								<td>Backend</td>
								<td><?php
								$suvtype_file = "/etc/mocha/suvtype";
								if (file_exists($suvtype_file))
								{
									echo (file_get_contents($suvtype_file));
								}
								else
								{
									echo ("(unknown)");
								}
								?></td>
							</tr>
							<tr>
								<td>Instance Id</td>
								<td><?php echo($_SERVER["SERVER_NAME"]); ?></td>
							</tr>
							<tr>
								<td>Host Name</td>
								<td><?php echo($_SERVER["SERVER_NAME"]); ?></td>
							</tr>
							<tr>
								<td>Environment Version</td>
								<td>58132</td>
							</tr>
							<tr>
								<td>Confidence Level</td>
								<td>prod</td>
							</tr>
							<tr>
								<td>Status</td>
								<td style="background-color: #ccffcc;">completed</td>
							</tr>
						</tbody>
					</table>
					<h3>Actions</h3>
					<button class="uwt-button uwt-color-primary">SUV Logs</button>
					<?php
				};
				$tabContainer->TabPages[] = $page;

				$page = new TabPage();
				$page->Title = "Tenants";
				$page->Content = function()
				{
					?>
					<div style="margin-bottom: 16px;">
						<a id="btnAddTenant" class="uwt-button uwt-color-primary" href="#">Add Tenant</a>
						<form method="POST">
							<input type="hidden" id="hidResetTenantsConfirm" name="reset" value="0" />
							<button class="uwt-button" id="btnResetTenants">Reset Tenants</button>
						</form>
					</div>
					<table class="uwt-listview">
						<thead>
							<tr>
								<th>Tenant Name</th>
								<th>Status</th>
								<th>Tenant Type</th>
								<th>Data Center</th>
								<th>Charge</th>
								<th>Initial Term</th>
								<th>Renewal Term</th>
								<th>Tenant Start Date</th>
								<th>Tenant Expiration Date</th>
								<th>Purpose</th>
							</tr>
						</thead>
						<tbody>
							<?php
							global $basepath;
							$tenants = $this->getTenants();
							foreach ($tenants as $tenant)
							{
								?>
								<tr>
									<td><a class="uwt-external-link" target="_blank" href="<?php echo ("https://" . $basepath . "/" . $tenant["name"]); ?>"><?php echo ($tenant["name"]); ?></a></td>
									<td><?php echo($tenant["status"]); ?></td>
									<td><?php echo($tenant["tenantType"]); ?></td>
									<td><?php echo($tenant["dataCenter"]); ?></td>
									<td><?php echo($tenant["charge"]); ?></td>
									<td><?php echo($tenant["initialTerm"]); ?></td>
									<td><?php echo($tenant["renewalTerm"]); ?></td>
									<td><?php echo($tenant["tenantStartDate"]); ?></td>
									<td><?php echo($tenant["tenantExpirationDate"]); ?></td>
									<td><?php echo($tenant["purpose"]); ?></td>
								</tr>
								<?php
							}
							?>
						</tbody>
					</table>
					<?php
				};
				$tabContainer->TabPages[] = $page;

				$page = new TabPage();
				$page->Title = "Database";
				$page->Content = function()
				{
					$oms = mocha_get_oms();
					?>
					<table class="uwt-listview">
						<thead>
							<tr>
								<th>Property</th>
								<th>Value</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>Backend</td>
								<td><?php echo($oms->getBackendName()); ?></td>
							</tr>
							<tr>
								<td>User</td>
								<td><?php
								if ($oms->getBackendName() == "mysql") {
									echo (System::GetConfigurationValue("Database.UserName"));
								}
								?></td>
							</tr>
							<tr>
								<td>Host</td>
								<td><?php echo(System::GetConfigurationValue("Database.ServerName")); ?></td>
							</tr>
							<tr>
								<td>Port</td>
								<td><?php echo($oms->PortNumber); ?></td>
							</tr>
							<tr>
								<td>Status</td>
								<td style="background-color: #ccffcc;">running</td>
							</tr>
						</tbody>
					</table>
					<?php
				};
				$tabContainer->TabPages[] = $page;

				global $passwd_file;
				$passwd_file = "/etc/mocha/passwd";
				if (file_exists($passwd_file))
				{
					$page = new TabPage();
					$page->Title = "Access";
					$page->Content = function()
					{
						global $passwd_file;
						?>
						<h1>SFTP Accounts</h1>
						<p>Use these details to log into your SUV for SFTP transfers.</p>
						<p>
							<strong>These credentials are stored as plain text and should not be used in production environments.</strong>
							To push changes from your SUV to a production server, run <em>mocha suv migrate</em> from a shell.
						</p>
						<table class="uwt-listview">
							<thead>
								<tr>
									<th>User name</th>
									<th>Password</th>
								</tr>
							</thead>
							<tbody>
							<?php
							$contents = file_get_contents($passwd_file);
							$lines = explode("\n", $contents);
							foreach ($lines as $line)
							{
								if (trim($line) == "") continue;
								$lineSplit = explode(":", $line);
								if (count($lineSplit) != 2) continue;

								echo ("<tr><td>" . trim($lineSplit[0]) . "</td><td>" . trim($lineSplit[1]) . "</td></tr>");
							}
							?>
							</tbody>
						</table>
						<?php
					};
					$tabContainer->TabPages[] = $page;
				}

				$tabContainer->Render();
			}

			$htmlRenderer->renderEndContent();

			$htmlRenderer->renderEndPage();
		}
	}

?>