<?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 AnnouncementSearch extends Announcement
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

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

    // Rendering View
    public $RenderingView = false;

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

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

    // Page layout
    public $UseLayout = true;

    // Page terminated
    private $terminated = false;

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

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

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

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

    // Show Page Header
    public function showPageHeader()
    {
        $header = $this->PageHeader;
        $this->pageDataRendering($header);
        if ($header != "") { // Header exists, display
            echo '<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>';
        }
    }

    // Set field visibility
    public function setVisibility()
    {
        $this->Announcement_ID->setVisibility();
        $this->Is_Active->setVisibility();
        $this->Topic->setVisibility();
        $this->_Message->setVisibility();
        $this->Date_LastUpdate->setVisibility();
        $this->_Language->setVisibility();
        $this->Auto_Publish->setVisibility();
        $this->Date_Start->setVisibility();
        $this->Date_End->setVisibility();
        $this->Date_Created->setVisibility();
        $this->Created_By->setVisibility();
        $this->Translated_ID->setVisibility();
    }

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

        // Table CSS class
        $this->TableClass = "table table-striped table-bordered table-hover table-sm ew-desktop-table ew-search-table";

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

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

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

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

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

        // Debug message
        LoadDebugMessage();

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

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

    // Get content from stream
    public function getContents(): string
    {
        global $Response;
        return 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
        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();
            }

            // Handle modal response (Assume return to modal for simplicity)
            if ($this->IsModal) { // Show as modal
                $result = ["url" => GetUrl($url), "modal" => "1"];
                $pageName = GetPageName($url);
                if ($pageName != $this->getListUrl()) { // Not List page => View page
                    $result["caption"] = $this->getModalCaption($pageName);
                    $result["view"] = $pageName == "announcementview"; // If View page, no primary button
                } else { // List page
                    // $result["list"] = $this->PageID == "search"; // Refresh List page if current page is Search page
                    $result["error"] = $this->getFailureMessage(); // List page should not be shown as modal => error
                    $this->clearFailureMessage();
                }
                WriteJson($result);
            } else {
                SaveDebugMessage();
                Redirect(GetUrl($url));
            }
        }
        return; // Return to controller
    }

    // Get records from recordset
    protected function getRecordsFromRecordset($rs, $current = false)
    {
        $rows = [];
        if (is_object($rs)) { // Recordset
            while ($rs && !$rs->EOF) {
                $this->loadRowValues($rs); // Set up DbValue/CurrentValue
                $row = $this->getRecordFromArray($rs->fields);
                if ($current) {
                    return $row;
                } else {
                    $rows[] = $row;
                }
                $rs->moveNext();
            }
        } elseif (is_array($rs)) {
            foreach ($rs as $ar) {
                $row = $this->getRecordFromArray($ar);
                if ($current) {
                    return $row;
                } else {
                    $rows[] = $row;
                }
            }
        }
        return $rows;
    }

    // Get record from array
    protected function getRecordFromArray($ar)
    {
        $row = [];
        if (is_array($ar)) {
            foreach ($ar as $fldname => $val) {
                if (array_key_exists($fldname, $this->Fields) && ($this->Fields[$fldname]->Visible || $this->Fields[$fldname]->IsPrimaryKey)) { // Primary key or Visible
                    $fld = &$this->Fields[$fldname];
                    if ($fld->HtmlTag == "FILE") { // Upload field
                        if (EmptyValue($val)) {
                            $row[$fldname] = null;
                        } else {
                            if ($fld->DataType == DATATYPE_BLOB) {
                                $url = FullUrl(GetApiUrl(Config("API_FILE_ACTION") .
                                    "/" . $fld->TableVar . "/" . $fld->Param . "/" . rawurlencode($this->getRecordKeyValue($ar))));
                                $row[$fldname] = ["type" => ContentType($val), "url" => $url, "name" => $fld->Param . ContentExtension($val)];
                            } elseif (!$fld->UploadMultiple || !ContainsString($val, Config("MULTIPLE_UPLOAD_SEPARATOR"))) { // Single file
                                $url = FullUrl(GetApiUrl(Config("API_FILE_ACTION") .
                                    "/" . $fld->TableVar . "/" . Encrypt($fld->physicalUploadPath() . $val)));
                                $row[$fldname] = ["type" => MimeContentType($val), "url" => $url, "name" => $val];
                            } else { // Multiple files
                                $files = explode(Config("MULTIPLE_UPLOAD_SEPARATOR"), $val);
                                $ar = [];
                                foreach ($files as $file) {
                                    $url = FullUrl(GetApiUrl(Config("API_FILE_ACTION") .
                                        "/" . $fld->TableVar . "/" . Encrypt($fld->physicalUploadPath() . $file)));
                                    if (!EmptyValue($file)) {
                                        $ar[] = ["type" => MimeContentType($file), "url" => $url, "name" => $file];
                                    }
                                }
                                $row[$fldname] = $ar;
                            }
                        }
                    } else {
                        $row[$fldname] = $val;
                    }
                }
            }
        }
        return $row;
    }

    // Get record key value from array
    protected function getRecordKeyValue($ar)
    {
        $key = "";
        if (is_array($ar)) {
            $key .= @$ar['Announcement_ID'];
        }
        return $key;
    }

    /**
     * Hide fields for add/edit
     *
     * @return void
     */
    protected function hideFieldsForAddEdit()
    {
        if ($this->isAdd() || $this->isCopy() || $this->isGridAdd()) {
            $this->Announcement_ID->Visible = false;
        }
    }

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

        // 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
    }
    public $FormClassName = "ew-form ew-search-form";
    public $IsModal = false;
    public $IsMobileOrModal = false;

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

