<?php
namespace PHPMaker2020\project2;

/**
 * Page class
 */
class kp_lab_ot_det_edit extends kp_lab_ot_det
{

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

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

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

	// Page object name
	public $PageObjName = "kp_lab_ot_det_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_lab_ot_det)
		if (!isset($GLOBALS["kp_lab_ot_det"]) || get_class($GLOBALS["kp_lab_ot_det"]) == PROJECT_NAMESPACE . "kp_lab_ot_det") {
			$GLOBALS["kp_lab_ot_det"] = &$this;
			$GLOBALS["Table"] = &$GLOBALS["kp_lab_ot_det"];
		}

		// 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_lab_ot_det');

		// 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_lab_ot_det;
		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_lab_ot_det);
				$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_lab_ot_detview.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_lab_ot_detlist.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->numero->setVisibility();
		$this->idarticuloemp->setVisibility();
		$this->numcantidad->setVisibility();
		$this->codlote->setVisibility();
		$this->comentariodet->setVisibility();
		$this->fechavencimiento->setVisibility();
		$this->codproveedor->setVisibility();
		$this->fechaemision->setVisibility();
		$this->fechaentrega->setVisibility();
		$this->comentarioesp->setVisibility();
		$this->tipo_registro->setVisibility();
		$this->destinatario->setVisibility();
		$this->fecha_reg->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_lab_ot_detlist.php"); // No matching record, return to list
				}
				break;
			case "update": // Update
				$returnUrl = $this->getReturnUrl();
				if (GetPageName($returnUrl) == "kp_lab_ot_detlist.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 'numero' first before field var 'x_numero'
		$val = $CurrentForm->hasValue("numero") ? $CurrentForm->getValue("numero") : $CurrentForm->getValue("x_numero");
		if (!$this->numero->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->numero->Visible = FALSE; // Disable update for API request
			else
				$this->numero->setFormValue($val);
		}

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

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

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

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

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

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

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

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

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

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

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

		// Check field name 'fecha_reg' first before field var 'x_fecha_reg'
		$val = $CurrentForm->hasValue("fecha_reg") ? $CurrentForm->getValue("fecha_reg") : $CurrentForm->getValue("x_fecha_reg");
		if (!$this->fecha_reg->IsDetailKey) {
			if (IsApi() && $val == NULL)
				$this->fecha_reg->Visible = FALSE; // Disable update for API request
			else
				$this->fecha_reg->setFormValue($val);
			$this->fecha_reg->CurrentValue = UnFormatDateTime($this->fecha_reg->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->numero->CurrentValue = $this->numero->FormValue;
		$this->idarticuloemp->CurrentValue = $this->idarticuloemp->FormValue;
		$this->numcantidad->CurrentValue = $this->numcantidad->FormValue;
		$this->codlote->CurrentValue = $this->codlote->FormValue;
		$this->comentariodet->CurrentValue = $this->comentariodet->FormValue;
		$this->fechavencimiento->CurrentValue = $this->fechavencimiento->FormValue;
		$this->fechavencimiento->CurrentValue = UnFormatDateTime($this->fechavencimiento->CurrentValue, 0);
		$this->codproveedor->CurrentValue = $this->codproveedor->FormValue;
		$this->fechaemision->CurrentValue = $this->fechaemision->FormValue;
		$this->fechaemision->CurrentValue = UnFormatDateTime($this->fechaemision->CurrentValue, 0);
		$this->fechaentrega->CurrentValue = $this->fechaentrega->FormValue;
		$this->fechaentrega->CurrentValue = UnFormatDateTime($this->fechaentrega->CurrentValue, 0);
		$this->comentarioesp->CurrentValue = $this->comentarioesp->FormValue;
		$this->tipo_registro->CurrentValue = $this->tipo_registro->FormValue;
		$this->destinatario->CurrentValue = $this->destinatario->FormValue;
		$this->fecha_reg->CurrentValue = $this->fecha_reg->FormValue;
		$this->fecha_reg->CurrentValue = UnFormatDateTime($this->fecha_reg->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->numero->setDbValue($row['numero']);
		$this->idarticuloemp->setDbValue($row['idarticuloemp']);
		$this->numcantidad->setDbValue($row['numcantidad']);
		$this->codlote->setDbValue($row['codlote']);
		$this->comentariodet->setDbValue($row['comentariodet']);
		$this->fechavencimiento->setDbValue($row['fechavencimiento']);
		$this->codproveedor->setDbValue($row['codproveedor']);
		$this->fechaemision->setDbValue($row['fechaemision']);
		$this->fechaentrega->setDbValue($row['fechaentrega']);
		$this->comentarioesp->setDbValue($row['comentarioesp']);
		$this->tipo_registro->setDbValue($row['tipo_registro']);
		$this->destinatario->setDbValue($row['destinatario']);
		$this->fecha_reg->setDbValue($row['fecha_reg']);
	}

	// Return a row with default values
	protected function newRow()
	{
		$row = [];
		$row['id_reg'] = NULL;
		$row['idempresa'] = NULL;
		$row['numero'] = NULL;
		$row['idarticuloemp'] = NULL;
		$row['numcantidad'] = NULL;
		$row['codlote'] = NULL;
		$row['comentariodet'] = NULL;
		$row['fechavencimiento'] = NULL;
		$row['codproveedor'] = NULL;
		$row['fechaemision'] = NULL;
		$row['fechaentrega'] = NULL;
		$row['comentarioesp'] = NULL;
		$row['tipo_registro'] = NULL;
		$row['destinatario'] = NULL;
		$row['fecha_reg'] = 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
		// numero
		// idarticuloemp
		// numcantidad
		// codlote
		// comentariodet
		// fechavencimiento
		// codproveedor
		// fechaemision
		// fechaentrega
		// comentarioesp
		// tipo_registro
		// destinatario
		// fecha_reg

		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 = "";

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

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

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

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

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

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

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

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

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

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

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

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

			// fecha_reg
			$this->fecha_reg->ViewValue = $this->fecha_reg->CurrentValue;
			$this->fecha_reg->ViewValue = FormatDateTime($this->fecha_reg->ViewValue, 0);
			$this->fecha_reg->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 = "";

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

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

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

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

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

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

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

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

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

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

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

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

			// fecha_reg
			$this->fecha_reg->LinkCustomAttributes = "";
			$this->fecha_reg->HrefValue = "";
			$this->fecha_reg->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());

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Edit refer script
			// id_reg

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// fecha_reg
			$this->fecha_reg->LinkCustomAttributes = "";
			$this->fecha_reg->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->numero->Required) {
			if (!$this->numero->IsDetailKey && $this->numero->FormValue != NULL && $this->numero->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->numero->caption(), $this->numero->RequiredErrorMessage));
			}
		}
		if ($this->idarticuloemp->Required) {
			if (!$this->idarticuloemp->IsDetailKey && $this->idarticuloemp->FormValue != NULL && $this->idarticuloemp->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->idarticuloemp->caption(), $this->idarticuloemp->RequiredErrorMessage));
			}
		}
		if ($this->numcantidad->Required) {
			if (!$this->numcantidad->IsDetailKey && $this->numcantidad->FormValue != NULL && $this->numcantidad->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->numcantidad->caption(), $this->numcantidad->RequiredErrorMessage));
			}
		}
		if (!CheckInteger($this->numcantidad->FormValue)) {
			AddMessage($FormError, $this->numcantidad->errorMessage());
		}
		if ($this->codlote->Required) {
			if (!$this->codlote->IsDetailKey && $this->codlote->FormValue != NULL && $this->codlote->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->codlote->caption(), $this->codlote->RequiredErrorMessage));
			}
		}
		if ($this->comentariodet->Required) {
			if (!$this->comentariodet->IsDetailKey && $this->comentariodet->FormValue != NULL && $this->comentariodet->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->comentariodet->caption(), $this->comentariodet->RequiredErrorMessage));
			}
		}
		if ($this->fechavencimiento->Required) {
			if (!$this->fechavencimiento->IsDetailKey && $this->fechavencimiento->FormValue != NULL && $this->fechavencimiento->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->fechavencimiento->caption(), $this->fechavencimiento->RequiredErrorMessage));
			}
		}
		if (!CheckDate($this->fechavencimiento->FormValue)) {
			AddMessage($FormError, $this->fechavencimiento->errorMessage());
		}
		if ($this->codproveedor->Required) {
			if (!$this->codproveedor->IsDetailKey && $this->codproveedor->FormValue != NULL && $this->codproveedor->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->codproveedor->caption(), $this->codproveedor->RequiredErrorMessage));
			}
		}
		if ($this->fechaemision->Required) {
			if (!$this->fechaemision->IsDetailKey && $this->fechaemision->FormValue != NULL && $this->fechaemision->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->fechaemision->caption(), $this->fechaemision->RequiredErrorMessage));
			}
		}
		if (!CheckDate($this->fechaemision->FormValue)) {
			AddMessage($FormError, $this->fechaemision->errorMessage());
		}
		if ($this->fechaentrega->Required) {
			if (!$this->fechaentrega->IsDetailKey && $this->fechaentrega->FormValue != NULL && $this->fechaentrega->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->fechaentrega->caption(), $this->fechaentrega->RequiredErrorMessage));
			}
		}
		if (!CheckDate($this->fechaentrega->FormValue)) {
			AddMessage($FormError, $this->fechaentrega->errorMessage());
		}
		if ($this->comentarioesp->Required) {
			if (!$this->comentarioesp->IsDetailKey && $this->comentarioesp->FormValue != NULL && $this->comentarioesp->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->comentarioesp->caption(), $this->comentarioesp->RequiredErrorMessage));
			}
		}
		if ($this->tipo_registro->Required) {
			if (!$this->tipo_registro->IsDetailKey && $this->tipo_registro->FormValue != NULL && $this->tipo_registro->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->tipo_registro->caption(), $this->tipo_registro->RequiredErrorMessage));
			}
		}
		if ($this->destinatario->Required) {
			if (!$this->destinatario->IsDetailKey && $this->destinatario->FormValue != NULL && $this->destinatario->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->destinatario->caption(), $this->destinatario->RequiredErrorMessage));
			}
		}
		if ($this->fecha_reg->Required) {
			if (!$this->fecha_reg->IsDetailKey && $this->fecha_reg->FormValue != NULL && $this->fecha_reg->FormValue == "") {
				AddMessage($FormError, str_replace("%s", $this->fecha_reg->caption(), $this->fecha_reg->RequiredErrorMessage));
			}
		}
		if (!CheckDate($this->fecha_reg->FormValue)) {
			AddMessage($FormError, $this->fecha_reg->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);

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

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

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

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

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

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

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

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

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

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

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

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

			// fecha_reg
			$this->fecha_reg->setDbValueDef($rsnew, UnFormatDateTime($this->fecha_reg->CurrentValue, 0), CurrentDate(), $this->fecha_reg->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_lab_ot_detlist.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
?>