<?php
if (!defined("PSWE_MODULELOADED")) {
   exit;
}

class Column {
	var $name;
	var $type;
	var $nullable;

	function Column($name, $type, $nullable) {
		$this->name = $name;
		$this->type = $type;
		$this->nullable = $nullable=="NO"?false:true;
	}

	function getName() {
		return $this->name;
	}

	function getType() {
		return $this->type;
	}

	function isNullable() {
		return $this->nullable;
	}

	function toString() {
		return("name=".$this->name.",type=".$this->type.",nullable=".$this->nullable);
	}
}

function columnDefault($column) {
	switch ($column->getType()) {
		case "uniqueidentifier":
			if (!IsNewRecord()) {
				DrawFormHidden("fld".$column->getName(), $_SESSION['fld'.$column->getName()]);
			} elseif ($column->getName() != 'GUID') {
				if (RequestValue(strtolower($column->getName())) == "") {
					DrawFormField(CreateFieldCaption("fld".$column->getName(), $column->getName()),CreateSQLSelectField("fld".$column->getName(), db_Relationship($table,$column->getName())));
				} else {
					DrawFormHidden("fld".$column->getName(), RequestValue(strtolower($column->getName())));
				}
			}
			break;
		case "text":
			DrawFormField(CreateFieldCaption("fld".$column->getName(), $column->getName()),CreateMemoField("fld".$column->getName()),$column->isNullable());
			break;
		default:
			DrawFormField(CreateFieldCaption("fld".$column->getName(), $column->getName()),CreateTextField("fld".$column->getName()),$column->isNullable());
			break;
	}
}

DrawTitle(RequestValue("table"));

$table = RequestValue("table");

$columns= array();
$tableQuery= db_OpenTable("EXEC sp_columns @table_name = '".$table."'");
while (($blah = db_Next($tableQuery)) != null) {
	if ($blah["COLUMN_NAME"]!='keycolumn') {
		$column = new Column($blah["COLUMN_NAME"], $blah["TYPE_NAME"], $blah["IS_NULLABLE"]);
		array_push($columns, $column);
	}
}
db_CloseTable($tableQuery);

InitializeFormEngine();
InitializeForm($table,'GUID');
DrawFormHeader(PSWE_SYS_ROOTFOLDER."module.php?module=msa&page=maintenance/index_edittable_ack");

if (!IsNewRecord()) {
	$tableQuery = db_OpenTable("SELECT TOP 1 * FROM $table WHERE GUID = '".RequestValue("id")."'");
	$tableResult = db_Next($tableQuery);
	db_CloseTable($tableQuery);

	foreach ($tableResult as $key => $value) {
		$_SESSION["fld".$key] = $value;
	}
} else {
	foreach ($columns as $myColumn) {
		if (RequestValue($myColumn->getName()) != "") {
			$_SESSION["fld".$myColumn->getName()] = RequestValue($myColumn->getName());
		}
	}
}

$tableDir = PSWE_SYS_PHYSICALROOTFOLDER.'modules/msa/maintenance/tables/';
foreach ($columns as $column) {
	if ((is_file($tableDir.$table.'.php'))&&($column->getName()!='GUID')) {
		include(PSWE_SYS_PHYSICALROOTFOLDER.'modules/msa/maintenance/tables/'.$table.'.php');
	} else {
		columnDefault($column);
	}
}
DrawFormHidden('fldTable',$table);
DrawFormFooter();
