<?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 CustomersEdit extends Customers
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

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

    // Rendering View
    public $RenderingView = false;

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

    // 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->customerid->setVisibility();
        $this->customername->setVisibility();
        $this->address->setVisibility();
        $this->ParentAgent->setVisibility();
        $this->isAgent->setVisibility();
        $this->priceListId->setVisibility();
        $this->city->setVisibility();
        $this->country->setVisibility();
        $this->postcode->setVisibility();
        $this->phone1->setVisibility();
        $this->phone2->setVisibility();
        $this->emailaddress->setVisibility();
        $this->notes->setVisibility();
        $this->customercode->setVisibility();
        $this->schedule->setVisibility();
    }

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

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

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

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

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

        // 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("customerid") ?? Key(0) ?? Route(2)) !== null) {
                $this->customerid->setQueryStringValue($keyValue);
                $this->customerid->setOldValue($this->customerid->QueryStringValue);
            } elseif (Post("customerid") !== null) {
                $this->customerid->setFormValue(Post("customerid"));
                $this->customerid->setOldValue($this->customerid->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("customerid") ?? Route("customerid")) !== null) {
                    $this->customerid->setQueryStringValue($keyValue);
                    $loadByQuery = true;
                } else {
                    $this->customerid->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("customerslist"); // 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) == "customerslist") {
                    $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) != "customerslist") {
                            Container("app.flash")->addMessage("Return-Url", $returnUrl); // Save return URL
                            $returnUrl = "customerslist"; // 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;
        $this->notes->Upload->Index = $CurrentForm->Index;
        $this->notes->Upload->uploadFile();
    }

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

        // 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) {
            $this->customerid->setFormValue($val);
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->customerid->CurrentValue = $this->customerid->FormValue;
        $this->customername->CurrentValue = $this->customername->FormValue;
        $this->address->CurrentValue = $this->address->FormValue;
        $this->ParentAgent->CurrentValue = $this->ParentAgent->FormValue;
        $this->isAgent->CurrentValue = $this->isAgent->FormValue;
        $this->priceListId->CurrentValue = $this->priceListId->FormValue;
        $this->city->CurrentValue = $this->city->FormValue;
        $this->country->CurrentValue = $this->country->FormValue;
        $this->postcode->CurrentValue = $this->postcode->FormValue;
        $this->phone1->CurrentValue = $this->phone1->FormValue;
        $this->phone2->CurrentValue = $this->phone2->FormValue;
        $this->emailaddress->CurrentValue = $this->emailaddress->FormValue;
        $this->customercode->CurrentValue = $this->customercode->FormValue;
        $this->schedule->CurrentValue = $this->schedule->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->customerid->setDbValue($row['customerid']);
        $this->customername->setDbValue($row['customername']);
        $this->address->setDbValue($row['address']);
        $this->ParentAgent->setDbValue($row['ParentAgent']);
        $this->isAgent->setDbValue($row['isAgent']);
        $this->priceListId->setDbValue($row['priceListId']);
        $this->city->setDbValue($row['city']);
        $this->country->setDbValue($row['country']);
        $this->postcode->setDbValue($row['postcode']);
        $this->phone1->setDbValue($row['phone1']);
        $this->phone2->setDbValue($row['phone2']);
        $this->emailaddress->setDbValue($row['emailaddress']);
        $this->notes->Upload->DbValue = $row['notes'];
        if (is_resource($this->notes->Upload->DbValue) && get_resource_type($this->notes->Upload->DbValue) == "stream") { // Byte array
            $this->notes->Upload->DbValue = stream_get_contents($this->notes->Upload->DbValue);
        }
        $this->customercode->setDbValue($row['customercode']);
        $this->schedule->setDbValue($row['schedule']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $row = [];
        $row['customerid'] = $this->customerid->DefaultValue;
        $row['customername'] = $this->customername->DefaultValue;
        $row['address'] = $this->address->DefaultValue;
        $row['ParentAgent'] = $this->ParentAgent->DefaultValue;
        $row['isAgent'] = $this->isAgent->DefaultValue;
        $row['priceListId'] = $this->priceListId->DefaultValue;
        $row['city'] = $this->city->DefaultValue;
        $row['country'] = $this->country->DefaultValue;
        $row['postcode'] = $this->postcode->DefaultValue;
        $row['phone1'] = $this->phone1->DefaultValue;
        $row['phone2'] = $this->phone2->DefaultValue;
        $row['emailaddress'] = $this->emailaddress->DefaultValue;
        $row['notes'] = $this->notes->DefaultValue;
        $row['customercode'] = $this->customercode->DefaultValue;
        $row['schedule'] = $this->schedule->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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // notes
            if (!EmptyValue($this->notes->Upload->DbValue)) {
                $this->notes->ViewValue = $this->customerid->CurrentValue;
                $this->notes->IsBlobImage = IsImageFile(ContentExtension($this->notes->Upload->DbValue));
            } else {
                $this->notes->ViewValue = "";
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // notes
            if (!empty($this->notes->Upload->DbValue)) {
                $this->notes->HrefValue = GetFileUploadUrl($this->notes, $this->customerid->CurrentValue);
                $this->notes->LinkAttrs["target"] = "";
                if ($this->notes->IsBlobImage && empty($this->notes->LinkAttrs["target"])) {
                    $this->notes->LinkAttrs["target"] = "_blank";
                }
                if ($this->isExport()) {
                    $this->notes->HrefValue = FullUrl($this->notes->HrefValue, "href");
                }
            } else {
                $this->notes->HrefValue = "";
            }
            $this->notes->ExportHrefValue = GetFileUploadUrl($this->notes, $this->customerid->CurrentValue);

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

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

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

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

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

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

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

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

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

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

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

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

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

            // notes
            $this->notes->setupEditAttributes();
            if (!EmptyValue($this->notes->Upload->DbValue)) {
                $this->notes->EditValue = $this->customerid->CurrentValue;
                $this->notes->IsBlobImage = IsImageFile(ContentExtension($this->notes->Upload->DbValue));
            } else {
                $this->notes->EditValue = "";
            }
            if ($this->isShow()) {
                RenderUploadField($this->notes);
            }

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

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

            // Edit refer script

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

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

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

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

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

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

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

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

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

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

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

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

            // notes
            if (!empty($this->notes->Upload->DbValue)) {
                $this->notes->HrefValue = GetFileUploadUrl($this->notes, $this->customerid->CurrentValue);
                $this->notes->LinkAttrs["target"] = "";
                if ($this->notes->IsBlobImage && empty($this->notes->LinkAttrs["target"])) {
                    $this->notes->LinkAttrs["target"] = "_blank";
                }
                if ($this->isExport()) {
                    $this->notes->HrefValue = FullUrl($this->notes->HrefValue, "href");
                }
            } else {
                $this->notes->HrefValue = "";
            }
            $this->notes->ExportHrefValue = GetFileUploadUrl($this->notes, $this->customerid->CurrentValue);

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

            // schedule
            $this->schedule->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->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 ($this->customername->Visible && $this->customername->Required) {
                if (!$this->customername->IsDetailKey && EmptyValue($this->customername->FormValue)) {
                    $this->customername->addErrorMessage(str_replace("%s", $this->customername->caption(), $this->customername->RequiredErrorMessage));
                }
            }
            if ($this->address->Visible && $this->address->Required) {
                if (!$this->address->IsDetailKey && EmptyValue($this->address->FormValue)) {
                    $this->address->addErrorMessage(str_replace("%s", $this->address->caption(), $this->address->RequiredErrorMessage));
                }
            }
            if ($this->ParentAgent->Visible && $this->ParentAgent->Required) {
                if (!$this->ParentAgent->IsDetailKey && EmptyValue($this->ParentAgent->FormValue)) {
                    $this->ParentAgent->addErrorMessage(str_replace("%s", $this->ParentAgent->caption(), $this->ParentAgent->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->ParentAgent->FormValue)) {
                $this->ParentAgent->addErrorMessage($this->ParentAgent->getErrorMessage(false));
            }
            if ($this->isAgent->Visible && $this->isAgent->Required) {
                if (!$this->isAgent->IsDetailKey && EmptyValue($this->isAgent->FormValue)) {
                    $this->isAgent->addErrorMessage(str_replace("%s", $this->isAgent->caption(), $this->isAgent->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->isAgent->FormValue)) {
                $this->isAgent->addErrorMessage($this->isAgent->getErrorMessage(false));
            }
            if ($this->priceListId->Visible && $this->priceListId->Required) {
                if (!$this->priceListId->IsDetailKey && EmptyValue($this->priceListId->FormValue)) {
                    $this->priceListId->addErrorMessage(str_replace("%s", $this->priceListId->caption(), $this->priceListId->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->priceListId->FormValue)) {
                $this->priceListId->addErrorMessage($this->priceListId->getErrorMessage(false));
            }
            if ($this->city->Visible && $this->city->Required) {
                if (!$this->city->IsDetailKey && EmptyValue($this->city->FormValue)) {
                    $this->city->addErrorMessage(str_replace("%s", $this->city->caption(), $this->city->RequiredErrorMessage));
                }
            }
            if ($this->country->Visible && $this->country->Required) {
                if (!$this->country->IsDetailKey && EmptyValue($this->country->FormValue)) {
                    $this->country->addErrorMessage(str_replace("%s", $this->country->caption(), $this->country->RequiredErrorMessage));
                }
            }
            if ($this->postcode->Visible && $this->postcode->Required) {
                if (!$this->postcode->IsDetailKey && EmptyValue($this->postcode->FormValue)) {
                    $this->postcode->addErrorMessage(str_replace("%s", $this->postcode->caption(), $this->postcode->RequiredErrorMessage));
                }
            }
            if ($this->phone1->Visible && $this->phone1->Required) {
                if (!$this->phone1->IsDetailKey && EmptyValue($this->phone1->FormValue)) {
                    $this->phone1->addErrorMessage(str_replace("%s", $this->phone1->caption(), $this->phone1->RequiredErrorMessage));
                }
            }
            if ($this->phone2->Visible && $this->phone2->Required) {
                if (!$this->phone2->IsDetailKey && EmptyValue($this->phone2->FormValue)) {
                    $this->phone2->addErrorMessage(str_replace("%s", $this->phone2->caption(), $this->phone2->RequiredErrorMessage));
                }
            }
            if ($this->emailaddress->Visible && $this->emailaddress->Required) {
                if (!$this->emailaddress->IsDetailKey && EmptyValue($this->emailaddress->FormValue)) {
                    $this->emailaddress->addErrorMessage(str_replace("%s", $this->emailaddress->caption(), $this->emailaddress->RequiredErrorMessage));
                }
            }
            if ($this->notes->Visible && $this->notes->Required) {
                if ($this->notes->Upload->FileName == "" && !$this->notes->Upload->KeepFile) {
                    $this->notes->addErrorMessage(str_replace("%s", $this->notes->caption(), $this->notes->RequiredErrorMessage));
                }
            }
            if ($this->customercode->Visible && $this->customercode->Required) {
                if (!$this->customercode->IsDetailKey && EmptyValue($this->customercode->FormValue)) {
                    $this->customercode->addErrorMessage(str_replace("%s", $this->customercode->caption(), $this->customercode->RequiredErrorMessage));
                }
            }
            if ($this->schedule->Visible && $this->schedule->Required) {
                if (!$this->schedule->IsDetailKey && EmptyValue($this->schedule->FormValue)) {
                    $this->schedule->addErrorMessage(str_replace("%s", $this->schedule->caption(), $this->schedule->RequiredErrorMessage));
                }
            }

        // Validate detail grid
        $detailTblVar = explode(",", $this->getCurrentDetailTable());
        $detailPage = Container("CustomerhasarticlesGrid");
        if (in_array("customerhasarticles", $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("CustomerhasarticlesGrid");
            if (in_array("customerhasarticles", $detailTblVar) && $detailPage->DetailEdit && $editRow) {
                $Security->loadCurrentUserLevel($this->ProjectID . "customerhasarticles"); // 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 = [];

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

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

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

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

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

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

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

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

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

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

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

        // notes
        if ($this->notes->Visible && !$this->notes->ReadOnly && !$this->notes->Upload->KeepFile) {
            if ($this->notes->Upload->Value === null) {
                $rsnew['notes'] = null;
            } else {
                $rsnew['notes'] = $this->notes->Upload->Value;
            }
        }

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

        // schedule
        $this->schedule->setDbValueDef($rsnew, $this->schedule->CurrentValue, $this->schedule->ReadOnly);
        return $rsnew;
    }

    /**
     * Restore edit form from row
     * @param array $row Row
     */
    protected function restoreEditFormFromRow($row)
    {
        if (isset($row['customername'])) { // customername
            $this->customername->CurrentValue = $row['customername'];
        }
        if (isset($row['address'])) { // address
            $this->address->CurrentValue = $row['address'];
        }
        if (isset($row['ParentAgent'])) { // ParentAgent
            $this->ParentAgent->CurrentValue = $row['ParentAgent'];
        }
        if (isset($row['isAgent'])) { // isAgent
            $this->isAgent->CurrentValue = $row['isAgent'];
        }
        if (isset($row['priceListId'])) { // priceListId
            $this->priceListId->CurrentValue = $row['priceListId'];
        }
        if (isset($row['city'])) { // city
            $this->city->CurrentValue = $row['city'];
        }
        if (isset($row['country'])) { // country
            $this->country->CurrentValue = $row['country'];
        }
        if (isset($row['postcode'])) { // postcode
            $this->postcode->CurrentValue = $row['postcode'];
        }
        if (isset($row['phone1'])) { // phone1
            $this->phone1->CurrentValue = $row['phone1'];
        }
        if (isset($row['phone2'])) { // phone2
            $this->phone2->CurrentValue = $row['phone2'];
        }
        if (isset($row['emailaddress'])) { // emailaddress
            $this->emailaddress->CurrentValue = $row['emailaddress'];
        }
        if (isset($row['notes'])) { // notes
            $this->notes->CurrentValue = $row['notes'];
        }
        if (isset($row['customercode'])) { // customercode
            $this->customercode->CurrentValue = $row['customercode'];
        }
        if (isset($row['schedule'])) { // schedule
            $this->schedule->CurrentValue = $row['schedule'];
        }
    }

    // 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("customerhasarticles", $detailTblVar)) {
                $detailPageObj = Container("CustomerhasarticlesGrid");
                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->customerId->IsDetailKey = true;
                    $detailPageObj->customerId->CurrentValue = $this->customerid->CurrentValue;
                    $detailPageObj->customerId->setSessionValue($detailPageObj->customerId->CurrentValue);
                }
            }
        }
    }

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