<?php

namespace ProjectManagement\prjProjectManagement;

use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Container\ContainerInterface;
use Slim\Routing\RouteCollectorProxy;
use Slim\App;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Closure;

/**
 * Page class
 */
class MasteruserAddopt extends Masteruser
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

    // Title
    public $Title = null; // Title for <title> tag

    // Rendering View
    public $RenderingView = false;

    // CSS class/style
    public $CurrentPageName = "masteruseraddopt";

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

    // Page layout
    public $UseLayout = true;

    // Page terminated
    private $terminated = false;

    // 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($withArgs = true)
    {
        $route = GetRoute();
        $args = RemoveXss($route->getArguments());
        if (!$withArgs) {
            foreach ($args as $key => &$val) {
                $val = "";
            }
            unset($val);
        }
        return rtrim(UrlFor($route->getName(), $args), "/") . "?";
    }

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

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

    // Set field visibility
    public function setVisibility()
    {
        $this->EmployeeID->Visible = false;
        $this->FirstName->setVisibility();
        $this->LastName->setVisibility();
        $this->FullName->setVisibility();
        $this->_Username->setVisibility();
        $this->UserPassword->setVisibility();
        $this->Level->setVisibility();
        $this->_Email->setVisibility();
        $this->Position->setVisibility();
        $this->Department->setVisibility();
        $this->Employee->setVisibility();
        $this->WhatsAppNumber->setVisibility();
        $this->Active->setVisibility();
        $this->Created_Date->setVisibility();
        $this->Created_By->setVisibility();
        $this->Last_Updated_Date->setVisibility();
        $this->Last_Updated_By->setVisibility();
    }

    // Constructor
    public function __construct()
    {
        parent::__construct();
        global $Language, $DashboardReport, $DebugTimer, $UserTable;
        $this->TableVar = 'masteruser';
        $this->TableName = 'masteruser';

        // Table CSS class
        $this->TableClass = "table table-striped table-bordered table-hover table-sm ew-view-table";

        // Initialize
        $GLOBALS["Page"] = &$this;

        // Language object
        $Language = Container("app.language");

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

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

        // Start timer
        $DebugTimer = Container("debug.timer");

        // Debug message
        LoadDebugMessage();

        // Open connection
        $GLOBALS["Conn"] ??= $this->getConnection();

        // User table object
        $UserTable = Container("usertable");
    }

    // Get content from stream
    public function getContents(): string
    {
        global $Response;
        return $Response?->getBody() ?? ob_get_clean();
    }

    // Is lookup
    public function isLookup()
    {
        return SameText(Route(0), Config("API_LOOKUP_ACTION"));
    }

    // Is AutoFill
    public function isAutoFill()
    {
        return $this->isLookup() && SameText(Post("ajax"), "autofill");
    }

    // Is AutoSuggest
    public function isAutoSuggest()
    {
        return $this->isLookup() && SameText(Post("ajax"), "autosuggest");
    }

    // Is modal lookup
    public function isModalLookup()
    {
        return $this->isLookup() && SameText(Post("ajax"), "modal");
    }

    // Is terminated
    public function isTerminated()
    {
        return $this->terminated;
    }

    /**
     * Terminate page
     *
     * @param string $url URL for direction
     * @return void
     */
    public function terminate($url = "")
    {
        if ($this->terminated) {
            return;
        }
        global $TempImages, $DashboardReport, $Response;

        // Page is terminated
        $this->terminated = true;

        // Page Unload event
        if (method_exists($this, "pageUnload")) {
            $this->pageUnload();
        }
        DispatchEvent(new PageUnloadedEvent($this), PageUnloadedEvent::NAME);
        if (!IsApi() && method_exists($this, "pageRedirecting")) {
            $this->pageRedirecting($url);
        }

        // Close connection
        CloseConnections();

        // Return for API
        if (IsApi()) {
            $res = $url === true;
            if (!$res) { // Show response for API
                $ar = array_merge($this->getMessages(), $url ? ["url" => GetUrl($url)] : []);
                WriteJson($ar);
            }
            $this->clearMessages(); // Clear messages for API request
            return;
        } else { // Check if response is JSON
            if (WithJsonResponse()) { // With JSON response
                $this->clearMessages();
                return;
            }
        }

        // Go to URL if specified
        if ($url != "") {
            if (!Config("DEBUG") && ob_get_length()) {
                ob_end_clean();
            }
            SaveDebugMessage();
            Redirect(GetUrl($url));
        }
        return; // Return to controller
    }

    // Get records from result set
    protected function getRecordsFromRecordset($rs, $current = false)
    {
        $rows = [];
        if (is_object($rs)) { // Result set
            while ($row = $rs->fetch()) {
                $this->loadRowValues($row); // Set up DbValue/CurrentValue
                $row = $this->getRecordFromArray($row);
                if ($current) {
                    return $row;
                } else {
                    $rows[] = $row;
                }
            }
        } 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") .
                                    "/" . $fld->TableVar . "/" . $fld->Param . "/" . rawurlencode($this->getRecordKeyValue($ar))));
                                $row[$fldname] = ["type" => ContentType($val), "url" => $url, "name" => $fld->Param . ContentExtension($val)];
                            } elseif (!$fld->UploadMultiple || !ContainsString($val, Config("MULTIPLE_UPLOAD_SEPARATOR"))) { // Single file
                                $url = FullUrl(GetApiUrl(Config("API_FILE_ACTION") .
                                    "/" . $fld->TableVar . "/" . Encrypt($fld->physicalUploadPath() . $val)));
                                $row[$fldname] = ["type" => MimeContentType($val), "url" => $url, "name" => $val];
                            } else { // Multiple files
                                $files = explode(Config("MULTIPLE_UPLOAD_SEPARATOR"), $val);
                                $ar = [];
                                foreach ($files as $file) {
                                    $url = FullUrl(GetApiUrl(Config("API_FILE_ACTION") .
                                        "/" . $fld->TableVar . "/" . Encrypt($fld->physicalUploadPath() . $file)));
                                    if (!EmptyValue($file)) {
                                        $ar[] = ["type" => MimeContentType($file), "url" => $url, "name" => $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['EmployeeID'];
        }
        return $key;
    }

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

    // Lookup data
    public function lookup(array $req = [], bool $response = true)
    {
        global $Language, $Security;

        // Get lookup object
        $fieldName = $req["field"] ?? null;
        if (!$fieldName) {
            return [];
        }
        $fld = $this->Fields[$fieldName];
        $lookup = $fld->Lookup;
        $name = $req["name"] ?? "";
        if (ContainsString($name, "query_builder_rule")) {
            $lookup->FilterFields = []; // Skip parent fields if any
        }

        // Get lookup parameters
        $lookupType = $req["ajax"] ?? "unknown";
        $pageSize = -1;
        $offset = -1;
        $searchValue = "";
        if (SameText($lookupType, "modal") || SameText($lookupType, "filter")) {
            $searchValue = $req["q"] ?? $req["sv"] ?? "";
            $pageSize = $req["n"] ?? $req["recperpage"] ?? 10;
        } elseif (SameText($lookupType, "autosuggest")) {
            $searchValue = $req["q"] ?? "";
            $pageSize = $req["n"] ?? -1;
            $pageSize = is_numeric($pageSize) ? (int)$pageSize : -1;
            if ($pageSize <= 0) {
                $pageSize = Config("AUTO_SUGGEST_MAX_ENTRIES");
            }
        }
        $start = $req["start"] ?? -1;
        $start = is_numeric($start) ? (int)$start : -1;
        $page = $req["page"] ?? -1;
        $page = is_numeric($page) ? (int)$page : -1;
        $offset = $start >= 0 ? $start : ($page > 0 && $pageSize > 0 ? ($page - 1) * $pageSize : 0);
        $userSelect = Decrypt($req["s"] ?? "");
        $userFilter = Decrypt($req["f"] ?? "");
        $userOrderBy = Decrypt($req["o"] ?? "");
        $keys = $req["keys"] ?? null;
        $lookup->LookupType = $lookupType; // Lookup type
        $lookup->FilterValues = []; // Clear filter values first
        if ($keys !== null) { // Selected records from modal
            if (is_array($keys)) {
                $keys = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $keys);
            }
            $lookup->FilterFields = []; // Skip parent fields if any
            $lookup->FilterValues[] = $keys; // Lookup values
            $pageSize = -1; // Show all records
        } else { // Lookup values
            $lookup->FilterValues[] = $req["v0"] ?? $req["lookupValue"] ?? "";
        }
        $cnt = is_array($lookup->FilterFields) ? count($lookup->FilterFields) : 0;
        for ($i = 1; $i <= $cnt; $i++) {
            $lookup->FilterValues[] = $req["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;
        }
        return $lookup->toJson($this, $response); // Use settings from current page
    }
    public $IsModal = false;
    public $IsMobileOrModal = true; // Add option page is always modal

    /**
     * Page run
     *
     * @return void
     */
    public function run()
    {
        global $ExportType, $Language, $Security, $CurrentForm;

        // Use layout
        $this->UseLayout = $this->UseLayout && ConvertToBool(Param(Config("PAGE_LAYOUT"), true));

        // View
        $this->View = Get(Config("VIEW"));

        // Load user profile
        if (IsLoggedIn()) {
            Profile()->setUserName(CurrentUserName())->loadFromStorage();
        }

        // Create form object
        $CurrentForm = new HttpForm();
        $this->CurrentAction = Param("action"); // Set up current action
        $this->setVisibility();

        // Set lookup cache
        if (!in_array($this->PageID, Config("LOOKUP_CACHE_PAGE_IDS"))) {
            $this->setUseLookupCache(false);
        }

        // Global Page Loading event (in userfn*.php)
        DispatchEvent(new PageLoadingEvent($this), PageLoadingEvent::NAME);

        // Page Load event
        if (method_exists($this, "pageLoad")) {
            $this->pageLoad();
        }

        // Hide fields for add/edit
        if (!$this->UseAjaxActions) {
            $this->hideFieldsForAddEdit();
        }
        // Use inline delete
        if ($this->UseAjaxActions) {
            $this->InlineDelete = true;
        }

        // Set up lookup cache
        $this->setupLookupOptions($this->Level);
        $this->setupLookupOptions($this->Position);
        $this->setupLookupOptions($this->Employee);
        $this->setupLookupOptions($this->Active);

        // Load default values for add
        $this->loadDefaultValues();

        // Set up Breadcrumb
        // $this->setupBreadcrumb(); // Not used
        $this->loadRowValues(); // Load default values

        // Render row
        $this->RowType = RowType::ADD; // Render add type
        $this->resetAttributes();
        $this->renderRow();

        // Set LoginStatus / Page_Rendering / Page_Render
        if (!IsApi() && !$this->isTerminated()) {
            // Setup login status
            SetupLoginStatus();

            // Pass login status to client side
            SetClientVar("login", LoginStatus());

            // Global Page Rendering event (in userfn*.php)
            DispatchEvent(new PageRenderingEvent($this), PageRenderingEvent::NAME);

            // Page Render event
            if (method_exists($this, "pageRender")) {
                $this->pageRender();
            }

            // Render search option
            if (method_exists($this, "renderSearchOptions")) {
                $this->renderSearchOptions();
            }
        }
    }

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

    // Load default values
    protected function loadDefaultValues()
    {
        $this->Level->DefaultValue = $this->Level->getDefault(); // PHP
        $this->Level->OldValue = $this->Level->DefaultValue;
        $this->Employee->DefaultValue = $this->Employee->getDefault(); // PHP
        $this->Employee->OldValue = $this->Employee->DefaultValue;
        $this->Active->DefaultValue = $this->Active->getDefault(); // PHP
        $this->Active->OldValue = $this->Active->DefaultValue;
        $this->Created_Date->DefaultValue = $this->Created_Date->getDefault(); // PHP
        $this->Created_Date->OldValue = $this->Created_Date->DefaultValue;
        $this->Created_By->DefaultValue = $this->Created_By->getDefault(); // PHP
        $this->Created_By->OldValue = $this->Created_By->DefaultValue;
        $this->Last_Updated_Date->DefaultValue = $this->Last_Updated_Date->getDefault(); // PHP
        $this->Last_Updated_Date->OldValue = $this->Last_Updated_Date->DefaultValue;
        $this->Last_Updated_By->DefaultValue = $this->Last_Updated_By->getDefault(); // PHP
        $this->Last_Updated_By->OldValue = $this->Last_Updated_By->DefaultValue;
    }

    // Load form values
    protected function loadFormValues()
    {
        // Load from form
        global $CurrentForm;
        $validate = !Config("SERVER_VALIDATE");

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

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

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

        // Check field name 'Username' first before field var 'x__Username'
        $val = $CurrentForm->hasValue("Username") ? $CurrentForm->getValue("Username") : $CurrentForm->getValue("x__Username");
        if (!$this->_Username->IsDetailKey) {
            $this->_Username->setFormValue($val);
        }

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

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

        // Check field name 'Email' first before field var 'x__Email'
        $val = $CurrentForm->hasValue("Email") ? $CurrentForm->getValue("Email") : $CurrentForm->getValue("x__Email");
        if (!$this->_Email->IsDetailKey) {
            $this->_Email->setFormValue($val);
        }

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

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

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

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

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

        // Check field name 'Created_Date' first before field var 'x_Created_Date'
        $val = $CurrentForm->hasValue("Created_Date") ? $CurrentForm->getValue("Created_Date") : $CurrentForm->getValue("x_Created_Date");
        if (!$this->Created_Date->IsDetailKey) {
            $this->Created_Date->setFormValue($val);
            $this->Created_Date->CurrentValue = UnFormatDateTime($this->Created_Date->CurrentValue, $this->Created_Date->formatPattern());
        }

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

        // Check field name 'Last_Updated_Date' first before field var 'x_Last_Updated_Date'
        $val = $CurrentForm->hasValue("Last_Updated_Date") ? $CurrentForm->getValue("Last_Updated_Date") : $CurrentForm->getValue("x_Last_Updated_Date");
        if (!$this->Last_Updated_Date->IsDetailKey) {
            $this->Last_Updated_Date->setFormValue($val);
            $this->Last_Updated_Date->CurrentValue = UnFormatDateTime($this->Last_Updated_Date->CurrentValue, $this->Last_Updated_Date->formatPattern());
        }

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

        // Check field name 'EmployeeID' first before field var 'x_EmployeeID'
        $val = $CurrentForm->hasValue("EmployeeID") ? $CurrentForm->getValue("EmployeeID") : $CurrentForm->getValue("x_EmployeeID");
    }

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->FirstName->CurrentValue = ConvertToUtf8($this->FirstName->FormValue);
        $this->LastName->CurrentValue = ConvertToUtf8($this->LastName->FormValue);
        $this->FullName->CurrentValue = ConvertToUtf8($this->FullName->FormValue);
        $this->_Username->CurrentValue = ConvertToUtf8($this->_Username->FormValue);
        $this->UserPassword->CurrentValue = ConvertToUtf8($this->UserPassword->FormValue);
        $this->Level->CurrentValue = ConvertToUtf8($this->Level->FormValue);
        $this->_Email->CurrentValue = ConvertToUtf8($this->_Email->FormValue);
        $this->Position->CurrentValue = ConvertToUtf8($this->Position->FormValue);
        $this->Department->CurrentValue = ConvertToUtf8($this->Department->FormValue);
        $this->Employee->CurrentValue = ConvertToUtf8($this->Employee->FormValue);
        $this->WhatsAppNumber->CurrentValue = ConvertToUtf8($this->WhatsAppNumber->FormValue);
        $this->Active->CurrentValue = ConvertToUtf8($this->Active->FormValue);
        $this->Created_Date->CurrentValue = ConvertToUtf8($this->Created_Date->FormValue);
        $this->Created_Date->CurrentValue = UnFormatDateTime($this->Created_Date->CurrentValue, $this->Created_Date->formatPattern());
        $this->Created_By->CurrentValue = ConvertToUtf8($this->Created_By->FormValue);
        $this->Last_Updated_Date->CurrentValue = ConvertToUtf8($this->Last_Updated_Date->FormValue);
        $this->Last_Updated_Date->CurrentValue = UnFormatDateTime($this->Last_Updated_Date->CurrentValue, $this->Last_Updated_Date->formatPattern());
        $this->Last_Updated_By->CurrentValue = ConvertToUtf8($this->Last_Updated_By->FormValue);
    }

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

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

        // Load SQL based on filter
        $this->CurrentFilter = $filter;
        $sql = $this->getCurrentSql();
        $conn = $this->getConnection();
        $res = false;
        $row = $conn->fetchAssociative($sql);
        if ($row) {
            $res = true;
            $this->loadRowValues($row); // Load row values
        }
        return $res;
    }

    /**
     * Load row values from result set or record
     *
     * @param array $row Record
     * @return void
     */
    public function loadRowValues($row = null)
    {
        $row = is_array($row) ? $row : $this->newRow();

        // Call Row Selected event
        $this->rowSelected($row);
        $this->EmployeeID->setDbValue($row['EmployeeID']);
        $this->FirstName->setDbValue($row['FirstName']);
        $this->LastName->setDbValue($row['LastName']);
        $this->FullName->setDbValue($row['FullName']);
        $this->_Username->setDbValue($row['Username']);
        $this->UserPassword->setDbValue($row['UserPassword']);
        $this->Level->setDbValue($row['Level']);
        $this->_Email->setDbValue($row['Email']);
        $this->Position->setDbValue($row['Position']);
        $this->Department->setDbValue($row['Department']);
        $this->Employee->setDbValue($row['Employee']);
        $this->WhatsAppNumber->setDbValue($row['WhatsAppNumber']);
        $this->Active->setDbValue($row['Active']);
        $this->Created_Date->setDbValue($row['Created_Date']);
        $this->Created_By->setDbValue($row['Created_By']);
        $this->Last_Updated_Date->setDbValue($row['Last_Updated_Date']);
        $this->Last_Updated_By->setDbValue($row['Last_Updated_By']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $row = [];
        $row['EmployeeID'] = $this->EmployeeID->DefaultValue;
        $row['FirstName'] = $this->FirstName->DefaultValue;
        $row['LastName'] = $this->LastName->DefaultValue;
        $row['FullName'] = $this->FullName->DefaultValue;
        $row['Username'] = $this->_Username->DefaultValue;
        $row['UserPassword'] = $this->UserPassword->DefaultValue;
        $row['Level'] = $this->Level->DefaultValue;
        $row['Email'] = $this->_Email->DefaultValue;
        $row['Position'] = $this->Position->DefaultValue;
        $row['Department'] = $this->Department->DefaultValue;
        $row['Employee'] = $this->Employee->DefaultValue;
        $row['WhatsAppNumber'] = $this->WhatsAppNumber->DefaultValue;
        $row['Active'] = $this->Active->DefaultValue;
        $row['Created_Date'] = $this->Created_Date->DefaultValue;
        $row['Created_By'] = $this->Created_By->DefaultValue;
        $row['Last_Updated_Date'] = $this->Last_Updated_Date->DefaultValue;
        $row['Last_Updated_By'] = $this->Last_Updated_By->DefaultValue;
        return $row;
    }

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

        // Initialize URLs

        // Call Row_Rendering event
        $this->rowRendering();

        // Common render codes for all row types

        // EmployeeID
        $this->EmployeeID->RowCssClass = "row";

        // FirstName
        $this->FirstName->RowCssClass = "row";

        // LastName
        $this->LastName->RowCssClass = "row";

        // FullName
        $this->FullName->RowCssClass = "row";

        // Username
        $this->_Username->RowCssClass = "row";

        // UserPassword
        $this->UserPassword->RowCssClass = "row";

        // Level
        $this->Level->RowCssClass = "row";

        // Email
        $this->_Email->RowCssClass = "row";

        // Position
        $this->Position->RowCssClass = "row";

        // Department
        $this->Department->RowCssClass = "row";

        // Employee
        $this->Employee->RowCssClass = "row";

        // WhatsAppNumber
        $this->WhatsAppNumber->RowCssClass = "row";

        // Active
        $this->Active->RowCssClass = "row";

        // Created_Date
        $this->Created_Date->RowCssClass = "row";

        // Created_By
        $this->Created_By->RowCssClass = "row";

        // Last_Updated_Date
        $this->Last_Updated_Date->RowCssClass = "row";

        // Last_Updated_By
        $this->Last_Updated_By->RowCssClass = "row";

        // View row
        if ($this->RowType == RowType::VIEW) {
            // EmployeeID
            $this->EmployeeID->ViewValue = $this->EmployeeID->CurrentValue;

            // FirstName
            $this->FirstName->ViewValue = $this->FirstName->CurrentValue;

            // LastName
            $this->LastName->ViewValue = $this->LastName->CurrentValue;

            // FullName
            $this->FullName->ViewValue = $this->FullName->CurrentValue;

            // Username
            $this->_Username->ViewValue = $this->_Username->CurrentValue;

            // UserPassword
            $this->UserPassword->ViewValue = $Language->phrase("PasswordMask");

            // Level
            if ($Security->canAdmin()) { // System admin
                $curVal = strval($this->Level->CurrentValue);
                if ($curVal != "") {
                    $this->Level->ViewValue = $this->Level->lookupCacheOption($curVal);
                    if ($this->Level->ViewValue === null) { // Lookup from database
                        $filterWrk = SearchFilter($this->Level->Lookup->getTable()->Fields["userlevelid"]->searchExpression(), "=", $curVal, $this->Level->Lookup->getTable()->Fields["userlevelid"]->searchDataType(), "");
                        $sqlWrk = $this->Level->Lookup->getSql(false, $filterWrk, '', $this, true, true);
                        $conn = Conn();
                        $config = $conn->getConfiguration();
                        $config->setResultCache($this->Cache);
                        $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                        $ari = count($rswrk);
                        if ($ari > 0) { // Lookup values found
                            $arwrk = $this->Level->Lookup->renderViewRow($rswrk[0]);
                            $this->Level->ViewValue = $this->Level->displayValue($arwrk);
                        } else {
                            $this->Level->ViewValue = FormatNumber($this->Level->CurrentValue, $this->Level->formatPattern());
                        }
                    }
                } else {
                    $this->Level->ViewValue = null;
                }
            } else {
                $this->Level->ViewValue = $Language->phrase("PasswordMask");
            }

            // Email
            $this->_Email->ViewValue = $this->_Email->CurrentValue;

            // Position
            if (strval($this->Position->CurrentValue) != "") {
                $this->Position->ViewValue = $this->Position->optionCaption($this->Position->CurrentValue);
            } else {
                $this->Position->ViewValue = null;
            }

            // Department
            $this->Department->ViewValue = $this->Department->CurrentValue;

            // Employee
            if (ConvertToBool($this->Employee->CurrentValue)) {
                $this->Employee->ViewValue = $this->Employee->tagCaption(1) != "" ? $this->Employee->tagCaption(1) : "Yes";
            } else {
                $this->Employee->ViewValue = $this->Employee->tagCaption(2) != "" ? $this->Employee->tagCaption(2) : "No";
            }
            $this->Employee->CellCssStyle .= "text-align: center;";

            // WhatsAppNumber
            $this->WhatsAppNumber->ViewValue = $this->WhatsAppNumber->CurrentValue;

            // Active
            if (ConvertToBool($this->Active->CurrentValue)) {
                $this->Active->ViewValue = $this->Active->tagCaption(1) != "" ? $this->Active->tagCaption(1) : "Yes";
            } else {
                $this->Active->ViewValue = $this->Active->tagCaption(2) != "" ? $this->Active->tagCaption(2) : "No";
            }
            $this->Active->CellCssStyle .= "text-align: center;";

            // Created_Date
            $this->Created_Date->ViewValue = $this->Created_Date->CurrentValue;
            $this->Created_Date->ViewValue = FormatDateTime($this->Created_Date->ViewValue, $this->Created_Date->formatPattern());

            // Created_By
            $this->Created_By->ViewValue = $this->Created_By->CurrentValue;

            // Last_Updated_Date
            $this->Last_Updated_Date->ViewValue = $this->Last_Updated_Date->CurrentValue;
            $this->Last_Updated_Date->ViewValue = FormatDateTime($this->Last_Updated_Date->ViewValue, $this->Last_Updated_Date->formatPattern());

            // Last_Updated_By
            $this->Last_Updated_By->ViewValue = $this->Last_Updated_By->CurrentValue;

            // FirstName
            $this->FirstName->HrefValue = "";
            $this->FirstName->TooltipValue = "";

            // LastName
            $this->LastName->HrefValue = "";
            $this->LastName->TooltipValue = "";

            // FullName
            $this->FullName->HrefValue = "";
            $this->FullName->TooltipValue = "";

            // Username
            $this->_Username->HrefValue = "";
            $this->_Username->TooltipValue = "";

            // UserPassword
            $this->UserPassword->HrefValue = "";
            $this->UserPassword->TooltipValue = "";

            // Level
            $this->Level->HrefValue = "";
            $this->Level->TooltipValue = "";

            // Email
            $this->_Email->HrefValue = "";
            $this->_Email->TooltipValue = "";

            // Position
            $this->Position->HrefValue = "";
            $this->Position->TooltipValue = "";

            // Department
            $this->Department->HrefValue = "";
            $this->Department->TooltipValue = "";

            // Employee
            $this->Employee->HrefValue = "";
            $this->Employee->TooltipValue = "";

            // WhatsAppNumber
            $this->WhatsAppNumber->HrefValue = "";
            $this->WhatsAppNumber->TooltipValue = "";

            // Active
            $this->Active->HrefValue = "";
            $this->Active->TooltipValue = "";

            // Created_Date
            $this->Created_Date->HrefValue = "";
            $this->Created_Date->TooltipValue = "";

            // Created_By
            $this->Created_By->HrefValue = "";
            $this->Created_By->TooltipValue = "";

            // Last_Updated_Date
            $this->Last_Updated_Date->HrefValue = "";
            $this->Last_Updated_Date->TooltipValue = "";

            // Last_Updated_By
            $this->Last_Updated_By->HrefValue = "";
            $this->Last_Updated_By->TooltipValue = "";
        } elseif ($this->RowType == RowType::ADD) {
            // FirstName
            $this->FirstName->setupEditAttributes();
            if (!$this->FirstName->Raw) {
                $this->FirstName->CurrentValue = HtmlDecode($this->FirstName->CurrentValue);
            }
            $this->FirstName->EditValue = HtmlEncode($this->FirstName->CurrentValue);
            $this->FirstName->PlaceHolder = RemoveHtml($this->FirstName->caption());

            // LastName
            $this->LastName->setupEditAttributes();
            if (!$this->LastName->Raw) {
                $this->LastName->CurrentValue = HtmlDecode($this->LastName->CurrentValue);
            }
            $this->LastName->EditValue = HtmlEncode($this->LastName->CurrentValue);
            $this->LastName->PlaceHolder = RemoveHtml($this->LastName->caption());

            // FullName
            $this->FullName->setupEditAttributes();
            if (!$this->FullName->Raw) {
                $this->FullName->CurrentValue = HtmlDecode($this->FullName->CurrentValue);
            }
            $this->FullName->EditValue = HtmlEncode($this->FullName->CurrentValue);
            $this->FullName->PlaceHolder = RemoveHtml($this->FullName->caption());

            // Username
            $this->_Username->setupEditAttributes();
            if (!$this->_Username->Raw) {
                $this->_Username->CurrentValue = HtmlDecode($this->_Username->CurrentValue);
            }
            $this->_Username->EditValue = HtmlEncode($this->_Username->CurrentValue);
            $this->_Username->PlaceHolder = RemoveHtml($this->_Username->caption());

            // UserPassword
            $this->UserPassword->setupEditAttributes();
            $this->UserPassword->PlaceHolder = RemoveHtml($this->UserPassword->caption());

            // Level
            $this->Level->setupEditAttributes();
            if (!$Security->canAdmin()) { // System admin
                $this->Level->EditValue = $Language->phrase("PasswordMask");
            } else {
                $curVal = trim(strval($this->Level->CurrentValue));
                if ($curVal != "") {
                    $this->Level->ViewValue = $this->Level->lookupCacheOption($curVal);
                } else {
                    $this->Level->ViewValue = $this->Level->Lookup !== null && is_array($this->Level->lookupOptions()) && count($this->Level->lookupOptions()) > 0 ? $curVal : null;
                }
                if ($this->Level->ViewValue !== null) { // Load from cache
                    $this->Level->EditValue = array_values($this->Level->lookupOptions());
                } else { // Lookup from database
                    if ($curVal == "") {
                        $filterWrk = "0=1";
                    } else {
                        $filterWrk = SearchFilter($this->Level->Lookup->getTable()->Fields["userlevelid"]->searchExpression(), "=", $this->Level->CurrentValue, $this->Level->Lookup->getTable()->Fields["userlevelid"]->searchDataType(), "");
                    }
                    $sqlWrk = $this->Level->Lookup->getSql(true, $filterWrk, '', $this, false, true);
                    $conn = Conn();
                    $config = $conn->getConfiguration();
                    $config->setResultCache($this->Cache);
                    $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                    $ari = count($rswrk);
                    $arwrk = $rswrk;
                    $this->Level->EditValue = $arwrk;
                }
                $this->Level->PlaceHolder = RemoveHtml($this->Level->caption());
            }

            // Email
            $this->_Email->setupEditAttributes();
            if (!$this->_Email->Raw) {
                $this->_Email->CurrentValue = HtmlDecode($this->_Email->CurrentValue);
            }
            $this->_Email->EditValue = HtmlEncode($this->_Email->CurrentValue);
            $this->_Email->PlaceHolder = RemoveHtml($this->_Email->caption());

            // Position
            $this->Position->setupEditAttributes();
            $this->Position->EditValue = $this->Position->options(true);
            $this->Position->PlaceHolder = RemoveHtml($this->Position->caption());

            // Department
            $this->Department->setupEditAttributes();
            if (!$this->Department->Raw) {
                $this->Department->CurrentValue = HtmlDecode($this->Department->CurrentValue);
            }
            $this->Department->EditValue = HtmlEncode($this->Department->CurrentValue);
            $this->Department->PlaceHolder = RemoveHtml($this->Department->caption());

            // Employee
            $this->Employee->EditValue = $this->Employee->options(false);
            $this->Employee->PlaceHolder = RemoveHtml($this->Employee->caption());

            // WhatsAppNumber
            $this->WhatsAppNumber->setupEditAttributes();
            if (!$this->WhatsAppNumber->Raw) {
                $this->WhatsAppNumber->CurrentValue = HtmlDecode($this->WhatsAppNumber->CurrentValue);
            }
            $this->WhatsAppNumber->EditValue = HtmlEncode($this->WhatsAppNumber->CurrentValue);
            $this->WhatsAppNumber->PlaceHolder = RemoveHtml($this->WhatsAppNumber->caption());

            // Active
            $this->Active->EditValue = $this->Active->options(false);
            $this->Active->PlaceHolder = RemoveHtml($this->Active->caption());

            // Created_Date
            $this->Created_Date->setupEditAttributes();
            $this->Created_Date->CurrentValue = FormatDateTime($this->Created_Date->getDefault(), $this->Created_Date->formatPattern());

            // Created_By
            $this->Created_By->setupEditAttributes();
            $this->Created_By->CurrentValue = $this->Created_By->getDefault();

            // Last_Updated_Date
            $this->Last_Updated_Date->setupEditAttributes();
            $this->Last_Updated_Date->CurrentValue = FormatDateTime(CurrentDateTime(), $this->Last_Updated_Date->formatPattern());

            // Last_Updated_By
            $this->Last_Updated_By->setupEditAttributes();
            $this->Last_Updated_By->CurrentValue = CurrentUserName();

            // Add refer script

            // FirstName
            $this->FirstName->HrefValue = "";

            // LastName
            $this->LastName->HrefValue = "";

            // FullName
            $this->FullName->HrefValue = "";

            // Username
            $this->_Username->HrefValue = "";

            // UserPassword
            $this->UserPassword->HrefValue = "";

            // Level
            $this->Level->HrefValue = "";

            // Email
            $this->_Email->HrefValue = "";

            // Position
            $this->Position->HrefValue = "";

            // Department
            $this->Department->HrefValue = "";

            // Employee
            $this->Employee->HrefValue = "";

            // WhatsAppNumber
            $this->WhatsAppNumber->HrefValue = "";

            // Active
            $this->Active->HrefValue = "";

            // Created_Date
            $this->Created_Date->HrefValue = "";

            // Created_By
            $this->Created_By->HrefValue = "";

            // Last_Updated_Date
            $this->Last_Updated_Date->HrefValue = "";

            // Last_Updated_By
            $this->Last_Updated_By->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->rowRendered();
        }
    }

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

        // Check if validation required
        if (!Config("SERVER_VALIDATE")) {
            return true;
        }
        $validateForm = true;
            if ($this->FirstName->Visible && $this->FirstName->Required) {
                if (!$this->FirstName->IsDetailKey && EmptyValue($this->FirstName->FormValue)) {
                    $this->FirstName->addErrorMessage(str_replace("%s", $this->FirstName->caption(), $this->FirstName->RequiredErrorMessage));
                }
            }
            if ($this->LastName->Visible && $this->LastName->Required) {
                if (!$this->LastName->IsDetailKey && EmptyValue($this->LastName->FormValue)) {
                    $this->LastName->addErrorMessage(str_replace("%s", $this->LastName->caption(), $this->LastName->RequiredErrorMessage));
                }
            }
            if ($this->FullName->Visible && $this->FullName->Required) {
                if (!$this->FullName->IsDetailKey && EmptyValue($this->FullName->FormValue)) {
                    $this->FullName->addErrorMessage(str_replace("%s", $this->FullName->caption(), $this->FullName->RequiredErrorMessage));
                }
            }
            if ($this->_Username->Visible && $this->_Username->Required) {
                if (!$this->_Username->IsDetailKey && EmptyValue($this->_Username->FormValue)) {
                    $this->_Username->addErrorMessage(str_replace("%s", $this->_Username->caption(), $this->_Username->RequiredErrorMessage));
                }
            }
            if (!$this->_Username->Raw && Config("REMOVE_XSS") && CheckUsername($this->_Username->FormValue)) {
                $this->_Username->addErrorMessage($Language->phrase("InvalidUsernameChars"));
            }
            if ($this->UserPassword->Visible && $this->UserPassword->Required) {
                if (!$this->UserPassword->IsDetailKey && EmptyValue($this->UserPassword->FormValue)) {
                    $this->UserPassword->addErrorMessage(str_replace("%s", $this->UserPassword->caption(), $this->UserPassword->RequiredErrorMessage));
                }
            }
            if (!$this->UserPassword->Raw && Config("REMOVE_XSS") && CheckPassword($this->UserPassword->FormValue)) {
                $this->UserPassword->addErrorMessage($Language->phrase("InvalidPasswordChars"));
            }
            if ($this->Level->Visible && $this->Level->Required) {
                if ($Security->canAdmin() && !$this->Level->IsDetailKey && EmptyValue($this->Level->FormValue)) {
                    $this->Level->addErrorMessage(str_replace("%s", $this->Level->caption(), $this->Level->RequiredErrorMessage));
                }
            }
            if ($this->_Email->Visible && $this->_Email->Required) {
                if (!$this->_Email->IsDetailKey && EmptyValue($this->_Email->FormValue)) {
                    $this->_Email->addErrorMessage(str_replace("%s", $this->_Email->caption(), $this->_Email->RequiredErrorMessage));
                }
            }
            if ($this->Position->Visible && $this->Position->Required) {
                if (!$this->Position->IsDetailKey && EmptyValue($this->Position->FormValue)) {
                    $this->Position->addErrorMessage(str_replace("%s", $this->Position->caption(), $this->Position->RequiredErrorMessage));
                }
            }
            if ($this->Department->Visible && $this->Department->Required) {
                if (!$this->Department->IsDetailKey && EmptyValue($this->Department->FormValue)) {
                    $this->Department->addErrorMessage(str_replace("%s", $this->Department->caption(), $this->Department->RequiredErrorMessage));
                }
            }
            if ($this->Employee->Visible && $this->Employee->Required) {
                if ($this->Employee->FormValue == "") {
                    $this->Employee->addErrorMessage(str_replace("%s", $this->Employee->caption(), $this->Employee->RequiredErrorMessage));
                }
            }
            if ($this->WhatsAppNumber->Visible && $this->WhatsAppNumber->Required) {
                if (!$this->WhatsAppNumber->IsDetailKey && EmptyValue($this->WhatsAppNumber->FormValue)) {
                    $this->WhatsAppNumber->addErrorMessage(str_replace("%s", $this->WhatsAppNumber->caption(), $this->WhatsAppNumber->RequiredErrorMessage));
                }
            }
            if ($this->Active->Visible && $this->Active->Required) {
                if ($this->Active->FormValue == "") {
                    $this->Active->addErrorMessage(str_replace("%s", $this->Active->caption(), $this->Active->RequiredErrorMessage));
                }
            }
            if ($this->Created_Date->Visible && $this->Created_Date->Required) {
                if (!$this->Created_Date->IsDetailKey && EmptyValue($this->Created_Date->FormValue)) {
                    $this->Created_Date->addErrorMessage(str_replace("%s", $this->Created_Date->caption(), $this->Created_Date->RequiredErrorMessage));
                }
            }
            if ($this->Created_By->Visible && $this->Created_By->Required) {
                if (!$this->Created_By->IsDetailKey && EmptyValue($this->Created_By->FormValue)) {
                    $this->Created_By->addErrorMessage(str_replace("%s", $this->Created_By->caption(), $this->Created_By->RequiredErrorMessage));
                }
            }
            if ($this->Last_Updated_Date->Visible && $this->Last_Updated_Date->Required) {
                if (!$this->Last_Updated_Date->IsDetailKey && EmptyValue($this->Last_Updated_Date->FormValue)) {
                    $this->Last_Updated_Date->addErrorMessage(str_replace("%s", $this->Last_Updated_Date->caption(), $this->Last_Updated_Date->RequiredErrorMessage));
                }
            }
            if ($this->Last_Updated_By->Visible && $this->Last_Updated_By->Required) {
                if (!$this->Last_Updated_By->IsDetailKey && EmptyValue($this->Last_Updated_By->FormValue)) {
                    $this->Last_Updated_By->addErrorMessage(str_replace("%s", $this->Last_Updated_By->caption(), $this->Last_Updated_By->RequiredErrorMessage));
                }
            }

        // Return validate result
        $validateForm = $validateForm && !$this->hasInvalidFields();

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

    // Set up Breadcrumb
    protected function setupBreadcrumb()
    {
        global $Breadcrumb, $Language;
        $Breadcrumb = new Breadcrumb("masterprojectlist");
        $url = CurrentUrl();
        $Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("masteruserlist"), "", $this->TableVar, true);
        $pageId = "addopt";
        $Breadcrumb->add("addopt", $pageId, $url);
    }

    // Setup lookup options
    public function setupLookupOptions($fld)
    {
        if ($fld->Lookup && $fld->Lookup->Options === null) {
            // Get default connection and filter
            $conn = $this->getConnection();
            $lookupFilter = "";

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

            // Set up lookup SQL and connection
            switch ($fld->FieldVar) {
                case "x_Level":
                    break;
                case "x_Position":
                    break;
                case "x_Employee":
                    break;
                case "x_Active":
                    break;
                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->hasLookupOptions() && $fld->UseLookupCache && $sql != "" && count($fld->Lookup->Options) == 0 && count($fld->Lookup->FilterFields) == 0) {
                $totalCnt = $this->getRecordCount($sql, $conn);
                if ($totalCnt > $fld->LookupCacheCount) { // Total count > cache count, do not cache
                    return;
                }
                $rows = $conn->executeQuery($sql)->fetchAll();
                $ar = [];
                foreach ($rows as $row) {
                    $row = $fld->Lookup->renderViewRow($row, Container($fld->Lookup->LinkTable));
                    $key = $row["lf"];
                    if (IsFloatType($fld->Type)) { // Handle float field
                        $key = (float)$key;
                    }
                    $ar[strval($key)] = $row;
                }
                $fld->Lookup->Options = $ar;
            }
        }
    }

    // Page Load event
    public function pageLoad()
    {
        //Log("Page Load");
    }

    // Page Unload event
    public function pageUnload()
    {
        //Log("Page Unload");
    }

    // Page Redirecting event
    public function pageRedirecting(&$url)
    {
        // Example:
        //$url = "your URL";
    }

    // Message Showing event
    // $type = ''|'success'|'failure'|'warning'
    public function messageShowing(&$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
    public function pageRender()
    {
        //Log("Page Render");
    }

    // Page Data Rendering event
    public function pageDataRendering(&$header)
    {
        // Example:
        //$header = "your header";
    }

    // Page Data Rendered event
    public function pageDataRendered(&$footer)
    {
        // Example:
        //$footer = "your footer";
    }

    // Page Breaking event
    public function pageBreaking(&$break, &$content)
    {
        // Example:
        //$break = false; // Skip page break, or
        //$content = "<div style=\"break-after:page;\"></div>"; // Modify page break content
    }
}
