<?php

namespace ProjectManagement\prjProjectManagement;

use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Container\ContainerInterface;
use Slim\Routing\RouteCollectorProxy;
use Slim\App;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Closure;

/**
 * Table class for projecttemplateresult
 */
class Projecttemplateresult 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 $ResultID;
    public $Activities;
    public $Category;
    public $Weight;
    public $Description;
    public $File;
    public $templateid;
    public $Created_Date;
    public $Created_By;
    public $Last_Updated_Date;
    public $Last_Updated_By;

    // 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 = "projecttemplateresult";
        $this->TableName = 'projecttemplateresult';
        $this->TableType = "TABLE";
        $this->ImportUseTransaction = $this->supportsTransaction() && Config("IMPORT_USE_TRANSACTION");
        $this->UseTransaction = $this->supportsTransaction() && Config("USE_TRANSACTION");

        // Update Table
        $this->UpdateTable = "projecttemplateresult";
        $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 = \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_DEFAULT; // Page orientation (PhpSpreadsheet only)
        $this->ExportExcelPageSize = \PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4; // Page size (PhpSpreadsheet only)

        // PHPWord
        $this->ExportWordPageOrientation = "portrait"; // Page orientation (PHPWord only)
        $this->ExportWordPageSize = "A4"; // 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 = true; // 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->UseColumnVisibility = true;
        $this->UserIDAllowSecurity = Config("DEFAULT_USER_ID_ALLOW_SECURITY"); // Default User ID allowed permissions
        $this->BasicSearch = new BasicSearch($this);

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

        // Activities
        $this->Activities = new DbField(
            $this, // Table
            'x_Activities', // Variable name
            'Activities', // Name
            '`Activities`', // Expression
            '`Activities`', // Basic search expression
            200, // Type
            500, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`Activities`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->Activities->InputTextType = "text";
        $this->Activities->UseFilter = true; // Table header filter
        global $CurrentLanguage;
        switch ($CurrentLanguage) {
            case "en-US":
                $this->Activities->Lookup = new Lookup($this->Activities, 'projecttemplateresult', true, 'Activities', ["Activities","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
            default:
                $this->Activities->Lookup = new Lookup($this->Activities, 'projecttemplateresult', true, 'Activities', ["Activities","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
        }
        $this->Activities->SearchOperators = ["=", "<>", "IN", "NOT IN", "STARTS WITH", "NOT STARTS WITH", "LIKE", "NOT LIKE", "ENDS WITH", "NOT ENDS WITH", "IS EMPTY", "IS NOT EMPTY", "IS NULL", "IS NOT NULL"];
        $this->Fields['Activities'] = &$this->Activities;

        // Category
        $this->Category = new DbField(
            $this, // Table
            'x_Category', // Variable name
            'Category', // Name
            '`Category`', // Expression
            '`Category`', // Basic search expression
            200, // Type
            255, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`Category`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'SELECT' // Edit Tag
        );
        $this->Category->addMethod("getSelectFilter", fn() => "`Active`=1");
        $this->Category->InputTextType = "text";
        $this->Category->setSelectMultiple(false); // Select one
        $this->Category->UsePleaseSelect = true; // Use PleaseSelect by default
        $this->Category->PleaseSelectText = $Language->phrase("PleaseSelect"); // "PleaseSelect" text
        $this->Category->UseFilter = true; // Table header filter
        global $CurrentLanguage;
        switch ($CurrentLanguage) {
            case "en-US":
                $this->Category->Lookup = new Lookup($this->Category, 'masterprojectcategory', true, 'CategoryName', ["CategoryName","","",""], '', '', [], [], [], [], [], [], false, '', '', "`CategoryName`");
                break;
            default:
                $this->Category->Lookup = new Lookup($this->Category, 'masterprojectcategory', true, 'CategoryName', ["CategoryName","","",""], '', '', [], [], [], [], [], [], false, '', '', "`CategoryName`");
                break;
        }
        $this->Category->SearchOperators = ["=", "<>", "IS NULL", "IS NOT NULL"];
        $this->Fields['Category'] = &$this->Category;

        // Weight
        $this->Weight = new DbField(
            $this, // Table
            'x_Weight', // Variable name
            'Weight', // Name
            '`Weight`', // Expression
            '`Weight`', // Basic search expression
            3, // Type
            11, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`Weight`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXT' // Edit Tag
        );
        $this->Weight->InputTextType = "text";
        $this->Weight->Raw = true;
        $this->Weight->UseFilter = true; // Table header filter
        global $CurrentLanguage;
        switch ($CurrentLanguage) {
            case "en-US":
                $this->Weight->Lookup = new Lookup($this->Weight, 'projecttemplateresult', true, 'Weight', ["Weight","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
            default:
                $this->Weight->Lookup = new Lookup($this->Weight, 'projecttemplateresult', true, 'Weight', ["Weight","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
        }
        $this->Weight->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->Weight->SearchOperators = ["=", "<>", "IN", "NOT IN", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN", "IS NULL", "IS NOT NULL"];
        $this->Fields['Weight'] = &$this->Weight;

        // Description
        $this->Description = new DbField(
            $this, // Table
            'x_Description', // Variable name
            'Description', // Name
            '`Description`', // Expression
            '`Description`', // Basic search expression
            200, // Type
            4000, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`Description`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'TEXTAREA' // Edit Tag
        );
        $this->Description->InputTextType = "text";
        $this->Description->UseFilter = true; // Table header filter
        global $CurrentLanguage;
        switch ($CurrentLanguage) {
            case "en-US":
                $this->Description->Lookup = new Lookup($this->Description, 'projecttemplateresult', true, 'Description', ["Description","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
            default:
                $this->Description->Lookup = new Lookup($this->Description, 'projecttemplateresult', true, 'Description', ["Description","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
        }
        $this->Description->SearchOperators = ["=", "<>", "IN", "NOT IN", "STARTS WITH", "NOT STARTS WITH", "LIKE", "NOT LIKE", "ENDS WITH", "NOT ENDS WITH", "IS EMPTY", "IS NOT EMPTY", "IS NULL", "IS NOT NULL"];
        $this->Fields['Description'] = &$this->Description;

        // File
        $this->File = new DbField(
            $this, // Table
            'x_File', // Variable name
            'File', // Name
            '`File`', // Expression
            '`File`', // Basic search expression
            200, // Type
            500, // Size
            -1, // Date/Time format
            true, // Is upload field
            '`File`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'FILE' // Edit Tag
        );
        $this->File->addMethod("getUploadPath", fn() => "files/templates/".$this->templateid->DbValue . "/results");
        $this->File->InputTextType = "text";
        $this->File->SearchOperators = ["=", "<>", "STARTS WITH", "NOT STARTS WITH", "LIKE", "NOT LIKE", "ENDS WITH", "NOT ENDS WITH", "IS EMPTY", "IS NOT EMPTY", "IS NULL", "IS NOT NULL"];
        $this->Fields['File'] = &$this->File;

        // templateid
        $this->templateid = new DbField(
            $this, // Table
            'x_templateid', // Variable name
            'templateid', // Name
            '`templateid`', // Expression
            '`templateid`', // Basic search expression
            3, // Type
            11, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`templateid`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'SELECT' // Edit Tag
        );
        $this->templateid->addMethod("getSelectFilter", fn() => "`Active`=1");
        $this->templateid->InputTextType = "text";
        $this->templateid->Raw = true;
        $this->templateid->IsForeignKey = true; // Foreign key field
        $this->templateid->Required = true; // Required field
        $this->templateid->setSelectMultiple(false); // Select one
        $this->templateid->UsePleaseSelect = true; // Use PleaseSelect by default
        $this->templateid->PleaseSelectText = $Language->phrase("PleaseSelect"); // "PleaseSelect" text
        global $CurrentLanguage;
        switch ($CurrentLanguage) {
            case "en-US":
                $this->templateid->Lookup = new Lookup($this->templateid, 'projecttemplate', false, 'ID', ["template_name","","",""], '', '', [], [], [], [], [], [], false, '', '', "`template_name`");
                break;
            default:
                $this->templateid->Lookup = new Lookup($this->templateid, 'projecttemplate', false, 'ID', ["template_name","","",""], '', '', [], [], [], [], [], [], false, '', '', "`template_name`");
                break;
        }
        $this->templateid->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->templateid->SearchOperators = ["=", "<>", "<", "<=", ">", ">=", "BETWEEN", "NOT BETWEEN", "IS NULL", "IS NOT NULL"];
        $this->Fields['templateid'] = &$this->templateid;

        // Created_Date
        $this->Created_Date = new DbField(
            $this, // Table
            'x_Created_Date', // Variable name
            'Created_Date', // Name
            '`Created_Date`', // Expression
            CastDateFieldForLike("`Created_Date`", 109, "DB"), // Basic search expression
            135, // Type
            19, // Size
            109, // Date/Time format
            false, // Is upload field
            '`Created_Date`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'HIDDEN' // Edit Tag
        );
        $this->Created_Date->addMethod("getDefault", fn() => CurrentDateTime());
        $this->Created_Date->InputTextType = "text";
        $this->Created_Date->Raw = true;
        $this->Created_Date->UseFilter = true; // Table header filter
        global $CurrentLanguage;
        switch ($CurrentLanguage) {
            case "en-US":
                $this->Created_Date->Lookup = new Lookup($this->Created_Date, 'projecttemplateresult', true, 'Created_Date', ["Created_Date","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
            default:
                $this->Created_Date->Lookup = new Lookup($this->Created_Date, 'projecttemplateresult', true, 'Created_Date', ["Created_Date","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
        }
        $this->Created_Date->DefaultErrorMessage = str_replace("%s", DateFormat(109), $Language->phrase("IncorrectDate"));
        $this->Created_Date->SearchOperators = ["=", "<>", "IS NULL", "IS NOT NULL"];
        $this->Fields['Created_Date'] = &$this->Created_Date;

        // Created_By
        $this->Created_By = new DbField(
            $this, // Table
            'x_Created_By', // Variable name
            'Created_By', // Name
            '`Created_By`', // Expression
            '`Created_By`', // Basic search expression
            200, // Type
            255, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`Created_By`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'HIDDEN' // Edit Tag
        );
        $this->Created_By->addMethod("getDefault", fn() => CurrentUserName());
        $this->Created_By->InputTextType = "text";
        $this->Created_By->UseFilter = true; // Table header filter
        global $CurrentLanguage;
        switch ($CurrentLanguage) {
            case "en-US":
                $this->Created_By->Lookup = new Lookup($this->Created_By, 'projecttemplateresult', true, 'Created_By', ["Created_By","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
            default:
                $this->Created_By->Lookup = new Lookup($this->Created_By, 'projecttemplateresult', true, 'Created_By', ["Created_By","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
        }
        $this->Created_By->SearchOperators = ["=", "<>", "IS NULL", "IS NOT NULL"];
        $this->Fields['Created_By'] = &$this->Created_By;

        // Last_Updated_Date
        $this->Last_Updated_Date = new DbField(
            $this, // Table
            'x_Last_Updated_Date', // Variable name
            'Last_Updated_Date', // Name
            '`Last_Updated_Date`', // Expression
            CastDateFieldForLike("`Last_Updated_Date`", 109, "DB"), // Basic search expression
            135, // Type
            19, // Size
            109, // Date/Time format
            false, // Is upload field
            '`Last_Updated_Date`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'HIDDEN' // Edit Tag
        );
        $this->Last_Updated_Date->addMethod("getAutoUpdateValue", fn() => CurrentDateTime());
        $this->Last_Updated_Date->addMethod("getDefault", fn() => CurrentDateTime());
        $this->Last_Updated_Date->InputTextType = "text";
        $this->Last_Updated_Date->Raw = true;
        $this->Last_Updated_Date->UseFilter = true; // Table header filter
        global $CurrentLanguage;
        switch ($CurrentLanguage) {
            case "en-US":
                $this->Last_Updated_Date->Lookup = new Lookup($this->Last_Updated_Date, 'projecttemplateresult', true, 'Last_Updated_Date', ["Last_Updated_Date","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
            default:
                $this->Last_Updated_Date->Lookup = new Lookup($this->Last_Updated_Date, 'projecttemplateresult', true, 'Last_Updated_Date', ["Last_Updated_Date","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
        }
        $this->Last_Updated_Date->DefaultErrorMessage = str_replace("%s", DateFormat(109), $Language->phrase("IncorrectDate"));
        $this->Last_Updated_Date->SearchOperators = ["=", "<>", "IS NULL", "IS NOT NULL"];
        $this->Fields['Last_Updated_Date'] = &$this->Last_Updated_Date;

        // Last_Updated_By
        $this->Last_Updated_By = new DbField(
            $this, // Table
            'x_Last_Updated_By', // Variable name
            'Last_Updated_By', // Name
            '`Last_Updated_By`', // Expression
            '`Last_Updated_By`', // Basic search expression
            200, // Type
            255, // Size
            -1, // Date/Time format
            false, // Is upload field
            '`Last_Updated_By`', // Virtual expression
            false, // Is virtual
            false, // Force selection
            false, // Is Virtual search
            'FORMATTED TEXT', // View Tag
            'HIDDEN' // Edit Tag
        );
        $this->Last_Updated_By->addMethod("getAutoUpdateValue", fn() => CurrentUserName());
        $this->Last_Updated_By->addMethod("getDefault", fn() => CurrentUserName());
        $this->Last_Updated_By->InputTextType = "text";
        $this->Last_Updated_By->UseFilter = true; // Table header filter
        global $CurrentLanguage;
        switch ($CurrentLanguage) {
            case "en-US":
                $this->Last_Updated_By->Lookup = new Lookup($this->Last_Updated_By, 'projecttemplateresult', true, 'Last_Updated_By', ["Last_Updated_By","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
            default:
                $this->Last_Updated_By->Lookup = new Lookup($this->Last_Updated_By, 'projecttemplateresult', true, 'Last_Updated_By', ["Last_Updated_By","","",""], '', '', [], [], [], [], [], [], false, '', '', "");
                break;
        }
        $this->Last_Updated_By->SearchOperators = ["=", "<>", "IS NULL", "IS NOT NULL"];
        $this->Fields['Last_Updated_By'] = &$this->Last_Updated_By;

        // 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 master table name
    public function getCurrentMasterTable()
    {
        return Session(PROJECT_NAME . "_" . $this->TableVar . "_" . Config("TABLE_MASTER_TABLE"));
    }

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

    // Get master WHERE clause from session values
    public function getMasterFilterFromSession()
    {
        // Master filter
        $masterFilter = "";
        if ($this->getCurrentMasterTable() == "projecttemplate") {
            $masterTable = Container("projecttemplate");
            if ($this->templateid->getSessionValue() != "") {
                $masterFilter .= "" . GetKeyFilter($masterTable->ID, $this->templateid->getSessionValue(), $masterTable->ID->DataType, $masterTable->Dbid);
            } else {
                return "";
            }
        }
        return $masterFilter;
    }

    // Get detail WHERE clause from session values
    public function getDetailFilterFromSession()
    {
        // Detail filter
        $detailFilter = "";
        if ($this->getCurrentMasterTable() == "projecttemplate") {
            $masterTable = Container("projecttemplate");
            if ($this->templateid->getSessionValue() != "") {
                $detailFilter .= "" . GetKeyFilter($this->templateid, $this->templateid->getSessionValue(), $masterTable->ID->DataType, $this->Dbid);
            } else {
                return "";
            }
        }
        return $detailFilter;
    }

    /**
     * Get master filter
     *
     * @param object $masterTable Master Table
     * @param array $keys Detail Keys
     * @return mixed NULL is returned if all keys are empty, Empty string is returned if some keys are empty and is required
     */
    public function getMasterFilter($masterTable, $keys)
    {
        $validKeys = true;
        switch ($masterTable->TableVar) {
            case "projecttemplate":
                $key = $keys["templateid"] ?? "";
                if (EmptyValue($key)) {
                    if ($masterTable->ID->Required) { // Required field and empty value
                        return ""; // Return empty filter
                    }
                    $validKeys = false;
                } elseif (!$validKeys) { // Already has empty key
                    return ""; // Return empty filter
                }
                if ($validKeys) {
                    return GetKeyFilter($masterTable->ID, $keys["templateid"], $this->templateid->DataType, $this->Dbid);
                }
                break;
        }
        return null; // All null values and no required fields
    }

    // Get detail filter
    public function getDetailFilter($masterTable)
    {
        switch ($masterTable->TableVar) {
            case "projecttemplate":
                return GetKeyFilter($this->templateid, $masterTable->ID->DbValue, $masterTable->ID->DataType, $masterTable->Dbid);
        }
        return "";
    }

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

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

    // 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->ResultID->setDbValue($conn->lastInsertId());
            $rs['ResultID'] = $this->ResultID->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)
    {
        // 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['ResultID']) && !EmptyValue($this->ResultID->CurrentValue)) {
                $rs['ResultID'] = $this->ResultID->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('ResultID', $rs)) {
                AddFilter($where, QuotedName('ResultID', $this->Dbid) . '=' . QuotedValue($rs['ResultID'], $this->ResultID->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;
        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->ResultID->DbValue = $row['ResultID'];
        $this->Activities->DbValue = $row['Activities'];
        $this->Category->DbValue = $row['Category'];
        $this->Weight->DbValue = $row['Weight'];
        $this->Description->DbValue = $row['Description'];
        $this->File->Upload->DbValue = $row['File'];
        $this->templateid->DbValue = $row['templateid'];
        $this->Created_Date->DbValue = $row['Created_Date'];
        $this->Created_By->DbValue = $row['Created_By'];
        $this->Last_Updated_Date->DbValue = $row['Last_Updated_Date'];
        $this->Last_Updated_By->DbValue = $row['Last_Updated_By'];
    }

    // Delete uploaded files
    public function deleteUploadedFiles($row)
    {
        $this->loadDbValues($row);
        $this->File->OldUploadPath = $this->File->getUploadPath(); // PHP
        $oldFiles = EmptyValue($row['File']) ? [] : [$row['File']];
        foreach ($oldFiles as $oldFile) {
            if (file_exists($this->File->oldPhysicalUploadPath() . $oldFile)) {
                @unlink($this->File->oldPhysicalUploadPath() . $oldFile);
            }
        }
    }

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

    // Get Key
    public function getKey($current = false, $keySeparator = null)
    {
        $keys = [];
        $val = $current ? $this->ResultID->CurrentValue : $this->ResultID->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->ResultID->CurrentValue = $keys[0];
            } else {
                $this->ResultID->OldValue = $keys[0];
            }
        }
    }

    // Get record filter
    public function getRecordFilter($row = null, $current = false)
    {
        $keyFilter = $this->sqlKeyFilter();
        if (is_array($row)) {
            $val = array_key_exists('ResultID', $row) ? $row['ResultID'] : null;
        } else {
            $val = !EmptyValue($this->ResultID->OldValue) && !$current ? $this->ResultID->OldValue : $this->ResultID->CurrentValue;
        }
        if (!is_numeric($val)) {
            return "0=1"; // Invalid key
        }
        if ($val === null) {
            return "0=1"; // Invalid key
        } else {
            $keyFilter = str_replace("@ResultID@", 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("projecttemplateresultlist");
    }

    // 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) {
            "projecttemplateresultview" => $Language->phrase("View"),
            "projecttemplateresultedit" => $Language->phrase("Edit"),
            "projecttemplateresultadd" => $Language->phrase("Add"),
            default => ""
        };
    }

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

    // API page name
    public function getApiPageName($action)
    {
        return match (strtolower($action)) {
            Config("API_VIEW_ACTION") => "ProjecttemplateresultView",
            Config("API_ADD_ACTION") => "ProjecttemplateresultAdd",
            Config("API_EDIT_ACTION") => "ProjecttemplateresultEdit",
            Config("API_DELETE_ACTION") => "ProjecttemplateresultDelete",
            Config("API_LIST_ACTION") => "ProjecttemplateresultList",
            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 "projecttemplateresultlist";
    }

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

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

    // Edit URL
    public function getEditUrl($parm = "")
    {
        $url = $this->keyUrl("projecttemplateresultedit", $parm);
        return $this->addMasterUrl($url);
    }

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

    // Copy URL
    public function getCopyUrl($parm = "")
    {
        $url = $this->keyUrl("projecttemplateresultadd", $parm);
        return $this->addMasterUrl($url);
    }

    // Inline copy URL
    public function getInlineCopyUrl()
    {
        $url = $this->keyUrl("projecttemplateresultlist", "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("projecttemplateresultdelete", $parm);
        }
    }

    // Add master url
    public function addMasterUrl($url)
    {
        if ($this->getCurrentMasterTable() == "projecttemplate" && !ContainsString($url, Config("TABLE_SHOW_MASTER") . "=")) {
            $url .= (ContainsString($url, "?") ? "&" : "?") . Config("TABLE_SHOW_MASTER") . "=" . $this->getCurrentMasterTable();
            $url .= "&" . GetForeignKeyUrl("fk_ID", $this->templateid->getSessionValue()); // Use Session Value
        }
        return $url;
    }

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

    // Add key value to URL
    public function keyUrl($url, $parm = "")
    {
        if ($this->ResultID->CurrentValue !== null) {
            $url .= "/" . $this->encodeKeyValue($this->ResultID->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("ResultID") ?? Route("ResultID")) !== 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->ResultID->CurrentValue = $key;
            } else {
                $this->ResultID->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->ResultID->setDbValue($row['ResultID']);
        $this->Activities->setDbValue($row['Activities']);
        $this->Category->setDbValue($row['Category']);
        $this->Weight->setDbValue($row['Weight']);
        $this->Description->setDbValue($row['Description']);
        $this->File->Upload->DbValue = $row['File'];
        $this->templateid->setDbValue($row['templateid']);
        $this->Created_Date->setDbValue($row['Created_Date']);
        $this->Created_By->setDbValue($row['Created_By']);
        $this->Last_Updated_Date->setDbValue($row['Last_Updated_Date']);
        $this->Last_Updated_By->setDbValue($row['Last_Updated_By']);
    }

    // Render list content
    public function renderListContent($filter)
    {
        global $Response;
        $listPage = "ProjecttemplateresultList";
        $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

        // ResultID

        // Activities
        $this->Activities->CellCssStyle = "white-space: nowrap;";

        // Category
        $this->Category->CellCssStyle = "white-space: nowrap;";

        // Weight
        $this->Weight->CellCssStyle = "white-space: nowrap;";

        // Description

        // File
        $this->File->CellCssStyle = "white-space: nowrap;";

        // templateid
        $this->templateid->CellCssStyle = "white-space: nowrap;";

        // Created_Date
        $this->Created_Date->CellCssStyle = "white-space: nowrap;";

        // Created_By
        $this->Created_By->CellCssStyle = "white-space: nowrap;";

        // Last_Updated_Date
        $this->Last_Updated_Date->CellCssStyle = "white-space: nowrap;";

        // Last_Updated_By
        $this->Last_Updated_By->CellCssStyle = "white-space: nowrap;";

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

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

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

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

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

        // File
        $this->File->UploadPath = $this->File->getUploadPath(); // PHP
        if (!EmptyValue($this->File->Upload->DbValue)) {
            $this->File->ViewValue = $this->File->Upload->DbValue;
        } else {
            $this->File->ViewValue = "";
        }

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

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

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

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

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

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

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

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

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

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

        // File
        $this->File->UploadPath = $this->File->getUploadPath(); // PHP
        if (!EmptyValue($this->File->Upload->DbValue)) {
            $this->File->HrefValue = GetFileUploadUrl($this->File, $this->File->htmlDecode($this->File->Upload->DbValue)); // Add prefix/suffix
            $this->File->LinkAttrs["target"] = ""; // Add target
            if ($this->isExport()) {
                $this->File->HrefValue = FullUrl($this->File->HrefValue, "href");
            }
        } else {
            $this->File->HrefValue = "";
        }
        $this->File->ExportHrefValue = $this->File->UploadPath . $this->File->Upload->DbValue;
        if (!$this->isExport()) {
            $this->File->TooltipValue = $this->Activities->ViewValue != "" ? $this->Activities->ViewValue : $this->Activities->CurrentValue;
            if ($this->File->HrefValue == "") {
                $this->File->HrefValue = "javascript:void(0);";
            }
            $this->File->LinkAttrs->appendClass("ew-tooltip-link");
            $this->File->LinkAttrs["data-tooltip-id"] = "tt_projecttemplateresult_x" . (($this->RowType != RowType::MASTER) ? @$this->RowCount : "") . "_File";
            $this->File->LinkAttrs["data-tooltip-width"] = $this->File->TooltipWidth;
            $this->File->LinkAttrs["data-bs-placement"] = IsRTL() ? "left" : "right";
        }

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

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

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

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

        // Last_Updated_By
        $this->Last_Updated_By->HrefValue = "";
        $this->Last_Updated_By->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();

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

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

        // Category
        $this->Category->setupEditAttributes();
        $this->Category->PlaceHolder = RemoveHtml($this->Category->caption());

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

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

        // File
        $this->File->setupEditAttributes();
        $this->File->UploadPath = $this->File->getUploadPath(); // PHP
        if (!EmptyValue($this->File->Upload->DbValue)) {
            $this->File->EditValue = $this->File->Upload->DbValue;
        } else {
            $this->File->EditValue = "";
        }
        if (!EmptyValue($this->File->CurrentValue)) {
            $this->File->Upload->FileName = $this->File->CurrentValue;
        }

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

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

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

        // Last_Updated_Date

        // Last_Updated_By

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

    // Aggregate list row values
    public function aggregateListRowValues()
    {
            if (is_numeric($this->Weight->CurrentValue)) {
                $this->Weight->Total += $this->Weight->CurrentValue; // Accumulate total
            }
    }

    // Aggregate list row (for rendering)
    public function aggregateListRow()
    {
            $this->Weight->CurrentValue = $this->Weight->Total;
            $this->Weight->ViewValue = $this->Weight->CurrentValue;
            $this->Weight->ViewValue = FormatNumber($this->Weight->ViewValue, $this->Weight->formatPattern());
            $this->Weight->CellCssStyle .= "text-align: right;";
            $this->Weight->HrefValue = ""; // Clear href value

        // 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->ResultID);
                    $doc->exportCaption($this->Activities);
                    $doc->exportCaption($this->Category);
                    $doc->exportCaption($this->Weight);
                    $doc->exportCaption($this->Description);
                    $doc->exportCaption($this->File);
                    $doc->exportCaption($this->templateid);
                    $doc->exportCaption($this->Created_Date);
                    $doc->exportCaption($this->Created_By);
                    $doc->exportCaption($this->Last_Updated_Date);
                    $doc->exportCaption($this->Last_Updated_By);
                } else {
                    $doc->exportCaption($this->ResultID);
                    $doc->exportCaption($this->Activities);
                    $doc->exportCaption($this->Category);
                    $doc->exportCaption($this->Weight);
                    $doc->exportCaption($this->Description);
                    $doc->exportCaption($this->File);
                    $doc->exportCaption($this->templateid);
                    $doc->exportCaption($this->Created_Date);
                    $doc->exportCaption($this->Created_By);
                    $doc->exportCaption($this->Last_Updated_Date);
                    $doc->exportCaption($this->Last_Updated_By);
                }
                $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);
                $this->aggregateListRowValues(); // Aggregate row values

                // 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->ResultID);
                        $doc->exportField($this->Activities);
                        $doc->exportField($this->Category);
                        $doc->exportField($this->Weight);
                        $doc->exportField($this->Description);
                        $doc->exportField($this->File);
                        $doc->exportField($this->templateid);
                        $doc->exportField($this->Created_Date);
                        $doc->exportField($this->Created_By);
                        $doc->exportField($this->Last_Updated_Date);
                        $doc->exportField($this->Last_Updated_By);
                    } else {
                        $doc->exportField($this->ResultID);
                        $doc->exportField($this->Activities);
                        $doc->exportField($this->Category);
                        $doc->exportField($this->Weight);
                        $doc->exportField($this->Description);
                        $doc->exportField($this->File);
                        $doc->exportField($this->templateid);
                        $doc->exportField($this->Created_Date);
                        $doc->exportField($this->Created_By);
                        $doc->exportField($this->Last_Updated_Date);
                        $doc->exportField($this->Last_Updated_By);
                    }
                    $doc->endExportRow($rowCnt);
                }
            }

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

        // Export aggregates (horizontal format only)
        if ($doc->Horizontal) {
            $this->RowType = RowType::AGGREGATE;
            $this->resetAttributes();
            $this->aggregateListRow();
            if (!$doc->ExportCustom) {
                $doc->beginExportRow(-1);
                $doc->exportAggregate($this->ResultID, '');
                $doc->exportAggregate($this->Activities, '');
                $doc->exportAggregate($this->Category, '');
                $doc->exportAggregate($this->Weight, 'TOTAL');
                $doc->exportAggregate($this->Description, '');
                $doc->exportAggregate($this->File, '');
                $doc->exportAggregate($this->templateid, '');
                $doc->exportAggregate($this->Created_Date, '');
                $doc->exportAggregate($this->Created_By, '');
                $doc->exportAggregate($this->Last_Updated_Date, '');
                $doc->exportAggregate($this->Last_Updated_By, '');
                $doc->endExportRow();
            }
        }
        if (!$doc->ExportCustom) {
            $doc->exportTableFooter();
        }
    }

    // Get file data
    public function getFileData($fldparm, $key, $resize, $width = 0, $height = 0, $plugins = [])
    {
        global $DownloadFileName;
        $width = ($width > 0) ? $width : Config("THUMBNAIL_DEFAULT_WIDTH");
        $height = ($height > 0) ? $height : Config("THUMBNAIL_DEFAULT_HEIGHT");

        // Set up field name / file name field / file type field
        $fldName = "";
        $fileNameFld = "";
        $fileTypeFld = "";
        if ($fldparm == 'File') {
            $fldName = "File";
            $fileNameFld = "File";
        } else {
            return false; // Incorrect field
        }

        // Set up key values
        $ar = explode(Config("COMPOSITE_KEY_SEPARATOR"), $key);
        if (count($ar) == 1) {
            $this->ResultID->CurrentValue = $ar[0];
        } else {
            return false; // Incorrect key
        }

        // Set up filter (WHERE Clause)
        $filter = $this->getRecordFilter();
        $this->CurrentFilter = $filter;
        $sql = $this->getCurrentSql();
        $conn = $this->getConnection();
        $dbtype = GetConnectionType($this->Dbid);
        if ($row = $conn->fetchAssociative($sql)) {
            $val = $row[$fldName];
            if (!EmptyValue($val)) {
                $fld = $this->Fields[$fldName];

                // Binary data
                if ($fld->DataType == DataType::BLOB) {
                    if ($dbtype != "MYSQL") {
                        if (is_resource($val) && get_resource_type($val) == "stream") { // Byte array
                            $val = stream_get_contents($val);
                        }
                    }
                    if ($resize) {
                        ResizeBinary($val, $width, $height, $plugins);
                    }

                    // Write file type
                    if ($fileTypeFld != "" && !EmptyValue($row[$fileTypeFld])) {
                        AddHeader("Content-type", $row[$fileTypeFld]);
                    } else {
                        AddHeader("Content-type", ContentType($val));
                    }

                    // Write file name
                    $downloadPdf = !Config("EMBED_PDF") && Config("DOWNLOAD_PDF_FILE");
                    if ($fileNameFld != "" && !EmptyValue($row[$fileNameFld])) {
                        $fileName = $row[$fileNameFld];
                        $pathinfo = pathinfo($fileName);
                        $ext = strtolower($pathinfo["extension"] ?? "");
                        $isPdf = SameText($ext, "pdf");
                        if ($downloadPdf || !$isPdf) { // Skip header if not download PDF
                            AddHeader("Content-Disposition", "attachment; filename=\"" . $fileName . "\"");
                        }
                    } else {
                        $ext = ContentExtension($val);
                        $isPdf = SameText($ext, ".pdf");
                        if ($isPdf && $downloadPdf) { // Add header if download PDF
                            AddHeader("Content-Disposition", "attachment" . ($DownloadFileName ? "; filename=\"" . $DownloadFileName . "\"" : ""));
                        }
                    }

                    // Write file data
                    if (
                        StartsString("PK", $val) &&
                        ContainsString($val, "[Content_Types].xml") &&
                        ContainsString($val, "_rels") &&
                        ContainsString($val, "docProps")
                    ) { // Fix Office 2007 documents
                        if (!EndsString("\0\0\0", $val)) { // Not ends with 3 or 4 \0
                            $val .= "\0\0\0\0";
                        }
                    }

                    // Clear any debug message
                    if (ob_get_length()) {
                        ob_end_clean();
                    }

                    // Write binary data
                    Write($val);

                // Upload to folder
                } else {
                    if ($fld->UploadMultiple) {
                        $files = explode(Config("MULTIPLE_UPLOAD_SEPARATOR"), $val);
                    } else {
                        $files = [$val];
                    }
                    $data = [];
                    $ar = [];
                    if ($fld->hasMethod("getUploadPath")) { // Check field level upload path
                        $fld->UploadPath = $fld->getUploadPath();
                    }
                    foreach ($files as $file) {
                        if (!EmptyValue($file)) {
                            if (Config("ENCRYPT_FILE_PATH")) {
                                $ar[$file] = FullUrl(GetApiUrl(Config("API_FILE_ACTION") .
                                    "/" . $this->TableVar . "/" . Encrypt($fld->physicalUploadPath() . $file)));
                            } else {
                                $ar[$file] = FullUrl($fld->hrefPath() . $file);
                            }
                        }
                    }
                    $data[$fld->Param] = $ar;
                    WriteJson($data);
                }
            }
            return true;
        }
        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
    }
}
