<?php
namespace PHPMaker2020\project2;

/**
 * Page class
 */
class kp_citas_edit extends kp_citas
{

	// Page ID
	public $PageID = "edit";

	// Project ID
	public $ProjectID = "{AA140015-983A-47F7-B2DB-866F9851A082}";

	// Table name
	public $TableName = 'kp_citas';

	// Page object name
	public $PageObjName = "kp_citas_edit";

	// Page headings
	public $Heading = "";
	public $Subheading = "";
	public $PageHeader;
	public $PageFooter;

	// Token
	public $Token = "";
	public $TokenTimeout = 0;
	public $CheckToken;

	// Page heading
	public function pageHeading()
	{
		global $Language;
		if ($this->Heading != "")
			return $this->Heading;
		if (method_exists($this, "tableCaption"))
			return $this->tableCaption();
		return "";
	}

	// Page subheading
	public function pageSubheading()
	{
		global $Language;
		if ($this->Subheading != "")
			return $this->Subheading;
		if ($this->TableName)
			return $Language->phrase($this->PageID);
		return "";
	}

	// Page name
	public function pageName()
	{
		return CurrentPageName();
	}

	// Page URL
	public function pageUrl()
	{
		$url = CurrentPageName() . "?";
		if ($this->UseTokenInUrl)
			$url .= "t=" . $this->TableVar . "&"; // Add page token
		return $url;
	}

	// Messages
	private $_message = "";
	private $_failureMessage = "";
	private $_successMessage = "";
	private $_warningMessage = "";

	// Get message
	public function getMessage()
	{
		return isset($_SESSION[SESSION_MESSAGE]) ? $_SESSION[SESSION_MESSAGE] : $this->_message;
	}

	// Set message
	public function setMessage($v)
	{
		AddMessage($this->_message, $v);
		$_SESSION[SESSION_MESSAGE] = $this->_message;
	}

	// Get failure message
	public function getFailureMessage()
	{
		return isset($_SESSION[SESSION_FAILURE_MESSAGE]) ? $_SESSION[SESSION_FAILURE_MESSAGE] : $this->_failureMessage;
	}

	// Set failure message
	public function setFailureMessage($v)
	{
		AddMessage($this->_failureMessage, $v);
		$_SESSION[SESSION_FAILURE_MESSAGE] = $this->_failureMessage;
	}

	// Get success message
	public function getSuccessMessage()
	{
		return isset($_SESSION[SESSION_SUCCESS_MESSAGE]) ? $_SESSION[SESSION_SUCCESS_MESSAGE] : $this->_successMessage;
	}

	// Set success message
	public function setSuccessMessage($v)
	{
		AddMessage($this->_successMessage, $v);
		$_SESSION[SESSION_SUCCESS_MESSAGE] = $this->_successMessage;
	}

	// Get warning message
	public function getWarningMessage()
	{
		return isset($_SESSION[SESSION_WARNING_MESSAGE]) ? $_SESSION[SESSION_WARNING_MESSAGE] : $this->_warningMessage;
	}

	// Set warning message
	public function setWarningMessage($v)
	{
		AddMessage($this->_warningMessage, $v);
		$_SESSION[SESSION_WARNING_MESSAGE] = $this->_warningMessage;
	}

	// Clear message
	public function clearMessage()
	{
		$this->_message = "";
		$_SESSION[SESSION_MESSAGE] = "";
	}

	// Clear failure message
	public function clearFailureMessage()
	{
		$this->_failureMessage = "";
		$_SESSION[SESSION_FAILURE_MESSAGE] = "";
	}

	// Clear success message
	public function clearSuccessMessage()
	{
		$this->_successMessage = "";
		$_SESSION[SESSION_SUCCESS_MESSAGE] = "";
	}

	// Clear warning message
	public function clearWarningMessage()
	{
		$this->_warningMessage = "";
		$_SESSION[SESSION_WARNING_MESSAGE] = "";
	}

	// Clear messages
	public function clearMessages()
	{
		$this->clearMessage();
		$this->clearFailureMessage();
		$this->clearSuccessMessage();
		$this->clearWarningMessage();
	}

	// Show message
	public function showMessage()
	{
		$hidden = TRUE;
		$html = "";

		// Message
		$message = $this->getMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($message, "");
		if ($message != "") { // Message in Session, display
			if (!$hidden)
				$message = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $message;
			$html .= '<div class="alert alert-info alert-dismissible ew-info"><i class="icon fas fa-info"></i>' . $message . '</div>';
			$_SESSION[SESSION_MESSAGE] = ""; // Clear message in Session
		}

		// Warning message
		$warningMessage = $this->getWarningMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($warningMessage, "warning");
		if ($warningMessage != "") { // Message in Session, display
			if (!$hidden)
				$warningMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $warningMessage;
			$html .= '<div class="alert alert-warning alert-dismissible ew-warning"><i class="icon fas fa-exclamation"></i>' . $warningMessage . '</div>';
			$_SESSION[SESSION_WARNING_MESSAGE] = ""; // Clear message in Session
		}

		// Success message
		$successMessage = $this->getSuccessMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($successMessage, "success");
		if ($successMessage != "") { // Message in Session, display
			if (!$hidden)
				$successMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $successMessage;
			$html .= '<div class="alert alert-success alert-dismissible ew-success"><i class="icon fas fa-check"></i>' . $successMessage . '</div>';
			$_SESSION[SESSION_SUCCESS_MESSAGE] = ""; // Clear message in Session
		}

		// Failure message
		$errorMessage = $this->getFailureMessage();
		if (method_exists($this, "Message_Showing"))
			$this->Message_Showing($errorMessage, "failure");
		if ($errorMessage != "") { // Message in Session, display
			if (!$hidden)
				$errorMessage = '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' . $errorMessage;
			$html .= '<div class="alert alert-danger alert-dismissible ew-error"><i class="icon fas fa-ban"></i>' . $errorMessage . '</div>';
			$_SESSION[SESSION_FAILURE_MESSAGE] = ""; // Clear message in Session
		}
		echo '<div class="ew-message-dialog' . (($hidden) ? ' d-none' : "") . '">' . $html . '</div>';
	}

	// Get message as array
	public function getMessages()
	{
		$ar = [];

		// Message
		$message = $this->getMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($message, "");

		if ($message != "") { // Message in Session, display
			$ar["message"] = $message;
			$_SESSION[SESSION_MESSAGE] = ""; // Clear message in Session
		}

		// Warning message
		$warningMessage = $this->getWarningMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($warningMessage, "warning");

		if ($warningMessage != "") { // Message in Session, display
			$ar["warningMessage"] = $warningMessage;
			$_SESSION[SESSION_WARNING_MESSAGE] = ""; // Clear message in Session
		}

		// Success message
		$successMessage = $this->getSuccessMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($successMessage, "success");

		if ($successMessage != "") { // Message in Session, display
			$ar["successMessage"] = $successMessage;
			$_SESSION[SESSION_SUCCESS_MESSAGE] = ""; // Clear message in Session
		}

		// Failure message
		$failureMessage = $this->getFailureMessage();

		//if (method_exists($this, "Message_Showing"))
		//	$this->Message_Showing($failureMessage, "failure");

		if ($failureMessage != "") { // Message in Session, display
			$ar["failureMessage"] = $failureMessage;
			$_SESSION[SESSION_FAILURE_MESSAGE] = ""; // Clear message in Session
		}
		return $ar;
	}

