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

/**
 * Table class for orders
 */
class Orders extends DbTable
{
    protected $SqlFrom = "";
    protected $SqlSelect = null;
    protected $SqlSelectList = null;
    protected $SqlWhere = "";
    protected $SqlGroupBy = "";
    protected $SqlHaving = "";
    protected $SqlOrderBy = "";
    public $DbErrorMessage = "";
    public $UseSessionForListSql = true;

    // Column CSS classes
    public $LeftColumnClass = "col-sm-2 col-form-label ew-label";
    public $RightColumnClass = "col-sm-10";
    public $OffsetColumnClass = "col-sm-10 offset-sm-2";
    public $TableLeftColumnClass = "w-col-2";

    // Ajax / Modal
    public $UseAjaxActions = false;
    public $ModalSearch = false;
    public $ModalView = false;
    public $ModalAdd = false;
    public $ModalEdit = false;
    public $ModalUpdate = false;
    public $InlineDelete = false;
    public $ModalGridAdd = false;
    public $ModalGridEdit = false;
    public $ModalMultiEdit = false;

    // Fields
    public $orderid;
    public $customerid;
    public $bookingdatetime;
    public $dueby;
    public $ordertype;
    public $invoiced;
    public $paid;
    public $ordervalue;
    public $jobType;
    public $createdOn;
    public $createdBy;
    public $siteId;
    public $pickupComplete;
    public $pickupDatetime;

    // Page ID
    public $PageID = ""; // To be overridden by subclass