// Is modal
        $this->IsModal = ConvertToBool(Param("modal"));
        $this->UseLayout = $this->UseLayout && !$this->IsModal;

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

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

        // Update last accessed time
        if (!IsSysAdmin() && !$UserProfile->isValidUser(CurrentUserName(), session_id())) {
            $this->setFailureMessage($Language->phrase("UserProfileCorrupted"));
            $this->terminate('logout');
            // return;
        }

        // Create form object
        $CurrentForm = new HttpForm();
        $this->CurrentAction = Param("action"); // Set up current action
        $this->setVisibility();

        // Set lookup cache
        if (!in_array($this->PageID, Config("LOOKUP_CACHE_PAGE_IDS"))) {
            $this->setUseLookupCache(false);
        }

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

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

        // Hide fields for add/edit
        if (!$this->UseAjaxActions) {
            $this->hideFieldsForAddEdit();
        }
        // Use inline delete
        if ($this->UseAjaxActions) {
            $this->InlineDelete = true;
        }

        // Set up lookup cache
        $this->setupLookupOptions($this->Is_Active);
        $this->setupLookupOptions($this->Auto_Publish);
		My_Global_Check(); // Modified by Unique Digital Solutions Ltd, October 6, 2021

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

        // Check modal
        if ($this->IsModal) {
            $SkipHeaderFooter = true;
        }
        $this->IsMobileOrModal = IsMobile() || $this->IsModal;

        // Get action
        $this->CurrentAction = Post("action");
        if ($this->isSearch()) {
            // Build search string for advanced search, remove blank field
            $this->loadSearchValues(); // Get search values
            $srchStr = $this->validateSearch() ? $this->buildAdvancedSearch() : "";
            if ($srchStr != "") {
                $srchStr = "announcementlist" . "?" . $srchStr;
                // Do not return Json for UseAjaxActions
                if ($this->IsModal && $this->UseAjaxActions) {
                    $this->IsModal = false;
                }
                $this->terminate($srchStr); // Go to list page
                return;
            }
        }

        // Restore search settings from Session
        if (!$this->hasInvalidFields()) {
            $this->loadAdvancedSearch();
        }

        // Render row for search
        $this->RowType = ROWTYPE_SEARCH;
        $this->resetAttributes();
        $this->renderRow();

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

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

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

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

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

    // Build advanced search
    protected function buildAdvancedSearch()
    {
        $srchUrl = "";
        $this->buildSearchUrl($srchUrl, $this->Announcement_ID); // Announcement_ID
        $this->buildSearchUrl($srchUrl, $this->Is_Active, true); // Is_Active
        $this->buildSearchUrl($srchUrl, $this->Topic); // Topic
        $this->buildSearchUrl($srchUrl, $this->_Message); // Message
        $this->buildSearchUrl($srchUrl, $this->Date_LastUpdate); // Date_LastUpdate
        $this->buildSearchUrl($srchUrl, $this->_Language); // Language
        $this->buildSearchUrl($srchUrl, $this->Auto_Publish, true); // Auto_Publish
        $this->buildSearchUrl($srchUrl, $this->Date_Start); // Date_Start
        $this->buildSearchUrl($srchUrl, $this->Date_End); // Date_End
        $this->buildSearchUrl($srchUrl, $this->Date_Created); // Date_Created
        $this->buildSearchUrl($srchUrl, $this->Created_By); // Created_By
        $this->buildSearchUrl($srchUrl, $this->Translated_ID); // Translated_ID
        if ($srchUrl != "") {
            $srchUrl .= "&";
        }
        $srchUrl .= "cmd=search";
        return $srchUrl;
    }

    // Build search URL
    protected function buildSearchUrl(&$url, $fld, $oprOnly = false)
    {
        global $CurrentForm;
        $wrk = "";
        $fldParm = $fld->Param;
        [
            "value" => $fldVal,
            "operator" => $fldOpr,
            "condition" => $fldCond,
            "value2" => $fldVal2,
            "operator2" => $fldOpr2
        ] = $CurrentForm->getSearchValues($fldParm);
        if (is_array($fldVal)) {
            $fldVal = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $fldVal);
        }
        if (is_array($fldVal2)) {
            $fldVal2 = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $fldVal2);
        }
        $fldDataType = $fld->DataType;
        $value = ConvertSearchValue($fldVal, $fldOpr, $fld); // For testing if numeric only
        $value2 = ConvertSearchValue($fldVal2, $fldOpr2, $fld); // For testing if numeric only
        $fldOpr = ConvertSearchOperator($fldOpr, $fld, $value);
        $fldOpr2 = ConvertSearchOperator($fldOpr2, $fld, $value2);
        if (in_array($fldOpr, ["BETWEEN", "NOT BETWEEN"])) {
            $isValidValue = $fldDataType != DATATYPE_NUMBER || $fld->VirtualSearch || IsNumericSearchValue($value, $fldOpr, $fld) && IsNumericSearchValue($value2, $fldOpr2, $fld);
            if ($fldVal != "" && $fldVal2 != "" && $isValidValue) {
                $wrk = "x_" . $fldParm . "=" . urlencode($fldVal) . "&y_" . $fldParm . "=" . urlencode($fldVal2) . "&z_" . $fldParm . "=" . urlencode($fldOpr);
            }
        } else {
            $isValidValue = $fldDataType != DATATYPE_NUMBER || $fld->VirtualSearch || IsNumericSearchValue($value, $fldOpr, $fld);
            if ($fldVal != "" && $isValidValue && IsValidOperator($fldOpr)) {
                $wrk = "x_" . $fldParm . "=" . urlencode($fldVal) . "&z_" . $fldParm . "=" . urlencode($fldOpr);
            } elseif (in_array($fldOpr, ["IS NULL", "IS NOT NULL", "IS EMPTY", "IS NOT EMPTY"]) || ($fldOpr != "" && $oprOnly && IsValidOperator($fldOpr))) {
                $wrk = "z_" . $fldParm . "=" . urlencode($fldOpr);
            }
            $isValidValue = $fldDataType != DATATYPE_NUMBER || $fld->VirtualSearch || IsNumericSearchValue($value2, $fldOpr2, $fld);
            if ($fldVal2 != "" && $isValidValue && IsValidOperator($fldOpr2)) {
                if ($wrk != "") {
                    $wrk .= "&v_" . $fldParm . "=" . urlencode($fldCond) . "&";
                }
                $wrk .= "y_" . $fldParm . "=" . urlencode($fldVal2) . "&w_" . $fldParm . "=" . urlencode($fldOpr2);
            } elseif (in_array($fldOpr2, ["IS NULL", "IS NOT NULL", "IS EMPTY", "IS NOT EMPTY"]) || ($fldOpr2 != "" && $oprOnly && IsValidOperator($fldOpr2))) {
                if ($wrk != "") {
                    $wrk .= "&v_" . $fldParm . "=" . urlencode($fldCond) . "&";
                }
                $wrk .= "w_" . $fldParm . "=" . urlencode($fldOpr2);
            }
        }
        if ($wrk != "") {
            if ($url != "") {
                $url .= "&";
            }
            $url .= $wrk;
        }
    }