	// Show Page Header
	public function showPageHeader()
	{
		$header = $this->PageHeader;
		$this->Page_DataRendering($header);
		if ($header != "") { // Header exists, display
			echo '<p id="ew-page-header">' . $header . '</p>';
		}
	}

	// Show Page Footer
	public function showPageFooter()
	{
		$footer = $this->PageFooter;
		$this->Page_DataRendered($footer);
		if ($footer != "") { // Footer exists, display
			echo '<p id="ew-page-footer">' . $footer . '</p>';
		}
	}

	// Validate page request
	protected function isPageRequest()
	{
		global $CurrentForm;
		if ($this->UseTokenInUrl) {
			if ($CurrentForm)
				return ($this->TableVar == $CurrentForm->getValue("t"));
			if (Get("t") !== NULL)
				return ($this->TableVar == Get("t"));
		}
		return TRUE;
	}

	// Valid Post
	protected function validPost()
	{
		if (!$this->CheckToken || !IsPost() || IsApi())
			return TRUE;
		if (Post(Config("TOKEN_NAME")) === NULL)
			return FALSE;
		$fn = Config("CHECK_TOKEN_FUNC");
		if (is_callable($fn))
			return $fn(Post(Config("TOKEN_NAME")), $this->TokenTimeout);
		return FALSE;
	}

	// Create Token
	public function createToken()
	{
		global $CurrentToken;
		$fn = Config("CREATE_TOKEN_FUNC"); // Always create token, required by API file/lookup request
		if ($this->Token == "" && is_callable($fn)) // Create token
			$this->Token = $fn();
		$CurrentToken = $this->Token; // Save to global variable
	}

	// Constructor
	public function __construct()
	{
		global $Language, $DashboardReport;

		// Check token
		$this->CheckToken = Config("CHECK_TOKEN");

		// Initialize
		$GLOBALS["Page"] = &$this;
		$this->TokenTimeout = SessionTimeoutTime();

		// Language object
		if (!isset($Language))
			$Language = new Language();

		// Parent constuctor
		parent::__construct();

		// Table object (kp_citas)
		if (!isset($GLOBALS["kp_citas"]) || get_class($GLOBALS["kp_citas"]) == PROJECT_NAMESPACE . "kp_citas") {
			$GLOBALS["kp_citas"] = &$this;
			$GLOBALS["Table"] = &$GLOBALS["kp_citas"];
		}

		// Page ID (for backward compatibility only)
		if (!defined(PROJECT_NAMESPACE . "PAGE_ID"))
			define(PROJECT_NAMESPACE . "PAGE_ID", 'edit');

		// Table name (for backward compatibility only)
		if (!defined(PROJECT_NAMESPACE . "TABLE_NAME"))
			define(PROJECT_NAMESPACE . "TABLE_NAME", 'kp_citas');

		// Start timer
		if (!isset($GLOBALS["DebugTimer"]))
			$GLOBALS["DebugTimer"] = new Timer();

		// Debug message
		LoadDebugMessage();

		// Open connection
		if (!isset($GLOBALS["Conn"]))
			$GLOBALS["Conn"] = $this->getConnection();
	}

	// Terminate page
	public function terminate($url = "")
	{
		global $ExportFileName, $TempImages, $DashboardReport;

		// Page Unload event
		$this->Page_Unload();

		// Global Page Unloaded event (in userfn*.php)
		Page_Unloaded();

		// Export
		global $kp_citas;
		if ($this->CustomExport && $this->CustomExport == $this->Export && array_key_exists($this->CustomExport, Config("EXPORT_CLASSES"))) {
				$content = ob_get_contents();
			if ($ExportFileName == "")
				$ExportFileName = $this->TableVar;
			$class = PROJECT_NAMESPACE . Config("EXPORT_CLASSES." . $this->CustomExport);
			if (class_exists($class)) {
				$doc = new $class($kp_citas);
				$doc->Text = @$content;
				if ($this->isExport("email"))
					echo $this->exportEmail($doc->Text);
				else
					$doc->export();
				DeleteTempImages(); // Delete temp images
				exit();
			}
		}
		if (!IsApi())
			$this->Page_Redirecting($url);

		// Close connection
		CloseConnections();

		// Return for API
		if (IsApi()) {
			$res = $url === TRUE;
			if (!$res) // Show error
				WriteJson(array_merge(["success" => FALSE], $this->getMessages()));
			return;
		}

		// Go to URL if specified
		if ($url != "") {
			if (!Config("DEBUG") && ob_get_length())
				ob_end_clean();

			// Handle modal response
			if ($this->IsModal) { // Show as modal
				$row = ["url" => $url, "modal" => "1"];
				$pageName = GetPageName($url);
				if ($pageName != $this->getListUrl()) { // Not List page
					$row["caption"] = $this->getModalCaption($pageName);
					if ($pageName == "kp_citasview.php")
						$row["view"] = "1";
				} else { // List page should not be shown as modal => error
					$row["error"] = $this->getFailureMessage();
					$this->clearFailureMessage();
				}
				WriteJson($row);
			} else {
				SaveDebugMessage();
				AddHeader("Location", $url);
			}
		}
		exit();
	}

	// Get records from recordset
	protected function getRecordsFromRecordset($rs, $current = FALSE)
	{
		$rows = [];
		if (is_object($rs)) { // Recordset
			while ($rs && !$rs->EOF) {
				$this->loadRowValues($rs); // Set up DbValue/CurrentValue
				$row = $this->getRecordFromArray($rs->fields);
				if ($current)
					return $row;
				else
					$rows[] = $row;
				$rs->moveNext();
			}
		} elseif (is_array($rs)) {
			foreach ($rs as $ar) {
				$row = $this->getRecordFromArray($ar);
				if ($current)
					return $row;
				else
					$rows[] = $row;
			}
		}
		return $rows;
	}

	// Get record from array
	protected function getRecordFromArray($ar)
	{
		$row = [];
		if (is_array($ar)) {
			foreach ($ar as $fldname => $val) {
				if (array_key_exists($fldname, $this->fields) && ($this->fields[$fldname]->Visible || $this->fields[$fldname]->IsPrimaryKey)) { // Primary key or Visible
					$fld = &$this->fields[$fldname];
					if ($fld->HtmlTag == "FILE") { // Upload field
						if (EmptyValue($val)) {
							$row[$fldname] = NULL;
						} else {
							if ($fld->DataType == DATATYPE_BLOB) {
								$url = FullUrl(GetApiUrl(Config("API_FILE_ACTION"),
									Config("API_OBJECT_NAME") . "=" . $fld->TableVar . "&" .
									Config("API_FIELD_NAME") . "=" . $fld->Param . "&" .
									Config("API_KEY_NAME") . "=" . rawurlencode($this->getRecordKeyValue($ar)))); //*** need to add this? API may not be in the same folder
								$row[$fldname] = ["mimeType" => ContentType($val), "url" => $url];
							} elseif (!$fld->UploadMultiple || !ContainsString($val, Config("MULTIPLE_UPLOAD_SEPARATOR"))) { // Single file
								$row[$fldname] = ["mimeType" => MimeContentType($val), "url" => FullUrl($fld->hrefPath() . $val)];
							} else { // Multiple files
								$files = explode(Config("MULTIPLE_UPLOAD_SEPARATOR"), $val);
								$ar = [];
								foreach ($files as $file) {
									if (!EmptyValue($file))
										$ar[] = ["type" => MimeContentType($file), "url" => FullUrl($fld->hrefPath() . $file)];
								}
								$row[$fldname] = $ar;
							}
						}
					} else {
						$row[$fldname] = $val;
					}
				}
			}
		}
		return $row;
	}