    // Constructor
    public function __construct()
    {
        parent::__construct();
        global $Language, $CurrentLanguage, $CurrentLocale;

        // Language object
        $Language = Container("app.language");
        $this->TableVar = "orders";
        $this->TableName = 'orders';
        $this->TableType = "TABLE";
        $this->ImportUseTransaction = $this->supportsTransaction() && Config("IMPORT_USE_TRANSACTION");
        $this->UseTransaction = $this->supportsTransaction() && Config("USE_TRANSACTION");

        // Update Table
        $this->UpdateTable = "orders";
        $this->Dbid = 'DB';
        $this->ExportAll = true;
        $this->ExportPageBreakCount = 0; // Page break per every n record (PDF only)

        // PDF
        $this->ExportPageOrientation = "portrait"; // Page orientation (PDF only)
        $this->ExportPageSize = "a4"; // Page size (PDF only)

        // PhpSpreadsheet
        $this->ExportExcelPageOrientation = null; // Page orientation (PhpSpreadsheet only)
        $this->ExportExcelPageSize = null; // Page size (PhpSpreadsheet only)

        // PHPWord
        $this->ExportWordPageOrientation = ""; // Page orientation (PHPWord only)
        $this->ExportWordPageSize = ""; // Page orientation (PHPWord only)
        $this->ExportWordColumnWidth = null; // Cell width (PHPWord only)
        $this->DetailAdd = false; // Allow detail add
        $this->DetailEdit = false; // Allow detail edit
        $this->DetailView = false; // Allow detail view
        $this->ShowMultipleDetails = false; // Show multiple details
        $this->GridAddRowCount = 5;
        $this->AllowAddDeleteRow = true; // Allow add/delete row
        $this->UseAjaxActions = $this->UseAjaxActions || Config("USE_AJAX_ACTIONS");
        $this->UserIDAllowSecurity = Config("DEFAULT_USER_ID_ALLOW_SECURITY"); // Default User ID allowed permissions
        $this->BasicSearch = new BasicSearch($this);

        // orderid
        $this->orderid = new DbField(
            $this, // Table
            'x_orderid', // Variable name
            'orderid', // Name
            '`orderid`', // Expression
            '`orderid`', // Basic search expression
            3, // Type
            11, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`orderid`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'NO' // Edit Tag
        );
        $this->orderid->InputTextType = "text";
        $this->orderid->Raw = true;
        $this->orderid->IsAutoIncrement = true; // Autoincrement field
        $this->orderid->IsPrimaryKey = true; // Primary key field
        $this->orderid->IsForeignKey = true; // Foreign key field
        $this->orderid->Nullable = false; // NOT NULL field
        $this->orderid->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->orderid->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN"];
        $this->Fields['orderid'] = &$this->orderid;

        // customerid
        $this->customerid = new DbField(
            $this, // Table
            'x_customerid', // Variable name
            'customerid', // Name
            '`customerid`', // Expression
            '`customerid`', // Basic search expression
            3, // Type
            11, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`customerid`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->customerid->InputTextType = "text";
        $this->customerid->Raw = true;
        $this->customerid->Nullable = false; // NOT NULL field
        $this->customerid->Required = true; // Required field
        $this->customerid->Lookup = new Lookup($this->customerid, 'customers', false, 'customerid', ["customername","ParentAgent","",""], '', '', [], [], [], [], [], [], false, '', '', "CONCAT(COALESCE(`customername`, ''),'" . ValueSeparator(1, $this->customerid) . "',COALESCE(`ParentAgent`,''))");
        $this->customerid->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->customerid->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN"];
        $this->Fields['customerid'] = &$this->customerid;

        // bookingdatetime
        $this->bookingdatetime = new DbField(
            $this, // Table
            'x_bookingdatetime', // Variable name
            'bookingdatetime', // Name
            '`bookingdatetime`', // Expression
            CastDateFieldForLike("`bookingdatetime`", 0, "DB"), // Basic search expression
            135, // Type
            19, // Size
            0, // Date/Time format
            false, // Is upload field
            '`bookingdatetime`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->bookingdatetime->InputTextType = "text";
        $this->bookingdatetime->Raw = true;
        $this->bookingdatetime->Nullable = false; // NOT NULL field
        $this->bookingdatetime->Required = true; // Required field
        $this->bookingdatetime->DefaultErrorMessage = str_replace("%s", $GLOBALS["DATE_FORMAT"], $Language->phrase("IncorrectDate"));
        $this->bookingdatetime->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN"];
        $this->Fields['bookingdatetime'] = &$this->bookingdatetime;

        // dueby
        $this->dueby = new DbField(
            $this, // Table
            'x_dueby', // Variable name
            'dueby', // Name
            '`dueby`', // Expression
            CastDateFieldForLike("`dueby`", 0, "DB"), // Basic search expression
            135, // Type
            19, // Size
            0, // Date/Time format
            false, // Is upload field
            '`dueby`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->dueby->InputTextType = "text";
        $this->dueby->Raw = true;
        $this->dueby->Nullable = false; // NOT NULL field
        $this->dueby->Required = true; // Required field
        $this->dueby->DefaultErrorMessage = str_replace("%s", $GLOBALS["DATE_FORMAT"], $Language->phrase("IncorrectDate"));
        $this->dueby->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN"];
        $this->Fields['dueby'] = &$this->dueby;

        // ordertype
        $this->ordertype = new DbField(
            $this, // Table
            'x_ordertype', // Variable name
            'ordertype', // Name
            '`ordertype`', // Expression
            '`ordertype`', // Basic search expression
            3, // Type
            11, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`ordertype`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->ordertype->InputTextType = "text";
        $this->ordertype->Raw = true;
        $this->ordertype->Lookup = new Lookup($this->ordertype, 'ordertypes', false, 'ordertypeid', ["ordertypename","","",""], '', '', [], [], [], [], [], [], false, '', '', "`ordertypename`");
        $this->ordertype->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->ordertype->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN", "IS NULL", "IS NOT NULL"];
        $this->Fields['ordertype'] = &$this->ordertype;

        // invoiced
        $this->invoiced = new DbField(
            $this, // Table
            'x_invoiced', // Variable name
            'invoiced', // Name
            '`invoiced`', // Expression
            '`invoiced`', // Basic search expression
            3, // Type
            11, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`invoiced`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->invoiced->InputTextType = "text";
        $this->invoiced->Raw = true;
        $this->invoiced->Nullable = false; // NOT NULL field
        $this->invoiced->Required = true; // Required field
        $this->invoiced->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->invoiced->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN"];
        $this->Fields['invoiced'] = &$this->invoiced;

        // paid
        $this->paid = new DbField(
            $this, // Table
            'x_paid', // Variable name
            'paid', // Name
            '`paid`', // Expression
            '`paid`', // Basic search expression
            3, // Type
            11, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`paid`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->paid->InputTextType = "text";
        $this->paid->Raw = true;
        $this->paid->Nullable = false; // NOT NULL field
        $this->paid->Required = true; // Required field
        $this->paid->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->paid->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN"];
        $this->Fields['paid'] = &$this->paid;

        // ordervalue
        $this->ordervalue = new DbField(
            $this, // Table
            'x_ordervalue', // Variable name
            'ordervalue', // Name
            '`ordervalue`', // Expression
            '`ordervalue`', // Basic search expression
            5, // Type
            22, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`ordervalue`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->ordervalue->InputTextType = "text";
        $this->ordervalue->Raw = true;
        $this->ordervalue->DefaultErrorMessage = $Language->phrase("IncorrectFloat");
        $this->ordervalue->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN", "IS NULL", "IS NOT NULL"];
        $this->Fields['ordervalue'] = &$this->ordervalue;

        // jobType
        $this->jobType = new DbField(
            $this, // Table
            'x_jobType', // Variable name
            'jobType', // Name
            '`jobType`', // Expression
            '`jobType`', // Basic search expression
            3, // Type
            11, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`jobType`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->jobType->InputTextType = "text";
        $this->jobType->Raw = true;
        $this->jobType->Nullable = false; // NOT NULL field
        $this->jobType->Required = true; // Required field
        $this->jobType->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->jobType->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN"];
        $this->Fields['jobType'] = &$this->jobType;

        // createdOn
        $this->createdOn = new DbField(
            $this, // Table
            'x_createdOn', // Variable name
            'createdOn', // Name
            '`createdOn`', // Expression
            CastDateFieldForLike("`createdOn`", 0, "DB"), // Basic search expression
            135, // Type
            19, // Size
            0, // Date/Time format
            false, // Is upload field
            '`createdOn`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->createdOn->InputTextType = "text";
        $this->createdOn->Raw = true;
        $this->createdOn->Nullable = false; // NOT NULL field
        $this->createdOn->Required = true; // Required field
        $this->createdOn->DefaultErrorMessage = str_replace("%s", $GLOBALS["DATE_FORMAT"], $Language->phrase("IncorrectDate"));
        $this->createdOn->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN"];
        $this->Fields['createdOn'] = &$this->createdOn;

        // createdBy
        $this->createdBy = new DbField(
            $this, // Table
            'x_createdBy', // Variable name
            'createdBy', // Name
            '`createdBy`', // Expression
            '`createdBy`', // Basic search expression
            3, // Type
            11, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`createdBy`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->createdBy->InputTextType = "text";
        $this->createdBy->Raw = true;
        $this->createdBy->Nullable = false; // NOT NULL field
        $this->createdBy->Required = true; // Required field
        $this->createdBy->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->createdBy->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN"];
        $this->Fields['createdBy'] = &$this->createdBy;

        // siteId
        $this->siteId = new DbField(
            $this, // Table
            'x_siteId', // Variable name
            'siteId', // Name
            '`siteId`', // Expression
            '`siteId`', // Basic search expression
            3, // Type
            11, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`siteId`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->siteId->InputTextType = "text";
        $this->siteId->Raw = true;
        $this->siteId->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->siteId->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN", "IS NULL", "IS NOT NULL"];
        $this->Fields['siteId'] = &$this->siteId;

        // pickupComplete
        $this->pickupComplete = new DbField(
            $this, // Table
            'x_pickupComplete', // Variable name
            'pickupComplete', // Name
            '`pickupComplete`', // Expression
            '`pickupComplete`', // Basic search expression
            3, // Type
            11, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`pickupComplete`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->pickupComplete->InputTextType = "text";
        $this->pickupComplete->Raw = true;
        $this->pickupComplete->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->pickupComplete->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN", "IS NULL", "IS NOT NULL"];
        $this->Fields['pickupComplete'] = &$this->pickupComplete;

        // pickupDatetime
        $this->pickupDatetime = new DbField(
            $this, // Table
            'x_pickupDatetime', // Variable name
            'pickupDatetime', // Name
            '`pickupDatetime`', // Expression
            CastDateFieldForLike("`pickupDatetime`", 0, "DB"), // Basic search expression
            135, // Type
            19, // Size
            0, // Date/Time format
            false, // Is upload field
            '`pickupDatetime`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->pickupDatetime->InputTextType = "text";
        $this->pickupDatetime->Raw = true;
        $this->pickupDatetime->DefaultErrorMessage = str_replace("%s", $GLOBALS["DATE_FORMAT"], $Language->phrase("IncorrectDate"));
        $this->pickupDatetime->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN", "IS NULL", "IS NOT NULL"];
        $this->Fields['pickupDatetime'] = &$this->pickupDatetime;

        // Add Doctrine Cache
        $this->Cache = new \Symfony\Component\Cache\Adapter\ArrayAdapter();
        $this->CacheProfile = new \Doctrine\DBAL\Cache\QueryCacheProfile(0, $this->TableVar);

        // Call Table Load event
        $this->tableLoad();
    }

    // Field Visibility
    public function getFieldVisibility($fldParm)
    {
        global $Security;
        return $this->$fldParm->Visible; // Returns original value
    }

    // Set left column class (must be predefined col-*-* classes of Bootstrap grid system)
    public function setLeftColumnClass($class)
    {
        if (preg_match('/^col\-(\w+)\-(\d+)$/', $class, $match)) {
            $this->LeftColumnClass = $class . " col-form-label ew-label";
            $this->RightColumnClass = "col-" . $match[1] . "-" . strval(12 - (int)$match[2]);
            $this->OffsetColumnClass = $this->RightColumnClass . " " . str_replace("col-", "offset-", $class);
            $this->TableLeftColumnClass = preg_replace('/^col-\w+-(\d+)$/', "w-col-$1", $class); // Change to w-col-*
        }
    }

    // Single column sort
    public function updateSort(&$fld)
    {
        if ($this->CurrentOrder == $fld->Name) {
            $sortField = $fld->Expression;
            $lastSort = $fld->getSort();
            if (in_array($this->CurrentOrderType, ["ASC", "DESC", "NO"])) {
                $curSort = $this->CurrentOrderType;
            } else {
                $curSort = $lastSort;
            }
            $orderBy = in_array($curSort, ["ASC", "DESC"]) ? $sortField . " " . $curSort : "";
            $this->setSessionOrderBy($orderBy); // Save to Session
        }
    }

    // Update field sort
    public function updateFieldSort()
    {
        $orderBy = $this->getSessionOrderBy(); // Get ORDER BY from Session
        $flds = GetSortFields($orderBy);
        foreach ($this->Fields as $field) {
            $fldSort = "";
            foreach ($flds as $fld) {
                if ($fld[0] == $field->Expression || $fld[0] == $field->VirtualExpression) {
                    $fldSort = $fld[1];
                }
            }
            $field->setSort($fldSort);
        }
    }

    // Current detail table name
    public function getCurrentDetailTable()
    {
        return Session(PROJECT_NAME . "_" . $this->TableVar . "_" . Config("TABLE_DETAIL_TABLE")) ?? "";
    }

    public function setCurrentDetailTable($v)
    {
        $_SESSION[PROJECT_NAME . "_" . $this->TableVar . "_" . Config("TABLE_DETAIL_TABLE")] = $v;
    }

    // Get detail url
    public function getDetailUrl()
    {
        // Detail url
        $detailUrl = "";
        if ($this->getCurrentDetailTable() == "ordercontainers") {
            $detailUrl = Container("ordercontainers")->getListUrl() . "?" . Config("TABLE_SHOW_MASTER") . "=" . $this->TableVar;
            $detailUrl .= "&" . GetForeignKeyUrl("fk_orderid", $this->orderid->CurrentValue);
        }
        if ($this->getCurrentDetailTable() == "orderstages") {
            $detailUrl = Container("orderstages")->getListUrl() . "?" . Config("TABLE_SHOW_MASTER") . "=" . $this->TableVar;
            $detailUrl .= "&" . GetForeignKeyUrl("fk_orderid", $this->orderid->CurrentValue);
        }
        if ($this->getCurrentDetailTable() == "orderarticles") {
            $detailUrl = Container("orderarticles")->getListUrl() . "?" . Config("TABLE_SHOW_MASTER") . "=" . $this->TableVar;
            $detailUrl .= "&" . GetForeignKeyUrl("fk_orderid", $this->orderid->CurrentValue);
        }
        if ($detailUrl == "") {
            $detailUrl = "orderslist";
        }
        return $detailUrl;
    }

    // Render X Axis for chart
    public function renderChartXAxis($chartVar, $chartRow)
    {
        return $chartRow;
    }

    // Get FROM clause
    public function getSqlFrom()
    {
        return ($this->SqlFrom != "") ? $this->SqlFrom : "orders";
    }

    // Get FROM clause (for backward compatibility)
    public function sqlFrom()
    {
        return $this->getSqlFrom();
    }

    // Set FROM clause
    public function setSqlFrom($v)
    {
        $this->SqlFrom = $v;
    }

    // Get SELECT clause
    public function getSqlSelect() // Select
    {
        return $this->SqlSelect ?? $this->getQueryBuilder()->select($this->sqlSelectFields());
    }

    // Get list of fields
    private function sqlSelectFields()
    {
        $useFieldNames = false;
        $fieldNames = [];
        $platform = $this->getConnection()->getDatabasePlatform();
        foreach ($this->Fields as $field) {
            $expr = $field->Expression;
            $customExpr = $field->CustomDataType?->convertToPHPValueSQL($expr, $platform) ?? $expr;
            if ($customExpr != $expr) {
                $fieldNames[] = $customExpr . " AS " . QuotedName($field->Name, $this->Dbid);
                $useFieldNames = true;
            } else {
                $fieldNames[] = $expr;
            }
        }
        return $useFieldNames ? implode(", ", $fieldNames) : "*";
    }

    // Get SELECT clause (for backward compatibility)
    public function sqlSelect()
    {
        return $this->getSqlSelect();
    }

    // Set SELECT clause
    public function setSqlSelect($v)
    {
        $this->SqlSelect = $v;
    }

    // Get WHERE clause
    public function getSqlWhere()
    {
        $where = ($this->SqlWhere != "") ? $this->SqlWhere : "";
        $this->DefaultFilter = "";
        AddFilter($where, $this->DefaultFilter);
        return $where;
    }

    // Get WHERE clause (for backward compatibility)
    public function sqlWhere()
    {
        return $this->getSqlWhere();
    }

    // Set WHERE clause
    public function setSqlWhere($v)
    {
        $this->SqlWhere = $v;
    }

    // Get GROUP BY clause
    public function getSqlGroupBy()
    {
        return $this->SqlGroupBy != "" ? $this->SqlGroupBy : "";
    }

    // Get GROUP BY clause (for backward compatibility)
    public function sqlGroupBy()
    {
        return $this->getSqlGroupBy();
    }

    // set GROUP BY clause
    public function setSqlGroupBy($v)
    {
        $this->SqlGroupBy = $v;
    }

    // Get HAVING clause
    public function getSqlHaving() // Having
    {
        return ($this->SqlHaving != "") ? $this->SqlHaving : "";
    }

    // Get HAVING clause (for backward compatibility)
    public function sqlHaving()
    {
        return $this->getSqlHaving();
    }

    // Set HAVING clause
    public function setSqlHaving($v)
    {
        $this->SqlHaving = $v;
    }

    // Get ORDER BY clause
    public function getSqlOrderBy()
    {
        return ($this->SqlOrderBy != "") ? $this->SqlOrderBy : "";
    }

    // Get ORDER BY clause (for backward compatibility)
    public function sqlOrderBy()
    {
        return $this->getSqlOrderBy();
    }

    // set ORDER BY clause
    public function setSqlOrderBy($v)
    {
        $this->SqlOrderBy = $v;
    }

    // Apply User ID filters
    public function applyUserIDFilters($filter, $id = "")
    {
        return $filter;
    }

    // Check if User ID security allows view all
    public function userIDAllow($id = "")
    {
        $allow = $this->UserIDAllowSecurity;
        switch ($id) {
            case "add":
            case "copy":
            case "gridadd":
            case "register":
            case "addopt":
                return ($allow & Allow::ADD->value) == Allow::ADD->value;
            case "edit":
            case "gridedit":
            case "update":
            case "changepassword":
            case "resetpassword":
                return ($allow & Allow::EDIT->value) == Allow::EDIT->value;
            case "delete":
                return ($allow & Allow::DELETE->value) == Allow::DELETE->value;
            case "view":
                return ($allow & Allow::VIEW->value) == Allow::VIEW->value;
            case "search":
                return ($allow & Allow::SEARCH->value) == Allow::SEARCH->value;
            case "lookup":
                return ($allow & Allow::LOOKUP->value) == Allow::LOOKUP->value;
            default:
                return ($allow & Allow::LIST->value) == Allow::LIST->value;
        }
    }

    /**
     * Get record count
     *
     * @param string|QueryBuilder $sql SQL or QueryBuilder
     * @param mixed $c Connection
     * @return int
     */
    public function getRecordCount($sql, $c = null)
    {
        $cnt = -1;
        $sqlwrk = $sql instanceof QueryBuilder // Query builder
            ? (clone $sql)->resetQueryPart("orderBy")->getSQL()
            : $sql;
        $pattern = '/^SELECT\s([\s\S]+)\sFROM\s/i';
        // Skip Custom View / SubQuery / SELECT DISTINCT / ORDER BY
        if (
            in_array($this->TableType, ["TABLE", "VIEW", "LINKTABLE"]) &&
            preg_match($pattern, $sqlwrk) &&
            !preg_match('/\(\s*(SELECT[^)]+)\)/i', $sqlwrk) &&
            !preg_match('/^\s*SELECT\s+DISTINCT\s+/i', $sqlwrk) &&
            !preg_match('/\s+ORDER\s+BY\s+/i', $sqlwrk)
        ) {
            $sqlcnt = "SELECT COUNT(*) FROM " . preg_replace($pattern, "", $sqlwrk);
        } else {
            $sqlcnt = "SELECT COUNT(*) FROM (" . $sqlwrk . ") COUNT_TABLE";
        }
        $conn = $c ?? $this->getConnection();
        $cnt = $conn->fetchOne($sqlcnt);
        if ($cnt !== false) {
            return (int)$cnt;
        }
        // Unable to get count by SELECT COUNT(*), execute the SQL to get record count directly
        $result = $conn->executeQuery($sqlwrk);
        $cnt = $result->rowCount();
        if ($cnt == 0) { // Unable to get record count, count directly
            while ($result->fetch()) {
                $cnt++;
            }
        }
        return $cnt;
    }

    // Get SQL
    public function getSql($where, $orderBy = "")
    {
        return $this->getSqlAsQueryBuilder($where, $orderBy)->getSQL();
    }

    // Get QueryBuilder
    public function getSqlAsQueryBuilder($where, $orderBy = "")
    {
        return $this->buildSelectSql(
            $this->getSqlSelect(),
            $this->getSqlFrom(),
            $this->getSqlWhere(),
            $this->getSqlGroupBy(),
            $this->getSqlHaving(),
            $this->getSqlOrderBy(),
            $where,
            $orderBy
        );
    }

    // Table SQL
    public function getCurrentSql()
    {
        $filter = $this->CurrentFilter;
        $filter = $this->applyUserIDFilters($filter);
        $sort = $this->getSessionOrderBy();
        return $this->getSql($filter, $sort);
    }

    /**
     * Table SQL with List page filter
     *
     * @return QueryBuilder
     */
    public function getListSql()
    {
        $filter = $this->UseSessionForListSql ? $this->getSessionWhere() : "";
        AddFilter($filter, $this->CurrentFilter);
        $filter = $this->applyUserIDFilters($filter);
        $this->recordsetSelecting($filter);
        $select = $this->getSqlSelect();
        $from = $this->getSqlFrom();
        $sort = $this->UseSessionForListSql ? $this->getSessionOrderBy() : "";
        $this->Sort = $sort;
        return $this->buildSelectSql(
            $select,
            $from,
            $this->getSqlWhere(),
            $this->getSqlGroupBy(),
            $this->getSqlHaving(),
            $this->getSqlOrderBy(),
            $filter,
            $sort
        );
    }

    // Get ORDER BY clause
    public function getOrderBy()
    {
        $orderBy = $this->getSqlOrderBy();
        $sort = $this->getSessionOrderBy();
        if ($orderBy != "" && $sort != "") {
            $orderBy .= ", " . $sort;
        } elseif ($sort != "") {
            $orderBy = $sort;
        }
        return $orderBy;
    }

    // Get record count based on filter (for detail record count in master table pages)
    public function loadRecordCount($filter)
    {
        $origFilter = $this->CurrentFilter;
        $this->CurrentFilter = $filter;
        $this->recordsetSelecting($this->CurrentFilter);
        $isCustomView = $this->TableType == "CUSTOMVIEW";
        $select = $isCustomView ? $this->getSqlSelect() : $this->getQueryBuilder()->select("*");
        $groupBy = $isCustomView ? $this->getSqlGroupBy() : "";
        $having = $isCustomView ? $this->getSqlHaving() : "";
        $sql = $this->buildSelectSql($select, $this->getSqlFrom(), $this->getSqlWhere(), $groupBy, $having, "", $this->CurrentFilter, "");
        $cnt = $this->getRecordCount($sql);
        $this->CurrentFilter = $origFilter;
        return $cnt;
    }

    // Get record count (for current List page)
    public function listRecordCount()
    {
        $filter = $this->getSessionWhere();
        AddFilter($filter, $this->CurrentFilter);
        $filter = $this->applyUserIDFilters($filter);
        $this->recordsetSelecting($filter);
        $isCustomView = $this->TableType == "CUSTOMVIEW";
        $select = $isCustomView ? $this->getSqlSelect() : $this->getQueryBuilder()->select("*");
        $groupBy = $isCustomView ? $this->getSqlGroupBy() : "";
        $having = $isCustomView ? $this->getSqlHaving() : "";
        $sql = $this->buildSelectSql($select, $this->getSqlFrom(), $this->getSqlWhere(), $groupBy, $having, "", $filter, "");
        $cnt = $this->getRecordCount($sql);
        return $cnt;
    }

    /**
     * INSERT statement
     *
     * @param mixed $rs
     * @return QueryBuilder
     */
    public function insertSql(&$rs)
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->insert($this->UpdateTable);
        $platform = $this->getConnection()->getDatabasePlatform();
        foreach ($rs as $name => $value) {
            if (!isset($this->Fields[$name]) || $this->Fields[$name]->IsCustom) {
                continue;
            }
            $field = $this->Fields[$name];
            $parm = $queryBuilder->createPositionalParameter($value, $field->getParameterType());
            $parm = $field->CustomDataType?->convertToDatabaseValueSQL($parm, $platform) ?? $parm; // Convert database SQL
            $queryBuilder->setValue($field->Expression, $parm);
        }
        return $queryBuilder;
    }

    // Insert
    public function insert(&$rs)
    {
        $conn = $this->getConnection();
        try {
            $queryBuilder = $this->insertSql($rs);
            $result = $queryBuilder->executeStatement();
            $this->DbErrorMessage = "";
        } catch (\Exception $e) {
            $result = false;
            $this->DbErrorMessage = $e->getMessage();
        }
        if ($result) {
            $this->orderid->setDbValue($conn->lastInsertId());
            $rs['orderid'] = $this->orderid->DbValue;
        }
        return $result;
    }

    /**
     * UPDATE statement
     *
     * @param array $rs Data to be updated
     * @param string|array $where WHERE clause
     * @param string $curfilter Filter
     * @return QueryBuilder
     */
    public function updateSql(&$rs, $where = "", $curfilter = true)
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->update($this->UpdateTable);
        $platform = $this->getConnection()->getDatabasePlatform();
        foreach ($rs as $name => $value) {
            if (!isset($this->Fields[$name]) || $this->Fields[$name]->IsCustom || $this->Fields[$name]->IsAutoIncrement) {
                continue;
            }
            $field = $this->Fields[$name];
            $parm = $queryBuilder->createPositionalParameter($value, $field->getParameterType());
            $parm = $field->CustomDataType?->convertToDatabaseValueSQL($parm, $platform) ?? $parm; // Convert database SQL
            $queryBuilder->set($field->Expression, $parm);
        }
        $filter = $curfilter ? $this->CurrentFilter : "";
        if (is_array($where)) {
            $where = $this->arrayToFilter($where);
        }
        AddFilter($filter, $where);
        if ($filter != "") {
            $queryBuilder->where($filter);
        }
        return $queryBuilder;
    }

    // Update
    public function update(&$rs, $where = "", $rsold = null, $curfilter = true)
    {
        // Cascade Update detail table 'ordercontainers'
        $cascadeUpdate = false;
        $rscascade = [];
        if ($rsold && (isset($rs['orderid']) && $rsold['orderid'] != $rs['orderid'])) { // Update detail field 'orderId'
            $cascadeUpdate = true;
            $rscascade['orderId'] = $rs['orderid'];
        }
        if ($cascadeUpdate) {
            $rswrk = Container("ordercontainers")->loadRs("`orderId` = " . QuotedValue($rsold['orderid'], DataType::NUMBER, 'DB'))->fetchAllAssociative();
            foreach ($rswrk as $rsdtlold) {
                $rskey = [];
                $fldname = 'orderContainerId';
                $rskey[$fldname] = $rsdtlold[$fldname];
                $rsdtlnew = array_merge($rsdtlold, $rscascade);
                // Call Row_Updating event
                $success = Container("ordercontainers")->rowUpdating($rsdtlold, $rsdtlnew);
                if ($success) {
                    $success = Container("ordercontainers")->update($rscascade, $rskey, $rsdtlold);
                }
                if (!$success) {
                    return false;
                }
                // Call Row_Updated event
                Container("ordercontainers")->rowUpdated($rsdtlold, $rsdtlnew);
            }
        }

        // Cascade Update detail table 'orderstages'
        $cascadeUpdate = false;
        $rscascade = [];
        if ($rsold && (isset($rs['orderid']) && $rsold['orderid'] != $rs['orderid'])) { // Update detail field 'orderid'
            $cascadeUpdate = true;
            $rscascade['orderid'] = $rs['orderid'];
        }
        if ($cascadeUpdate) {
            $rswrk = Container("orderstages")->loadRs("`orderid` = " . QuotedValue($rsold['orderid'], DataType::NUMBER, 'DB'))->fetchAllAssociative();
            foreach ($rswrk as $rsdtlold) {
                $rskey = [];
                $fldname = 'orderstageid';
                $rskey[$fldname] = $rsdtlold[$fldname];
                $rsdtlnew = array_merge($rsdtlold, $rscascade);
                // Call Row_Updating event
                $success = Container("orderstages")->rowUpdating($rsdtlold, $rsdtlnew);
                if ($success) {
                    $success = Container("orderstages")->update($rscascade, $rskey, $rsdtlold);
                }
                if (!$success) {
                    return false;
                }
                // Call Row_Updated event
                Container("orderstages")->rowUpdated($rsdtlold, $rsdtlnew);
            }
        }

        // If no field is updated, execute may return 0. Treat as success
        try {
            $success = $this->updateSql($rs, $where, $curfilter)->executeStatement();
            $success = $success > 0 ? $success : true;
            $this->DbErrorMessage = "";
        } catch (\Exception $e) {
            $success = false;
            $this->DbErrorMessage = $e->getMessage();
        }

        // Return auto increment field
        if ($success) {
            if (!isset($rs['orderid']) && !EmptyValue($this->orderid->CurrentValue)) {
                $rs['orderid'] = $this->orderid->CurrentValue;
            }
        }
        return $success;
    }

    /**
     * DELETE statement
     *
     * @param array $rs Key values
     * @param string|array $where WHERE clause
     * @param string $curfilter Filter
     * @return QueryBuilder
     */
    public function deleteSql(&$rs, $where = "", $curfilter = true)
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->delete($this->UpdateTable);
        if (is_array($where)) {
            $where = $this->arrayToFilter($where);
        }
        if ($rs) {
            if (array_key_exists('orderid', $rs)) {
                AddFilter($where, QuotedName('orderid', $this->Dbid) . '=' . QuotedValue($rs['orderid'], $this->orderid->DataType, $this->Dbid));
            }
        }
        $filter = $curfilter ? $this->CurrentFilter : "";
        AddFilter($filter, $where);
        return $queryBuilder->where($filter != "" ? $filter : "0=1");
    }

    // Delete
    public function delete(&$rs, $where = "", $curfilter = false)
    {
        $success = true;

        // Cascade delete detail table 'ordercontainers'
        $dtlrows = Container("ordercontainers")->loadRs("`orderId` = " . QuotedValue($rs['orderid'], DataType::NUMBER, "DB"))->fetchAllAssociative();
        // Call Row Deleting event
        foreach ($dtlrows as $dtlrow) {
            $success = Container("ordercontainers")->rowDeleting($dtlrow);
            if (!$success) {
                break;
            }
        }
        if ($success) {
            foreach ($dtlrows as $dtlrow) {
                $success = Container("ordercontainers")->delete($dtlrow); // Delete
                if (!$success) {
                    break;
                }
            }
        }
        // Call Row Deleted event
        if ($success) {
            foreach ($dtlrows as $dtlrow) {
                Container("ordercontainers")->rowDeleted($dtlrow);
            }
        }

        // Cascade delete detail table 'orderstages'
        $dtlrows = Container("orderstages")->loadRs("`orderid` = " . QuotedValue($rs['orderid'], DataType::NUMBER, "DB"))->fetchAllAssociative();
        // Call Row Deleting event
        foreach ($dtlrows as $dtlrow) {
            $success = Container("orderstages")->rowDeleting($dtlrow);
            if (!$success) {
                break;
            }
        }
        if ($success) {
            foreach ($dtlrows as $dtlrow) {
                $success = Container("orderstages")->delete($dtlrow); // Delete
                if (!$success) {
                    break;
                }
            }
        }
        // Call Row Deleted event
        if ($success) {
            foreach ($dtlrows as $dtlrow) {
                Container("orderstages")->rowDeleted($dtlrow);
            }
        }
        if ($success) {
            try {
                $success = $this->deleteSql($rs, $where, $curfilter)->executeStatement();
                $this->DbErrorMessage = "";
            } catch (\Exception $e) {
                $success = false;
                $this->DbErrorMessage = $e->getMessage();
            }
        }
        return $success;
    }

    // Load DbValue from result set or array
    protected function loadDbValues($row)
    {
        if (!is_array($row)) {
            return;
        }
        $this->orderid->DbValue = $row['orderid'];
        $this->customerid->DbValue = $row['customerid'];
        $this->bookingdatetime->DbValue = $row['bookingdatetime'];
        $this->dueby->DbValue = $row['dueby'];
        $this->ordertype->DbValue = $row['ordertype'];
        $this->invoiced->DbValue = $row['invoiced'];
        $this->paid->DbValue = $row['paid'];
        $this->ordervalue->DbValue = $row['ordervalue'];
        $this->jobType->DbValue = $row['jobType'];
        $this->createdOn->DbValue = $row['createdOn'];
        $this->createdBy->DbValue = $row['createdBy'];
        $this->siteId->DbValue = $row['siteId'];
        $this->pickupComplete->DbValue = $row['pickupComplete'];
        $this->pickupDatetime->DbValue = $row['pickupDatetime'];
    }

    // Delete uploaded files
    public function deleteUploadedFiles($row)
    {
        $this->loadDbValues($row);
    }

    // Record filter WHERE clause
    protected function sqlKeyFilter()
    {
        return "`orderid` = @orderid@";
    }

    // Get Key
    public function getKey($current = false, $keySeparator = null)
    {
        $keys = [];
        $val = $current ? $this->orderid->CurrentValue : $this->orderid->OldValue;
        if (EmptyValue($val)) {
            return "";
        } else {
            $keys[] = $val;
        }
        $keySeparator ??= Config("COMPOSITE_KEY_SEPARATOR");
        return implode($keySeparator, $keys);
    }

    // Set Key
    public function setKey($key, $current = false, $keySeparator = null)
    {
        $keySeparator ??= Config("COMPOSITE_KEY_SEPARATOR");
        $this->OldKey = strval($key);
        $keys = explode($keySeparator, $this->OldKey);
        if (count($keys) == 1) {
            if ($current) {
                $this->orderid->CurrentValue = $keys[0];
            } else {
                $this->orderid->OldValue = $keys[0];
            }
        }
    }

    // Get record filter
    public function getRecordFilter($row = null, $current = false)
    {
        $keyFilter = $this->sqlKeyFilter();
        if (is_array($row)) {
            $val = array_key_exists('orderid', $row) ? $row['orderid'] : null;
        } else {
            $val = !EmptyValue($this->orderid->OldValue) && !$current ? $this->orderid->OldValue : $this->orderid->CurrentValue;
        }
        if (!is_numeric($val)) {
            return "0=1"; // Invalid key
        }
        if ($val === null) {
            return "0=1"; // Invalid key
        } else {
            $keyFilter = str_replace("@orderid@", AdjustSql($val, $this->Dbid), $keyFilter); // Replace key value
        }
        return $keyFilter;
    }

    // Return page URL
    public function getReturnUrl()
    {
        $referUrl = ReferUrl();
        $referPageName = ReferPageName();
        $name = PROJECT_NAME . "_" . $this->TableVar . "_" . Config("TABLE_RETURN_URL");
        // Get referer URL automatically
        if ($referUrl != "" && $referPageName != CurrentPageName() && $referPageName != "login") { // Referer not same page or login page
            $_SESSION[$name] = $referUrl; // Save to Session
        }
        return $_SESSION[$name] ?? GetUrl("orderslist");
    }

    // Set return page URL
    public function setReturnUrl($v)
    {
        $_SESSION[PROJECT_NAME . "_" . $this->TableVar . "_" . Config("TABLE_RETURN_URL")] = $v;
    }

    // Get modal caption
    public function getModalCaption($pageName)
    {
        global $Language;
        return match ($pageName) {
            "ordersview" => $Language->phrase("View"),
            "ordersedit" => $Language->phrase("Edit"),
            "ordersadd" => $Language->phrase("Add"),
            default => ""
        };
    }

    // Default route URL
    public function getDefaultRouteUrl()
    {
        return "orderslist";
    }

    // API page name
    public function getApiPageName($action)
    {
        return match (strtolower($action)) {
            Config("API_VIEW_ACTION") => "OrdersView",
            Config("API_ADD_ACTION") => "OrdersAdd",
            Config("API_EDIT_ACTION") => "OrdersEdit",
            Config("API_DELETE_ACTION") => "OrdersDelete",
            Config("API_LIST_ACTION") => "OrdersList",
            default => ""
        };
    }

    // Current URL
    public function getCurrentUrl($parm = "")
    {
        $url = CurrentPageUrl(false);
        if ($parm != "") {
            $url = $this->keyUrl($url, $parm);
        } else {
            $url = $this->keyUrl($url, Config("TABLE_SHOW_DETAIL") . "=");
        }
        return $this->addMasterUrl($url);
    }

    // List URL
    public function getListUrl()
    {
        return "orderslist";
    }

    // View URL
    public function getViewUrl($parm = "")
    {
        if ($parm != "") {
            $url = $this->keyUrl("ordersview", $parm);
        } else {
            $url = $this->keyUrl("ordersview", Config("TABLE_SHOW_DETAIL") . "=");
        }
        return $this->addMasterUrl($url);
    }

    // Add URL
    public function getAddUrl($parm = "")
    {
        if ($parm != "") {
            $url = "ordersadd?" . $parm;
        } else {
            $url = "ordersadd";
        }
        return $this->addMasterUrl($url);
    }

    // Edit URL
    public function getEditUrl($parm = "")
    {
        if ($parm != "") {
            $url = $this->keyUrl("ordersedit", $parm);
        } else {
            $url = $this->keyUrl("ordersedit", Config("TABLE_SHOW_DETAIL") . "=");
        }
        return $this->addMasterUrl($url);
    }

    // Inline edit URL
    public function getInlineEditUrl()
    {
        $url = $this->keyUrl("orderslist", "action=edit");
        return $this->addMasterUrl($url);
    }

    // Copy URL
    public function getCopyUrl($parm = "")
    {
        if ($parm != "") {
            $url = $this->keyUrl("ordersadd", $parm);
        } else {
            $url = $this->keyUrl("ordersadd", Config("TABLE_SHOW_DETAIL") . "=");
        }
        return $this->addMasterUrl($url);
    }

    // Inline copy URL
    public function getInlineCopyUrl()
    {
        $url = $this->keyUrl("orderslist", "action=copy");
        return $this->addMasterUrl($url);
    }

    // Delete URL
    public function getDeleteUrl($parm = "")
    {
        if ($this->UseAjaxActions && ConvertToBool(Param("infinitescroll")) && CurrentPageID() == "list") {
            return $this->keyUrl(GetApiUrl(Config("API_DELETE_ACTION") . "/" . $this->TableVar));
        } else {
            return $this->keyUrl("ordersdelete", $parm);
        }
    }

    // Add master url
    public function addMasterUrl($url)
    {
        return $url;
    }

    public function keyToJson($htmlEncode = false)
    {
        $json = "";
        $json .= "\"orderid\":" . VarToJson($this->orderid->CurrentValue, "number");
        $json = "{" . $json . "}";
        if ($htmlEncode) {
            $json = HtmlEncode($json);
        }
        return $json;
    }

    // Add key value to URL
    public function keyUrl($url, $parm = "")
    {
        if ($this->orderid->CurrentValue !== null) {
            $url .= "/" . $this->encodeKeyValue($this->orderid->CurrentValue);
        } else {
            return "javascript:ew.alert(ew.language.phrase('InvalidRecord'));";
        }
        if ($parm != "") {
            $url .= "?" . $parm;
        }
        return $url;
    }

    // Render sort
    public function renderFieldHeader($fld)
    {
        global $Security, $Language;
        $sortUrl = "";
        $attrs = "";
        if ($this->PageID != "grid" && $fld->Sortable) {
            $sortUrl = $this->sortUrl($fld);
            $attrs = ' role="button" data-ew-action="sort" data-ajax="' . ($this->UseAjaxActions ? "true" : "false") . '" data-sort-url="' . $sortUrl . '" data-sort-type="1"';
            if ($this->ContextClass) { // Add context
                $attrs .= ' data-context="' . HtmlEncode($this->ContextClass) . '"';
            }
        }
        $html = '<div class="ew-table-header-caption"' . $attrs . '>' . $fld->caption() . '</div>';
        if ($sortUrl) {
            $html .= '<div class="ew-table-header-sort">' . $fld->getSortIcon() . '</div>';
        }
        if ($this->PageID != "grid" && !$this->isExport() && $fld->UseFilter && $Security->canSearch()) {
            $html .= '<div class="ew-filter-dropdown-btn" data-ew-action="filter" data-table="' . $fld->TableVar . '" data-field="' . $fld->FieldVar .
                '"><div class="ew-table-header-filter" role="button" aria-haspopup="true">' . $Language->phrase("Filter") .
                (is_array($fld->EditValue) ? str_replace("%c", count($fld->EditValue), $Language->phrase("FilterCount")) : '') .
                '</div></div>';
        }
        $html = '<div class="ew-table-header-btn">' . $html . '</div>';
        if ($this->UseCustomTemplate) {
            $scriptId = str_replace("{id}", $fld->TableVar . "_" . $fld->Param, "tpc_{id}");
            $html = '<template id="' . $scriptId . '">' . $html . '</template>';
        }
        return $html;
    }

    // Sort URL
    public function sortUrl($fld)
    {
        global $DashboardReport;
        if (
            $this->CurrentAction || $this->isExport() ||
            in_array($fld->Type, [128, 204, 205])
        ) { // Unsortable data type
                return "";
        } elseif ($fld->Sortable) {
            $urlParm = "order=" . urlencode($fld->Name) . "&amp;ordertype=" . $fld->getNextSort();
            if ($DashboardReport) {
                $urlParm .= "&amp;" . Config("PAGE_DASHBOARD") . "=" . $DashboardReport;
            }
            return $this->addMasterUrl($this->CurrentPageName . "?" . $urlParm);
        } else {
            return "";
        }
    }

    // Get record keys from Post/Get/Session
    public function getRecordKeys()
    {
        $arKeys = [];
        $arKey = [];
        if (Param("key_m") !== null) {
            $arKeys = Param("key_m");
            $cnt = count($arKeys);
        } else {
            $isApi = IsApi();
            $keyValues = $isApi
                ? (Route(0) == "export"
                    ? array_map(fn ($i) => Route($i + 3), range(0, 0))  // Export API
                    : array_map(fn ($i) => Route($i + 2), range(0, 0))) // Other API
                : []; // Non-API
            if (($keyValue = Param("orderid") ?? Route("orderid")) !== null) {
                $arKeys[] = $keyValue;
            } elseif ($isApi && (($keyValue = Key(0) ?? $keyValues[0] ?? null) !== null)) {
                $arKeys[] = $keyValue;
            } else {
                $arKeys = null; // Do not setup
            }
        }
        // Check keys
        $ar = [];
        if (is_array($arKeys)) {
            foreach ($arKeys as $key) {
                if (!is_numeric($key)) {
                    continue;
                }
                $ar[] = $key;
            }
        }
        return $ar;
    }

    // Get filter from records
    public function getFilterFromRecords($rows)
    {
        $keyFilter = "";
        foreach ($rows as $row) {
            if ($keyFilter != "") {
                $keyFilter .= " OR ";
            }
            $keyFilter .= "(" . $this->getRecordFilter($row) . ")";
        }
        return $keyFilter;
    }

    // Get filter from record keys
    public function getFilterFromRecordKeys($setCurrent = true)
    {
        $arKeys = $this->getRecordKeys();
        $keyFilter = "";
        foreach ($arKeys as $key) {
            if ($keyFilter != "") {
                $keyFilter .= " OR ";
            }
            if ($setCurrent) {
                $this->orderid->CurrentValue = $key;
            } else {
                $this->orderid->OldValue = $key;
            }
            $keyFilter .= "(" . $this->getRecordFilter() . ")";
        }
        return $keyFilter;
    }

    // Load result set based on filter/sort
    public function loadRs($filter, $sort = "")
    {
        $sql = $this->getSql($filter, $sort); // Set up filter (WHERE Clause) / sort (ORDER BY Clause)
        $conn = $this->getConnection();
        return $conn->executeQuery($sql);
    }

    // Load row values from record
    public function loadListRowValues(&$rs)
    {
        if (is_array($rs)) {
            $row = $rs;
        } elseif ($rs && property_exists($rs, "fields")) { // Recordset
            $row = $rs->fields;
        } else {
            return;
        }
        $this->orderid->setDbValue($row['orderid']);
        $this->customerid->setDbValue($row['customerid']);
        $this->bookingdatetime->setDbValue($row['bookingdatetime']);
        $this->dueby->setDbValue($row['dueby']);
        $this->ordertype->setDbValue($row['ordertype']);
        $this->invoiced->setDbValue($row['invoiced']);
        $this->paid->setDbValue($row['paid']);
        $this->ordervalue->setDbValue($row['ordervalue']);
        $this->jobType->setDbValue($row['jobType']);
        $this->createdOn->setDbValue($row['createdOn']);
        $this->createdBy->setDbValue($row['createdBy']);
        $this->siteId->setDbValue($row['siteId']);
        $this->pickupComplete->setDbValue($row['pickupComplete']);
        $this->pickupDatetime->setDbValue($row['pickupDatetime']);
    }

    // Render list content
    public function renderListContent($filter)
    {
        global $Response;
        $listPage = "OrdersList";
        $listClass = PROJECT_NAMESPACE . $listPage;
        $page = new $listClass();
        $page->loadRecordsetFromFilter($filter);
        $view = Container("app.view");
        $template = $listPage . ".php"; // View
        $GLOBALS["Title"] ??= $page->Title; // Title
        try {
            $Response = $view->render($Response, $template, $GLOBALS);
        } finally {
            $page->terminate(); // Terminate page and clean up
        }
    }

    // Render list row values
    public function renderListRow()
    {
        global $Security, $CurrentLanguage, $Language;

        // Call Row Rendering event
        $this->rowRendering();

        // Common render codes

        // orderid

        // customerid

        // bookingdatetime

        // dueby

        // ordertype

        // invoiced

        // paid

        // ordervalue

        // jobType

        // createdOn

        // createdBy

        // siteId

        // pickupComplete

        // pickupDatetime

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // Call Row Rendered event
        $this->rowRendered();

        // Save data for Custom Template
        $this->Rows[] = $this->customTemplateFieldValues();
    }

    // Render edit row values
    public function renderEditRow()
    {
        global $Security, $CurrentLanguage, $Language;

        // Call Row Rendering event
        $this->rowRendering();

        // orderid
        $this->orderid->setupEditAttributes();
        $this->orderid->EditValue = $this->orderid->CurrentValue;

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

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

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

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

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

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

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

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

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

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

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

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

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

        // Call Row Rendered event
        $this->rowRendered();
    }

    // Aggregate list row values
    public function aggregateListRowValues()
    {
    }

    // Aggregate list row (for rendering)
    public function aggregateListRow()
    {
        // Call Row Rendered event
        $this->rowRendered();
    }

    // Export data in HTML/CSV/Word/Excel/Email/PDF format
    public function exportDocument($doc, $result, $startRec = 1, $stopRec = 1, $exportPageType = "")
    {
        if (!$result || !$doc) {
            return;
        }
        if (!$doc->ExportCustom) {
            // Write header
            $doc->exportTableHeader();
            if ($doc->Horizontal) { // Horizontal format, write header
                $doc->beginExportRow();
                if ($exportPageType == "view") {
                    $doc->exportCaption($this->orderid);
                    $doc->exportCaption($this->customerid);
                    $doc->exportCaption($this->bookingdatetime);
                    $doc->exportCaption($this->dueby);
                    $doc->exportCaption($this->ordertype);
                    $doc->exportCaption($this->invoiced);
                    $doc->exportCaption($this->paid);
                    $doc->exportCaption($this->ordervalue);
                    $doc->exportCaption($this->jobType);
                    $doc->exportCaption($this->createdOn);
                    $doc->exportCaption($this->createdBy);
                    $doc->exportCaption($this->siteId);
                    $doc->exportCaption($this->pickupComplete);
                    $doc->exportCaption($this->pickupDatetime);
                } else {
                    $doc->exportCaption($this->orderid);
                    $doc->exportCaption($this->customerid);
                    $doc->exportCaption($this->bookingdatetime);
                    $doc->exportCaption($this->dueby);
                    $doc->exportCaption($this->ordertype);
                    $doc->exportCaption($this->invoiced);
                    $doc->exportCaption($this->paid);
                    $doc->exportCaption($this->ordervalue);
                    $doc->exportCaption($this->jobType);
                    $doc->exportCaption($this->createdOn);
                    $doc->exportCaption($this->createdBy);
                    $doc->exportCaption($this->siteId);
                    $doc->exportCaption($this->pickupComplete);
                    $doc->exportCaption($this->pickupDatetime);
                }
                $doc->endExportRow();
            }
        }
        $recCnt = $startRec - 1;
        $stopRec = $stopRec > 0 ? $stopRec : PHP_INT_MAX;
        while (($row = $result->fetch()) && $recCnt < $stopRec) {
            $recCnt++;
            if ($recCnt >= $startRec) {
                $rowCnt = $recCnt - $startRec + 1;

                // Page break
                if ($this->ExportPageBreakCount > 0) {
                    if ($rowCnt > 1 && ($rowCnt - 1) % $this->ExportPageBreakCount == 0) {
                        $doc->exportPageBreak();
                    }
                }
                $this->loadListRowValues($row);

                // Render row
                $this->RowType = RowType::VIEW; // Render view
                $this->resetAttributes();
                $this->renderListRow();
                if (!$doc->ExportCustom) {
                    $doc->beginExportRow($rowCnt); // Allow CSS styles if enabled
                    if ($exportPageType == "view") {
                        $doc->exportField($this->orderid);
                        $doc->exportField($this->customerid);
                        $doc->exportField($this->bookingdatetime);
                        $doc->exportField($this->dueby);
                        $doc->exportField($this->ordertype);
                        $doc->exportField($this->invoiced);
                        $doc->exportField($this->paid);
                        $doc->exportField($this->ordervalue);
                        $doc->exportField($this->jobType);
                        $doc->exportField($this->createdOn);
                        $doc->exportField($this->createdBy);
                        $doc->exportField($this->siteId);
                        $doc->exportField($this->pickupComplete);
                        $doc->exportField($this->pickupDatetime);
                    } else {
                        $doc->exportField($this->orderid);
                        $doc->exportField($this->customerid);
                        $doc->exportField($this->bookingdatetime);
                        $doc->exportField($this->dueby);
                        $doc->exportField($this->ordertype);
                        $doc->exportField($this->invoiced);
                        $doc->exportField($this->paid);
                        $doc->exportField($this->ordervalue);
                        $doc->exportField($this->jobType);
                        $doc->exportField($this->createdOn);
                        $doc->exportField($this->createdBy);
                        $doc->exportField($this->siteId);
                        $doc->exportField($this->pickupComplete);
                        $doc->exportField($this->pickupDatetime);
                    }
                    $doc->endExportRow($rowCnt);
                }
            }

            // Call Row Export server event
            if ($doc->ExportCustom) {
                $this->rowExport($doc, $row);
            }
        }
        if (!$doc->ExportCustom) {
            $doc->exportTableFooter();
        }
    }

    // Get file data
    public function getFileData($fldparm, $key, $resize, $width = 0, $height = 0, $plugins = [])
    {
        global $DownloadFileName;

        // No binary fields
        return false;
    }

    // Table level events

    // Table Load event
    public function tableLoad()
    {
        // Enter your code here
    }

    // Recordset Selecting event
    public function recordsetSelecting(&$filter)
    {
        // Enter your code here
    }

    // Recordset Selected event
    public function recordsetSelected($rs)
    {
        //Log("Recordset Selected");
    }

    // Recordset Search Validated event
    public function recordsetSearchValidated()
    {
        // Example:
        //$this->MyField1->AdvancedSearch->SearchValue = "your search criteria"; // Search value
    }

    // Recordset Searching event
    public function recordsetSearching(&$filter)
    {
        // Enter your code here
    }

    // Row_Selecting event
    public function rowSelecting(&$filter)
    {
        // Enter your code here
    }

    // Row Selected event
    public function rowSelected(&$rs)
    {
        //Log("Row Selected");
    }

    // Row Inserting event
    public function rowInserting($rsold, &$rsnew)
    {
        // Enter your code here
        // To cancel, set return value to false
        return true;
    }

    // Row Inserted event
    public function rowInserted($rsold, $rsnew)
    {
        //Log("Row Inserted");
    }

    // Row Updating event
    public function rowUpdating($rsold, &$rsnew)
    {
        // Enter your code here
        // To cancel, set return value to false
        return true;
    }

    // Row Updated event
    public function rowUpdated($rsold, $rsnew)
    {
        //Log("Row Updated");
    }

    // Row Update Conflict event
    public function rowUpdateConflict($rsold, &$rsnew)
    {
        // Enter your code here
        // To ignore conflict, set return value to false
        return true;
    }

    // Grid Inserting event
    public function gridInserting()
    {
        // Enter your code here
        // To reject grid insert, set return value to false
        return true;
    }

    // Grid Inserted event
    public function gridInserted($rsnew)
    {
        //Log("Grid Inserted");
    }

    // Grid Updating event
    public function gridUpdating($rsold)
    {
        // Enter your code here
        // To reject grid update, set return value to false
        return true;
    }

    // Grid Updated event
    public function gridUpdated($rsold, $rsnew)
    {
        //Log("Grid Updated");
    }

    // Row Deleting event
    public function rowDeleting(&$rs)
    {
        // Enter your code here
        // To cancel, set return value to False
        return true;
    }

    // Row Deleted event
    public function rowDeleted($rs)
    {
        //Log("Row Deleted");
    }

    // Email Sending event
    public function emailSending($email, $args)
    {
        //var_dump($email, $args); exit();
        return true;
    }

    // Lookup Selecting event
    public function lookupSelecting($fld, &$filter)
    {
        //var_dump($fld->Name, $fld->Lookup, $filter); // Uncomment to view the filter
        // Enter your code here
    }

    // Row Rendering event
    public function rowRendering()
    {
        // Enter your code here
    }

    // Row Rendered event
    public function rowRendered()
    {
        // To view properties of field class, use:
        //var_dump($this-><FieldName>);
    }

    // User ID Filtering event
    public function userIdFiltering(&$filter)
    {
        // Enter your code here
    }
}
