<?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
	{
		protected function OnPreRender(CancelEventArgs $e)
		{
			global $pdo;
			global $basepath;
			
			$e->Cancel = true;

			if ($_POST["reset"] == "1")
			{
				$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;
			}
			
			$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>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 $pdo;
							global $basepath;
							
							$query = "SELECT * FROM mocha_tenants";
							$stmt = $pdo->prepare($query);
							$result = $stmt->execute();
							$rows = $stmt->fetchAll();
							foreach ($rows as $values)
							{
								if ($values["is_library"] != 0)
								{
									continue;
								}
							?>
							<tr>
								<td><a class="uwt-external-link" target="_blank" href="<?php echo("https://" . $basepath . "/" . $values["tenant_name"]); ?>"><?php echo ($values["tenant_name"]); ?></a></td>
								<td>Active</td>
								<td>Development</td>
								<td>Local</td>
								<td>No Charge</td>
								<td></td>
								<td></td>
								<td></td>
								<td></td>
								<td>Default Tenant</td>
							</tr>
							<?php
							}
							?>
						</tbody>
					</table>
					<?php
				};
				$tabContainer->TabPages[] = $page;

				$page = new TabPage();
				$page->Title = "Database";
				$page->Content = function()
				{
					?>
					<table class="uwt-listview">
						<thead>
							<tr>
								<th>Property</th>
								<th>Value</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>Backend</td>
								<td>mysql</td>
							</tr>
							<tr>
								<td>User</td>
								<td><?php 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(System::GetConfigurationValue("Database.PortNumber")); ?></td>
							</tr>
							<tr>
								<td>Status</td>
								<td style="background-color: #ccffcc;">running</td>
							</tr>
						</tbody>
					</table>
					<?php
				};
				$tabContainer->TabPages[] = $page;


				$tabContainer->Render();
			}

			$htmlRenderer->renderEndContent();

			$htmlRenderer->renderEndPage();
		}
	}

?>