<?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 PricelistdetailsEdit extends Pricelistdetails
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

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

    // Rendering View
    public $RenderingView = false;

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

    // 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->priceListDetailId->setVisibility();
        $this->priceListid->setVisibility();
        $this->articleid->setVisibility();
        $this->rate->setVisibility();
        $this->discount->setVisibility();
        $this->discountType->setVisibility();
        $this->netAmount->setVisibility();
    }

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

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

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

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

    /**
     * Hide fields for add/edit
     *
     * @return void
     */
    protected function hideFieldsForAddEdit()
    {
        if ($this->isAdd() || $this->isCopy() || $this->isGridAdd()) {
            $this->priceListDetailId->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("priceListDetailId") ?? Key(0) ?? Route(2)) !== null) {
                $this->priceListDetailId->setQueryStringValue($keyValue);
                $this->priceListDetailId->setOldValue($this->priceListDetailId->QueryStringValue);
            } elseif (Post("priceListDetailId") !== null) {
                $this->priceListDetailId->setFormValue(Post("priceListDetailId"));
                $this->priceListDetailId->setOldValue($this->priceListDetailId->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("priceListDetailId") ?? Route("priceListDetailId")) !== null) {
                    $this->priceListDetailId->setQueryStringValue($keyValue);
                    $loadByQuery = true;
                } else {
                    $this->priceListDetailId->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
        }

        // 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("pricelistdetailslist"); // No matching record, return to list
                        return;
                    }
                break;
            case "update": // Update
                $returnUrl = $this->getReturnUrl();
                if (GetPageName($returnUrl) == "pricelistdetailslist") {
                    $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) != "pricelistdetailslist") {
                            Container("app.flash")->addMessage("Return-Url", $returnUrl); // Save return URL
                            $returnUrl = "pricelistdetailslist"; // Return list page content
                        }
                    }
                    if (IsJsonResponse()) {
                        $this->terminate(true);
                        return;
                    } else {
                        $this->terminate($returnUrl); // Return to caller
                        return;
                    }
                } elseif (IsApi()) { // API request, return
                    $this->terminate();
                    return;
                } elseif ($this->IsModal && $this->UseAjaxActions) { // Return JSON error message
                    WriteJson(["success" => false, "validation" => $this->getValidationErrors(), "error" => $this->getFailureMessage()]);
                    $this->clearFailureMessage();
                    $this->terminate();
                    return;
                } elseif ($this->getFailureMessage() == $Language->phrase("NoRecord")) {
                    $this->terminate($returnUrl); // Return to caller
                    return;
                } else {
                    $this->EventCancelled = true; // Event cancelled
                    $this->restoreFormValues(); // Restore form values if update failed
                }
        }

        // Set up Breadcrumb
        $this->setupBreadcrumb();

        // Render the record
        $this->RowType = RowType::EDIT; // Render as Edit
        $this->resetAttributes();
        $this->renderRow();

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

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

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

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

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

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

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

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

        // 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 'articleid' first before field var 'x_articleid'
        $val = $CurrentForm->hasValue("articleid") ? $CurrentForm->getValue("articleid") : $CurrentForm->getValue("x_articleid");
        if (!$this->articleid->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->articleid->Visible = false; // Disable update for API request
            } else {
                $this->articleid->setFormValue($val, true, $validate);
            }
        }

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

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

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

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

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->priceListDetailId->CurrentValue = $this->priceListDetailId->FormValue;
        $this->priceListid->CurrentValue = $this->priceListid->FormValue;
        $this->articleid->CurrentValue = $this->articleid->FormValue;
        $this->rate->CurrentValue = $this->rate->FormValue;
        $this->discount->CurrentValue = $this->discount->FormValue;
        $this->discountType->CurrentValue = $this->discountType->FormValue;
        $this->netAmount->CurrentValue = $this->netAmount->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->priceListDetailId->setDbValue($row['priceListDetailId']);
        $this->priceListid->setDbValue($row['priceListid']);
        $this->articleid->setDbValue($row['articleid']);
        $this->rate->setDbValue($row['rate']);
        $this->discount->setDbValue($row['discount']);
        $this->discountType->setDbValue($row['discountType']);
        $this->netAmount->setDbValue($row['netAmount']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $row = [];
        $row['priceListDetailId'] = $this->priceListDetailId->DefaultValue;
        $row['priceListid'] = $this->priceListid->DefaultValue;
        $row['articleid'] = $this->articleid->DefaultValue;
        $row['rate'] = $this->rate->DefaultValue;
        $row['discount'] = $this->discount->DefaultValue;
        $row['discountType'] = $this->discountType->DefaultValue;
        $row['netAmount'] = $this->netAmount->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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Edit refer script

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

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

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

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

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

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

            // netAmount
            $this->netAmount->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->priceListDetailId->Visible && $this->priceListDetailId->Required) {
                if (!$this->priceListDetailId->IsDetailKey && EmptyValue($this->priceListDetailId->FormValue)) {
                    $this->priceListDetailId->addErrorMessage(str_replace("%s", $this->priceListDetailId->caption(), $this->priceListDetailId->RequiredErrorMessage));
                }
            }
            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->articleid->Visible && $this->articleid->Required) {
                if (!$this->articleid->IsDetailKey && EmptyValue($this->articleid->FormValue)) {
                    $this->articleid->addErrorMessage(str_replace("%s", $this->articleid->caption(), $this->articleid->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->articleid->FormValue)) {
                $this->articleid->addErrorMessage($this->articleid->getErrorMessage(false));
            }
            if ($this->rate->Visible && $this->rate->Required) {
                if (!$this->rate->IsDetailKey && EmptyValue($this->rate->FormValue)) {
                    $this->rate->addErrorMessage(str_replace("%s", $this->rate->caption(), $this->rate->RequiredErrorMessage));
                }
            }
            if (!CheckNumber($this->rate->FormValue)) {
                $this->rate->addErrorMessage($this->rate->getErrorMessage(false));
            }
            if ($this->discount->Visible && $this->discount->Required) {
                if (!$this->discount->IsDetailKey && EmptyValue($this->discount->FormValue)) {
                    $this->discount->addErrorMessage(str_replace("%s", $this->discount->caption(), $this->discount->RequiredErrorMessage));
                }
            }
            if (!CheckNumber($this->discount->FormValue)) {
                $this->discount->addErrorMessage($this->discount->getErrorMessage(false));
            }
            if ($this->discountType->Visible && $this->discountType->Required) {
                if (!$this->discountType->IsDetailKey && EmptyValue($this->discountType->FormValue)) {
                    $this->discountType->addErrorMessage(str_replace("%s", $this->discountType->caption(), $this->discountType->RequiredErrorMessage));
                }
            }
            if (!CheckInteger($this->discountType->FormValue)) {
                $this->discountType->addErrorMessage($this->discountType->getErrorMessage(false));
            }
            if ($this->netAmount->Visible && $this->netAmount->Required) {
                if (!$this->netAmount->IsDetailKey && EmptyValue($this->netAmount->FormValue)) {
                    $this->netAmount->addErrorMessage(str_replace("%s", $this->netAmount->caption(), $this->netAmount->RequiredErrorMessage));
                }
            }
            if (!CheckNumber($this->netAmount->FormValue)) {
                $this->netAmount->addErrorMessage($this->netAmount->getErrorMessage(false));
            }

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

        // Call Row Updating event
        $updateRow = $this->rowUpdating($rsold, $rsnew);
        if ($updateRow) {
            if (count($rsnew) > 0) {
                $this->CurrentFilter = $filter; // Set up current filter
                $editRow = $this->update($rsnew, "", $rsold);
                if (!$editRow && !EmptyValue($this->DbErrorMessage)) { // Show database error
                    $this->setFailureMessage($this->DbErrorMessage);
                }
            } else {
                $editRow = true; // No field to update
            }
            if ($editRow) {
            }
        } else {
            if ($this->getSuccessMessage() != "" || $this->getFailureMessage() != "") {
                // Use the message, do nothing
            } elseif ($this->CancelMessage != "") {
                $this->setFailureMessage($this->CancelMessage);
                $this->CancelMessage = "";
            } else {
                $this->setFailureMessage($Language->phrase("UpdateCancelled"));
            }
            $editRow = false;
        }

        // Call Row_Updated event
        if ($editRow) {
            $this->rowUpdated($rsold, $rsnew);
        }

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

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

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

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

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

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

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

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

    /**
     * Restore edit form from row
     * @param array $row Row
     */
    protected function restoreEditFormFromRow($row)
    {
        if (isset($row['priceListid'])) { // priceListid
            $this->priceListid->CurrentValue = $row['priceListid'];
        }
        if (isset($row['articleid'])) { // articleid
            $this->articleid->CurrentValue = $row['articleid'];
        }
        if (isset($row['rate'])) { // rate
            $this->rate->CurrentValue = $row['rate'];
        }
        if (isset($row['discount'])) { // discount
            $this->discount->CurrentValue = $row['discount'];
        }
        if (isset($row['discountType'])) { // discountType
            $this->discountType->CurrentValue = $row['discountType'];
        }
        if (isset($row['netAmount'])) { // netAmount
            $this->netAmount->CurrentValue = $row['netAmount'];
        }
    }

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