	// Get record key value from array
	protected function getRecordKeyValue($ar)
	{
		$key = "";
		if (is_array($ar)) {
			$key .= @$ar['id_reg'];
		}
		return $key;
	}

	/**
	 * Hide fields for add/edit
	 *
	 * @return void
	 */
	protected function hideFieldsForAddEdit()
	{
		if ($this->isAdd() || $this->isCopy() || $this->isGridAdd())
			$this->id_reg->Visible = FALSE;
	}

	// Lookup data
	public function lookup()
	{
		global $Language, $Security;
		if (!isset($Language))
			$Language = new Language(Config("LANGUAGE_FOLDER"), Post("language", ""));

		// Set up API request
		if (!$this->setupApiRequest())
			return FALSE;

		// Get lookup object
		$fieldName = Post("field");
		if (!array_key_exists($fieldName, $this->fields))
			return FALSE;
		$lookupField = $this->fields[$fieldName];
		$lookup = $lookupField->Lookup;
		if ($lookup === NULL)
			return FALSE;
		if (!$Security->isLoggedIn()) // Logged in
			return FALSE;

		// Get lookup parameters
		$lookupType = Post("ajax", "unknown");
		$pageSize = -1;
		$offset = -1;
		$searchValue = "";
		if (SameText($lookupType, "modal")) {
			$searchValue = Post("sv", "");
			$pageSize = Post("recperpage", 10);
			$offset = Post("start", 0);
		} elseif (SameText($lookupType, "autosuggest")) {
			$searchValue = Get("q", "");
			$pageSize = Param("n", -1);
			$pageSize = is_numeric($pageSize) ? (int)$pageSize : -1;
			if ($pageSize <= 0)
				$pageSize = Config("AUTO_SUGGEST_MAX_ENTRIES");
			$start = Param("start", -1);
			$start = is_numeric($start) ? (int)$start : -1;
			$page = Param("page", -1);
			$page = is_numeric($page) ? (int)$page : -1;
			$offset = $start >= 0 ? $start : ($page > 0 && $pageSize > 0 ? ($page - 1) * $pageSize : 0);
		}
		$userSelect = Decrypt(Post("s", ""));
		$userFilter = Decrypt(Post("f", ""));
		$userOrderBy = Decrypt(Post("o", ""));
		$keys = Post("keys");
		$lookup->LookupType = $lookupType; // Lookup type
		if ($keys !== NULL) { // Selected records from modal
			if (is_array($keys))
				$keys = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $keys);
			$lookup->FilterValues[] = $keys; // Lookup values
		} else { // Lookup values
			$lookup->FilterValues[] = Post("v0", Post("lookupValue", ""));
		}
		$cnt = is_array($lookup->FilterFields) ? count($lookup->FilterFields) : 0;
		for ($i = 1; $i <= $cnt; $i++)
			$lookup->FilterValues[] = Post("v" . $i, "");
		$lookup->SearchValue = $searchValue;
		$lookup->PageSize = $pageSize;
		$lookup->Offset = $offset;
		if ($userSelect != "")
			$lookup->UserSelect = $userSelect;
		if ($userFilter != "")
			$lookup->UserFilter = $userFilter;
		if ($userOrderBy != "")
			$lookup->UserOrderBy = $userOrderBy;
		$lookup->toJson($this); // Use settings from current page
	}

	// Set up API request
	public function setupApiRequest()
	{
		global $Security;

		// Check security for API request
		If (ValidApiRequest()) {
			return TRUE;
		}
		return FALSE;
	}
	public $FormClassName = "ew-horizontal ew-form ew-edit-form";
	public $IsModal = FALSE;
	public $IsMobileOrModal = FALSE;
	public $DbMasterFilter;
	public $DbDetailFilter;

	//
	// Page run
	//

	public function run()
	{
		global $ExportType, $CustomExportType, $ExportFileName, $UserProfile, $Language, $Security, $CurrentForm,
			$FormError, $SkipHeaderFooter;

		// Is modal
		$this->IsModal = (Param("modal") == "1");

		// User profile
		$UserProfile = new UserProfile();

		// Security
		if (!$this->setupApiRequest()) {
			$Security = new AdvancedSecurity();
			if (!$Security->isLoggedIn())
				$Security->autoLogin();
			$Security->loadCurrentUserLevel($this->ProjectID . $this->TableName);
			if (!$Security->canEdit()) {
				$Security->saveLastUrl();
				$this->setFailureMessage(DeniedMessage()); // Set no permission
				if ($Security->canList())
					$this->terminate(GetUrl("kp_citaslist.php"));
				else
					$this->terminate(GetUrl("login.php"));
				return;
			}
		}

		// Create form object
		$CurrentForm = new HttpForm();
		$this->CurrentAction = Param("action"); // Set up current action
		$this->id_reg->setVisibility();
		$this->idempresa->setVisibility();
		$this->numcompra->setVisibility();
		$this->codcita->setVisibility();
		$this->codrampa->setVisibility();
		$this->idestado->setVisibility();
		$this->fechacita->setVisibility();
		$this->fechaatencion->setVisibility();
		$this->horaatencion->setVisibility();
		$this->tiposervicio->setVisibility();
		$this->numtotal->setVisibility();
		$this->fechareg->setVisibility();
		$this->hideFieldsForAddEdit();

		// Do not use lookup cache
		$this->setUseLookupCache(FALSE);

		// Global Page Loading event (in userfn*.php)
		Page_Loading();

		// Page Load event
		$this->Page_Load();

		// Check token
		if (!$this->validPost()) {
			Write($Language->phrase("InvalidPostRequest"));
			$this->terminate();
		}

		// Create Token
		$this->createToken();

		// Set up lookup cache
		// Check modal

		if ($this->IsModal)
			$SkipHeaderFooter = TRUE;
		$this->IsMobileOrModal = IsMobile() || $this->IsModal;
		$this->FormClassName = "ew-form ew-edit-form ew-horizontal";
		$loaded = FALSE;
		$postBack = FALSE;

		// Set up current action and primary key
		if (IsApi()) {
			$this->CurrentAction = "update"; // Update record directly
			$postBack = TRUE;
		} elseif (Post("action") !== NULL) {
			$this->CurrentAction = Post("action"); // Get action code
			if (!$this->isShow()) // Not reload record, handle as postback
				$postBack = TRUE;

			// Load key from Form
			if ($CurrentForm->hasValue("x_id_reg")) {
				$this->id_reg->setFormValue($CurrentForm->getValue("x_id_reg"));
			}
		} else {
			$this->CurrentAction = "show"; // Default action is display

			// Load key from QueryString
			$loadByQuery = FALSE;
			if (Get("id_reg") !== NULL) {
				$this->id_reg->setQueryStringValue(Get("id_reg"));
				$loadByQuery = TRUE;
			} else {
				$this->id_reg->CurrentValue = NULL;
			}
		}

		// Load current record
		$loaded = $this->loadRow();

		// Process form if post back
		if ($postBack) {
			$this->loadFormValues(); // Get form values
		}

		// Validate form if post back
		if ($postBack) {
			if (!$this->validateForm()) {
				$this->setFailureMessage($FormError);
				$this->EventCancelled = TRUE; // Event cancelled
				$this->restoreFormValues();
				if (IsApi()) {
					$this->terminate();
					return;
				} else {
					$this->CurrentAction = ""; // Form error, reset action
				}
			}
		}

		// Perform current action
		switch ($this->CurrentAction) {
			case "show": // Get a record to display
				if (!$loaded) { // Load record based on key
					if ($this->getFailureMessage() == "")
						$this->setFailureMessage($Language->phrase("NoRecord")); // No record found
					$this->terminate("kp_citaslist.php"); // No matching record, return to list
				}
				break;
			case "update": // Update
				$returnUrl = $this->getReturnUrl();
				if (GetPageName($returnUrl) == "kp_citaslist.php")
					$returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
				$this->SendEmail = TRUE; // Send email on update success
				if ($this->editRow()) { // Update record based on key
					if ($this->getSuccessMessage() == "")
						$this->setSuccessMessage($Language->phrase("UpdateSuccess")); // Update success
					if (IsApi()) {
						$this->terminate(TRUE);
						return;
					} else {
						$this->terminate($returnUrl); // Return to caller
					}
				} elseif (IsApi()) { // API request, return
					$this->terminate();
					return;
				} elseif ($this->getFailureMessage() == $Language->phrase("NoRecord")) {
					$this->terminate($returnUrl); // Return to caller
				} else {
					$this->EventCancelled = TRUE; // Event cancelled
					$this->restoreFormValues(); // Restore form values if update failed
				}
		}

		// Set up Breadcrumb
		$this->setupBreadcrumb();

		// Render the record
		$this->RowType = ROWTYPE_EDIT; // Render as Edit
		$this->resetAttributes();
		$this->renderRow();
	}

	// Get upload files
	protected function getUploadFiles()
	{
		global $CurrentForm, $Language;
	}

	// Load form values
	protected function loadFormValues()
	{

		// Load from form
		global $CurrentForm;

		// Check field name 'id_reg' first before field var 'x_id_reg'
		$val = $CurrentForm->hasValue("id_reg") ? $CurrentForm->getValue("id_reg") : $CurrentForm->getValue("x_id_reg");
		if (!$this->id_reg->IsDetailKey)
			$this->id_reg->setFormValue($val);

		// Check field name 'idempresa' first before field var 'x_idempresa'
		$val = $CurrentForm->hasValue("idempresa") ? $CurrentForm->getValue("idempresa") : $CurrentForm->getValue("x_idempresa");
		if (!$this->idempresa->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->idempresa->Visible = FALSE; // Disable update for API request
			else
				$this->idempresa->setFormValue($val);
		}

		// Check field name 'numcompra' first before field var 'x_numcompra'
		$val = $CurrentForm->hasValue("numcompra") ? $CurrentForm->getValue("numcompra") : $CurrentForm->getValue("x_numcompra");
		if (!$this->numcompra->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->numcompra->Visible = FALSE; // Disable update for API request
			else
				$this->numcompra->setFormValue($val);
		}

		// Check field name 'codcita' first before field var 'x_codcita'
		$val = $CurrentForm->hasValue("codcita") ? $CurrentForm->getValue("codcita") : $CurrentForm->getValue("x_codcita");
		if (!$this->codcita->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->codcita->Visible = FALSE; // Disable update for API request
			else
				$this->codcita->setFormValue($val);
		}

		// Check field name 'codrampa' first before field var 'x_codrampa'
		$val = $CurrentForm->hasValue("codrampa") ? $CurrentForm->getValue("codrampa") : $CurrentForm->getValue("x_codrampa");
		if (!$this->codrampa->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->codrampa->Visible = FALSE; // Disable update for API request
			else
				$this->codrampa->setFormValue($val);
		}

		// Check field name 'idestado' first before field var 'x_idestado'
		$val = $CurrentForm->hasValue("idestado") ? $CurrentForm->getValue("idestado") : $CurrentForm->getValue("x_idestado");
		if (!$this->idestado->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->idestado->Visible = FALSE; // Disable update for API request
			else
				$this->idestado->setFormValue($val);
		}

		// Check field name 'fechacita' first before field var 'x_fechacita'
		$val = $CurrentForm->hasValue("fechacita") ? $CurrentForm->getValue("fechacita") : $CurrentForm->getValue("x_fechacita");
		if (!$this->fechacita->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->fechacita->Visible = FALSE; // Disable update for API request
			else
				$this->fechacita->setFormValue($val);
			$this->fechacita->CurrentValue = UnFormatDateTime($this->fechacita->CurrentValue, 0);
		}

		// Check field name 'fechaatencion' first before field var 'x_fechaatencion'
		$val = $CurrentForm->hasValue("fechaatencion") ? $CurrentForm->getValue("fechaatencion") : $CurrentForm->getValue("x_fechaatencion");
		if (!$this->fechaatencion->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->fechaatencion->Visible = FALSE; // Disable update for API request
			else
				$this->fechaatencion->setFormValue($val);
			$this->fechaatencion->CurrentValue = UnFormatDateTime($this->fechaatencion->CurrentValue, 0);
		}

		// Check field name 'horaatencion' first before field var 'x_horaatencion'
		$val = $CurrentForm->hasValue("horaatencion") ? $CurrentForm->getValue("horaatencion") : $CurrentForm->getValue("x_horaatencion");
		if (!$this->horaatencion->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->horaatencion->Visible = FALSE; // Disable update for API request
			else
				$this->horaatencion->setFormValue($val);
			$this->horaatencion->CurrentValue = UnFormatDateTime($this->horaatencion->CurrentValue, 4);
		}

		// Check field name 'tiposervicio' first before field var 'x_tiposervicio'
		$val = $CurrentForm->hasValue("tiposervicio") ? $CurrentForm->getValue("tiposervicio") : $CurrentForm->getValue("x_tiposervicio");
		if (!$this->tiposervicio->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->tiposervicio->Visible = FALSE; // Disable update for API request
			else
				$this->tiposervicio->setFormValue($val);
		}

		// Check field name 'numtotal' first before field var 'x_numtotal'
		$val = $CurrentForm->hasValue("numtotal") ? $CurrentForm->getValue("numtotal") : $CurrentForm->getValue("x_numtotal");
		if (!$this->numtotal->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->numtotal->Visible = FALSE; // Disable update for API request
			else
				$this->numtotal->setFormValue($val);
		}

		// Check field name 'fechareg' first before field var 'x_fechareg'
		$val = $CurrentForm->hasValue("fechareg") ? $CurrentForm->getValue("fechareg") : $CurrentForm->getValue("x_fechareg");
		if (!$this->fechareg->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->fechareg->Visible = FALSE; // Disable update for API request
			else
				$this->fechareg->setFormValue($val);
			$this->fechareg->CurrentValue = UnFormatDateTime($this->fechareg->CurrentValue, 0);
		}
	}

	// Restore form values
	public function restoreFormValues()
	{
		global $CurrentForm;
		$this->id_reg->CurrentValue = $this->id_reg->FormValue;
		$this->idempresa->CurrentValue = $this->idempresa->FormValue;
		$this->numcompra->CurrentValue = $this->numcompra->FormValue;
		$this->codcita->CurrentValue = $this->codcita->FormValue;
		$this->codrampa->CurrentValue = $this->codrampa->FormValue;
		$this->idestado->CurrentValue = $this->idestado->FormValue;
		$this->fechacita->CurrentValue = $this->fechacita->FormValue;
		$this->fechacita->CurrentValue = UnFormatDateTime($this->fechacita->CurrentValue, 0);
		$this->fechaatencion->CurrentValue = $this->fechaatencion->FormValue;
		$this->fechaatencion->CurrentValue = UnFormatDateTime($this->fechaatencion->CurrentValue, 0);
		$this->horaatencion->CurrentValue = $this->horaatencion->FormValue;
		$this->horaatencion->CurrentValue = UnFormatDateTime($this->horaatencion->CurrentValue, 4);
		$this->tiposervicio->CurrentValue = $this->tiposervicio->FormValue;
		$this->numtotal->CurrentValue = $this->numtotal->FormValue;
		$this->fechareg->CurrentValue = $this->fechareg->FormValue;
		$this->fechareg->CurrentValue = UnFormatDateTime($this->fechareg->CurrentValue, 0);
	}

	// Load row based on key values
	public function loadRow()
	{
		global $Security, $Language;
		$filter = $this->getRecordFilter();

		// Call Row Selecting event
		$this->Row_Selecting($filter);

		// Load SQL based on filter
		$this->CurrentFilter = $filter;
		$sql = $this->getCurrentSql();
		$conn = $this->getConnection();
		$res = FALSE;
		$rs = LoadRecordset($sql, $conn);
		if ($rs && !$rs->EOF) {
			$res = TRUE;
			$this->loadRowValues($rs); // Load row values
			$rs->close();
		}
		return $res;
	}

	// Load row values from recordset
	public function loadRowValues($rs = NULL)
	{
		if ($rs && !$rs->EOF)
			$row = $rs->fields;
		else
			$row = $this->newRow();

		// Call Row Selected event
		$this->Row_Selected($row);
		if (!$rs || $rs->EOF)
			return;
		$this->id_reg->setDbValue($row['id_reg']);
		$this->idempresa->setDbValue($row['idempresa']);
		$this->numcompra->setDbValue($row['numcompra']);
		$this->codcita->setDbValue($row['codcita']);
		$this->codrampa->setDbValue($row['codrampa']);
		$this->idestado->setDbValue($row['idestado']);
		$this->fechacita->setDbValue($row['fechacita']);
		$this->fechaatencion->setDbValue($row['fechaatencion']);
		$this->horaatencion->setDbValue($row['horaatencion']);
		$this->tiposervicio->setDbValue($row['tiposervicio']);
		$this->numtotal->setDbValue($row['numtotal']);
		$this->fechareg->setDbValue($row['fechareg']);
	}

	// Return a row with default values
	protected function newRow()
	{
		$row = [];
		$row['id_reg'] = NULL;
		$row['idempresa'] = NULL;
		$row['numcompra'] = NULL;
		$row['codcita'] = NULL;
		$row['codrampa'] = NULL;
		$row['idestado'] = NULL;
		$row['fechacita'] = NULL;
		$row['fechaatencion'] = NULL;
		$row['horaatencion'] = NULL;
		$row['tiposervicio'] = NULL;
		$row['numtotal'] = NULL;
		$row['fechareg'] = NULL;
		return $row;
	}

	// Load old record
	protected function loadOldRecord()
	{

		// Load key values from Session
		$validKey = TRUE;
		if (strval($this->getKey("id_reg")) != "")
			$this->id_reg->OldValue = $this->getKey("id_reg"); // id_reg
		else
			$validKey = FALSE;

		// Load old record
		$this->OldRecordset = NULL;
		if ($validKey) {
			$this->CurrentFilter = $this->getRecordFilter();
			$sql = $this->getCurrentSql();
			$conn = $this->getConnection();
			$this->OldRecordset = LoadRecordset($sql, $conn);
		}
		$this->loadRowValues($this->OldRecordset); // Load row values
		return $validKey;
	}

	// Render row values based on field settings
	public function renderRow()
	{
		global $Security, $Language, $CurrentLanguage;

		// Initialize URLs
		// Call Row_Rendering event

		$this->Row_Rendering();

		// Common render codes for all row types
		// id_reg
		// idempresa
		// numcompra
		// codcita
		// codrampa
		// idestado
		// fechacita
		// fechaatencion
		// horaatencion
		// tiposervicio
		// numtotal
		// fechareg

		if ($this->RowType == ROWTYPE_VIEW) { // View row

			// id_reg
			$this->id_reg->ViewValue = $this->id_reg->CurrentValue;
			$this->id_reg->ViewCustomAttributes = "";

			// idempresa
			$this->idempresa->ViewValue = $this->idempresa->CurrentValue;
			$this->idempresa->ViewValue = FormatNumber($this->idempresa->ViewValue, 0, -2, -2, -2);
			$this->idempresa->ViewCustomAttributes = "";

			// numcompra
			$this->numcompra->ViewValue = $this->numcompra->CurrentValue;
			$this->numcompra->ViewCustomAttributes = "";

			// codcita
			$this->codcita->ViewValue = $this->codcita->CurrentValue;
			$this->codcita->ViewCustomAttributes = "";

			// codrampa
			$this->codrampa->ViewValue = $this->codrampa->CurrentValue;
			$this->codrampa->ViewCustomAttributes = "";

			// idestado
			$this->idestado->ViewValue = $this->idestado->CurrentValue;
			$this->idestado->ViewValue = FormatNumber($this->idestado->ViewValue, 0, -2, -2, -2);
			$this->idestado->ViewCustomAttributes = "";

			// fechacita
			$this->fechacita->ViewValue = $this->fechacita->CurrentValue;
			$this->fechacita->ViewValue = FormatDateTime($this->fechacita->ViewValue, 0);
			$this->fechacita->ViewCustomAttributes = "";

			// fechaatencion
			$this->fechaatencion->ViewValue = $this->fechaatencion->CurrentValue;
			$this->fechaatencion->ViewValue = FormatDateTime($this->fechaatencion->ViewValue, 0);
			$this->fechaatencion->ViewCustomAttributes = "";

			// horaatencion
			$this->horaatencion->ViewValue = $this->horaatencion->CurrentValue;
			$this->horaatencion->ViewValue = FormatDateTime($this->horaatencion->ViewValue, 4);
			$this->horaatencion->ViewCustomAttributes = "";

			// tiposervicio
			$this->tiposervicio->ViewValue = $this->tiposervicio->CurrentValue;
			$this->tiposervicio->ViewCustomAttributes = "";

			// numtotal
			$this->numtotal->ViewValue = $this->numtotal->CurrentValue;
			$this->numtotal->ViewValue = FormatNumber($this->numtotal->ViewValue, 0, -2, -2, -2);
			$this->numtotal->ViewCustomAttributes = "";

			// fechareg
			$this->fechareg->ViewValue = $this->fechareg->CurrentValue;
			$this->fechareg->ViewValue = FormatDateTime($this->fechareg->ViewValue, 0);
			$this->fechareg->ViewCustomAttributes = "";

			// id_reg
			$this->id_reg->LinkCustomAttributes = "";
			$this->id_reg->HrefValue = "";
			$this->id_reg->TooltipValue = "";

			// idempresa
			$this->idempresa->LinkCustomAttributes = "";
			$this->idempresa->HrefValue = "";
			$this->idempresa->TooltipValue = "";

			// numcompra
			$this->numcompra->LinkCustomAttributes = "";
			$this->numcompra->HrefValue = "";
			$this->numcompra->TooltipValue = "";

			// codcita
			$this->codcita->LinkCustomAttributes = "";
			$this->codcita->HrefValue = "";
			$this->codcita->TooltipValue = "";

			// codrampa
			$this->codrampa->LinkCustomAttributes = "";
			$this->codrampa->HrefValue = "";
			$this->codrampa->TooltipValue = "";

			// idestado
			$this->idestado->LinkCustomAttributes = "";
			$this->idestado->HrefValue = "";
			$this->idestado->TooltipValue = "";

			// fechacita
			$this->fechacita->LinkCustomAttributes = "";
			$this->fechacita->HrefValue = "";
			$this->fechacita->TooltipValue = "";

			// fechaatencion
			$this->fechaatencion->LinkCustomAttributes = "";
			$this->fechaatencion->HrefValue = "";
			$this->fechaatencion->TooltipValue = "";

			// horaatencion
			$this->horaatencion->LinkCustomAttributes = "";
			$this->horaatencion->HrefValue = "";
			$this->horaatencion->TooltipValue = "";

			// tiposervicio
			$this->tiposervicio->LinkCustomAttributes = "";
			$this->tiposervicio->HrefValue = "";
			$this->tiposervicio->TooltipValue = "";

			// numtotal
			$this->numtotal->LinkCustomAttributes = "";
			$this->numtotal->HrefValue = "";
			$this->numtotal->TooltipValue = "";

			// fechareg
			$this->fechareg->LinkCustomAttributes = "";
			$this->fechareg->HrefValue = "";
			$this->fechareg->TooltipValue = "";
		} elseif ($this->RowType == ROWTYPE_EDIT) { // Edit row

			// id_reg
			$this->id_reg->EditAttrs["class"] = "form-control";
			$this->id_reg->EditCustomAttributes = "";
			$this->id_reg->EditValue = $this->id_reg->CurrentValue;
			$this->id_reg->ViewCustomAttributes = "";

			// idempresa
			$this->idempresa->EditAttrs["class"] = "form-control";
			$this->idempresa->EditCustomAttributes = "";
			$this->idempresa->EditValue = HtmlEncode($this->idempresa->CurrentValue);
			$this->idempresa->PlaceHolder = RemoveHtml($this->idempresa->caption());

			// numcompra
			$this->numcompra->EditAttrs["class"] = "form-control";
			$this->numcompra->EditCustomAttributes = "";
			if (!$this->numcompra->Raw)
				$this->numcompra->CurrentValue = HtmlDecode($this->numcompra->CurrentValue);
			$this->numcompra->EditValue = HtmlEncode($this->numcompra->CurrentValue);
			$this->numcompra->PlaceHolder = RemoveHtml($this->numcompra->caption());

			// codcita
			$this->codcita->EditAttrs["class"] = "form-control";
			$this->codcita->EditCustomAttributes = "";
			if (!$this->codcita->Raw)
				$this->codcita->CurrentValue = HtmlDecode($this->codcita->CurrentValue);
			$this->codcita->EditValue = HtmlEncode($this->codcita->CurrentValue);
			$this->codcita->PlaceHolder = RemoveHtml($this->codcita->caption());

			// codrampa
			$this->codrampa->EditAttrs["class"] = "form-control";
			$this->codrampa->EditCustomAttributes = "";
			if (!$this->codrampa->Raw)
				$this->codrampa->CurrentValue = HtmlDecode($this->codrampa->CurrentValue);
			$this->codrampa->EditValue = HtmlEncode($this->codrampa->CurrentValue);
			$this->codrampa->PlaceHolder = RemoveHtml($this->codrampa->caption());

			// idestado
			$this->idestado->EditAttrs["class"] = "form-control";
			$this->idestado->EditCustomAttributes = "";
			$this->idestado->EditValue = HtmlEncode($this->idestado->CurrentValue);
			$this->idestado->PlaceHolder = RemoveHtml($this->idestado->caption());

			// fechacita
			$this->fechacita->EditAttrs["class"] = "form-control";
			$this->fechacita->EditCustomAttributes = "";
			$this->fechacita->EditValue = HtmlEncode(FormatDateTime($this->fechacita->CurrentValue, 8));
			$this->fechacita->PlaceHolder = RemoveHtml($this->fechacita->caption());

			// fechaatencion
			$this->fechaatencion->EditAttrs["class"] = "form-control";
			$this->fechaatencion->EditCustomAttributes = "";
			$this->fechaatencion->EditValue = HtmlEncode(FormatDateTime($this->fechaatencion->CurrentValue, 8));
			$this->fechaatencion->PlaceHolder = RemoveHtml($this->fechaatencion->caption());

			// horaatencion
			$this->horaatencion->EditAttrs["class"] = "form-control";
			$this->horaatencion->EditCustomAttributes = "";
			$this->horaatencion->EditValue = HtmlEncode($this->horaatencion->CurrentValue);
			$this->horaatencion->PlaceHolder = RemoveHtml($this->horaatencion->caption());

			// tiposervicio
			$this->tiposervicio->EditAttrs["class"] = "form-control";
			$this->tiposervicio->EditCustomAttributes = "";
			if (!$this->tiposervicio->Raw)
				$this->tiposervicio->CurrentValue = HtmlDecode($this->tiposervicio->CurrentValue);
			$this->tiposervicio->EditValue = HtmlEncode($this->tiposervicio->CurrentValue);
			$this->tiposervicio->PlaceHolder = RemoveHtml($this->tiposervicio->caption());

			// numtotal
			$this->numtotal->EditAttrs["class"] = "form-control";
			$this->numtotal->EditCustomAttributes = "";
			$this->numtotal->EditValue = HtmlEncode($this->numtotal->CurrentValue);
			$this->numtotal->PlaceHolder = RemoveHtml($this->numtotal->caption());

			// fechareg
			$this->fechareg->EditAttrs["class"] = "form-control";
			$this->fechareg->EditCustomAttributes = "";
			$this->fechareg->EditValue = HtmlEncode(FormatDateTime($this->fechareg->CurrentValue, 8));
			$this->fechareg->PlaceHolder = RemoveHtml($this->fechareg->caption());

			// Edit refer script
			// id_reg

			$this->id_reg->LinkCustomAttributes = "";
			$this->id_reg->HrefValue = "";

			// idempresa
			$this->idempresa->LinkCustomAttributes = "";
			$this->idempresa->HrefValue = "";

			// numcompra
			$this->numcompra->LinkCustomAttributes = "";
			$this->numcompra->HrefValue = "";

			// codcita
			$this->codcita->LinkCustomAttributes = "";
			$this->codcita->HrefValue = "";

			// codrampa
			$this->codrampa->LinkCustomAttributes = "";
			$this->codrampa->HrefValue = "";

			// idestado
			$this->idestado->LinkCustomAttributes = "";
			$this->idestado->HrefValue = "";

			// fechacita
			$this->fechacita->LinkCustomAttributes = "";
			$this->fechacita->HrefValue = "";

			// fechaatencion
			$this->fechaatencion->LinkCustomAttributes = "";
			$this->fechaatencion->HrefValue = "";

			// horaatencion
			$this->horaatencion->LinkCustomAttributes = "";
			$this->horaatencion->HrefValue = "";

			// tiposervicio
			$this->tiposervicio->LinkCustomAttributes = "";
			$this->tiposervicio->HrefValue = "";

			// numtotal
			$this->numtotal->LinkCustomAttributes = "";
			$this->numtotal->HrefValue = "";

			// fechareg
			$this->fechareg->LinkCustomAttributes = "";
			$this->fechareg->HrefValue = "";
		}
		if ($this->RowType == ROWTYPE_ADD || $this->RowType == ROWTYPE_EDIT || $this->RowType == ROWTYPE_SEARCH) // Add/Edit/Search row
			$this->setupFieldTitles();

		// Call Row Rendered event
		if ($this->RowType != ROWTYPE_AGGREGATEINIT)
			$this->Row_Rendered();
	}

	// Validate form
	protected function validateForm()
	{
		global $Language, $FormError;

		// Initialize form error message
		$FormError = "";

		// Check if validation required
		if (!Config("SERVER_VALIDATE"))
			return ($FormError == "");
		if ($this->id_reg->Required) {
			if (!$this->id_reg->IsDetailKey && $this->id_reg->FormValue != NULL && $this->id_reg->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->id_reg->caption(), $this->id_reg->RequiredErrorMessage));
			}
		}
		if ($this->idempresa->Required) {
			if (!$this->idempresa->IsDetailKey && $this->idempresa->FormValue != NULL && $this->idempresa->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->idempresa->caption(), $this->idempresa->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->idempresa->FormValue)) {
			AddMessage($FormError, $this->idempresa->errorMessage());
		}
		if ($this->numcompra->Required) {
			if (!$this->numcompra->IsDetailKey && $this->numcompra->FormValue != NULL && $this->numcompra->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->numcompra->caption(), $this->numcompra->RequiredErrorMessage));
			}
		}
		if ($this->codcita->Required) {
			if (!$this->codcita->IsDetailKey && $this->codcita->FormValue != NULL && $this->codcita->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->codcita->caption(), $this->codcita->RequiredErrorMessage));
			}
		}
		if ($this->codrampa->Required) {
			if (!$this->codrampa->IsDetailKey && $this->codrampa->FormValue != NULL && $this->codrampa->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->codrampa->caption(), $this->codrampa->RequiredErrorMessage));
			}
		}
		if ($this->idestado->Required) {
			if (!$this->idestado->IsDetailKey && $this->idestado->FormValue != NULL && $this->idestado->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->idestado->caption(), $this->idestado->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->idestado->FormValue)) {
			AddMessage($FormError, $this->idestado->errorMessage());
		}
		if ($this->fechacita->Required) {
			if (!$this->fechacita->IsDetailKey && $this->fechacita->FormValue != NULL && $this->fechacita->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->fechacita->caption(), $this->fechacita->RequiredErrorMessage));
			}
		}
		if (!CheckDate($this->fechacita->FormValue)) {
			AddMessage($FormError, $this->fechacita->errorMessage());
		}
		if ($this->fechaatencion->Required) {
			if (!$this->fechaatencion->IsDetailKey && $this->fechaatencion->FormValue != NULL && $this->fechaatencion->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->fechaatencion->caption(), $this->fechaatencion->RequiredErrorMessage));
			}
		}
		if (!CheckDate($this->fechaatencion->FormValue)) {
			AddMessage($FormError, $this->fechaatencion->errorMessage());
		}
		if ($this->horaatencion->Required) {
			if (!$this->horaatencion->IsDetailKey && $this->horaatencion->FormValue != NULL && $this->horaatencion->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->horaatencion->caption(), $this->horaatencion->RequiredErrorMessage));
			}
		}
		if (!CheckTime($this->horaatencion->FormValue)) {
			AddMessage($FormError, $this->horaatencion->errorMessage());
		}
		if ($this->tiposervicio->Required) {
			if (!$this->tiposervicio->IsDetailKey && $this->tiposervicio->FormValue != NULL && $this->tiposervicio->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->tiposervicio->caption(), $this->tiposervicio->RequiredErrorMessage));
			}
		}
		if ($this->numtotal->Required) {
			if (!$this->numtotal->IsDetailKey && $this->numtotal->FormValue != NULL && $this->numtotal->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->numtotal->caption(), $this->numtotal->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->numtotal->FormValue)) {
			AddMessage($FormError, $this->numtotal->errorMessage());
		}
		if ($this->fechareg->Required) {
			if (!$this->fechareg->IsDetailKey && $this->fechareg->FormValue != NULL && $this->fechareg->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->fechareg->caption(), $this->fechareg->RequiredErrorMessage));
			}
		}
		if (!CheckDate($this->fechareg->FormValue)) {
			AddMessage($FormError, $this->fechareg->errorMessage());
		}

		// Return validate result
		$validateForm = ($FormError == "");

		// Call Form_CustomValidate event
		$formCustomError = "";
		$validateForm = $validateForm && $this->Form_CustomValidate($formCustomError);
		if ($formCustomError != "") {
			AddMessage($FormError, $formCustomError);
		}
		return $validateForm;
	}

	// Update record based on key values
	protected function editRow()
	{
		global $Security, $Language;
		$oldKeyFilter = $this->getRecordFilter();
		$filter = $this->applyUserIDFilters($oldKeyFilter);
		$conn = $this->getConnection();
		$this->CurrentFilter = $filter;
		$sql = $this->getCurrentSql();
		$conn->raiseErrorFn = Config("ERROR_FUNC");
		$rs = $conn->execute($sql);
		$conn->raiseErrorFn = "";
		if ($rs === FALSE)
			return FALSE;
		if ($rs->EOF) {
			$this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
			$editRow = FALSE; // Update Failed
		} else {

			// Save old values
			$rsold = &$rs->fields;
			$this->loadDbValues($rsold);
			$rsnew = [];

			// idempresa
			$this->idempresa->setDbValueDef($rsnew, $this->idempresa->CurrentValue, 0, $this->idempresa->ReadOnly);

			// numcompra
			$this->numcompra->setDbValueDef($rsnew, $this->numcompra->CurrentValue, "", $this->numcompra->ReadOnly);

			// codcita
			$this->codcita->setDbValueDef($rsnew, $this->codcita->CurrentValue, "", $this->codcita->ReadOnly);

			// codrampa
			$this->codrampa->setDbValueDef($rsnew, $this->codrampa->CurrentValue, NULL, $this->codrampa->ReadOnly);

			// idestado
			$this->idestado->setDbValueDef($rsnew, $this->idestado->CurrentValue, 0, $this->idestado->ReadOnly);

			// fechacita
			$this->fechacita->setDbValueDef($rsnew, UnFormatDateTime($this->fechacita->CurrentValue, 0), CurrentDate(), $this->fechacita->ReadOnly);

			// fechaatencion
			$this->fechaatencion->setDbValueDef($rsnew, UnFormatDateTime($this->fechaatencion->CurrentValue, 0), NULL, $this->fechaatencion->ReadOnly);

			// horaatencion
			$this->horaatencion->setDbValueDef($rsnew, $this->horaatencion->CurrentValue, NULL, $this->horaatencion->ReadOnly);

			// tiposervicio
			$this->tiposervicio->setDbValueDef($rsnew, $this->tiposervicio->CurrentValue, "", $this->tiposervicio->ReadOnly);

			// numtotal
			$this->numtotal->setDbValueDef($rsnew, $this->numtotal->CurrentValue, 0, $this->numtotal->ReadOnly);

			// fechareg
			$this->fechareg->setDbValueDef($rsnew, UnFormatDateTime($this->fechareg->CurrentValue, 0), NULL, $this->fechareg->ReadOnly);

			// Call Row Updating event
			$updateRow = $this->Row_Updating($rsold, $rsnew);

			// Check for duplicate key when key changed
			if ($updateRow) {
				$newKeyFilter = $this->getRecordFilter($rsnew); 
				if ($newKeyFilter != $oldKeyFilter) {
					$rsChk = $this->loadRs($newKeyFilter);
					if ($rsChk && !$rsChk->EOF) {
						$keyErrMsg = str_replace("%f", $newKeyFilter, $Language->phrase("DupKey"));
						$this->setFailureMessage($keyErrMsg);
						$rsChk->close();
						$updateRow = FALSE;
					}
				}
			}
			if ($updateRow) {
				$conn->raiseErrorFn = Config("ERROR_FUNC");
				if (count($rsnew) > 0)
					$editRow = $this->update($rsnew, "", $rsold);
				else
					$editRow = TRUE; // No field to update
				$conn->raiseErrorFn = "";
				if ($editRow) {
				}
			} else {
				if ($this->getSuccessMessage() != "" || $this->getFailureMessage() != "") {

					// Use the message, do nothing
				} elseif ($this->CancelMessage != "") {
					$this->setFailureMessage($this->CancelMessage);
					$this->CancelMessage = "";
				} else {
					$this->setFailureMessage($Language->phrase("UpdateCancelled"));
				}
				$editRow = FALSE;
			}
		}

		// Call Row_Updated event
		if ($editRow)
			$this->Row_Updated($rsold, $rsnew);
		$rs->close();

		// Write JSON for API request
		if (IsApi() && $editRow) {
			$row = $this->getRecordsFromRecordset([$rsnew], TRUE);
			WriteJson(["success" => TRUE, $this->TableVar => $row]);
		}
		return $editRow;
	}

	// Set up Breadcrumb
	protected function setupBreadcrumb()
	{
		global $Breadcrumb, $Language;
		$Breadcrumb = new Breadcrumb();
		$url = substr(CurrentUrl(), strrpos(CurrentUrl(), "/")+1);
		$Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("kp_citaslist.php"), "", $this->TableVar, TRUE);
		$pageId = "edit";
		$Breadcrumb->add("edit", $pageId, $url);
	}

	// Setup lookup options
	public function setupLookupOptions($fld)
	{
		if ($fld->Lookup !== NULL && $fld->Lookup->Options === NULL) {

			// No need to check any more
			$fld->Lookup->Options = [];

			// Set up lookup SQL
			switch ($fld->FieldVar) {
				default:
					$lookupFilter = "";
					break;
			}

			// Always call to Lookup->getSql so that user can setup Lookup->Options in Lookup_Selecting server event
			$sql = $fld->Lookup->getSql(FALSE, "", $lookupFilter, $this);

			// Set up lookup cache
			if ($fld->UseLookupCache && $sql != "" && count($fld->Lookup->Options) == 0) {
				$conn = $this->getConnection();
				$totalCnt = $this->getRecordCount($sql);
				if ($totalCnt > $fld->LookupCacheCount) // Total count > cache count, do not cache
					return;
				$rs = $conn->execute($sql);
				$ar = [];
				while ($rs && !$rs->EOF) {
					$row = &$rs->fields;

					// Format the field values
					switch ($fld->FieldVar) {
					}
					$ar[strval($row[0])] = $row;
					$rs->moveNext();
				}
				if ($rs)
					$rs->close();
				$fld->Lookup->Options = $ar;
			}
		}
	}

	// Set up starting record parameters
	public function setupStartRecord()
	{
		if ($this->DisplayRecords == 0)
			return;
		if ($this->isPageRequest()) { // Validate request
			$startRec = Get(Config("TABLE_START_REC"));
			$pageNo = Get(Config("TABLE_PAGE_NO"));
			if ($startRec !== NULL) { // Check for "start" parameter
				$this->StartRecord = $startRec;
				$this->setStartRecordNumber($this->StartRecord);
			} elseif ($pageNo !== NULL) {
				if (is_numeric($pageNo)) {
					$this->StartRecord = ($pageNo - 1) * $this->DisplayRecords + 1;
					if ($this->StartRecord <= 0) {
						$this->StartRecord = 1;
					} elseif ($this->StartRecord >= (int)(($this->TotalRecords - 1)/$this->DisplayRecords) * $this->DisplayRecords + 1) {
						$this->StartRecord = (int)(($this->TotalRecords - 1)/$this->DisplayRecords) * $this->DisplayRecords + 1;
					}
					$this->setStartRecordNumber($this->StartRecord);
				}
			}
		}
		$this->StartRecord = $this->getStartRecordNumber();

		// Check if correct start record counter
		if (!is_numeric($this->StartRecord) || $this->StartRecord == "") { // Avoid invalid start record counter
			$this->StartRecord = 1; // Reset start record counter
			$this->setStartRecordNumber($this->StartRecord);
		} elseif ($this->StartRecord > $this->TotalRecords) { // Avoid starting record > total records
			$this->StartRecord = (int)(($this->TotalRecords - 1)/$this->DisplayRecords) * $this->DisplayRecords + 1; // Point to last page first record
			$this->setStartRecordNumber($this->StartRecord);
		} elseif (($this->StartRecord - 1) % $this->DisplayRecords != 0) {
			$this->StartRecord = (int)(($this->StartRecord - 1)/$this->DisplayRecords) * $this->DisplayRecords + 1; // Point to page boundary
			$this->setStartRecordNumber($this->StartRecord);
		}
	}

	// Page Load event
	function Page_Load() {

		//echo "Page Load";
	}

	// Page Unload event
	function Page_Unload() {

		//echo "Page Unload";
	}

	// Page Redirecting event
	function Page_Redirecting(&$url) {

		// Example:
		//$url = "your URL";

	}

	// Message Showing event
	// $type = ''|'success'|'failure'|'warning'
	function Message_Showing(&$msg, $type) {
		if ($type == 'success') {

			//$msg = "your success message";
		} elseif ($type == 'failure') {

			//$msg = "your failure message";
		} elseif ($type == 'warning') {

			//$msg = "your warning message";
		} else {

			//$msg = "your message";
		}
	}

	// Page Render event
	function Page_Render() {

		//echo "Page Render";
	}

	// Page Data Rendering event
	function Page_DataRendering(&$header) {

		// Example:
		//$header = "your header";

	}

	// Page Data Rendered event
	function Page_DataRendered(&$footer) {

		// Example:
		//$footer = "your footer";

	}

	// Form Custom Validate event
	function Form_CustomValidate(&$customError) {

		// Return error message in CustomError
		return TRUE;
	}
} // End class
?>