<?php

namespace PHPMaker2023\Jack_Jill_school;

use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\FetchMode;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Query\QueryBuilder;

/**
 * Page class
 */
class StudentsReportsSummary extends StudentsReports
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

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

    // Rendering View
    public $RenderingView = false;

    // CSS class/style
    public $ReportContainerClass = "ew-grid";
    public $CurrentPageName = "studentsreports";

    // Page headings
    public $Heading = "";
    public $Subheading = "";
    public $PageHeader;
    public $PageFooter;

    // Page layout
    public $UseLayout = true;

    // Page terminated
    private $terminated = false;

    // Page heading
    public function pageHeading()
    {
        global $Language;
        if ($this->Heading != "") {
            return $this->Heading;
        }
        if (method_exists($this, "tableCaption")) {
            return $this->tableCaption();
        }
        return "";
    }

    // Page subheading
    public function pageSubheading()
    {
        global $Language;
        if ($this->Subheading != "") {
            return $this->Subheading;
        }
        return "";
    }

    // Page name
    public function pageName()
    {
        return CurrentPageName();
    }

    // Page URL
    public function pageUrl($withArgs = true)
    {
        $route = GetRoute();
        $args = RemoveXss($route->getArguments());
        if (!$withArgs) {
            foreach ($args as $key => &$val) {
                $val = "";
            }
            unset($val);
        }
        return rtrim(UrlFor($route->getName(), $args), "/") . "?";
    }

    // Show Page Header
    public function showPageHeader()
    {
        $header = $this->PageHeader;
        $this->pageDataRendering($header);
        if ($header != "") { // Header exists, display
            echo '<p id="ew-page-header">' . $header . '</p>';
        }
    }

    // Show Page Footer
    public function showPageFooter()
    {
        $footer = $this->PageFooter;
        $this->pageDataRendered($footer);
        if ($footer != "") { // Footer exists, display
            echo '<p id="ew-page-footer">' . $footer . '</p>';
        }
    }

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

        // CSS class name as context
        $this->ContextClass = CheckClassName($this->TableVar);
        AppendClass($this->ReportContainerClass, $this->ContextClass);

        // Fixed header table
        if (!$this->UseCustomTemplate) {
            $this->setFixedHeaderTable(Config("USE_FIXED_HEADER_TABLE"), Config("FIXED_HEADER_TABLE_HEIGHT"));
        }

        // Initialize
        $GLOBALS["Page"] = &$this;

        // Language object
        $Language = Container("language");

        // Table object (Students_Reports)
        if (!isset($GLOBALS["Students_Reports"]) || get_class($GLOBALS["Students_Reports"]) == PROJECT_NAMESPACE . "Students_Reports") {
            $GLOBALS["Students_Reports"] = &$this;
        }

        // Page URL
        $pageUrl = $this->pageUrl(false);

        // Initialize URLs

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

        // Start timer
        $DebugTimer = Container("timer");

        // Debug message
        LoadDebugMessage();

        // Open connection
        $GLOBALS["Conn"] ??= $this->getConnection();

        // User table object
        $UserTable = Container("usertable");

        // Export options
        $this->ExportOptions = new ListOptions(["TagClassName" => "ew-export-option"]);

        // Filter options
        $this->FilterOptions = new ListOptions(["TagClassName" => "ew-filter-option"]);
    }

    // Get content from stream
    public function getContents(): string
    {
        global $Response;
        return is_object($Response) ? $Response->getBody() : ob_get_clean();
    }

    // Is lookup
    public function isLookup()
    {
        return SameText(Route(0), Config("API_LOOKUP_ACTION"));
    }

    // Is AutoFill
    public function isAutoFill()
    {
        return $this->isLookup() && SameText(Post("ajax"), "autofill");
    }

    // Is AutoSuggest
    public function isAutoSuggest()
    {
        return $this->isLookup() && SameText(Post("ajax"), "autosuggest");
    }

    // Is modal lookup
    public function isModalLookup()
    {
        return $this->isLookup() && SameText(Post("ajax"), "modal");
    }

    // Is terminated
    public function isTerminated()
    {
        return $this->terminated;
    }

    /**
     * Terminate page
     *
     * @param string $url URL for direction
     * @return void
     */
    public function terminate($url = "")
    {
        if ($this->terminated) {
            return;
        }
        global $TempImages, $DashboardReport, $Response;

        // Page is terminated
        $this->terminated = true;

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

        // Global Page Unloaded event (in userfn*.php)
        Page_Unloaded();
        if (!IsApi() && method_exists($this, "pageRedirecting")) {
            $this->pageRedirecting($url);
        }

        // Close connection if not in dashboard
        if (!$DashboardReport) {
            CloseConnections();
        }

        // Return for API
        if (IsApi()) {
            $res = $url === true;
            if (!$res) { // Show response for API
                $ar = array_merge($this->getMessages(), $url ? ["url" => GetUrl($url)] : []);
                WriteJson($ar);
            }
            $this->clearMessages(); // Clear messages for API request
            return;
        } else { // Check if response is JSON
            if (StartsString("application/json", $Response->getHeaderLine("Content-type")) && $Response->getBody()->getSize()) { // With JSON response
                $this->clearMessages();
                return;
            }
        }

        // Go to URL if specified
        if ($url != "") {
            if (!Config("DEBUG") && ob_get_length()) {
                ob_end_clean();
            }
            SaveDebugMessage();
            Redirect(GetUrl($url));
        }
        return; // Return to controller
    }

    // Lookup data
    public function lookup($ar = null)
    {
        global $Language, $Security;

        // Get lookup object
        $fieldName = $ar["field"] ?? Post("field");
        $lookup = $this->Fields[$fieldName]->Lookup;
        $name = $ar["name"] ?? Post("name");
        $isQuery = ContainsString($name, "query_builder_rule");
        if ($isQuery) {
            $lookup->FilterFields = []; // Skip parent fields if any
        }
        if ($lookup->LinkTable == $this->TableVar || property_exists($this, "ReportSourceTable") && $lookup->LinkTable == $this->ReportSourceTable) {
            $lookup->RenderViewFunc = "renderLookup"; // Set up view renderer
        }
        $lookup->RenderEditFunc = ""; // Set up edit renderer

        // Get lookup parameters
        $lookupType = $ar["ajax"] ?? Post("ajax", "unknown");
        $pageSize = -1;
        $offset = -1;
        $searchValue = "";
        if (SameText($lookupType, "modal") || SameText($lookupType, "filter")) {
            $searchValue = $ar["q"] ?? Param("q") ?? $ar["sv"] ?? Post("sv", "");
            $pageSize = $ar["n"] ?? Param("n") ?? $ar["recperpage"] ?? Post("recperpage", 10);
        } elseif (SameText($lookupType, "autosuggest")) {
            $searchValue = $ar["q"] ?? Param("q", "");
            $pageSize = $ar["n"] ?? Param("n", -1);
            $pageSize = is_numeric($pageSize) ? (int)$pageSize : -1;
            if ($pageSize <= 0) {
                $pageSize = Config("AUTO_SUGGEST_MAX_ENTRIES");
            }
        }
        $start = $ar["start"] ?? Param("start", -1);
        $start = is_numeric($start) ? (int)$start : -1;
        $page = $ar["page"] ?? Param("page", -1);
        $page = is_numeric($page) ? (int)$page : -1;
        $offset = $start >= 0 ? $start : ($page > 0 && $pageSize > 0 ? ($page - 1) * $pageSize : 0);
        $userSelect = Decrypt($ar["s"] ?? Post("s", ""));
        $userFilter = Decrypt($ar["f"] ?? Post("f", ""));
        $userOrderBy = Decrypt($ar["o"] ?? Post("o", ""));
        $keys = $ar["keys"] ?? Post("keys");
        $lookup->LookupType = $lookupType; // Lookup type
        $lookup->FilterValues = []; // Clear filter values first
        if ($keys !== null) { // Selected records from modal
            if (is_array($keys)) {
                $keys = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $keys);
            }
            $lookup->FilterFields = []; // Skip parent fields if any
            $lookup->FilterValues[] = $keys; // Lookup values
            $pageSize = -1; // Show all records
        } else { // Lookup values
            $lookup->FilterValues[] = $ar["v0"] ?? $ar["lookupValue"] ?? Post("v0", Post("lookupValue", ""));
        }
        $cnt = is_array($lookup->FilterFields) ? count($lookup->FilterFields) : 0;
        for ($i = 1; $i <= $cnt; $i++) {
            $lookup->FilterValues[] = $ar["v" . $i] ?? Post("v" . $i, "");
        }
        $lookup->SearchValue = $searchValue;
        $lookup->PageSize = $pageSize;
        $lookup->Offset = $offset;
        if ($userSelect != "") {
            $lookup->UserSelect = $userSelect;
        }
        if ($userFilter != "") {
            $lookup->UserFilter = $userFilter;
        }
        if ($userOrderBy != "") {
            $lookup->UserOrderBy = $userOrderBy;
        }
        return $lookup->toJson($this, !is_array($ar)); // Use settings from current page
    }

    // Options
    public $HideOptions = false;
    public $ExportOptions; // Export options
    public $SearchOptions; // Search options
    public $FilterOptions; // Filter options

    // Records
    public $GroupRecords = [];
    public $DetailRecords = [];
    public $DetailRecordCount = 0;

    // Paging variables
    public $RecordIndex = 0; // Record index
    public $RecordCount = 0; // Record count (start from 1 for each group)
    public $StartGroup = 0; // Start group
    public $StopGroup = 0; // Stop group
    public $TotalGroups = 0; // Total groups
    public $GroupCount = 0; // Group count
    public $GroupCounter = []; // Group counter
    public $DisplayGroups = 1; // Groups per page
    public $GroupRange = 10;
    public $PageSizes = ""; // Page sizes (comma separated)
    public $PageFirstGroupFilter = "";
    public $UserIDFilter = "";
    public $DefaultSearchWhere = ""; // Default search WHERE clause
    public $SearchWhere = "";
    public $SearchPanelClass = "ew-search-panel collapse"; // Search Panel class
    public $SearchColumnCount = 0; // For extended search
    public $SearchFieldsPerRow = 1; // For extended search
    public $DrillDownList = "";
    public $DbMasterFilter = ""; // Master filter
    public $DbDetailFilter = ""; // Detail filter
    public $SearchCommand = false;
    public $ShowHeader = true;
    public $GroupColumnCount = 0;
    public $SubGroupColumnCount = 0;
    public $DetailColumnCount = 0;
    public $TotalCount;
    public $PageTotalCount;
    public $TopContentClass = "ew-top";
    public $MiddleContentClass = "ew-middle";
    public $BottomContentClass = "ew-bottom";

    /**
     * Page run
     *
     * @return void
     */
    public function run()
    {
        global $ExportType, $Language, $Security, $UserProfile,
            $Security, $DrillDownInPanel, $Breadcrumb,
            $DashboardReport;

        // Set up dashboard report
        $DashboardReport = $DashboardReport || ConvertToBool(Param(Config("PAGE_DASHBOARD"), false));
        if ($DashboardReport) {
            $this->UseAjaxActions = true;
        }

// Use layout
        $this->UseLayout = $this->UseLayout && ConvertToBool(Param(Config("PAGE_LAYOUT"), true));

        // View
        $this->View = Get(Config("VIEW"));

        // Get export parameters
        $custom = "";
        if (Param("export") !== null) {
            $this->Export = Param("export");
            $custom = Param("custom", "");
        }
        $ExportType = $this->Export; // Get export parameter, used in header
        if ($ExportType != "") {
            global $SkipHeaderFooter;
            $SkipHeaderFooter = true;
        }
        $this->CurrentAction = Param("action"); // Set up current action

        // Setup export options
        $this->setupExportOptions();

        // Global Page Loading event (in userfn*.php)
        Page_Loading();

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

        // Setup other options
        $this->setupOtherOptions();

        // Set up table class
        if ($this->isExport("word") || $this->isExport("excel") || $this->isExport("pdf")) {
            $this->TableClass = "ew-table table-bordered table-sm";
        } else {
            PrependClass($this->TableClass, "table ew-table table-bordered table-sm");
        }

        // Set up report container class
        if (!$this->isExport("word") && !$this->isExport("excel")) {
            $this->ReportContainerClass .= " card ew-card";
        }
		My_Global_Check(); // Modified by Unique Digital Solutions Ltd, October 6, 2021

        // Set field visibility for detail fields
        $this->PIN->setVisibility();
        $this->Last_Name->setVisibility();
        $this->First_Name->setVisibility();
        $this->Gender->setVisibility();
        $this->Date_Of_Birth->setVisibility();
        $this->Place_Of_Birth->setVisibility();
        $this->Card_No->setVisibility();
        $this->Unique_QR->setVisibility();
        $this->Photo->setVisibility();
        $this->Expiry_Date->setVisibility();

        // Set up Breadcrumb
        if (!$this->isExport() && !$DashboardReport) {
            $this->setupBreadcrumb();
        }

        // Load custom filters
        $this->pageFilterLoad();

        // Extended filter
        $extendedFilter = "";

        // No filter
        $this->FilterOptions["savecurrentfilter"]->Visible = false;
        $this->FilterOptions["deletefilter"]->Visible = false;

        // Call Page Selecting event
        $this->pageSelecting($this->SearchWhere);

        // Set up search panel class
        if ($this->SearchWhere != "") {
            AppendClass($this->SearchPanelClass, "show");
        }

        // Get sort
        $this->Sort = $this->getSort();

        // Search options
        $this->setupSearchOptions();

        // Update filter
        AddFilter($this->Filter, $this->SearchWhere);

        // Get total group count
        $sql = $this->buildReportSql($this->getSqlSelectGroup(), $this->getSqlFrom(), $this->getSqlWhere(), $this->getSqlGroupBy(), $this->getSqlHaving(), "", $this->Filter, "");
        $this->TotalGroups = $this->getRecordCount($sql);
        if ($this->DisplayGroups <= 0 || $this->DrillDown) { // Display all groups
            $this->DisplayGroups = $this->TotalGroups;
        }
        $this->StartGroup = 1;

        // Set up start position if not export all
        if ($this->ExportAll && $this->isExport()) {
            $this->DisplayGroups = $this->TotalGroups;
        } else {
            $this->setupStartGroup();
        }

        // Set no record found message
        if ($this->TotalGroups == 0) {
            $this->ShowHeader = false;
            if ($Security->canList()) {
                if ($this->SearchWhere == "0=101") {
                    $this->setWarningMessage($Language->phrase("EnterSearchCriteria"));
                } else {
                    $this->setWarningMessage($Language->phrase("NoRecord"));
                }
            } else {
                $this->setWarningMessage(DeniedMessage());
            }
        }

        // Hide export options if export/dashboard report/hide options
        if ($this->isExport() || $DashboardReport || $this->HideOptions) {
            $this->ExportOptions->hideAllOptions();
        }

        // Hide search/filter options if export/drilldown/dashboard report/hide options
        if ($this->isExport() || $this->DrillDown || $DashboardReport || $this->HideOptions) {
            $this->SearchOptions->hideAllOptions();
            $this->FilterOptions->hideAllOptions();
        }

        // Get group records
        if ($this->TotalGroups > 0) {
            $grpSort = UpdateSortFields($this->getSqlOrderByGroup(), $this->Sort, 2); // Get grouping field only
            $sql = $this->buildReportSql($this->getSqlSelectGroup(), $this->getSqlFrom(), $this->getSqlWhere(), $this->getSqlGroupBy(), $this->getSqlHaving(), $this->getSqlOrderByGroup(), $this->Filter, $grpSort);
            $grpRs = $sql->setFirstResult(max($this->StartGroup - 1, 0))->setMaxResults($this->DisplayGroups)->execute();
            $this->GroupRecords = $grpRs->fetchAll(); // Get records of first grouping field
            $this->loadGroupRowValues();
            $this->GroupCount = 1;
        }

        // Init detail records
        $this->DetailRecords = [];
        $this->setupFieldCount();

        // Set the last group to display if not export all
        if ($this->ExportAll && $this->isExport()) {
            $this->StopGroup = $this->TotalGroups;
        } else {
            $this->StopGroup = $this->StartGroup + $this->DisplayGroups - 1;
        }

        // Stop group <= total number of groups
        if (intval($this->StopGroup) > intval($this->TotalGroups)) {
            $this->StopGroup = $this->TotalGroups;
        }
        $this->RecordCount = 0;
        $this->RecordIndex = 0;

        // Set up pager
        $this->Pager = new PrevNextPager($this, $this->StartGroup, $this->DisplayGroups, $this->TotalGroups, $this->PageSizes, $this->GroupRange, $this->AutoHidePager, $this->AutoHidePageSizeSelector);

        // Check if no records
        if ($this->TotalGroups == 0) {
            $this->ReportContainerClass .= " ew-no-record";
        }

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

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

            // Global Page Rendering event (in userfn*.php)
            Page_Rendering();

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

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

    // Load group row values
    public function loadGroupRowValues()
    {
        $cnt = count($this->GroupRecords); // Get record count
        if ($this->GroupCount < $cnt) {
            $this->SClass->setGroupValue(reset($this->GroupRecords[$this->GroupCount]));
        } else {
            $this->SClass->setGroupValue("");
        }
    }

    // Load row values
    public function loadRowValues($record)
    {
        $data = [];
        $data["studentID"] = $record['studentID'];
        $data["PIN"] = $record['PIN'];
        $data["First_Name"] = $record['First_Name'];
        $data["Gender"] = $record['Gender'];
        $data["Date_Of_Birth"] = $record['Date_Of_Birth'];
        $data["Place_Of_Birth"] = $record['Place_Of_Birth'];
        $data["Card_No"] = $record['Card_No'];
        $data["Unique_QR"] = $record['Unique_QR'];
        $data["Photo"] = $record['Photo'];
        $data["Address"] = $record['Address'];
        $data["Start_Date"] = $record['Start_Date'];
        $data["Expiry_Date"] = $record['Expiry_Date'];
        $data["SClass"] = $record['SClass'];
        $data["Contact_Incase"] = $record['Contact_Incase'];
        $data["Contact_Tel"] = $record['Contact_Tel'];
        $data["Reference"] = $record['Reference'];
        $data["EmployeeID"] = $record['EmployeeID'];
        $data["Status"] = $record['Status'];
        $this->Rows[] = $data;
        $this->studentID->setDbValue($record['studentID']);
        $this->PIN->setDbValue($record['PIN']);
        $this->Last_Name->setDbValue($record['Last_Name']);
        $this->First_Name->setDbValue($record['First_Name']);
        $this->Gender->setDbValue($record['Gender']);
        $this->Date_Of_Birth->setDbValue($record['Date_Of_Birth']);
        $this->Place_Of_Birth->setDbValue($record['Place_Of_Birth']);
        $this->Card_No->setDbValue($record['Card_No']);
        $this->Unique_QR->setDbValue($record['Unique_QR']);
        $this->Photo->Upload->DbValue = $record['Photo'];
        $this->Address->setDbValue($record['Address']);
        $this->Start_Date->setDbValue($record['Start_Date']);
        $this->Expiry_Date->setDbValue($record['Expiry_Date']);
        $this->SClass->setDbValue(GroupValue($this->SClass, $record['SClass']));
        $this->Contact_Incase->setDbValue($record['Contact_Incase']);
        $this->Contact_Tel->setDbValue($record['Contact_Tel']);
        $this->Reference->setDbValue($record['Reference']);
        $this->EmployeeID->setDbValue($record['EmployeeID']);
        $this->Status->setDbValue($record['Status']);
    }

    // Render row
    public function renderRow()
    {
        global $Security, $Language, $Language;
        $conn = $this->getConnection();
        if ($this->RowType == ROWTYPE_TOTAL && $this->RowTotalSubType == ROWTOTAL_FOOTER && $this->RowTotalType == ROWTOTAL_PAGE) {
            // Build detail SQL
            $firstGrpFld = &$this->SClass;
            $firstGrpFld->getDistinctValues($this->GroupRecords);
            $where = DetailFilterSql($firstGrpFld, $this->getSqlFirstGroupField(), $firstGrpFld->DistinctValues, $this->Dbid);
            if ($this->Filter != "") {
                $where = "($this->Filter) AND ($where)";
            }
            $sql = $this->buildReportSql($this->getSqlSelect(), $this->getSqlFrom(), $this->getSqlWhere(), $this->getSqlGroupBy(), $this->getSqlHaving(), $this->getSqlOrderBy(), $where, $this->Sort);
            $rs = $sql->execute();
            $records = $rs ? $rs->fetchAll() : [];
            $this->PageTotalCount = count($records);
        } elseif ($this->RowType == ROWTYPE_TOTAL && $this->RowTotalSubType == ROWTOTAL_FOOTER && $this->RowTotalType == ROWTOTAL_GRAND) { // Get Grand total
            $hasCount = false;
            $hasSummary = false;

            // Get total count from SQL directly
            $sql = $this->buildReportSql($this->getSqlSelectCount(), $this->getSqlFrom(), $this->getSqlWhere(), $this->getSqlGroupBy(), $this->getSqlHaving(), "", $this->Filter, "");
            $rstot = $conn->executeQuery($sql);
            if ($rstot && $cnt = $rstot->fetchOne()) {
                $hasCount = true;
            } else {
                $cnt = 0;
            }
            $this->TotalCount = $cnt;
            $hasSummary = true;

            // Accumulate grand summary from detail records
            if (!$hasCount || !$hasSummary) {
                $sql = $this->buildReportSql($this->getSqlSelect(), $this->getSqlFrom(), $this->getSqlWhere(), $this->getSqlGroupBy(), $this->getSqlHaving(), "", $this->Filter, "");
                $rs = $sql->execute();
                $this->DetailRecords = $rs ? $rs->fetchAll() : [];
            }
        }

        // Call Row_Rendering event
        $this->rowRendering();

        // SClass

        // PIN

        // Last_Name

        // First_Name

        // Gender

        // Date_Of_Birth

        // Place_Of_Birth

        // Card_No

        // Unique_QR

        // Photo

        // Expiry_Date
        if ($this->RowType == ROWTYPE_SEARCH) { // Search row
        } elseif ($this->RowType == ROWTYPE_TOTAL && !($this->RowTotalType == ROWTOTAL_GROUP && $this->RowTotalSubType == ROWTOTAL_HEADER)) { // Summary row
            $this->RowAttrs->prependClass(($this->RowTotalType == ROWTOTAL_PAGE || $this->RowTotalType == ROWTOTAL_GRAND) ? "ew-rpt-grp-aggregate" : ""); // Set up row class
            if ($this->RowTotalType == ROWTOTAL_GROUP) {
                $this->RowAttrs["data-group"] = $this->SClass->groupValue(); // Set up group attribute
            }

            // SClass
            $this->SClass->GroupViewValue = $this->SClass->groupValue();
            $this->SClass->CssClass = "fw-bold";
            $this->SClass->CellCssClass = ($this->RowGroupLevel == 1 ? "ew-rpt-grp-summary-1" : "ew-rpt-grp-field-1");
            $this->SClass->GroupViewValue = DisplayGroupValue($this->SClass, $this->SClass->GroupViewValue);

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

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

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

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

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

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

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

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

            // Unique_QR
            $this->Unique_QR->HrefValue = "";
            $this->Unique_QR->ExportHrefValue = PhpBarcode::barcode(true)->getHrefValue($this->Unique_QR->CurrentValue, 'QRCODE', 60);

            // Photo
            $this->Photo->UploadPath = $this->Photo->getUploadPath(); // PHP
            if (!EmptyValue($this->Photo->Upload->DbValue)) {
                $this->Photo->HrefValue = GetFileUploadUrl($this->Photo, $this->Photo->htmlDecode($this->Photo->Upload->DbValue)); // Add prefix/suffix
                $this->Photo->LinkAttrs["target"] = ""; // Add target
                if ($this->isExport()) {
                    $this->Photo->HrefValue = FullUrl($this->Photo->HrefValue, "href");
                }
            } else {
                $this->Photo->HrefValue = "";
            }
            $this->Photo->ExportHrefValue = $this->Photo->UploadPath . $this->Photo->Upload->DbValue;

            // Expiry_Date
            $this->Expiry_Date->HrefValue = "";
        } else {
            if ($this->RowTotalType == ROWTOTAL_GROUP && $this->RowTotalSubType == ROWTOTAL_HEADER) {
                $this->RowAttrs["data-group"] = $this->SClass->groupValue(); // Set up group attribute
            } else {
                $this->RowAttrs["data-group"] = $this->SClass->groupValue(); // Set up group attribute
            }

            // SClass
            $this->SClass->GroupViewValue = $this->SClass->groupValue();
            $this->SClass->CssClass = "fw-bold";
            $this->SClass->CellCssClass = "ew-rpt-grp-field-1";
            $this->SClass->GroupViewValue = DisplayGroupValue($this->SClass, $this->SClass->GroupViewValue);
            if (!$this->SClass->LevelBreak) {
                $this->SClass->GroupViewValue = "";
            } else {
                $this->SClass->LevelBreak = false;
            }

            // PIN
            $this->PIN->ViewValue = $this->PIN->CurrentValue;
            $arwrk = [];
            $arwrk["lf"] = $this->PIN->CurrentValue;
            $arwrk["df"] = $this->PIN->CurrentValue;
            $arwrk = $this->PIN->Lookup->renderViewRow($arwrk, $this);
            $dispVal = $this->PIN->displayValue($arwrk);
            if ($dispVal != "") {
                $this->PIN->ViewValue = $dispVal;
            }
            $this->PIN->CellCssClass = ($this->RecordCount % 2 != 1 ? "ew-table-alt-row" : "");

            // Last_Name
            $this->Last_Name->ViewValue = $this->Last_Name->CurrentValue;
            $arwrk = [];
            $arwrk["lf"] = $this->Last_Name->CurrentValue;
            $arwrk["df"] = $this->Last_Name->CurrentValue;
            $arwrk = $this->Last_Name->Lookup->renderViewRow($arwrk, $this);
            $dispVal = $this->Last_Name->displayValue($arwrk);
            if ($dispVal != "") {
                $this->Last_Name->ViewValue = $dispVal;
            }
            $this->Last_Name->CellCssClass = ($this->RecordCount % 2 != 1 ? "ew-table-alt-row" : "");

            // First_Name
            $this->First_Name->ViewValue = $this->First_Name->CurrentValue;
            $this->First_Name->CellCssClass = ($this->RecordCount % 2 != 1 ? "ew-table-alt-row" : "");

            // Gender
            if (strval($this->Gender->CurrentValue) != "") {
                $this->Gender->ViewValue = $this->Gender->optionCaption($this->Gender->CurrentValue);
            } else {
                $this->Gender->ViewValue = null;
            }
            $this->Gender->CellCssClass = ($this->RecordCount % 2 != 1 ? "ew-table-alt-row" : "");

            // Date_Of_Birth
            $this->Date_Of_Birth->ViewValue = $this->Date_Of_Birth->CurrentValue;
            $this->Date_Of_Birth->ViewValue = FormatDateTime($this->Date_Of_Birth->ViewValue, $this->Date_Of_Birth->formatPattern());
            $this->Date_Of_Birth->CellCssClass = ($this->RecordCount % 2 != 1 ? "ew-table-alt-row" : "");

            // Place_Of_Birth
            $this->Place_Of_Birth->ViewValue = $this->Place_Of_Birth->CurrentValue;
            $this->Place_Of_Birth->CellCssClass = ($this->RecordCount % 2 != 1 ? "ew-table-alt-row" : "");

            // Card_No
            $this->Card_No->ViewValue = $this->Card_No->CurrentValue;
            $arwrk = [];
            $arwrk["lf"] = $this->Card_No->CurrentValue;
            $arwrk["df"] = $this->Card_No->CurrentValue;
            $arwrk = $this->Card_No->Lookup->renderViewRow($arwrk, $this);
            $dispVal = $this->Card_No->displayValue($arwrk);
            if ($dispVal != "") {
                $this->Card_No->ViewValue = $dispVal;
            }
            $this->Card_No->CellCssClass = ($this->RecordCount % 2 != 1 ? "ew-table-alt-row" : "");

            // Unique_QR
            $this->Unique_QR->ViewValue = $this->Unique_QR->CurrentValue;
            $this->Unique_QR->CellCssClass = ($this->RecordCount % 2 != 1 ? "ew-table-alt-row" : "");

            // Photo
            $this->Photo->UploadPath = $this->Photo->getUploadPath(); // PHP
            if (!EmptyValue($this->Photo->Upload->DbValue)) {
                $this->Photo->ImageWidth = 100;
                $this->Photo->ImageHeight = 100;
                $this->Photo->ImageAlt = $this->Photo->alt();
                $this->Photo->ImageCssClass = "ew-image";
                $this->Photo->ViewValue = $this->Photo->Upload->DbValue;
            } else {
                $this->Photo->ViewValue = "";
            }
            $this->Photo->CellCssClass = ($this->RecordCount % 2 != 1 ? "ew-table-alt-row" : "");

            // Expiry_Date
            $this->Expiry_Date->ViewValue = $this->Expiry_Date->CurrentValue;
            $this->Expiry_Date->ViewValue = FormatDateTime($this->Expiry_Date->ViewValue, $this->Expiry_Date->formatPattern());
            $this->Expiry_Date->CellCssClass = ($this->RecordCount % 2 != 1 ? "ew-table-alt-row" : "");

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

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

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

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

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

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

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

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

            // Unique_QR
            $this->Unique_QR->HrefValue = "";
            $this->Unique_QR->ExportHrefValue = PhpBarcode::barcode(true)->getHrefValue($this->Unique_QR->CurrentValue, 'QRCODE', 60);
            $this->Unique_QR->TooltipValue = "";

            // Photo
            $this->Photo->UploadPath = $this->Photo->getUploadPath(); // PHP
            if (!EmptyValue($this->Photo->Upload->DbValue)) {
                $this->Photo->HrefValue = GetFileUploadUrl($this->Photo, $this->Photo->htmlDecode($this->Photo->Upload->DbValue)); // Add prefix/suffix
                $this->Photo->LinkAttrs["target"] = ""; // Add target
                if ($this->isExport()) {
                    $this->Photo->HrefValue = FullUrl($this->Photo->HrefValue, "href");
                }
            } else {
                $this->Photo->HrefValue = "";
            }
            $this->Photo->ExportHrefValue = $this->Photo->UploadPath . $this->Photo->Upload->DbValue;
            $this->Photo->TooltipValue = "";
            if ($this->Photo->UseColorbox) {
                if (EmptyValue($this->Photo->TooltipValue)) {
                    $this->Photo->LinkAttrs["title"] = $Language->phrase("ViewImageGallery");
                }
                $this->Photo->LinkAttrs["data-rel"] = "Students_Reports_x_Photo";
                $this->Photo->LinkAttrs->appendClass("ew-lightbox");
            }

            // Expiry_Date
            $this->Expiry_Date->HrefValue = "";
            $this->Expiry_Date->TooltipValue = "";
        }

        // Call Cell_Rendered event
        if ($this->RowType == ROWTYPE_TOTAL) {
            // SClass
            $currentValue = $this->SClass->GroupViewValue;
            $viewValue = &$this->SClass->GroupViewValue;
            $viewAttrs = &$this->SClass->ViewAttrs;
            $cellAttrs = &$this->SClass->CellAttrs;
            $hrefValue = &$this->SClass->HrefValue;
            $linkAttrs = &$this->SClass->LinkAttrs;
            $this->cellRendered($this->SClass, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);
        } else {
            // SClass
            $currentValue = $this->SClass->groupValue();
            $viewValue = &$this->SClass->GroupViewValue;
            $viewAttrs = &$this->SClass->ViewAttrs;
            $cellAttrs = &$this->SClass->CellAttrs;
            $hrefValue = &$this->SClass->HrefValue;
            $linkAttrs = &$this->SClass->LinkAttrs;
            $this->cellRendered($this->SClass, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);

            // PIN
            $currentValue = $this->PIN->CurrentValue;
            $viewValue = &$this->PIN->ViewValue;
            $viewAttrs = &$this->PIN->ViewAttrs;
            $cellAttrs = &$this->PIN->CellAttrs;
            $hrefValue = &$this->PIN->HrefValue;
            $linkAttrs = &$this->PIN->LinkAttrs;
            $this->cellRendered($this->PIN, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);

            // Last_Name
            $currentValue = $this->Last_Name->CurrentValue;
            $viewValue = &$this->Last_Name->ViewValue;
            $viewAttrs = &$this->Last_Name->ViewAttrs;
            $cellAttrs = &$this->Last_Name->CellAttrs;
            $hrefValue = &$this->Last_Name->HrefValue;
            $linkAttrs = &$this->Last_Name->LinkAttrs;
            $this->cellRendered($this->Last_Name, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);

            // First_Name
            $currentValue = $this->First_Name->CurrentValue;
            $viewValue = &$this->First_Name->ViewValue;
            $viewAttrs = &$this->First_Name->ViewAttrs;
            $cellAttrs = &$this->First_Name->CellAttrs;
            $hrefValue = &$this->First_Name->HrefValue;
            $linkAttrs = &$this->First_Name->LinkAttrs;
            $this->cellRendered($this->First_Name, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);

            // Gender
            $currentValue = $this->Gender->CurrentValue;
            $viewValue = &$this->Gender->ViewValue;
            $viewAttrs = &$this->Gender->ViewAttrs;
            $cellAttrs = &$this->Gender->CellAttrs;
            $hrefValue = &$this->Gender->HrefValue;
            $linkAttrs = &$this->Gender->LinkAttrs;
            $this->cellRendered($this->Gender, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);

            // Date_Of_Birth
            $currentValue = $this->Date_Of_Birth->CurrentValue;
            $viewValue = &$this->Date_Of_Birth->ViewValue;
            $viewAttrs = &$this->Date_Of_Birth->ViewAttrs;
            $cellAttrs = &$this->Date_Of_Birth->CellAttrs;
            $hrefValue = &$this->Date_Of_Birth->HrefValue;
            $linkAttrs = &$this->Date_Of_Birth->LinkAttrs;
            $this->cellRendered($this->Date_Of_Birth, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);

            // Place_Of_Birth
            $currentValue = $this->Place_Of_Birth->CurrentValue;
            $viewValue = &$this->Place_Of_Birth->ViewValue;
            $viewAttrs = &$this->Place_Of_Birth->ViewAttrs;
            $cellAttrs = &$this->Place_Of_Birth->CellAttrs;
            $hrefValue = &$this->Place_Of_Birth->HrefValue;
            $linkAttrs = &$this->Place_Of_Birth->LinkAttrs;
            $this->cellRendered($this->Place_Of_Birth, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);

            // Card_No
            $currentValue = $this->Card_No->CurrentValue;
            $viewValue = &$this->Card_No->ViewValue;
            $viewAttrs = &$this->Card_No->ViewAttrs;
            $cellAttrs = &$this->Card_No->CellAttrs;
            $hrefValue = &$this->Card_No->HrefValue;
            $linkAttrs = &$this->Card_No->LinkAttrs;
            $this->cellRendered($this->Card_No, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);

            // Unique_QR
            $currentValue = $this->Unique_QR->CurrentValue;
            $viewValue = &$this->Unique_QR->ViewValue;
            $viewAttrs = &$this->Unique_QR->ViewAttrs;
            $cellAttrs = &$this->Unique_QR->CellAttrs;
            $hrefValue = &$this->Unique_QR->HrefValue;
            $linkAttrs = &$this->Unique_QR->LinkAttrs;
            $this->cellRendered($this->Unique_QR, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);

            // Photo
            $currentValue = $this->Photo->CurrentValue;
            $viewValue = &$this->Photo->ViewValue;
            $viewAttrs = &$this->Photo->ViewAttrs;
            $cellAttrs = &$this->Photo->CellAttrs;
            $hrefValue = &$this->Photo->HrefValue;
            $linkAttrs = &$this->Photo->LinkAttrs;
            $this->cellRendered($this->Photo, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);

            // Expiry_Date
            $currentValue = $this->Expiry_Date->CurrentValue;
            $viewValue = &$this->Expiry_Date->ViewValue;
            $viewAttrs = &$this->Expiry_Date->ViewAttrs;
            $cellAttrs = &$this->Expiry_Date->CellAttrs;
            $hrefValue = &$this->Expiry_Date->HrefValue;
            $linkAttrs = &$this->Expiry_Date->LinkAttrs;
            $this->cellRendered($this->Expiry_Date, $currentValue, $viewValue, $viewAttrs, $cellAttrs, $hrefValue, $linkAttrs);
        }

        // Call Row_Rendered event
        $this->rowRendered();
        $this->setupFieldCount();
    }
    private $groupCounts = [];

    // Get group count
    public function getGroupCount(...$args)
    {
        $key = "";
        foreach ($args as $arg) {
            if ($key != "") {
                $key .= "_";
            }
            $key .= strval($arg);
        }
        if ($key == "") {
            return -1;
        } elseif ($key == "0") { // Number of first level groups
            $i = 1;
            while (isset($this->groupCounts[strval($i)])) {
                $i++;
            }
            return $i - 1;
        }
        return isset($this->groupCounts[$key]) ? $this->groupCounts[$key] : -1;
    }

    // Set group count
    public function setGroupCount($value, ...$args)
    {
        $key = "";
        foreach ($args as $arg) {
            if ($key != "") {
                $key .= "_";
            }
            $key .= strval($arg);
        }
        if ($key == "") {
            return;
        }
        $this->groupCounts[$key] = $value;
    }

    // Setup field count
    protected function setupFieldCount()
    {
        $this->GroupColumnCount = 0;
        $this->SubGroupColumnCount = 0;
        $this->DetailColumnCount = 0;
        if ($this->SClass->Visible) {
            $this->GroupColumnCount += 1;
        }
        if ($this->PIN->Visible) {
            $this->DetailColumnCount += 1;
        }
        if ($this->Last_Name->Visible) {
            $this->DetailColumnCount += 1;
        }
        if ($this->First_Name->Visible) {
            $this->DetailColumnCount += 1;
        }
        if ($this->Gender->Visible) {
            $this->DetailColumnCount += 1;
        }
        if ($this->Date_Of_Birth->Visible) {
            $this->DetailColumnCount += 1;
        }
        if ($this->Place_Of_Birth->Visible) {
            $this->DetailColumnCount += 1;
        }
        if ($this->Card_No->Visible) {
            $this->DetailColumnCount += 1;
        }
        if ($this->Unique_QR->Visible) {
            $this->DetailColumnCount += 1;
        }
        if ($this->Photo->Visible) {
            $this->DetailColumnCount += 1;
        }
        if ($this->Expiry_Date->Visible) {
            $this->DetailColumnCount += 1;
        }
    }

// Get export HTML tag
    protected function getExportTag($type, $custom = false)
    {
        global $Language;

        // if ($type == "print" || $custom) {
        //    $pageUrl = $this->pageUrl(false); // removed by Unique Digital Solutions Ltd, Sept 27, 2022 ... Printer Friendly (print) using API EXPORT ACTION, too!

        //    $exportUrl = GetUrl($pageUrl . "export=" . $type . ($custom ? "&amp;custom=1" : "")); // removed by Unique Digital Solutions Ltd, Sept 27, 2022 ... Printer Friendly (print) using API EXPORT ACTION, too!
        // } else {
            //$query = GetCsrfAsQuery();

            //$exportUrl = GetApiUrl(Config("API_EXPORT_ACTION") . "/" . $type . "/" . $this->TableVar, $query);
        // } // removed by Unique Digital Solutions Ltd, Sept 27, 2022 ... Printer Friendly (print) using API EXPORT ACTION, too!

		// Begin of modification, moved to Client-Side into masinoew.js file, by Unique Digital Solutions Ltd, September 27, 2022
		if ($type == "print" || $custom) { // Begin of added Printer Friendly, by Unique Digital Solutions Ltd, September 27, 2022
			$pageUrl = $this->pageUrl(false);
			$exportUrl = GetUrl($pageUrl . "export=" . $type . ($custom ? "&amp;custom=1" : ""));
		} else { // else for Export other than Printer Friendly
			$exportUrl = GetApiUrl(Config("API_EXPORT_ACTION") . "/" . $type . "/" . $this->TableVar);
		}
		// End of modification, moved to Client-Side into masinoew.js file, by Unique Digital Solutions Ltd, September 27, 2022
        if (SameText($type, "excel")) {
            return '<button type="button" class="btn btn-default ew-export-link ew-excel" title="' . HtmlEncode($Language->phrase("ExportToExcel", true)) . '" data-caption="' . HtmlEncode($Language->phrase("ExportToExcel", true)) . '" data-ew-action="export" data-export="excel" data-custom="false" data-export-selected="false" data-url="' . $exportUrl . '">' . $Language->phrase("ExportToExcel") . '</button>';
        } elseif (SameText($type, "word")) {
            return '<button type="button" class="btn btn-default ew-export-link ew-word" title="' . HtmlEncode($Language->phrase("ExportToWord", true)) . '" data-caption="' . HtmlEncode($Language->phrase("ExportToWord", true)) . '" data-ew-action="export" data-export="word" data-custom="false" data-export-selected="false" data-url="' . $exportUrl . '">' . $Language->phrase("ExportToWord") . '</button>';
        } elseif (SameText($type, "pdf")) {
            return '<button type="button" class="btn btn-default ew-export-link ew-pdf" title="' . HtmlEncode($Language->phrase("ExportToPdf", true)) . '" data-caption="' . HtmlEncode($Language->phrase("ExportToPdf", true)) . '" data-ew-action="export" data-export="pdf" data-custom="false" data-export-selected="false" data-url="' . $exportUrl . '">' . $Language->phrase("ExportToPdf") . '</button>';
        } elseif (SameText($type, "html")) {
            return '<button type="button" class="btn btn-default ew-export-link ew-html" title="' . HtmlEncode($Language->phrase("ExportToHtml", true)) . '" data-caption="' . HtmlEncode($Language->phrase("ExportToHtml", true)) . '" data-ew-action="export" data-export="html" data-custom="false" data-export-selected="false" data-url="' . $exportUrl . '">' . $Language->phrase("ExportToHtml") . '</button>';
        } elseif (SameText($type, "email")) {
            return '<button type="button" class="btn btn-default ew-export-link ew-email" title="' . HtmlEncode($Language->phrase("ExportToEmail", true)) . '" data-caption="' . HtmlEncode($Language->phrase("ExportToEmail", true)) . '" data-ew-action="email" data-custom="false" data-export-selected="false" data-hdr="' . HtmlEncode($Language->phrase("ExportToEmail", true)) . '" data-url="' . $exportUrl . '">' . $Language->phrase("ExportToEmail") . '</button>';
        } elseif (SameText($type, "print")) {
            return "<a href=\"$exportUrl\" class=\"btn btn-default ew-export-link ew-print\" title=\"" . HtmlEncode($Language->phrase("PrinterFriendly", true)) . "\" data-caption=\"" . HtmlEncode($Language->phrase("PrinterFriendly", true)) . "\">" . $Language->phrase("PrinterFriendly") . "</a>";
        }
    }

    // Set up export options
    protected function setupExportOptions()
    {
        global $Language, $Security;

        // Printer friendly
        $item = &$this->ExportOptions->add("print");
        $item->Body = $this->getExportTag("print");
        if (MS_ENABLE_PERMISSION_FOR_EXPORT_DATA == TRUE) { // customized by Unique Digital Solutions Ltd, September 25, 2020
			$item->Visible = $Security->canExportToPrint();
		} else {
			$item->Visible = true;
		}

        // Export to Excel
        $item = &$this->ExportOptions->add("excel");
        $item->Body = $this->getExportTag("excel");
        if (MS_ENABLE_PERMISSION_FOR_EXPORT_DATA == TRUE) { // customized by Unique Digital Solutions Ltd, September 25, 2020
			$item->Visible = $Security->canExportToExcel();
		} else {
			$item->Visible = true;
		}

        // Export to Word
        $item = &$this->ExportOptions->add("word");
        $item->Body = $this->getExportTag("word");
        if (MS_ENABLE_PERMISSION_FOR_EXPORT_DATA == TRUE) { // customized by Unique Digital Solutions Ltd, September 25, 2020
			$item->Visible = $Security->canExportToWord();
		} else {
			$item->Visible = true;
		}

        // Export to HTML
        $item = &$this->ExportOptions->add("html");
        $item->Body = $this->getExportTag("html");
        if (MS_ENABLE_PERMISSION_FOR_EXPORT_DATA == TRUE) { // customized by Unique Digital Solutions Ltd, September 25, 2020
			$item->Visible = $Security->canExportToHTML();
		} else {
			$item->Visible = true;
		}

        // Export to PDF
        $item = &$this->ExportOptions->add("pdf");
        $item->Body = $this->getExportTag("pdf");
        if (MS_ENABLE_PERMISSION_FOR_EXPORT_DATA == TRUE) { // customized by Unique Digital Solutions Ltd, September 25, 2020
			$item->Visible = $Security->canExportToPDF();
		} else {
			$item->Visible = false;
		}

        // Export to Email
        $item = &$this->ExportOptions->add("email");
        $item->Body = $this->getExportTag("email");
        if (MS_ENABLE_PERMISSION_FOR_EXPORT_DATA == TRUE) { // customized by Unique Digital Solutions Ltd, September 25, 2020
			$item->Visible = $Security->canExportToEmail();
		} else {
			$item->Visible = true;
		}

        // Drop down button for export
        $this->ExportOptions->UseButtonGroup = true;
        $this->ExportOptions->UseDropDownButton = true;
        if ($this->ExportOptions->UseButtonGroup && IsMobile()) {
            $this->ExportOptions->UseDropDownButton = true;
        }
        $this->ExportOptions->DropDownButtonPhrase = $Language->phrase("ButtonExport");

        // Add group option item
        $item = &$this->ExportOptions->addGroupOption();
        $item->Body = "";
        $item->Visible = false;

        // Hide options for export
        if ($this->isExport()) {
            $this->ExportOptions->hideAllOptions();
        }
        if (!$Security->canExport()) { // Export not allowed
            $this->ExportOptions->hideAllOptions();
        }
    }

    // Set up search options
    protected function setupSearchOptions()
    {
        global $Language, $Security;
        $pageUrl = $this->pageUrl(false);
        $this->SearchOptions = new ListOptions(["TagClassName" => "ew-search-option"]);

        // Button group for search
        $this->SearchOptions->UseDropDownButton = false;
        $this->SearchOptions->UseButtonGroup = true;
        $this->SearchOptions->DropDownButtonPhrase = $Language->phrase("ButtonSearch");

        // Add group option item
        $item = &$this->SearchOptions->addGroupOption();
        $item->Body = "";
        $item->Visible = false;

        // Hide search options
        if ($this->isExport() || $this->CurrentAction && $this->CurrentAction != "search") {
            $this->SearchOptions->hideAllOptions();
        }
        if (!$Security->canSearch()) {
            $this->SearchOptions->hideAllOptions();
            $this->FilterOptions->hideAllOptions();
        }
    }

    // Check if any search fields
    public function hasSearchFields()
    {
        return false;
    }

    // Render search options
    protected function renderSearchOptions()
    {
        if (!$this->hasSearchFields() && $this->SearchOptions["searchtoggle"]) {
            $this->SearchOptions["searchtoggle"]->Visible = false;
        }
    }

    // Set up Breadcrumb
    protected function setupBreadcrumb()
    {
        global $Breadcrumb, $Language;
        $Breadcrumb = new Breadcrumb("index");
        $url = CurrentUrl();
        $url = preg_replace('/\?cmd=reset(all){0,1}$/i', '', $url); // Remove cmd=reset(all)
        $Breadcrumb->add("summary", $this->TableVar, $url, "", $this->TableVar, true);
    }

    // Setup lookup options
    public function setupLookupOptions($fld)
    {
        if ($fld->Lookup !== null && $fld->Lookup->Options === null) {
            // Get default connection and filter
            $conn = $this->getConnection();
            $lookupFilter = "";

            // No need to check any more
            $fld->Lookup->Options = [];

            // Set up lookup SQL and connection
            switch ($fld->FieldVar) {
                case "x_PIN":
                    break;
                case "x_Last_Name":
                    break;
                case "x_Gender":
                    break;
                case "x_Card_No":
                    break;
                case "x_Status":
                    break;
                default:
                    $lookupFilter = "";
                    break;
            }

            // Always call to Lookup->getSql so that user can setup Lookup->Options in Lookup_Selecting server event
            $sql = $fld->Lookup->getSql(false, "", $lookupFilter, $this);

            // Set up lookup cache
            if (!$fld->hasLookupOptions() && $fld->UseLookupCache && $sql != "" && count($fld->Lookup->Options) == 0 && count($fld->Lookup->FilterFields) == 0) {
                $totalCnt = $this->getRecordCount($sql, $conn);
                if ($totalCnt > $fld->LookupCacheCount) { // Total count > cache count, do not cache
                    return;
                }
                $rows = $conn->executeQuery($sql)->fetchAll();
                $ar = [];
                foreach ($rows as $row) {
                    $row = $fld->Lookup->renderViewRow($row, Container($fld->Lookup->LinkTable));
                    $key = $row["lf"];
                    if (IsFloatType($fld->Type)) { // Handle float field
                        $key = (float)$key;
                    }
                    $ar[strval($key)] = $row;
                }
                $fld->Lookup->Options = $ar;
            }
        }
    }

    // Set up other options
    protected function setupOtherOptions()
    {
        global $Language, $Security;

        // Filter button
        $item = &$this->FilterOptions->add("savecurrentfilter");
        $item->Body = "<a class=\"ew-save-filter\" data-form=\"fStudents_Reportssrch\" data-ew-action=\"none\">" . $Language->phrase("SaveCurrentFilter") . "</a>";
        $item->Visible = false;
        $item = &$this->FilterOptions->add("deletefilter");
        $item->Body = "<a class=\"ew-delete-filter\" data-form=\"fStudents_Reportssrch\" data-ew-action=\"none\">" . $Language->phrase("DeleteFilter") . "</a>";
        $item->Visible = false;
        $this->FilterOptions->UseDropDownButton = true;
        $this->FilterOptions->UseButtonGroup = !$this->FilterOptions->UseDropDownButton;
        $this->FilterOptions->DropDownButtonPhrase = $Language->phrase("Filters");

        // Add group option item
        $item = &$this->FilterOptions->addGroupOption();
        $item->Body = "";
        $item->Visible = false;
    }

    // Set up starting group
    protected function setupStartGroup()
    {
        // Exit if no groups
        if ($this->DisplayGroups == 0) {
            return;
        }
        $startGrp = Param(Config("TABLE_START_GROUP"));
        $pageNo = Param(Config("TABLE_PAGE_NUMBER"));

        // Check for a 'start' parameter
        if ($startGrp !== null) {
            $this->StartGroup = $startGrp;
            $this->setStartGroup($this->StartGroup);
        } elseif ($pageNo !== null) {
            $pageNo = ParseInteger($pageNo);
            if (is_numeric($pageNo)) {
                $this->StartGroup = ($pageNo - 1) * $this->DisplayGroups + 1;
                if ($this->StartGroup <= 0) {
                    $this->StartGroup = 1;
                } elseif ($this->StartGroup >= intval(($this->TotalGroups - 1) / $this->DisplayGroups) * $this->DisplayGroups + 1) {
                    $this->StartGroup = intval(($this->TotalGroups - 1) / $this->DisplayGroups) * $this->DisplayGroups + 1;
                }
                $this->setStartGroup($this->StartGroup);
            } else {
                $this->StartGroup = $this->getStartGroup();
            }
        } else {
            $this->StartGroup = $this->getStartGroup();
        }

        // Check if correct start group counter
        if (!is_numeric($this->StartGroup) || intval($this->StartGroup) <= 0) { // Avoid invalid start group counter
            $this->StartGroup = 1; // Reset start group counter
            $this->setStartGroup($this->StartGroup);
        } elseif (intval($this->StartGroup) > intval($this->TotalGroups)) { // Avoid starting group > total groups
            $this->StartGroup = intval(($this->TotalGroups - 1) / $this->DisplayGroups) * $this->DisplayGroups + 1; // Point to last page first group
            $this->setStartGroup($this->StartGroup);
        } elseif (($this->StartGroup - 1) % $this->DisplayGroups != 0) {
            $this->StartGroup = intval(($this->StartGroup - 1) / $this->DisplayGroups) * $this->DisplayGroups + 1; // Point to page boundary
            $this->setStartGroup($this->StartGroup);
        }
    }

    // Reset pager
    protected function resetPager()
    {
        // Reset start position (reset command)
        $this->StartGroup = 1;
        $this->setStartGroup($this->StartGroup);
    }

    // Get sort parameters based on sort links clicked
    protected function getSort()
    {
        if ($this->DrillDown) {
            return "Card_No ASC";
        }
        $resetSort = Param("cmd") === "resetsort";
        $orderBy = Param("order", "");
        $orderType = Param("ordertype", "");

        // Check for a resetsort command
        if ($resetSort) {
            $this->setOrderBy("");
            $this->setStartGroup(1);
            $this->PIN->setSort("");
            $this->Last_Name->setSort("");
            $this->First_Name->setSort("");
            $this->Gender->setSort("");
            $this->Date_Of_Birth->setSort("");
            $this->Place_Of_Birth->setSort("");
            $this->Card_No->setSort("");
            $this->Unique_QR->setSort("");
            $this->Photo->setSort("");
            $this->Expiry_Date->setSort("");
            $this->SClass->setSort("");

        // Check for an Order parameter
        } elseif ($orderBy != "") {
            $this->CurrentOrder = $orderBy;
            $this->CurrentOrderType = $orderType;
            $this->updateSort($this->PIN); // PIN
            $this->updateSort($this->Last_Name); // Last_Name
            $this->updateSort($this->First_Name); // First_Name
            $this->updateSort($this->Gender); // Gender
            $this->updateSort($this->Date_Of_Birth); // Date_Of_Birth
            $this->updateSort($this->Place_Of_Birth); // Place_Of_Birth
            $this->updateSort($this->Card_No); // Card_No
            $this->updateSort($this->Unique_QR); // Unique_QR
            $this->updateSort($this->Photo); // Photo
            $this->updateSort($this->Expiry_Date); // Expiry_Date
            $this->updateSort($this->SClass); // SClass
            $sortSql = $this->sortSql();
            $this->setOrderBy($sortSql);
            $this->setStartGroup(1);
        }

        // Set up default sort
        if ($this->getOrderBy() == "") {
            $useDefaultSort = true;
            if ($useDefaultSort) {
                $this->setOrderBy("Card_No ASC");
            }
        }
        return $this->getOrderBy();
    }

    // Page Load event
    public function pageLoad()
    {
        //Log("Page Load");
    }

    // Page Unload event
    public function pageUnload()
    {
        //Log("Page Unload");
    }

    // Page Redirecting event
    public function pageRedirecting(&$url)
    {
        // Example:
        //$url = "your URL";
    }

    // Message Showing event
    // $type = ''|'success'|'failure'|'warning'
    public function messageShowing(&$msg, $type)
    {
        if ($type == 'success') {
            //$msg = "your success message";
        } elseif ($type == 'failure') {
            //$msg = "your failure message";
        } elseif ($type == 'warning') {
            //$msg = "your warning message";
        } else {
            //$msg = "your message";
        }
    }

    // Page Render event
    public function pageRender()
    {
        //Log("Page Render");
    }

    // Page Data Rendering event
    public function pageDataRendering(&$header)
    {
        // Example:
        //$header = "your header";
    }

    // Page Data Rendered event
    public function pageDataRendered(&$footer)
    {
        // Example:
        //$footer = "your footer";
    }

    // Page Breaking event
    public function pageBreaking(&$break, &$content)
    {
        // Example:
        //$break = false; // Skip page break, or
        //$content = "<div style=\"break-after:page;\"></div>"; // Modify page break content
    }

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

    // Load Filters event
    public function pageFilterLoad()
    {
        // Enter your code here
        // Example: Register/Unregister Custom Extended Filter
        //RegisterFilter($this-><Field>, 'StartsWithA', 'Starts With A', 'GetStartsWithAFilter'); // With function, or
        //RegisterFilter($this-><Field>, 'StartsWithA', 'Starts With A'); // No function, use Page_Filtering event
        //UnregisterFilter($this-><Field>, 'StartsWithA');
    }

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

    // Page Filtering event
    public function pageFiltering(&$fld, &$filter, $typ, $opr = "", $val = "", $cond = "", $opr2 = "", $val2 = "")
    {
        // Note: ALWAYS CHECK THE FILTER TYPE ($typ)! Example:
        //if ($typ == "dropdown" && $fld->Name == "MyField") // Dropdown filter
        //    $filter = "..."; // Modify the filter
        //if ($typ == "extended" && $fld->Name == "MyField") // Extended filter
        //    $filter = "..."; // Modify the filter
        //if ($typ == "custom" && $opr == "..." && $fld->Name == "MyField") // Custom filter, $opr is the custom filter ID
        //    $filter = "..."; // Modify the filter
    }

    // Cell Rendered event
    public function cellRendered(&$Field, $CurrentValue, &$ViewValue, &$ViewAttrs, &$CellAttrs, &$HrefValue, &$LinkAttrs)
    {
        //$ViewValue = "xxx";
        //$ViewAttrs["class"] = "xxx";
    }

    // Form Custom Validate event
    public function formCustomValidate(&$customError)
    {
        // Return error message in $customError
        return true;
    }
}
