<?php

namespace PHPMaker2024\laundrytech;

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

/**
 * Page class
 */
class OrdersEdit extends Orders
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

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

    // Rendering View
    public $RenderingView = false;

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

    // 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->orderid->setVisibility();
        $this->customerid->setVisibility();
        $this->bookingdatetime->setVisibility();
        $this->dueby->setVisibility();
        $this->ordertype->setVisibility();
        $this->invoiced->setVisibility();
        $this->paid->setVisibility();
        $this->ordervalue->setVisibility();
        $this->jobType->setVisibility();
        $this->createdOn->setVisibility();
        $this->createdBy->setVisibility();
        $this->siteId->setVisibility();
        $this->pickupComplete->setVisibility();
        $this->pickupDatetime->setVisibility();
    }

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

        // 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 (orders)
        if (!isset($GLOBALS["orders"]) || $GLOBALS["orders"]::class == PROJECT_NAMESPACE . "orders") {
            $GLOBALS["orders"] = &$this;
        }

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

        // 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, "ordersview"); // 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['orderid'];
        }
        return $key;
    }

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

        // 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("orderid") ?? Key(0) ?? Route(2)) !== null) {
                $this->orderid->setQueryStringValue($keyValue);
                $this->orderid->setOldValue($this->orderid->QueryStringValue);
            } elseif (Post("orderid") !== null) {
                $this->orderid->setFormValue(Post("orderid"));
                $this->orderid->setOldValue($this->orderid->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("orderid") ?? Route("orderid")) !== null) {
                    $this->orderid->setQueryStringValue($keyValue);
                    $loadByQuery = true;
                } else {
                    $this->orderid->CurrentValue = null;
                }
            }

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

            // Set up detail parameters
            $this->setupDetailParms();
        }

        // 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("orderslist"); // No matching record, return to list
                        return;
                    }

                // Set up detail parameters
                $this->setupDetailParms();
                break;
            case "update": // Update
                if ($this->getCurrentDetailTable() != "") { // Master/detail edit
                    $returnUrl = $this->getViewUrl(Config("TABLE_SHOW_DETAIL") . "=" . $this->getCurrentDetailTable()); // Master/Detail view page
                } else {
                    $returnUrl = $this->getReturnUrl();
                }
                if (GetPageName($returnUrl) == "orderslist") {
                    $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) != "orderslist") {
                            Container("app.flash")->addMessage("Return-Url", $returnUrl); // Save return URL
                            $returnUrl = "orderslist"; // 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 detail parameters
                    $this->setupDetailParms();
                }
        }

        // 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 'orderid' first before field var 'x_orderid'
        $val = $CurrentForm->hasValue("orderid") ? $CurrentForm->getValue("orderid") : $CurrentForm->getValue("x_orderid");
        if (!$this->orderid->IsDetailKey) {
            $this->orderid->setFormValue($val);
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->orderid->CurrentValue = $this->orderid->FormValue;
        $this->customerid->CurrentValue = $this->customerid->FormValue;
        $this->bookingdatetime->CurrentValue = $this->bookingdatetime->FormValue;
        $this->bookingdatetime->CurrentValue = UnFormatDateTime($this->bookingdatetime->CurrentValue, $this->bookingdatetime->formatPattern());
        $this->dueby->CurrentValue = $this->dueby->FormValue;
        $this->dueby->CurrentValue = UnFormatDateTime($this->dueby->CurrentValue, $this->dueby->formatPattern());
        $this->ordertype->CurrentValue = $this->ordertype->FormValue;
        $this->invoiced->CurrentValue = $this->invoiced->FormValue;
        $this->paid->CurrentValue = $this->paid->FormValue;
        $this->ordervalue->CurrentValue = $this->ordervalue->FormValue;
        $this->jobType->CurrentValue = $this->jobType->FormValue;
        $this->createdOn->CurrentValue = $this->createdOn->FormValue;
        $this->createdOn->CurrentValue = UnFormatDateTime($this->createdOn->CurrentValue, $this->createdOn->formatPattern());
        $this->createdBy->CurrentValue = $this->createdBy->FormValue;
        $this->siteId->CurrentValue = $this->siteId->FormValue;
        $this->pickupComplete->CurrentValue = $this->pickupComplete->FormValue;
        $this->pickupDatetime->CurrentValue = $this->pickupDatetime->FormValue;
        $this->pickupDatetime->CurrentValue = UnFormatDateTime($this->pickupDatetime->CurrentValue, $this->pickupDatetime->formatPattern());
    }

    /**
     * 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->orderid->setDbValue($row['orderid']);
        $this->customerid->setDbValue($row['customerid']);
        $this->bookingdatetime->setDbValue($row['bookingdatetime']);
        $this->dueby->setDbValue($row['dueby']);
        $this->ordertype->setDbValue($row['ordertype']);
        $this->invoiced->setDbValue($row['invoiced']);
        $this->paid->setDbValue($row['paid']);
        $this->ordervalue->setDbValue($row['ordervalue']);
        $this->jobType->setDbValue($row['jobType']);
        $this->createdOn->setDbValue($row['createdOn']);
        $this->createdBy->setDbValue($row['createdBy']);
        $this->siteId->setDbValue($row['siteId']);
        $this->pickupComplete->setDbValue($row['pickupComplete']);
        $this->pickupDatetime->setDbValue($row['pickupDatetime']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $row = [];
        $row['orderid'] = $this->orderid->DefaultValue;
        $row['customerid'] = $this->customerid->DefaultValue;
        $row['bookingdatetime'] = $this->bookingdatetime->DefaultValue;
        $row['dueby'] = $this->dueby->DefaultValue;
        $row['ordertype'] = $this->ordertype->DefaultValue;
        $row['invoiced'] = $this->invoiced->DefaultValue;
        $row['paid'] = $this->paid->DefaultValue;
        $row['ordervalue'] = $this->ordervalue->DefaultValue;
        $row['jobType'] = $this->jobType->DefaultValue;
        $row['createdOn'] = $this->createdOn->DefaultValue;
        $row['createdBy'] = $this->createdBy->DefaultValue;
        $row['siteId'] = $this->siteId->DefaultValue;
        $row['pickupComplete'] = $this->pickupComplete->DefaultValue;
        $row['pickupDatetime'] = $this->pickupDatetime->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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // invoiced
            $this->invoiced->ViewValue = $this->invoiced->CurrentValue;
            $this->invoiced->ViewValue = FormatNumber($this->invoiced->ViewValue, $this->invoiced->formatPattern());

            // paid
            $this->paid->ViewValue = $this->paid->CurrentValue;
            $this->paid->ViewValue = FormatNumber($this->paid->ViewValue, $this->paid->formatPattern());

            // ordervalue
            $this->ordervalue->ViewValue = $this->ordervalue->CurrentValue;
            $this->ordervalue->ViewValue = FormatNumber($this->ordervalue->ViewValue, $this->ordervalue->formatPattern());

            // jobType
            $this->jobType->ViewValue = $this->jobType->CurrentValue;
            $this->jobType->ViewValue = FormatNumber($this->jobType->ViewValue, $this->jobType->formatPattern());

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

            // createdBy
            $this->createdBy->ViewValue = $this->createdBy->CurrentValue;
            $this->createdBy->ViewValue = FormatNumber($this->createdBy->ViewValue, $this->createdBy->formatPattern());

            // siteId
            $this->siteId->ViewValue = $this->siteId->CurrentValue;
            $this->siteId->ViewValue = FormatNumber($this->siteId->ViewValue, $this->siteId->formatPattern());

            // pickupComplete
            $this->pickupComplete->ViewValue = $this->pickupComplete->CurrentValue;
            $this->pickupComplete->ViewValue = FormatNumber($this->pickupComplete->ViewValue, $this->pickupComplete->formatPattern());

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // pickupDatetime
            $this->pickupDatetime->HrefValue = "";
        } elseif ($this->RowType == RowType::EDIT) {
            // orderid
            $this->orderid->setupEditAttributes();
            $this->orderid->EditValue = $this->orderid->CurrentValue;

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Edit refer script

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

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

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

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

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

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

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

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

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

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

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

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

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

            // pickupDatetime
            $this->pickupDatetime->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->orderid->Visible && $this->orderid->Required) {
                if (!$this->orderid->IsDetailKey && EmptyValue($this->orderid->FormValue)) {
                    $this->orderid->addErrorMessage(str_replace("%s", $this->orderid->caption(), $this->orderid->RequiredErrorMessage));
                }
            }
            if ($this->customerid->Visible && $this->customerid->Required) {
                if (!$this->customerid->IsDetailKey && EmptyValue($this->customerid->FormValue)) {
                    $this->customerid->addErrorMessage(str_replace("%s", $this->customerid->caption(), $this->customerid->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->customerid->FormValue)) {
                $this->customerid->addErrorMessage($this->customerid->getErrorMessage(false));
            }
            if ($this->bookingdatetime->Visible && $this->bookingdatetime->Required) {
                if (!$this->bookingdatetime->IsDetailKey && EmptyValue($this->bookingdatetime->FormValue)) {
                    $this->bookingdatetime->addErrorMessage(str_replace("%s", $this->bookingdatetime->caption(), $this->bookingdatetime->RequiredErrorMessage));
                }
            }
            if (!CheckDate($this->bookingdatetime->FormValue, $this->bookingdatetime->formatPattern())) {
                $this->bookingdatetime->addErrorMessage($this->bookingdatetime->getErrorMessage(false));
            }
            if ($this->dueby->Visible && $this->dueby->Required) {
                if (!$this->dueby->IsDetailKey && EmptyValue($this->dueby->FormValue)) {
                    $this->dueby->addErrorMessage(str_replace("%s", $this->dueby->caption(), $this->dueby->RequiredErrorMessage));
                }
            }
            if (!CheckDate($this->dueby->FormValue, $this->dueby->formatPattern())) {
                $this->dueby->addErrorMessage($this->dueby->getErrorMessage(false));
            }
            if ($this->ordertype->Visible && $this->ordertype->Required) {
                if (!$this->ordertype->IsDetailKey && EmptyValue($this->ordertype->FormValue)) {
                    $this->ordertype->addErrorMessage(str_replace("%s", $this->ordertype->caption(), $this->ordertype->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->ordertype->FormValue)) {
                $this->ordertype->addErrorMessage($this->ordertype->getErrorMessage(false));
            }
            if ($this->invoiced->Visible && $this->invoiced->Required) {
                if (!$this->invoiced->IsDetailKey && EmptyValue($this->invoiced->FormValue)) {
                    $this->invoiced->addErrorMessage(str_replace("%s", $this->invoiced->caption(), $this->invoiced->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->invoiced->FormValue)) {
                $this->invoiced->addErrorMessage($this->invoiced->getErrorMessage(false));
            }
            if ($this->paid->Visible && $this->paid->Required) {
                if (!$this->paid->IsDetailKey && EmptyValue($this->paid->FormValue)) {
                    $this->paid->addErrorMessage(str_replace("%s", $this->paid->caption(), $this->paid->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->paid->FormValue)) {
                $this->paid->addErrorMessage($this->paid->getErrorMessage(false));
            }
            if ($this->ordervalue->Visible && $this->ordervalue->Required) {
                if (!$this->ordervalue->IsDetailKey && EmptyValue($this->ordervalue->FormValue)) {
                    $this->ordervalue->addErrorMessage(str_replace("%s", $this->ordervalue->caption(), $this->ordervalue->RequiredErrorMessage));
                }
            }
            if (!CheckNumber($this->ordervalue->FormValue)) {
                $this->ordervalue->addErrorMessage($this->ordervalue->getErrorMessage(false));
            }
            if ($this->jobType->Visible && $this->jobType->Required) {
                if (!$this->jobType->IsDetailKey && EmptyValue($this->jobType->FormValue)) {
                    $this->jobType->addErrorMessage(str_replace("%s", $this->jobType->caption(), $this->jobType->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->jobType->FormValue)) {
                $this->jobType->addErrorMessage($this->jobType->getErrorMessage(false));
            }
            if ($this->createdOn->Visible && $this->createdOn->Required) {
                if (!$this->createdOn->IsDetailKey && EmptyValue($this->createdOn->FormValue)) {
                    $this->createdOn->addErrorMessage(str_replace("%s", $this->createdOn->caption(), $this->createdOn->RequiredErrorMessage));
                }
            }
            if (!CheckDate($this->createdOn->FormValue, $this->createdOn->formatPattern())) {
                $this->createdOn->addErrorMessage($this->createdOn->getErrorMessage(false));
            }
            if ($this->createdBy->Visible && $this->createdBy->Required) {
                if (!$this->createdBy->IsDetailKey && EmptyValue($this->createdBy->FormValue)) {
                    $this->createdBy->addErrorMessage(str_replace("%s", $this->createdBy->caption(), $this->createdBy->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->createdBy->FormValue)) {
                $this->createdBy->addErrorMessage($this->createdBy->getErrorMessage(false));
            }
            if ($this->siteId->Visible && $this->siteId->Required) {
                if (!$this->siteId->IsDetailKey && EmptyValue($this->siteId->FormValue)) {
                    $this->siteId->addErrorMessage(str_replace("%s", $this->siteId->caption(), $this->siteId->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->siteId->FormValue)) {
                $this->siteId->addErrorMessage($this->siteId->getErrorMessage(false));
            }
            if ($this->pickupComplete->Visible && $this->pickupComplete->Required) {
                if (!$this->pickupComplete->IsDetailKey && EmptyValue($this->pickupComplete->FormValue)) {
                    $this->pickupComplete->addErrorMessage(str_replace("%s", $this->pickupComplete->caption(), $this->pickupComplete->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->pickupComplete->FormValue)) {
                $this->pickupComplete->addErrorMessage($this->pickupComplete->getErrorMessage(false));
            }
            if ($this->pickupDatetime->Visible && $this->pickupDatetime->Required) {
                if (!$this->pickupDatetime->IsDetailKey && EmptyValue($this->pickupDatetime->FormValue)) {
                    $this->pickupDatetime->addErrorMessage(str_replace("%s", $this->pickupDatetime->caption(), $this->pickupDatetime->RequiredErrorMessage));
                }
            }
            if (!CheckDate($this->pickupDatetime->FormValue, $this->pickupDatetime->formatPattern())) {
                $this->pickupDatetime->addErrorMessage($this->pickupDatetime->getErrorMessage(false));
            }

        // Validate detail grid
        $detailTblVar = explode(",", $this->getCurrentDetailTable());
        $detailPage = Container("OrdercontainersGrid");
        if (in_array("ordercontainers", $detailTblVar) && $detailPage->DetailEdit) {
            $detailPage->run();
            $validateForm = $validateForm && $detailPage->validateGridForm();
        }
        $detailPage = Container("OrderstagesGrid");
        if (in_array("orderstages", $detailTblVar) && $detailPage->DetailEdit) {
            $detailPage->run();
            $validateForm = $validateForm && $detailPage->validateGridForm();
        }
        $detailPage = Container("OrderarticlesGrid");
        if (in_array("orderarticles", $detailTblVar) && $detailPage->DetailEdit) {
            $detailPage->run();
            $validateForm = $validateForm && $detailPage->validateGridForm();
        }

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

        // Begin transaction
        if ($this->getCurrentDetailTable() != "" && $this->UseTransaction) {
            $conn->beginTransaction();
        }

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

            // Update detail records
            $detailTblVar = explode(",", $this->getCurrentDetailTable());
            $detailPage = Container("OrdercontainersGrid");
            if (in_array("ordercontainers", $detailTblVar) && $detailPage->DetailEdit && $editRow) {
                $Security->loadCurrentUserLevel($this->ProjectID . "ordercontainers"); // Load user level of detail table
                $editRow = $detailPage->gridUpdate();
                $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
            }
            $detailPage = Container("OrderstagesGrid");
            if (in_array("orderstages", $detailTblVar) && $detailPage->DetailEdit && $editRow) {
                $Security->loadCurrentUserLevel($this->ProjectID . "orderstages"); // Load user level of detail table
                $editRow = $detailPage->gridUpdate();
                $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
            }
            $detailPage = Container("OrderarticlesGrid");
            if (in_array("orderarticles", $detailTblVar) && $detailPage->DetailEdit && $editRow) {
                $Security->loadCurrentUserLevel($this->ProjectID . "orderarticles"); // Load user level of detail table
                $editRow = $detailPage->gridUpdate();
                $Security->loadCurrentUserLevel($this->ProjectID . $this->TableName); // Restore user level of master table
            }

            // Commit/Rollback transaction
            if ($this->getCurrentDetailTable() != "") {
                if ($editRow) {
                    if ($this->UseTransaction) { // Commit transaction
                        if ($conn->isTransactionActive()) {
                            $conn->commit();
                        }
                    }
                } else {
                    if ($this->UseTransaction) { // Rollback transaction
                        if ($conn->isTransactionActive()) {
                            $conn->rollback();
                        }
                    }
                }
            }
        } 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 = [];

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

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

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

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

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

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

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

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

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

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

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

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

        // pickupDatetime
        $this->pickupDatetime->setDbValueDef($rsnew, UnFormatDateTime($this->pickupDatetime->CurrentValue, $this->pickupDatetime->formatPattern()), $this->pickupDatetime->ReadOnly);
        return $rsnew;
    }

    /**
     * Restore edit form from row
     * @param array $row Row
     */
    protected function restoreEditFormFromRow($row)
    {
        if (isset($row['customerid'])) { // customerid
            $this->customerid->CurrentValue = $row['customerid'];
        }
        if (isset($row['bookingdatetime'])) { // bookingdatetime
            $this->bookingdatetime->CurrentValue = $row['bookingdatetime'];
        }
        if (isset($row['dueby'])) { // dueby
            $this->dueby->CurrentValue = $row['dueby'];
        }
        if (isset($row['ordertype'])) { // ordertype
            $this->ordertype->CurrentValue = $row['ordertype'];
        }
        if (isset($row['invoiced'])) { // invoiced
            $this->invoiced->CurrentValue = $row['invoiced'];
        }
        if (isset($row['paid'])) { // paid
            $this->paid->CurrentValue = $row['paid'];
        }
        if (isset($row['ordervalue'])) { // ordervalue
            $this->ordervalue->CurrentValue = $row['ordervalue'];
        }
        if (isset($row['jobType'])) { // jobType
            $this->jobType->CurrentValue = $row['jobType'];
        }
        if (isset($row['createdOn'])) { // createdOn
            $this->createdOn->CurrentValue = $row['createdOn'];
        }
        if (isset($row['createdBy'])) { // createdBy
            $this->createdBy->CurrentValue = $row['createdBy'];
        }
        if (isset($row['siteId'])) { // siteId
            $this->siteId->CurrentValue = $row['siteId'];
        }
        if (isset($row['pickupComplete'])) { // pickupComplete
            $this->pickupComplete->CurrentValue = $row['pickupComplete'];
        }
        if (isset($row['pickupDatetime'])) { // pickupDatetime
            $this->pickupDatetime->CurrentValue = $row['pickupDatetime'];
        }
    }

    // Set up detail parms based on QueryString
    protected function setupDetailParms()
    {
        // Get the keys for master table
        $detailTblVar = Get(Config("TABLE_SHOW_DETAIL"));
        if ($detailTblVar !== null) {
            $this->setCurrentDetailTable($detailTblVar);
        } else {
            $detailTblVar = $this->getCurrentDetailTable();
        }
        if ($detailTblVar != "") {
            $detailTblVar = explode(",", $detailTblVar);
            if (in_array("ordercontainers", $detailTblVar)) {
                $detailPageObj = Container("OrdercontainersGrid");
                if ($detailPageObj->DetailEdit) {
                    $detailPageObj->EventCancelled = $this->EventCancelled;
                    $detailPageObj->CurrentMode = "edit";
                    $detailPageObj->CurrentAction = "gridedit";

                    // Save current master table to detail table
                    $detailPageObj->setCurrentMasterTable($this->TableVar);
                    $detailPageObj->setStartRecordNumber(1);
                    $detailPageObj->orderId->IsDetailKey = true;
                    $detailPageObj->orderId->CurrentValue = $this->orderid->CurrentValue;
                    $detailPageObj->orderId->setSessionValue($detailPageObj->orderId->CurrentValue);
                }
            }
            if (in_array("orderstages", $detailTblVar)) {
                $detailPageObj = Container("OrderstagesGrid");
                if ($detailPageObj->DetailEdit) {
                    $detailPageObj->EventCancelled = $this->EventCancelled;
                    $detailPageObj->CurrentMode = "edit";
                    $detailPageObj->CurrentAction = "gridedit";

                    // Save current master table to detail table
                    $detailPageObj->setCurrentMasterTable($this->TableVar);
                    $detailPageObj->setStartRecordNumber(1);
                    $detailPageObj->orderid->IsDetailKey = true;
                    $detailPageObj->orderid->CurrentValue = $this->orderid->CurrentValue;
                    $detailPageObj->orderid->setSessionValue($detailPageObj->orderid->CurrentValue);
                }
            }
            if (in_array("orderarticles", $detailTblVar)) {
                $detailPageObj = Container("OrderarticlesGrid");
                if ($detailPageObj->DetailEdit) {
                    $detailPageObj->EventCancelled = $this->EventCancelled;
                    $detailPageObj->CurrentMode = "edit";
                    $detailPageObj->CurrentAction = "gridedit";

                    // Save current master table to detail table
                    $detailPageObj->setCurrentMasterTable($this->TableVar);
                    $detailPageObj->setStartRecordNumber(1);
                    $detailPageObj->orderId->IsDetailKey = true;
                    $detailPageObj->orderId->CurrentValue = $this->orderid->CurrentValue;
                    $detailPageObj->orderId->setSessionValue($detailPageObj->orderId->CurrentValue);
                }
            }
        }
    }

    // Set up Breadcrumb
    protected function setupBreadcrumb()
    {
        global $Breadcrumb, $Language;
        $Breadcrumb = new Breadcrumb("index");
        $url = CurrentUrl();
        $Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("orderslist"), "", $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_customerid":
                    break;
                case "x_ordertype":
                    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;
    }
}
