<?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 ProjecttaskEdit extends Projecttask
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

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

    // Rendering View
    public $RenderingView = false;

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

    // 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->TaskID->setVisibility();
        $this->TaskName->setVisibility();
        $this->Description->setVisibility();
        $this->AssignedTo->setVisibility();
        $this->Progress->setVisibility();
        $this->Complete->Visible = false;
        $this->Target->setVisibility();
        $this->Track->setVisibility();
        $this->PlanStart->setVisibility();
        $this->PlanEnd->setVisibility();
        $this->StartDate->setVisibility();
        $this->EndDate->setVisibility();
        $this->Priority->setVisibility();
        $this->Category->setVisibility();
        $this->_ProjectID->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 = 'projecttask';
        $this->TableName = 'projecttask';

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

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

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

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

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

        // 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();
            }

            // Handle modal response
            if ($this->IsModal) { // Show as modal
                $pageName = GetPageName($url);
                $result = ["url" => GetUrl($url), "modal" => "1"];  // Assume return to modal for simplicity
                if (
                    SameString($pageName, GetPageName($this->getListUrl())) ||
                    SameString($pageName, GetPageName($this->getViewUrl())) ||
                    SameString($pageName, GetPageName(CurrentMasterTable()?->getViewUrl() ?? ""))
                ) { // List / View / Master View page
                    if (!SameString($pageName, GetPageName($this->getListUrl()))) { // Not List page
                        $result["caption"] = $this->getModalCaption($pageName);
                        $result["view"] = SameString($pageName, "projecttaskview"); // If View page, no primary button
                    } else { // List page
                        $result["error"] = $this->getFailureMessage(); // List page should not be shown as modal => error
                        $this->clearFailureMessage();
                    }
                } else { // Other pages (add messages and then clear messages)
                    $result = array_merge($this->getMessages(), ["modal" => "1"]);
                    $this->clearMessages();
                }
                WriteJson($result);
            } else {
                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['TaskID'];
        }
        return $key;
    }

    /**
     * Hide fields for add/edit
     *
     * @return void
     */
    protected function hideFieldsForAddEdit()
    {
        if ($this->isAdd() || $this->isCopy() || $this->isGridAdd()) {
            $this->TaskID->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
    }

    // Properties
    public $FormClassName = "ew-form ew-edit-form overlay-wrapper";
    public $IsModal = false;
    public $IsMobileOrModal = false;
    public $DbMasterFilter;
    public $DbDetailFilter;
    public $HashValue; // Hash Value
    public $DisplayRecords = 1;
    public $StartRecord;
    public $StopRecord;
    public $TotalRecords = 0;
    public $RecordRange = 10;
    public $RecordCount;

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

        // Is modal
        $this->IsModal = ConvertToBool(Param("modal"));
        $this->UseLayout = $this->UseLayout && !$this->IsModal;

        // 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->AssignedTo);
        $this->setupLookupOptions($this->Priority);
        $this->setupLookupOptions($this->Category);
        $this->setupLookupOptions($this->_ProjectID);

        // Check modal
        if ($this->IsModal) {
            $SkipHeaderFooter = true;
        }
        $this->IsMobileOrModal = IsMobile() || $this->IsModal;
        $loaded = false;
        $postBack = false;

        // Set up current action and primary key
        if (IsApi()) {
            // Load key values
            $loaded = true;
            if (($keyValue = Get("TaskID") ?? Key(0) ?? Route(2)) !== null) {
                $this->TaskID->setQueryStringValue($keyValue);
                $this->TaskID->setOldValue($this->TaskID->QueryStringValue);
            } elseif (Post("TaskID") !== null) {
                $this->TaskID->setFormValue(Post("TaskID"));
                $this->TaskID->setOldValue($this->TaskID->FormValue);
            } else {
                $loaded = false; // Unable to load key
            }

            // Load record
            if ($loaded) {
                $loaded = $this->loadRow();
            }
            if (!$loaded) {
                $this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
                $this->terminate();
                return;
            }
            $this->CurrentAction = "update"; // Update record directly
            $this->OldKey = $this->getKey(true); // Get from CurrentValue
            $postBack = true;
        } else {
            if (Post("action", "") !== "") {
                $this->CurrentAction = Post("action"); // Get action code
                if (!$this->isShow()) { // Not reload record, handle as postback
                    $postBack = true;
                }

                // Get key from Form
                $this->setKey(Post($this->OldKeyName), $this->isShow());
            } else {
                $this->CurrentAction = "show"; // Default action is display

                // Load key from QueryString
                $loadByQuery = false;
                if (($keyValue = Get("TaskID") ?? Route("TaskID")) !== null) {
                    $this->TaskID->setQueryStringValue($keyValue);
                    $loadByQuery = true;
                } else {
                    $this->TaskID->CurrentValue = null;
                }
            }

            // Set up master detail parameters
            $this->setupMasterParms();

            // Load result set
            if ($this->isShow()) {
                    // Load current record
                    $loaded = $this->loadRow();
                $this->OldKey = $loaded ? $this->getKey(true) : ""; // Get from CurrentValue
            }
        }

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

        // Validate form if post back
        if ($postBack) {
            if (!$this->validateForm()) {
                $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("projecttasklist"); // No matching record, return to list
                        return;
                    }
                break;
            case "update": // Update
                $returnUrl = $this->getReturnUrl();
                if (GetPageName($returnUrl) == "projecttasklist") {
                    $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
                    }

                    // Handle UseAjaxActions with return page
                    if ($this->IsModal && $this->UseAjaxActions) {
                        $this->IsModal = false;
                        if (GetPageName($returnUrl) != "projecttasklist") {
                            Container("app.flash")->addMessage("Return-Url", $returnUrl); // Save return URL
                            $returnUrl = "projecttasklist"; // Return list page content
                        }
                    }
                    if (IsJsonResponse()) {
                        $this->terminate(true);
                        return;
                    } else {
                        $this->terminate($returnUrl); // Return to caller
                        return;
                    }
                } elseif (IsApi()) { // API request, return
                    $this->terminate();
                    return;
                } elseif ($this->IsModal && $this->UseAjaxActions) { // Return JSON error message
                    WriteJson(["success" => false, "validation" => $this->getValidationErrors(), "error" => $this->getFailureMessage()]);
                    $this->clearFailureMessage();
                    $this->terminate();
                    return;
                } elseif ($this->getFailureMessage() == $Language->phrase("NoRecord")) {
                    $this->terminate($returnUrl); // Return to caller
                    return;
                } 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();

        // 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 form values
    protected function loadFormValues()
    {
        // Load from form
        global $CurrentForm;
        $validate = !Config("SERVER_VALIDATE");

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

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

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

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

        // Check field name 'Progress' first before field var 'x_Progress'
        $val = $CurrentForm->hasValue("Progress") ? $CurrentForm->getValue("Progress") : $CurrentForm->getValue("x_Progress");
        if (!$this->Progress->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->Progress->Visible = false; // Disable update for API request
            } else {
                $this->Progress->setFormValue($val, true, $validate);
            }
        }

        // Check field name 'Target' first before field var 'x_Target'
        $val = $CurrentForm->hasValue("Target") ? $CurrentForm->getValue("Target") : $CurrentForm->getValue("x_Target");
        if (!$this->Target->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->Target->Visible = false; // Disable update for API request
            } else {
                $this->Target->setFormValue($val, true, $validate);
            }
        }

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

        // Check field name 'PlanStart' first before field var 'x_PlanStart'
        $val = $CurrentForm->hasValue("PlanStart") ? $CurrentForm->getValue("PlanStart") : $CurrentForm->getValue("x_PlanStart");
        if (!$this->PlanStart->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->PlanStart->Visible = false; // Disable update for API request
            } else {
                $this->PlanStart->setFormValue($val, true, $validate);
            }
            $this->PlanStart->CurrentValue = UnFormatDateTime($this->PlanStart->CurrentValue, $this->PlanStart->formatPattern());
        }

        // Check field name 'PlanEnd' first before field var 'x_PlanEnd'
        $val = $CurrentForm->hasValue("PlanEnd") ? $CurrentForm->getValue("PlanEnd") : $CurrentForm->getValue("x_PlanEnd");
        if (!$this->PlanEnd->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->PlanEnd->Visible = false; // Disable update for API request
            } else {
                $this->PlanEnd->setFormValue($val, true, $validate);
            }
            $this->PlanEnd->CurrentValue = UnFormatDateTime($this->PlanEnd->CurrentValue, $this->PlanEnd->formatPattern());
        }

        // Check field name 'StartDate' first before field var 'x_StartDate'
        $val = $CurrentForm->hasValue("StartDate") ? $CurrentForm->getValue("StartDate") : $CurrentForm->getValue("x_StartDate");
        if (!$this->StartDate->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->StartDate->Visible = false; // Disable update for API request
            } else {
                $this->StartDate->setFormValue($val, true, $validate);
            }
            $this->StartDate->CurrentValue = UnFormatDateTime($this->StartDate->CurrentValue, $this->StartDate->formatPattern());
        }

        // Check field name 'EndDate' first before field var 'x_EndDate'
        $val = $CurrentForm->hasValue("EndDate") ? $CurrentForm->getValue("EndDate") : $CurrentForm->getValue("x_EndDate");
        if (!$this->EndDate->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->EndDate->Visible = false; // Disable update for API request
            } else {
                $this->EndDate->setFormValue($val, true, $validate);
            }
            $this->EndDate->CurrentValue = UnFormatDateTime($this->EndDate->CurrentValue, $this->EndDate->formatPattern());
        }

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

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

        // Check field name 'ProjectID' first before field var 'x__ProjectID'
        $val = $CurrentForm->hasValue("ProjectID") ? $CurrentForm->getValue("ProjectID") : $CurrentForm->getValue("x__ProjectID");
        if (!$this->_ProjectID->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->_ProjectID->Visible = false; // Disable update for API request
            } else {
                $this->_ProjectID->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) {
            if (IsApi() && $val === null) {
                $this->Created_Date->Visible = false; // Disable update for API request
            } else {
                $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) {
            if (IsApi() && $val === null) {
                $this->Created_By->Visible = false; // Disable update for API request
            } else {
                $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) {
            if (IsApi() && $val === null) {
                $this->Last_Updated_Date->Visible = false; // Disable update for API request
            } else {
                $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) {
            if (IsApi() && $val === null) {
                $this->Last_Updated_By->Visible = false; // Disable update for API request
            } else {
                $this->Last_Updated_By->setFormValue($val);
            }
        }
    }

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->TaskID->CurrentValue = $this->TaskID->FormValue;
        $this->TaskName->CurrentValue = $this->TaskName->FormValue;
        $this->Description->CurrentValue = $this->Description->FormValue;
        $this->AssignedTo->CurrentValue = $this->AssignedTo->FormValue;
        $this->Progress->CurrentValue = $this->Progress->FormValue;
        $this->Target->CurrentValue = $this->Target->FormValue;
        $this->Track->CurrentValue = $this->Track->FormValue;
        $this->PlanStart->CurrentValue = $this->PlanStart->FormValue;
        $this->PlanStart->CurrentValue = UnFormatDateTime($this->PlanStart->CurrentValue, $this->PlanStart->formatPattern());
        $this->PlanEnd->CurrentValue = $this->PlanEnd->FormValue;
        $this->PlanEnd->CurrentValue = UnFormatDateTime($this->PlanEnd->CurrentValue, $this->PlanEnd->formatPattern());
        $this->StartDate->CurrentValue = $this->StartDate->FormValue;
        $this->StartDate->CurrentValue = UnFormatDateTime($this->StartDate->CurrentValue, $this->StartDate->formatPattern());
        $this->EndDate->CurrentValue = $this->EndDate->FormValue;
        $this->EndDate->CurrentValue = UnFormatDateTime($this->EndDate->CurrentValue, $this->EndDate->formatPattern());
        $this->Priority->CurrentValue = $this->Priority->FormValue;
        $this->Category->CurrentValue = $this->Category->FormValue;
        $this->_ProjectID->CurrentValue = $this->_ProjectID->FormValue;
        $this->Created_Date->CurrentValue = $this->Created_Date->FormValue;
        $this->Created_Date->CurrentValue = UnFormatDateTime($this->Created_Date->CurrentValue, $this->Created_Date->formatPattern());
        $this->Created_By->CurrentValue = $this->Created_By->FormValue;
        $this->Last_Updated_Date->CurrentValue = $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 = $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->TaskID->setDbValue($row['TaskID']);
        $this->TaskName->setDbValue($row['TaskName']);
        $this->Description->setDbValue($row['Description']);
        $this->AssignedTo->setDbValue($row['AssignedTo']);
        $this->Progress->setDbValue($row['Progress']);
        $this->Complete->setDbValue($row['Complete']);
        $this->Target->setDbValue($row['Target']);
        $this->Track->setDbValue($row['Track']);
        $this->PlanStart->setDbValue($row['PlanStart']);
        $this->PlanEnd->setDbValue($row['PlanEnd']);
        $this->StartDate->setDbValue($row['StartDate']);
        $this->EndDate->setDbValue($row['EndDate']);
        $this->Priority->setDbValue($row['Priority']);
        $this->Category->setDbValue($row['Category']);
        $this->_ProjectID->setDbValue($row['ProjectID']);
        $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['TaskID'] = $this->TaskID->DefaultValue;
        $row['TaskName'] = $this->TaskName->DefaultValue;
        $row['Description'] = $this->Description->DefaultValue;
        $row['AssignedTo'] = $this->AssignedTo->DefaultValue;
        $row['Progress'] = $this->Progress->DefaultValue;
        $row['Complete'] = $this->Complete->DefaultValue;
        $row['Target'] = $this->Target->DefaultValue;
        $row['Track'] = $this->Track->DefaultValue;
        $row['PlanStart'] = $this->PlanStart->DefaultValue;
        $row['PlanEnd'] = $this->PlanEnd->DefaultValue;
        $row['StartDate'] = $this->StartDate->DefaultValue;
        $row['EndDate'] = $this->EndDate->DefaultValue;
        $row['Priority'] = $this->Priority->DefaultValue;
        $row['Category'] = $this->Category->DefaultValue;
        $row['ProjectID'] = $this->_ProjectID->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;
    }

    // Load old record
    protected function loadOldRecord()
    {
        // Load old record
        if ($this->OldKey != "") {
            $this->setKey($this->OldKey);
            $this->CurrentFilter = $this->getRecordFilter();
            $sql = $this->getCurrentSql();
            $conn = $this->getConnection();
            $rs = ExecuteQuery($sql, $conn);
            if ($row = $rs->fetch()) {
                $this->loadRowValues($row); // Load row values
                return $row;
            }
        }
        $this->loadRowValues(); // Load default row values
        return null;
    }

    // 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // ProjectID
        $this->_ProjectID->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) {
            // TaskID
            $this->TaskID->ViewValue = $this->TaskID->CurrentValue;

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

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

            // AssignedTo
            $curVal = strval($this->AssignedTo->CurrentValue);
            if ($curVal != "") {
                $this->AssignedTo->ViewValue = $this->AssignedTo->lookupCacheOption($curVal);
                if ($this->AssignedTo->ViewValue === null) { // Lookup from database
                    $filterWrk = SearchFilter($this->AssignedTo->Lookup->getTable()->Fields["EmployeeID"]->searchExpression(), "=", $curVal, $this->AssignedTo->Lookup->getTable()->Fields["EmployeeID"]->searchDataType(), "");
                    $sqlWrk = $this->AssignedTo->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->AssignedTo->Lookup->renderViewRow($rswrk[0]);
                        $this->AssignedTo->ViewValue = $this->AssignedTo->displayValue($arwrk);
                    } else {
                        $this->AssignedTo->ViewValue = FormatNumber($this->AssignedTo->CurrentValue, $this->AssignedTo->formatPattern());
                    }
                }
            } else {
                $this->AssignedTo->ViewValue = null;
            }

            // Progress
            $this->Progress->ViewValue = $this->Progress->CurrentValue;
            $this->Progress->ViewValue = FormatPercent($this->Progress->ViewValue, $this->Progress->formatPattern());
            $this->Progress->CellCssStyle .= "text-align: right;";

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

            // Target
            $this->Target->ViewValue = $this->Target->CurrentValue;
            $this->Target->ViewValue = FormatPercent($this->Target->ViewValue, $this->Target->formatPattern());
            $this->Target->CellCssStyle .= "text-align: right;";

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

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

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

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

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

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

            // Category
            $curVal = strval($this->Category->CurrentValue);
            if ($curVal != "") {
                $this->Category->ViewValue = $this->Category->lookupCacheOption($curVal);
                if ($this->Category->ViewValue === null) { // Lookup from database
                    $filterWrk = SearchFilter($this->Category->Lookup->getTable()->Fields["CategoryName"]->searchExpression(), "=", $curVal, $this->Category->Lookup->getTable()->Fields["CategoryName"]->searchDataType(), "");
                    $lookupFilter = $this->Category->getSelectFilter($this); // PHP
                    $sqlWrk = $this->Category->Lookup->getSql(false, $filterWrk, $lookupFilter, $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->Category->Lookup->renderViewRow($rswrk[0]);
                        $this->Category->ViewValue = $this->Category->displayValue($arwrk);
                    } else {
                        $this->Category->ViewValue = $this->Category->CurrentValue;
                    }
                }
            } else {
                $this->Category->ViewValue = null;
            }

            // ProjectID
            $curVal = strval($this->_ProjectID->CurrentValue);
            if ($curVal != "") {
                $this->_ProjectID->ViewValue = $this->_ProjectID->lookupCacheOption($curVal);
                if ($this->_ProjectID->ViewValue === null) { // Lookup from database
                    $filterWrk = SearchFilter($this->_ProjectID->Lookup->getTable()->Fields["ProjectID"]->searchExpression(), "=", $curVal, $this->_ProjectID->Lookup->getTable()->Fields["ProjectID"]->searchDataType(), "");
                    $sqlWrk = $this->_ProjectID->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->_ProjectID->Lookup->renderViewRow($rswrk[0]);
                        $this->_ProjectID->ViewValue = $this->_ProjectID->displayValue($arwrk);
                    } else {
                        $this->_ProjectID->ViewValue = FormatNumber($this->_ProjectID->CurrentValue, $this->_ProjectID->formatPattern());
                    }
                }
            } else {
                $this->_ProjectID->ViewValue = null;
            }

            // 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;

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

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

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

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

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

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

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

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

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

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

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

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

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

            // ProjectID
            $this->_ProjectID->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 = "";
        } elseif ($this->RowType == RowType::EDIT) {
            // TaskID
            $this->TaskID->setupEditAttributes();
            $this->TaskID->EditValue = $this->TaskID->CurrentValue;

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

            // Description
            $this->Description->setupEditAttributes();
            $this->Description->EditValue = HtmlEncode($this->Description->CurrentValue);
            $this->Description->PlaceHolder = RemoveHtml($this->Description->caption());

            // AssignedTo
            $this->AssignedTo->setupEditAttributes();
            $curVal = trim(strval($this->AssignedTo->CurrentValue));
            if ($curVal != "") {
                $this->AssignedTo->ViewValue = $this->AssignedTo->lookupCacheOption($curVal);
            } else {
                $this->AssignedTo->ViewValue = $this->AssignedTo->Lookup !== null && is_array($this->AssignedTo->lookupOptions()) && count($this->AssignedTo->lookupOptions()) > 0 ? $curVal : null;
            }
            if ($this->AssignedTo->ViewValue !== null) { // Load from cache
                $this->AssignedTo->EditValue = array_values($this->AssignedTo->lookupOptions());
            } else { // Lookup from database
                if ($curVal == "") {
                    $filterWrk = "0=1";
                } else {
                    $filterWrk = SearchFilter($this->AssignedTo->Lookup->getTable()->Fields["EmployeeID"]->searchExpression(), "=", $this->AssignedTo->CurrentValue, $this->AssignedTo->Lookup->getTable()->Fields["EmployeeID"]->searchDataType(), "");
                }
                $sqlWrk = $this->AssignedTo->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->AssignedTo->EditValue = $arwrk;
            }
            $this->AssignedTo->PlaceHolder = RemoveHtml($this->AssignedTo->caption());

            // Progress
            $this->Progress->setupEditAttributes();
            $this->Progress->EditValue = $this->Progress->CurrentValue;
            $this->Progress->PlaceHolder = RemoveHtml($this->Progress->caption());
            if (strval($this->Progress->EditValue) != "" && is_numeric($this->Progress->EditValue)) {
                $this->Progress->EditValue = FormatNumber($this->Progress->EditValue, null);
            }

            // Target
            $this->Target->setupEditAttributes();
            $this->Target->EditValue = $this->Target->CurrentValue;
            $this->Target->PlaceHolder = RemoveHtml($this->Target->caption());
            if (strval($this->Target->EditValue) != "" && is_numeric($this->Target->EditValue)) {
                $this->Target->EditValue = FormatNumber($this->Target->EditValue, null);
            }

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

            // PlanStart
            $this->PlanStart->setupEditAttributes();
            $this->PlanStart->EditValue = HtmlEncode(FormatDateTime($this->PlanStart->CurrentValue, $this->PlanStart->formatPattern()));
            $this->PlanStart->PlaceHolder = RemoveHtml($this->PlanStart->caption());

            // PlanEnd
            $this->PlanEnd->setupEditAttributes();
            $this->PlanEnd->EditValue = HtmlEncode(FormatDateTime($this->PlanEnd->CurrentValue, $this->PlanEnd->formatPattern()));
            $this->PlanEnd->PlaceHolder = RemoveHtml($this->PlanEnd->caption());

            // StartDate
            $this->StartDate->setupEditAttributes();
            $this->StartDate->EditValue = HtmlEncode(FormatDateTime($this->StartDate->CurrentValue, $this->StartDate->formatPattern()));
            $this->StartDate->PlaceHolder = RemoveHtml($this->StartDate->caption());

            // EndDate
            $this->EndDate->setupEditAttributes();
            $this->EndDate->EditValue = HtmlEncode(FormatDateTime($this->EndDate->CurrentValue, $this->EndDate->formatPattern()));
            $this->EndDate->PlaceHolder = RemoveHtml($this->EndDate->caption());

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

            // Category
            $this->Category->setupEditAttributes();
            $curVal = trim(strval($this->Category->CurrentValue));
            if ($curVal != "") {
                $this->Category->ViewValue = $this->Category->lookupCacheOption($curVal);
            } else {
                $this->Category->ViewValue = $this->Category->Lookup !== null && is_array($this->Category->lookupOptions()) && count($this->Category->lookupOptions()) > 0 ? $curVal : null;
            }
            if ($this->Category->ViewValue !== null) { // Load from cache
                $this->Category->EditValue = array_values($this->Category->lookupOptions());
            } else { // Lookup from database
                if ($curVal == "") {
                    $filterWrk = "0=1";
                } else {
                    $filterWrk = SearchFilter($this->Category->Lookup->getTable()->Fields["CategoryName"]->searchExpression(), "=", $this->Category->CurrentValue, $this->Category->Lookup->getTable()->Fields["CategoryName"]->searchDataType(), "");
                }
                $lookupFilter = $this->Category->getSelectFilter($this); // PHP
                $sqlWrk = $this->Category->Lookup->getSql(true, $filterWrk, $lookupFilter, $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->Category->EditValue = $arwrk;
            }
            $this->Category->PlaceHolder = RemoveHtml($this->Category->caption());

            // ProjectID
            $this->_ProjectID->setupEditAttributes();
            if ($this->_ProjectID->getSessionValue() != "") {
                $this->_ProjectID->CurrentValue = GetForeignKeyValue($this->_ProjectID->getSessionValue());
                $curVal = strval($this->_ProjectID->CurrentValue);
                if ($curVal != "") {
                    $this->_ProjectID->ViewValue = $this->_ProjectID->lookupCacheOption($curVal);
                    if ($this->_ProjectID->ViewValue === null) { // Lookup from database
                        $filterWrk = SearchFilter($this->_ProjectID->Lookup->getTable()->Fields["ProjectID"]->searchExpression(), "=", $curVal, $this->_ProjectID->Lookup->getTable()->Fields["ProjectID"]->searchDataType(), "");
                        $sqlWrk = $this->_ProjectID->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->_ProjectID->Lookup->renderViewRow($rswrk[0]);
                            $this->_ProjectID->ViewValue = $this->_ProjectID->displayValue($arwrk);
                        } else {
                            $this->_ProjectID->ViewValue = FormatNumber($this->_ProjectID->CurrentValue, $this->_ProjectID->formatPattern());
                        }
                    }
                } else {
                    $this->_ProjectID->ViewValue = null;
                }
            } else {
                $curVal = trim(strval($this->_ProjectID->CurrentValue));
                if ($curVal != "") {
                    $this->_ProjectID->ViewValue = $this->_ProjectID->lookupCacheOption($curVal);
                } else {
                    $this->_ProjectID->ViewValue = $this->_ProjectID->Lookup !== null && is_array($this->_ProjectID->lookupOptions()) && count($this->_ProjectID->lookupOptions()) > 0 ? $curVal : null;
                }
                if ($this->_ProjectID->ViewValue !== null) { // Load from cache
                    $this->_ProjectID->EditValue = array_values($this->_ProjectID->lookupOptions());
                } else { // Lookup from database
                    if ($curVal == "") {
                        $filterWrk = "0=1";
                    } else {
                        $filterWrk = SearchFilter($this->_ProjectID->Lookup->getTable()->Fields["ProjectID"]->searchExpression(), "=", $this->_ProjectID->CurrentValue, $this->_ProjectID->Lookup->getTable()->Fields["ProjectID"]->searchDataType(), "");
                    }
                    $sqlWrk = $this->_ProjectID->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->_ProjectID->EditValue = $arwrk;
                }
                $this->_ProjectID->PlaceHolder = RemoveHtml($this->_ProjectID->caption());
            }

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

            // Created_By
            $this->Created_By->setupEditAttributes();

            // Last_Updated_Date

            // Last_Updated_By

            // Edit refer script

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

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

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

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

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

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

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

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

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

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

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

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

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

            // ProjectID
            $this->_ProjectID->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->TaskID->Visible && $this->TaskID->Required) {
                if (!$this->TaskID->IsDetailKey && EmptyValue($this->TaskID->FormValue)) {
                    $this->TaskID->addErrorMessage(str_replace("%s", $this->TaskID->caption(), $this->TaskID->RequiredErrorMessage));
                }
            }
            if ($this->TaskName->Visible && $this->TaskName->Required) {
                if (!$this->TaskName->IsDetailKey && EmptyValue($this->TaskName->FormValue)) {
                    $this->TaskName->addErrorMessage(str_replace("%s", $this->TaskName->caption(), $this->TaskName->RequiredErrorMessage));
                }
            }
            if ($this->Description->Visible && $this->Description->Required) {
                if (!$this->Description->IsDetailKey && EmptyValue($this->Description->FormValue)) {
                    $this->Description->addErrorMessage(str_replace("%s", $this->Description->caption(), $this->Description->RequiredErrorMessage));
                }
            }
            if ($this->AssignedTo->Visible && $this->AssignedTo->Required) {
                if (!$this->AssignedTo->IsDetailKey && EmptyValue($this->AssignedTo->FormValue)) {
                    $this->AssignedTo->addErrorMessage(str_replace("%s", $this->AssignedTo->caption(), $this->AssignedTo->RequiredErrorMessage));
                }
            }
            if ($this->Progress->Visible && $this->Progress->Required) {
                if (!$this->Progress->IsDetailKey && EmptyValue($this->Progress->FormValue)) {
                    $this->Progress->addErrorMessage(str_replace("%s", $this->Progress->caption(), $this->Progress->RequiredErrorMessage));
                }
            }
            if (!CheckNumber($this->Progress->FormValue)) {
                $this->Progress->addErrorMessage($this->Progress->getErrorMessage(false));
            }
            if ($this->Target->Visible && $this->Target->Required) {
                if (!$this->Target->IsDetailKey && EmptyValue($this->Target->FormValue)) {
                    $this->Target->addErrorMessage(str_replace("%s", $this->Target->caption(), $this->Target->RequiredErrorMessage));
                }
            }
            if (!CheckNumber($this->Target->FormValue)) {
                $this->Target->addErrorMessage($this->Target->getErrorMessage(false));
            }
            if ($this->Track->Visible && $this->Track->Required) {
                if (!$this->Track->IsDetailKey && EmptyValue($this->Track->FormValue)) {
                    $this->Track->addErrorMessage(str_replace("%s", $this->Track->caption(), $this->Track->RequiredErrorMessage));
                }
            }
            if ($this->PlanStart->Visible && $this->PlanStart->Required) {
                if (!$this->PlanStart->IsDetailKey && EmptyValue($this->PlanStart->FormValue)) {
                    $this->PlanStart->addErrorMessage(str_replace("%s", $this->PlanStart->caption(), $this->PlanStart->RequiredErrorMessage));
                }
            }
            if (!CheckDate($this->PlanStart->FormValue, $this->PlanStart->formatPattern())) {
                $this->PlanStart->addErrorMessage($this->PlanStart->getErrorMessage(false));
            }
            if ($this->PlanEnd->Visible && $this->PlanEnd->Required) {
                if (!$this->PlanEnd->IsDetailKey && EmptyValue($this->PlanEnd->FormValue)) {
                    $this->PlanEnd->addErrorMessage(str_replace("%s", $this->PlanEnd->caption(), $this->PlanEnd->RequiredErrorMessage));
                }
            }
            if (!CheckDate($this->PlanEnd->FormValue, $this->PlanEnd->formatPattern())) {
                $this->PlanEnd->addErrorMessage($this->PlanEnd->getErrorMessage(false));
            }
            if ($this->StartDate->Visible && $this->StartDate->Required) {
                if (!$this->StartDate->IsDetailKey && EmptyValue($this->StartDate->FormValue)) {
                    $this->StartDate->addErrorMessage(str_replace("%s", $this->StartDate->caption(), $this->StartDate->RequiredErrorMessage));
                }
            }
            if (!CheckDate($this->StartDate->FormValue, $this->StartDate->formatPattern())) {
                $this->StartDate->addErrorMessage($this->StartDate->getErrorMessage(false));
            }
            if ($this->EndDate->Visible && $this->EndDate->Required) {
                if (!$this->EndDate->IsDetailKey && EmptyValue($this->EndDate->FormValue)) {
                    $this->EndDate->addErrorMessage(str_replace("%s", $this->EndDate->caption(), $this->EndDate->RequiredErrorMessage));
                }
            }
            if (!CheckDate($this->EndDate->FormValue, $this->EndDate->formatPattern())) {
                $this->EndDate->addErrorMessage($this->EndDate->getErrorMessage(false));
            }
            if ($this->Priority->Visible && $this->Priority->Required) {
                if (!$this->Priority->IsDetailKey && EmptyValue($this->Priority->FormValue)) {
                    $this->Priority->addErrorMessage(str_replace("%s", $this->Priority->caption(), $this->Priority->RequiredErrorMessage));
                }
            }
            if ($this->Category->Visible && $this->Category->Required) {
                if (!$this->Category->IsDetailKey && EmptyValue($this->Category->FormValue)) {
                    $this->Category->addErrorMessage(str_replace("%s", $this->Category->caption(), $this->Category->RequiredErrorMessage));
                }
            }
            if ($this->_ProjectID->Visible && $this->_ProjectID->Required) {
                if (!$this->_ProjectID->IsDetailKey && EmptyValue($this->_ProjectID->FormValue)) {
                    $this->_ProjectID->addErrorMessage(str_replace("%s", $this->_ProjectID->caption(), $this->_ProjectID->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;
    }

    // Update record based on key values
    protected function editRow()
    {
        global $Security, $Language;
        $oldKeyFilter = $this->getRecordFilter();
        $filter = $this->applyUserIDFilters($oldKeyFilter);
        $conn = $this->getConnection();

        // Load old row
        $this->CurrentFilter = $filter;
        $sql = $this->getCurrentSql();
        $rsold = $conn->fetchAssociative($sql);
        if (!$rsold) {
            $this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
            return false; // Update Failed
        } else {
            // Load old values
            $this->loadDbValues($rsold);
        }

        // Get new row
        $rsnew = $this->getEditRow($rsold);

        // Update current values
        $this->setCurrentValues($rsnew);

        // Check referential integrity for master table 'masterproject'
        $detailKeys = [];
        $keyValue = $rsnew['ProjectID'] ?? $rsold['ProjectID'];
        $detailKeys['ProjectID'] = $keyValue;
        $masterTable = Container("masterproject");
        $masterFilter = $this->getMasterFilter($masterTable, $detailKeys);
        if (!EmptyValue($masterFilter)) {
            $rsmaster = $masterTable->loadRs($masterFilter)->fetch();
            $validMasterRecord = $rsmaster !== false;
        } else { // Allow null value if not required field
            $validMasterRecord = $masterFilter === null;
        }
        if (!$validMasterRecord) {
            $relatedRecordMsg = str_replace("%t", "masterproject", $Language->phrase("RelatedRecordRequired"));
            $this->setFailureMessage($relatedRecordMsg);
            return false;
        }

        // Call Row Updating event
        $updateRow = $this->rowUpdating($rsold, $rsnew);
        if ($updateRow) {
            if (count($rsnew) > 0) {
                $this->CurrentFilter = $filter; // Set up current filter
                $editRow = $this->update($rsnew, "", $rsold);
                if (!$editRow && !EmptyValue($this->DbErrorMessage)) { // Show database error
                    $this->setFailureMessage($this->DbErrorMessage);
                }
            } else {
                $editRow = true; // No field to update
            }
            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->rowUpdated($rsold, $rsnew);
        }

        // Write JSON response
        if (IsJsonResponse() && $editRow) {
            $row = $this->getRecordsFromRecordset([$rsnew], true);
            $table = $this->TableVar;
            WriteJson(["success" => true, "action" => Config("API_EDIT_ACTION"), $table => $row]);
        }
        return $editRow;
    }

    /**
     * Get edit row
     *
     * @return array
     */
    protected function getEditRow($rsold)
    {
        global $Security;
        $rsnew = [];

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

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

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

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

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

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

        // PlanStart
        $this->PlanStart->setDbValueDef($rsnew, UnFormatDateTime($this->PlanStart->CurrentValue, $this->PlanStart->formatPattern()), $this->PlanStart->ReadOnly);

        // PlanEnd
        $this->PlanEnd->setDbValueDef($rsnew, UnFormatDateTime($this->PlanEnd->CurrentValue, $this->PlanEnd->formatPattern()), $this->PlanEnd->ReadOnly);

        // StartDate
        $this->StartDate->setDbValueDef($rsnew, UnFormatDateTime($this->StartDate->CurrentValue, $this->StartDate->formatPattern()), $this->StartDate->ReadOnly);

        // EndDate
        $this->EndDate->setDbValueDef($rsnew, UnFormatDateTime($this->EndDate->CurrentValue, $this->EndDate->formatPattern()), $this->EndDate->ReadOnly);

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

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

        // ProjectID
        if ($this->_ProjectID->getSessionValue() != "") {
            $this->_ProjectID->ReadOnly = true;
        }
        $this->_ProjectID->setDbValueDef($rsnew, $this->_ProjectID->CurrentValue, $this->_ProjectID->ReadOnly);

        // Created_Date
        $this->Created_Date->setDbValueDef($rsnew, UnFormatDateTime($this->Created_Date->CurrentValue, $this->Created_Date->formatPattern()), $this->Created_Date->ReadOnly);

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

        // Last_Updated_Date
        $this->Last_Updated_Date->CurrentValue = $this->Last_Updated_Date->getAutoUpdateValue(); // PHP
        $this->Last_Updated_Date->setDbValueDef($rsnew, UnFormatDateTime($this->Last_Updated_Date->CurrentValue, $this->Last_Updated_Date->formatPattern()));

        // Last_Updated_By
        $this->Last_Updated_By->CurrentValue = $this->Last_Updated_By->getAutoUpdateValue(); // PHP
        $this->Last_Updated_By->setDbValueDef($rsnew, $this->Last_Updated_By->CurrentValue);
        return $rsnew;
    }

    /**
     * Restore edit form from row
     * @param array $row Row
     */
    protected function restoreEditFormFromRow($row)
    {
        if (isset($row['TaskName'])) { // TaskName
            $this->TaskName->CurrentValue = $row['TaskName'];
        }
        if (isset($row['Description'])) { // Description
            $this->Description->CurrentValue = $row['Description'];
        }
        if (isset($row['AssignedTo'])) { // AssignedTo
            $this->AssignedTo->CurrentValue = $row['AssignedTo'];
        }
        if (isset($row['Progress'])) { // Progress
            $this->Progress->CurrentValue = $row['Progress'];
        }
        if (isset($row['Target'])) { // Target
            $this->Target->CurrentValue = $row['Target'];
        }
        if (isset($row['Track'])) { // Track
            $this->Track->CurrentValue = $row['Track'];
        }
        if (isset($row['PlanStart'])) { // PlanStart
            $this->PlanStart->CurrentValue = $row['PlanStart'];
        }
        if (isset($row['PlanEnd'])) { // PlanEnd
            $this->PlanEnd->CurrentValue = $row['PlanEnd'];
        }
        if (isset($row['StartDate'])) { // StartDate
            $this->StartDate->CurrentValue = $row['StartDate'];
        }
        if (isset($row['EndDate'])) { // EndDate
            $this->EndDate->CurrentValue = $row['EndDate'];
        }
        if (isset($row['Priority'])) { // Priority
            $this->Priority->CurrentValue = $row['Priority'];
        }
        if (isset($row['Category'])) { // Category
            $this->Category->CurrentValue = $row['Category'];
        }
        if (isset($row['ProjectID'])) { // ProjectID
            $this->_ProjectID->CurrentValue = $row['ProjectID'];
        }
        if (isset($row['Created_Date'])) { // Created_Date
            $this->Created_Date->CurrentValue = $row['Created_Date'];
        }
        if (isset($row['Created_By'])) { // Created_By
            $this->Created_By->CurrentValue = $row['Created_By'];
        }
        if (isset($row['Last_Updated_Date'])) { // Last_Updated_Date
            $this->Last_Updated_Date->CurrentValue = $row['Last_Updated_Date'];
        }
        if (isset($row['Last_Updated_By'])) { // Last_Updated_By
            $this->Last_Updated_By->CurrentValue = $row['Last_Updated_By'];
        }
    }

    // Set up master/detail based on QueryString
    protected function setupMasterParms()
    {
        $validMaster = false;
        $foreignKeys = [];
        // Get the keys for master table
        if (($master = Get(Config("TABLE_SHOW_MASTER"), Get(Config("TABLE_MASTER")))) !== null) {
            $masterTblVar = $master;
            if ($masterTblVar == "") {
                $validMaster = true;
                $this->DbMasterFilter = "";
                $this->DbDetailFilter = "";
            }
            if ($masterTblVar == "masterproject") {
                $validMaster = true;
                $masterTbl = Container("masterproject");
                if (($parm = Get("fk__ProjectID", Get("_ProjectID"))) !== null) {
                    $masterTbl->_ProjectID->setQueryStringValue($parm);
                    $this->_ProjectID->QueryStringValue = $masterTbl->_ProjectID->QueryStringValue; // DO NOT change, master/detail key data type can be different
                    $this->_ProjectID->setSessionValue($this->_ProjectID->QueryStringValue);
                    $foreignKeys["_ProjectID"] = $this->_ProjectID->QueryStringValue;
                    if (!is_numeric($masterTbl->_ProjectID->QueryStringValue)) {
                        $validMaster = false;
                    }
                } else {
                    $validMaster = false;
                }
            }
        } elseif (($master = Post(Config("TABLE_SHOW_MASTER"), Post(Config("TABLE_MASTER")))) !== null) {
            $masterTblVar = $master;
            if ($masterTblVar == "") {
                    $validMaster = true;
                    $this->DbMasterFilter = "";
                    $this->DbDetailFilter = "";
            }
            if ($masterTblVar == "masterproject") {
                $validMaster = true;
                $masterTbl = Container("masterproject");
                if (($parm = Post("fk__ProjectID", Post("_ProjectID"))) !== null) {
                    $masterTbl->_ProjectID->setFormValue($parm);
                    $this->_ProjectID->FormValue = $masterTbl->_ProjectID->FormValue;
                    $this->_ProjectID->setSessionValue($this->_ProjectID->FormValue);
                    $foreignKeys["_ProjectID"] = $this->_ProjectID->FormValue;
                    if (!is_numeric($masterTbl->_ProjectID->FormValue)) {
                        $validMaster = false;
                    }
                } else {
                    $validMaster = false;
                }
            }
        }
        if ($validMaster) {
            // Save current master table
            $this->setCurrentMasterTable($masterTblVar);
            $this->setSessionWhere($this->getDetailFilterFromSession());

            // Reset start record counter (new master key)
            if (!$this->isAddOrEdit() && !$this->isGridUpdate()) {
                $this->StartRecord = 1;
                $this->setStartRecordNumber($this->StartRecord);
            }

            // Clear previous master key from Session
            if ($masterTblVar != "masterproject") {
                if (!array_key_exists("_ProjectID", $foreignKeys)) { // Not current foreign key
                    $this->_ProjectID->setSessionValue("");
                }
            }
        }
        $this->DbMasterFilter = $this->getMasterFilterFromSession(); // Get master filter from session
        $this->DbDetailFilter = $this->getDetailFilterFromSession(); // Get detail filter from session
    }

    // Set up Breadcrumb
    protected function setupBreadcrumb()
    {
        global $Breadcrumb, $Language;
        $Breadcrumb = new Breadcrumb("masterprojectlist");
        $url = CurrentUrl();
        $Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("projecttasklist"), "", $this->TableVar, true);
        $pageId = "edit";
        $Breadcrumb->add("edit", $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_AssignedTo":
                    break;
                case "x_Priority":
                    break;
                case "x_Category":
                    $lookupFilter = $fld->getSelectFilter(); // PHP
                    break;
                case "x__ProjectID":
                    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;
            }
        }
    }

    // Set up starting record parameters
    public function setupStartRecord()
    {
        if ($this->DisplayRecords == 0) {
            return;
        }
        $pageNo = Get(Config("TABLE_PAGE_NUMBER"));
        $startRec = Get(Config("TABLE_START_REC"));
        $infiniteScroll = false;
        $recordNo = $pageNo ?? $startRec; // Record number = page number or start record
        if ($recordNo !== null && is_numeric($recordNo)) {
            $this->StartRecord = $recordNo;
        } else {
            $this->StartRecord = $this->getStartRecordNumber();
        }

        // Check if correct start record counter
        if (!is_numeric($this->StartRecord) || intval($this->StartRecord) <= 0) { // Avoid invalid start record counter
            $this->StartRecord = 1; // Reset start record counter
        } 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
        } elseif (($this->StartRecord - 1) % $this->DisplayRecords != 0) {
            $this->StartRecord = (int)(($this->StartRecord - 1) / $this->DisplayRecords) * $this->DisplayRecords + 1; // Point to page boundary
        }
        if (!$infiniteScroll) {
            $this->setStartRecordNumber($this->StartRecord);
        }
    }

    // Get page count
    public function pageCount() {
        return ceil($this->TotalRecords / $this->DisplayRecords);
    }

    // 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
    }

    // Form Custom Validate event
    public function formCustomValidate(&$customError)
    {
        // Return error message in $customError
        return true;
    }
}