// Load search values for validation
    protected function loadSearchValues()
    {
        // Load search values
        $hasValue = false;

        // Announcement_ID
        if ($this->Announcement_ID->AdvancedSearch->get()) {
            $hasValue = true;
        }

        // Is_Active
        if ($this->Is_Active->AdvancedSearch->get()) {
            $hasValue = true;
        }
        if (is_array($this->Is_Active->AdvancedSearch->SearchValue)) {
            $this->Is_Active->AdvancedSearch->SearchValue = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $this->Is_Active->AdvancedSearch->SearchValue);
        }
        if (is_array($this->Is_Active->AdvancedSearch->SearchValue2)) {
            $this->Is_Active->AdvancedSearch->SearchValue2 = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $this->Is_Active->AdvancedSearch->SearchValue2);
        }

        // Topic
        if ($this->Topic->AdvancedSearch->get()) {
            $hasValue = true;
        }

        // Message
        if ($this->_Message->AdvancedSearch->get()) {
            $hasValue = true;
        }

        // Date_LastUpdate
        if ($this->Date_LastUpdate->AdvancedSearch->get()) {
            $hasValue = true;
        }

        // Language
        if ($this->_Language->AdvancedSearch->get()) {
            $hasValue = true;
        }

        // Auto_Publish
        if ($this->Auto_Publish->AdvancedSearch->get()) {
            $hasValue = true;
        }
        if (is_array($this->Auto_Publish->AdvancedSearch->SearchValue)) {
            $this->Auto_Publish->AdvancedSearch->SearchValue = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $this->Auto_Publish->AdvancedSearch->SearchValue);
        }
        if (is_array($this->Auto_Publish->AdvancedSearch->SearchValue2)) {
            $this->Auto_Publish->AdvancedSearch->SearchValue2 = implode(Config("MULTIPLE_OPTION_SEPARATOR"), $this->Auto_Publish->AdvancedSearch->SearchValue2);
        }

        // Date_Start
        if ($this->Date_Start->AdvancedSearch->get()) {
            $hasValue = true;
        }

        // Date_End
        if ($this->Date_End->AdvancedSearch->get()) {
            $hasValue = true;
        }

        // Date_Created
        if ($this->Date_Created->AdvancedSearch->get()) {
            $hasValue = true;
        }

        // Created_By
        if ($this->Created_By->AdvancedSearch->get()) {
            $hasValue = true;
        }

        // Translated_ID
        if ($this->Translated_ID->AdvancedSearch->get()) {
            $hasValue = true;
        }
        return $hasValue;
    }

    // Render row values based on field settings
    public function renderRow()
    {
        global $Security, $Language, $CurrentLanguage;

        // Initialize URLs

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

        // Common render codes for all row types

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

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

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

        // Message
        $this->_Message->RowCssClass = "row";

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

        // Language
        $this->_Language->RowCssClass = "row";

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

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

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

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

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

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

        // View row
        if ($this->RowType == ROWTYPE_VIEW) {
            // Announcement_ID
            $this->Announcement_ID->ViewValue = $this->Announcement_ID->CurrentValue;

            // Is_Active
            if (ConvertToBool($this->Is_Active->CurrentValue)) {
                $this->Is_Active->ViewValue = $this->Is_Active->tagCaption(2) != "" ? $this->Is_Active->tagCaption(2) : "Y";
            } else {
                $this->Is_Active->ViewValue = $this->Is_Active->tagCaption(1) != "" ? $this->Is_Active->tagCaption(1) : "N";
            }

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

            // Message
            $this->_Message->ViewValue = $this->_Message->CurrentValue;

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

            // Language
            $this->_Language->ViewValue = $this->_Language->CurrentValue;

            // Auto_Publish
            if (ConvertToBool($this->Auto_Publish->CurrentValue)) {
                $this->Auto_Publish->ViewValue = $this->Auto_Publish->tagCaption(1) != "" ? $this->Auto_Publish->tagCaption(1) : "Y";
            } else {
                $this->Auto_Publish->ViewValue = $this->Auto_Publish->tagCaption(2) != "" ? $this->Auto_Publish->tagCaption(2) : "N";
            }

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

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

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

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

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

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

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

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

            // Message
            $this->_Message->HrefValue = "";
            $this->_Message->TooltipValue = "";

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

            // Language
            $this->_Language->HrefValue = "";
            $this->_Language->TooltipValue = "";

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

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

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

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

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

            // Translated_ID
            $this->Translated_ID->HrefValue = "";
            $this->Translated_ID->TooltipValue = "";
        } elseif ($this->RowType == ROWTYPE_SEARCH) {
            // Announcement_ID
            $this->Announcement_ID->setupEditAttributes();
            $this->Announcement_ID->EditValue = HtmlEncode($this->Announcement_ID->AdvancedSearch->SearchValue);
            $this->Announcement_ID->PlaceHolder = RemoveHtml($this->Announcement_ID->caption());

            // Is_Active
            $this->Is_Active->EditValue = $this->Is_Active->options(false);
            $this->Is_Active->PlaceHolder = RemoveHtml($this->Is_Active->caption());

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

            // Message
            $this->_Message->setupEditAttributes();
            $this->_Message->EditValue = HtmlEncode($this->_Message->AdvancedSearch->SearchValue);
            $this->_Message->PlaceHolder = RemoveHtml($this->_Message->caption());

            // Date_LastUpdate
            $this->Date_LastUpdate->setupEditAttributes();
            $this->Date_LastUpdate->EditValue = HtmlEncode(FormatDateTime(UnFormatDateTime($this->Date_LastUpdate->AdvancedSearch->SearchValue, $this->Date_LastUpdate->formatPattern()), $this->Date_LastUpdate->formatPattern()));
            $this->Date_LastUpdate->PlaceHolder = RemoveHtml($this->Date_LastUpdate->caption());

            // Language
            $this->_Language->setupEditAttributes();
            if (!$this->_Language->Raw) {
                $this->_Language->AdvancedSearch->SearchValue = HtmlDecode($this->_Language->AdvancedSearch->SearchValue);
            }
            $this->_Language->EditValue = HtmlEncode($this->_Language->AdvancedSearch->SearchValue);
            $this->_Language->PlaceHolder = RemoveHtml($this->_Language->caption());

            // Auto_Publish
            $this->Auto_Publish->EditValue = $this->Auto_Publish->options(false);
            $this->Auto_Publish->PlaceHolder = RemoveHtml($this->Auto_Publish->caption());

            // Date_Start
            $this->Date_Start->setupEditAttributes();
            $this->Date_Start->EditValue = HtmlEncode(FormatDateTime(UnFormatDateTime($this->Date_Start->AdvancedSearch->SearchValue, $this->Date_Start->formatPattern()), $this->Date_Start->formatPattern()));
            $this->Date_Start->PlaceHolder = RemoveHtml($this->Date_Start->caption());

            // Date_End
            $this->Date_End->setupEditAttributes();
            $this->Date_End->EditValue = HtmlEncode(FormatDateTime(UnFormatDateTime($this->Date_End->AdvancedSearch->SearchValue, $this->Date_End->formatPattern()), $this->Date_End->formatPattern()));
            $this->Date_End->PlaceHolder = RemoveHtml($this->Date_End->caption());

            // Date_Created
            $this->Date_Created->setupEditAttributes();
            $this->Date_Created->EditValue = HtmlEncode(FormatDateTime(UnFormatDateTime($this->Date_Created->AdvancedSearch->SearchValue, $this->Date_Created->formatPattern()), $this->Date_Created->formatPattern()));
            $this->Date_Created->PlaceHolder = RemoveHtml($this->Date_Created->caption());

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

            // Translated_ID
            $this->Translated_ID->setupEditAttributes();
            $this->Translated_ID->EditValue = HtmlEncode($this->Translated_ID->AdvancedSearch->SearchValue);
            $this->Translated_ID->PlaceHolder = RemoveHtml($this->Translated_ID->caption());
        }
        if ($this->RowType == ROWTYPE_ADD || $this->RowType == ROWTYPE_EDIT || $this->RowType == ROWTYPE_SEARCH) { // Add/Edit/Search row
            $this->setupFieldTitles();
        }

        // Call Row Rendered event
        if ($this->RowType != ROWTYPE_AGGREGATEINIT) {
            $this->rowRendered();
        }
    }

    // Validate search
    protected function validateSearch()
    {
        // Check if validation required
        if (!Config("SERVER_VALIDATE")) {
            return true;
        }
        if (!CheckInteger($this->Announcement_ID->AdvancedSearch->SearchValue)) {
            $this->Announcement_ID->addErrorMessage($this->Announcement_ID->getErrorMessage(false));
        }
        if (!CheckDate($this->Date_LastUpdate->AdvancedSearch->SearchValue, $this->Date_LastUpdate->formatPattern())) {
            $this->Date_LastUpdate->addErrorMessage($this->Date_LastUpdate->getErrorMessage(false));
        }
        if (!CheckDate($this->Date_Start->AdvancedSearch->SearchValue, $this->Date_Start->formatPattern())) {
            $this->Date_Start->addErrorMessage($this->Date_Start->getErrorMessage(false));
        }
        if (!CheckDate($this->Date_End->AdvancedSearch->SearchValue, $this->Date_End->formatPattern())) {
            $this->Date_End->addErrorMessage($this->Date_End->getErrorMessage(false));
        }
        if (!CheckDate($this->Date_Created->AdvancedSearch->SearchValue, $this->Date_Created->formatPattern())) {
            $this->Date_Created->addErrorMessage($this->Date_Created->getErrorMessage(false));
        }
        if (!CheckInteger($this->Translated_ID->AdvancedSearch->SearchValue)) {
            $this->Translated_ID->addErrorMessage($this->Translated_ID->getErrorMessage(false));
        }

        // Return validate result
        $validateSearch = !$this->hasInvalidFields();

        // Call Form_CustomValidate event
        $formCustomError = "";
        $validateSearch = $validateSearch && $this->formCustomValidate($formCustomError);
        if ($formCustomError != "") {
            $this->setFailureMessage($formCustomError);
        }
        return $validateSearch;
    }

    // Load advanced search
    public function loadAdvancedSearch()
    {
        $this->Announcement_ID->AdvancedSearch->load();
        $this->Is_Active->AdvancedSearch->load();
        $this->Topic->AdvancedSearch->load();
        $this->_Message->AdvancedSearch->load();
        $this->Date_LastUpdate->AdvancedSearch->load();
        $this->_Language->AdvancedSearch->load();
        $this->Auto_Publish->AdvancedSearch->load();
        $this->Date_Start->AdvancedSearch->load();
        $this->Date_End->AdvancedSearch->load();
        $this->Date_Created->AdvancedSearch->load();
        $this->Created_By->AdvancedSearch->load();
        $this->Translated_ID->AdvancedSearch->load();
    }

    // Set up Breadcrumb
    protected function setupBreadcrumb()
    {
        global $Breadcrumb, $Language;
        $Breadcrumb = new Breadcrumb("index");
        $url = CurrentUrl();
        $Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("announcementlist"), "", $this->TableVar, true);
        $pageId = "search";
        $Breadcrumb->add("search", $pageId, $url);
    }

    // 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_Is_Active":
                    break;
                case "x_Auto_Publish":
                    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;
            }
        }
    }

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

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

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

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

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

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

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

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

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