<?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 EventsAdd extends Events
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

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

    // Rendering View
    public $RenderingView = false;

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

    // 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->Event_ID->Visible = false;
        $this->Event_Title->setVisibility();
        $this->Event_Color->setVisibility();
        $this->Event_Start->setVisibility();
        $this->Event_End->setVisibility();
        $this->Event_Description->setVisibility();
        $this->Event_User->setVisibility();
        $this->Repeat_Type->setVisibility();
        $this->Repeat_ID->setVisibility();
        $this->Event_AllDay->setVisibility();
        $this->Event_URL->setVisibility();
        $this->Event_Category->setVisibility();
        $this->Event_Timezone->setVisibility();
        $this->Added_By->setVisibility();
        $this->Date_Added->setVisibility();
        $this->Updated_By->setVisibility();
        $this->Date_Updated->setVisibility();
    }

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

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

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

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

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

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

        // 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 == "eventsview"; // 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['Event_ID'];
        }
        return $key;
    }

    /**
     * Hide fields for add/edit
     *
     * @return void
     */
    protected function hideFieldsForAddEdit()
    {
        if ($this->isAdd() || $this->isCopy() || $this->isGridAdd()) {
            $this->Event_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-add-form";
    public $IsModal = false;
    public $IsMobileOrModal = false;
    public $DbMasterFilter = "";
    public $DbDetailFilter = "";
    public $StartRecord;
    public $Priv = 0;
    public $CopyRecord;

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

        // Load default values for add
        $this->loadDefaultValues();
		My_Global_Check(); // Modified by Unique Digital Solutions Ltd, October 6, 2021

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

        // Set up current action
        if (IsApi()) {
            $this->CurrentAction = "insert"; // Add record directly
            $postBack = true;
        } elseif (Post("action", "") !== "") {
            $this->CurrentAction = Post("action"); // Get form action
            $this->setKey(Post($this->OldKeyName));
            $postBack = true;
        } else {
            // Load key values from QueryString
            if (($keyValue = Get("Event_ID") ?? Route("Event_ID")) !== null) {
                $this->Event_ID->setQueryStringValue($keyValue);
            }
            $this->OldKey = $this->getKey(true); // Get from CurrentValue
            $this->CopyRecord = !EmptyValue($this->OldKey);
            if ($this->CopyRecord) {
                $this->CurrentAction = "copy"; // Copy record
                $this->setKey($this->OldKey); // Set up record key
            } else {
                $this->CurrentAction = "show"; // Display blank record
            }
        }

        // Load old record or default values
        $rsold = $this->loadOldRecord();

        // Load form values
        if ($postBack) {
            $this->loadFormValues(); // Load form values
        }

        // Validate form if post back
        if ($postBack) {
            if (!$this->validateForm()) {
                $this->EventCancelled = true; // Event cancelled
                $this->restoreFormValues(); // Restore form values
                if (IsApi()) {
                    $this->terminate();
                    return;
                } else {
                    $this->CurrentAction = "show"; // Form error, reset action
                }
            }
        }

        // Perform current action
        switch ($this->CurrentAction) {
            case "copy": // Copy an existing record
                if (!$rsold) { // Record not loaded
                    if ($this->getFailureMessage() == "") {
                        $this->setFailureMessage($Language->phrase("NoRecord")); // No record found
                    }
                    $this->terminate("eventslist"); // No matching record, return to list
                    return;
                }
                break;
            case "insert": // Add new record
                $this->SendEmail = true; // Send email on add success
                if ($this->addRow($rsold)) { // Add successful
                    if ($this->getSuccessMessage() == "" && Post("addopt") != "1") { // Skip success message for addopt (done in JavaScript)
                        $this->setSuccessMessage($Language->phrase("AddSuccess")); // Set up success message
                    }
                    $returnUrl = $this->getReturnUrl();
                    if (GetPageName($returnUrl) == "eventslist") {
                        $returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
                    } elseif (GetPageName($returnUrl) == "eventsview") {
                        $returnUrl = $this->getViewUrl(); // View page, return to View page with keyurl directly
                    }

                    // Handle UseAjaxActions
                    if ($this->IsModal && $this->UseAjaxActions) {
                        $this->IsModal = false;
                        if (GetPageName($returnUrl) != "eventslist") {
                            Container("flash")->addMessage("Return-Url", $returnUrl); // Save return URL
                            $returnUrl = "eventslist"; // Return list page content
                        }
                    }
                    if (IsJsonResponse()) { // Return to caller
                        $this->terminate(true);
                        return;
                    } else {
                        $this->terminate($returnUrl);
                        return;
                    }
                } elseif (IsApi()) { // API request, return
                    $this->terminate();
                    return;
                } elseif ($this->IsModal && $this->UseAjaxActions) { // Return JSON error message
                    WriteJson([ "success" => false, "validation" => $this->getValidationErrors(), "error" => $this->getFailureMessage() ]);
                    $this->clearFailureMessage();
                    $this->terminate();
                    return;
                } else {
                    $this->EventCancelled = true; // Event cancelled
                    $this->restoreFormValues(); // Add failed, restore form values
                }
        }

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

        // Render row based on row type
        $this->RowType = ROWTYPE_ADD; // Render add type

        // Render row
        $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();
            }
        }
    }

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

    // Load default values
    protected function loadDefaultValues()
    {
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // Check field name 'Event_ID' first before field var 'x_Event_ID'
        $val = $CurrentForm->hasValue("Event_ID") ? $CurrentForm->getValue("Event_ID") : $CurrentForm->getValue("x_Event_ID");
    }

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->Event_Title->CurrentValue = $this->Event_Title->FormValue;
        $this->Event_Color->CurrentValue = $this->Event_Color->FormValue;
        $this->Event_Start->CurrentValue = $this->Event_Start->FormValue;
        $this->Event_Start->CurrentValue = UnFormatDateTime($this->Event_Start->CurrentValue, $this->Event_Start->formatPattern());
        $this->Event_End->CurrentValue = $this->Event_End->FormValue;
        $this->Event_End->CurrentValue = UnFormatDateTime($this->Event_End->CurrentValue, $this->Event_End->formatPattern());
        $this->Event_Description->CurrentValue = $this->Event_Description->FormValue;
        $this->Event_User->CurrentValue = $this->Event_User->FormValue;
        $this->Repeat_Type->CurrentValue = $this->Repeat_Type->FormValue;
        $this->Repeat_ID->CurrentValue = $this->Repeat_ID->FormValue;
        $this->Event_AllDay->CurrentValue = $this->Event_AllDay->FormValue;
        $this->Event_URL->CurrentValue = $this->Event_URL->FormValue;
        $this->Event_Category->CurrentValue = $this->Event_Category->FormValue;
        $this->Event_Timezone->CurrentValue = $this->Event_Timezone->FormValue;
        $this->Added_By->CurrentValue = $this->Added_By->FormValue;
        $this->Date_Added->CurrentValue = $this->Date_Added->FormValue;
        $this->Date_Added->CurrentValue = UnFormatDateTime($this->Date_Added->CurrentValue, $this->Date_Added->formatPattern());
        $this->Updated_By->CurrentValue = $this->Updated_By->FormValue;
        $this->Date_Updated->CurrentValue = $this->Date_Updated->FormValue;
        $this->Date_Updated->CurrentValue = UnFormatDateTime($this->Date_Updated->CurrentValue, $this->Date_Updated->formatPattern());
    }

    /**
     * Load row based on key values
     *
     * @return void
     */
    public function loadRow()
    {
        global $Security, $Language;
        $filter = $this->getRecordFilter();

        // Call Row Selecting event
        $this->rowSelecting($filter);

        // Load SQL based on filter
        $this->CurrentFilter = $filter;
        $sql = $this->getCurrentSql();
        $conn = $this->getConnection();
        $res = false;
        $row = $conn->fetchAssociative($sql);
        if ($row) {
            $res = true;
            $this->loadRowValues($row); // Load row values
        }
        return $res;
    }

    /**
     * Load row values from recordset or record
     *
     * @param Recordset|array $rs Record
     * @return void
     */
    public function loadRowValues($rs = null)
    {
        if (is_array($rs)) {
            $row = $rs;
        } elseif ($rs && property_exists($rs, "fields")) { // Recordset
            $row = $rs->fields;
        } else {
            $row = $this->newRow();
        }
        if (!$row) {
            return;
        }

        // Call Row Selected event
        $this->rowSelected($row);
        $this->Event_ID->setDbValue($row['Event_ID']);
        $this->Event_Title->setDbValue($row['Event_Title']);
        $this->Event_Color->setDbValue($row['Event_Color']);
        $this->Event_Start->setDbValue($row['Event_Start']);
        $this->Event_End->setDbValue($row['Event_End']);
        $this->Event_Description->setDbValue($row['Event_Description']);
        $this->Event_User->setDbValue($row['Event_User']);
        $this->Repeat_Type->setDbValue($row['Repeat_Type']);
        $this->Repeat_ID->setDbValue($row['Repeat_ID']);
        $this->Event_AllDay->setDbValue($row['Event_AllDay']);
        $this->Event_URL->setDbValue($row['Event_URL']);
        $this->Event_Category->setDbValue($row['Event_Category']);
        $this->Event_Timezone->setDbValue($row['Event_Timezone']);
        $this->Added_By->setDbValue($row['Added_By']);
        $this->Date_Added->setDbValue($row['Date_Added']);
        $this->Updated_By->setDbValue($row['Updated_By']);
        $this->Date_Updated->setDbValue($row['Date_Updated']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $row = [];
        $row['Event_ID'] = $this->Event_ID->DefaultValue;
        $row['Event_Title'] = $this->Event_Title->DefaultValue;
        $row['Event_Color'] = $this->Event_Color->DefaultValue;
        $row['Event_Start'] = $this->Event_Start->DefaultValue;
        $row['Event_End'] = $this->Event_End->DefaultValue;
        $row['Event_Description'] = $this->Event_Description->DefaultValue;
        $row['Event_User'] = $this->Event_User->DefaultValue;
        $row['Repeat_Type'] = $this->Repeat_Type->DefaultValue;
        $row['Repeat_ID'] = $this->Repeat_ID->DefaultValue;
        $row['Event_AllDay'] = $this->Event_AllDay->DefaultValue;
        $row['Event_URL'] = $this->Event_URL->DefaultValue;
        $row['Event_Category'] = $this->Event_Category->DefaultValue;
        $row['Event_Timezone'] = $this->Event_Timezone->DefaultValue;
        $row['Added_By'] = $this->Added_By->DefaultValue;
        $row['Date_Added'] = $this->Date_Added->DefaultValue;
        $row['Updated_By'] = $this->Updated_By->DefaultValue;
        $row['Date_Updated'] = $this->Date_Updated->DefaultValue;
        return $row;
    }

    // Load old record
    protected function loadOldRecord()
    {
        // Load old record
        if ($this->OldKey != "") {
            $this->setKey($this->OldKey);
            $this->CurrentFilter = $this->getRecordFilter();
            $sql = $this->getCurrentSql();
            $conn = $this->getConnection();
            $rs = LoadRecordset($sql, $conn);
            if ($rs && ($row = $rs->fields)) {
                $this->loadRowValues($row); // Load row values
                return $row;
            }
        }
        $this->loadRowValues(); // Load default row values
        return null;
    }

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

        // Initialize URLs

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

        // Common render codes for all row types

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Date_Updated
            $this->Date_Updated->HrefValue = "";
        } elseif ($this->RowType == ROWTYPE_ADD) {
            // Event_Title
            $this->Event_Title->setupEditAttributes();
            if (!$this->Event_Title->Raw) {
                $this->Event_Title->CurrentValue = HtmlDecode($this->Event_Title->CurrentValue);
            }
            $this->Event_Title->EditValue = HtmlEncode($this->Event_Title->CurrentValue);
            $this->Event_Title->PlaceHolder = RemoveHtml($this->Event_Title->caption());

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Add refer script

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Date_Updated
            $this->Date_Updated->HrefValue = "";
        }
        if ($this->RowType == ROWTYPE_ADD || $this->RowType == ROWTYPE_EDIT || $this->RowType == ROWTYPE_SEARCH) { // Add/Edit/Search row
            $this->setupFieldTitles();
        }

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

    // Validate form
    protected function validateForm()
    {
        global $Language, $Security;

        // Check if validation required
        if (!Config("SERVER_VALIDATE")) {
            return true;
        }
        $validateForm = true;
        if ($this->Event_Title->Required) {
            if (!$this->Event_Title->IsDetailKey && EmptyValue($this->Event_Title->FormValue)) {
                $this->Event_Title->addErrorMessage(str_replace("%s", $this->Event_Title->caption(), $this->Event_Title->RequiredErrorMessage));
            }
        }
        if ($this->Event_Color->Required) {
            if (!$this->Event_Color->IsDetailKey && EmptyValue($this->Event_Color->FormValue)) {
                $this->Event_Color->addErrorMessage(str_replace("%s", $this->Event_Color->caption(), $this->Event_Color->RequiredErrorMessage));
            }
        }
        if ($this->Event_Start->Required) {
            if (!$this->Event_Start->IsDetailKey && EmptyValue($this->Event_Start->FormValue)) {
                $this->Event_Start->addErrorMessage(str_replace("%s", $this->Event_Start->caption(), $this->Event_Start->RequiredErrorMessage));
            }
        }
        if (!CheckDate($this->Event_Start->FormValue, $this->Event_Start->formatPattern())) {
            $this->Event_Start->addErrorMessage($this->Event_Start->getErrorMessage(false));
        }
        if ($this->Event_End->Required) {
            if (!$this->Event_End->IsDetailKey && EmptyValue($this->Event_End->FormValue)) {
                $this->Event_End->addErrorMessage(str_replace("%s", $this->Event_End->caption(), $this->Event_End->RequiredErrorMessage));
            }
        }
        if (!CheckDate($this->Event_End->FormValue, $this->Event_End->formatPattern())) {
            $this->Event_End->addErrorMessage($this->Event_End->getErrorMessage(false));
        }
        if ($this->Event_Description->Required) {
            if (!$this->Event_Description->IsDetailKey && EmptyValue($this->Event_Description->FormValue)) {
                $this->Event_Description->addErrorMessage(str_replace("%s", $this->Event_Description->caption(), $this->Event_Description->RequiredErrorMessage));
            }
        }
        if ($this->Event_User->Required) {
            if (!$this->Event_User->IsDetailKey && EmptyValue($this->Event_User->FormValue)) {
                $this->Event_User->addErrorMessage(str_replace("%s", $this->Event_User->caption(), $this->Event_User->RequiredErrorMessage));
            }
        }
        if ($this->Repeat_Type->Required) {
            if (!$this->Repeat_Type->IsDetailKey && EmptyValue($this->Repeat_Type->FormValue)) {
                $this->Repeat_Type->addErrorMessage(str_replace("%s", $this->Repeat_Type->caption(), $this->Repeat_Type->RequiredErrorMessage));
            }
        }
        if ($this->Repeat_ID->Required) {
            if (!$this->Repeat_ID->IsDetailKey && EmptyValue($this->Repeat_ID->FormValue)) {
                $this->Repeat_ID->addErrorMessage(str_replace("%s", $this->Repeat_ID->caption(), $this->Repeat_ID->RequiredErrorMessage));
            }
        }
        if (!CheckInteger($this->Repeat_ID->FormValue)) {
            $this->Repeat_ID->addErrorMessage($this->Repeat_ID->getErrorMessage(false));
        }
        if ($this->Event_AllDay->Required) {
            if (!$this->Event_AllDay->IsDetailKey && EmptyValue($this->Event_AllDay->FormValue)) {
                $this->Event_AllDay->addErrorMessage(str_replace("%s", $this->Event_AllDay->caption(), $this->Event_AllDay->RequiredErrorMessage));
            }
        }
        if ($this->Event_URL->Required) {
            if (!$this->Event_URL->IsDetailKey && EmptyValue($this->Event_URL->FormValue)) {
                $this->Event_URL->addErrorMessage(str_replace("%s", $this->Event_URL->caption(), $this->Event_URL->RequiredErrorMessage));
            }
        }
        if ($this->Event_Category->Required) {
            if (!$this->Event_Category->IsDetailKey && EmptyValue($this->Event_Category->FormValue)) {
                $this->Event_Category->addErrorMessage(str_replace("%s", $this->Event_Category->caption(), $this->Event_Category->RequiredErrorMessage));
            }
        }
        if ($this->Event_Timezone->Required) {
            if (!$this->Event_Timezone->IsDetailKey && EmptyValue($this->Event_Timezone->FormValue)) {
                $this->Event_Timezone->addErrorMessage(str_replace("%s", $this->Event_Timezone->caption(), $this->Event_Timezone->RequiredErrorMessage));
            }
        }
        if ($this->Added_By->Required) {
            if (!$this->Added_By->IsDetailKey && EmptyValue($this->Added_By->FormValue)) {
                $this->Added_By->addErrorMessage(str_replace("%s", $this->Added_By->caption(), $this->Added_By->RequiredErrorMessage));
            }
        }
        if ($this->Date_Added->Required) {
            if (!$this->Date_Added->IsDetailKey && EmptyValue($this->Date_Added->FormValue)) {
                $this->Date_Added->addErrorMessage(str_replace("%s", $this->Date_Added->caption(), $this->Date_Added->RequiredErrorMessage));
            }
        }
        if (!CheckDate($this->Date_Added->FormValue, $this->Date_Added->formatPattern())) {
            $this->Date_Added->addErrorMessage($this->Date_Added->getErrorMessage(false));
        }
        if ($this->Updated_By->Required) {
            if (!$this->Updated_By->IsDetailKey && EmptyValue($this->Updated_By->FormValue)) {
                $this->Updated_By->addErrorMessage(str_replace("%s", $this->Updated_By->caption(), $this->Updated_By->RequiredErrorMessage));
            }
        }
        if ($this->Date_Updated->Required) {
            if (!$this->Date_Updated->IsDetailKey && EmptyValue($this->Date_Updated->FormValue)) {
                $this->Date_Updated->addErrorMessage(str_replace("%s", $this->Date_Updated->caption(), $this->Date_Updated->RequiredErrorMessage));
            }
        }
        if (!CheckDate($this->Date_Updated->FormValue, $this->Date_Updated->formatPattern())) {
            $this->Date_Updated->addErrorMessage($this->Date_Updated->getErrorMessage(false));
        }

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

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

    // Add record
    protected function addRow($rsold = null)
    {
        global $Language, $Security;

        // Set new row
        $rsnew = [];

        // Event_Title
        $this->Event_Title->setDbValueDef($rsnew, $this->Event_Title->CurrentValue, false);

        // Event_Color
        $this->Event_Color->setDbValueDef($rsnew, $this->Event_Color->CurrentValue, false);

        // Event_Start
        $this->Event_Start->setDbValueDef($rsnew, UnFormatDateTime($this->Event_Start->CurrentValue, $this->Event_Start->formatPattern()), false);

        // Event_End
        $this->Event_End->setDbValueDef($rsnew, UnFormatDateTime($this->Event_End->CurrentValue, $this->Event_End->formatPattern()), false);

        // Event_Description
        $this->Event_Description->setDbValueDef($rsnew, $this->Event_Description->CurrentValue, false);

        // Event_User
        $this->Event_User->setDbValueDef($rsnew, $this->Event_User->CurrentValue, false);

        // Repeat_Type
        $this->Repeat_Type->setDbValueDef($rsnew, $this->Repeat_Type->CurrentValue, false);

        // Repeat_ID
        $this->Repeat_ID->setDbValueDef($rsnew, $this->Repeat_ID->CurrentValue, false);

        // Event_AllDay
        $this->Event_AllDay->setDbValueDef($rsnew, $this->Event_AllDay->CurrentValue, false);

        // Event_URL
        $this->Event_URL->setDbValueDef($rsnew, $this->Event_URL->CurrentValue, false);

        // Event_Category
        $this->Event_Category->setDbValueDef($rsnew, $this->Event_Category->CurrentValue, false);

        // Event_Timezone
        $this->Event_Timezone->setDbValueDef($rsnew, $this->Event_Timezone->CurrentValue, false);

        // Added_By
        $this->Added_By->setDbValueDef($rsnew, $this->Added_By->CurrentValue, false);

        // Date_Added
        $this->Date_Added->setDbValueDef($rsnew, UnFormatDateTime($this->Date_Added->CurrentValue, $this->Date_Added->formatPattern()), false);

        // Updated_By
        $this->Updated_By->setDbValueDef($rsnew, $this->Updated_By->CurrentValue, false);

        // Date_Updated
        $this->Date_Updated->setDbValueDef($rsnew, UnFormatDateTime($this->Date_Updated->CurrentValue, $this->Date_Updated->formatPattern()), false);

        // Update current values
        $this->setCurrentValues($rsnew);
        $conn = $this->getConnection();

        // Load db values from old row
        $this->loadDbValues($rsold);

        // Call Row Inserting event
        $insertRow = $this->rowInserting($rsold, $rsnew);
        if ($insertRow) {
            $addRow = $this->insert($rsnew);
            if ($addRow) {
            } elseif (!EmptyValue($this->DbErrorMessage)) { // Show database error
                $this->setFailureMessage($this->DbErrorMessage);
            }
        } else {
            if ($this->getSuccessMessage() != "" || $this->getFailureMessage() != "") {
                // Use the message, do nothing
            } elseif ($this->CancelMessage != "") {
                $this->setFailureMessage($this->CancelMessage);
                $this->CancelMessage = "";
            } else {
                $this->setFailureMessage($Language->phrase("InsertCancelled"));
            }
            $addRow = false;
        }
        if ($addRow) {
            // Call Row Inserted event
            $this->rowInserted($rsold, $rsnew);
        }

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

    // Set up Breadcrumb
    protected function setupBreadcrumb()
    {
        global $Breadcrumb, $Language;
        $Breadcrumb = new Breadcrumb("index");
        $url = CurrentUrl();
        $Breadcrumb->add("list", $this->TableVar, $this->addMasterUrl("eventslist"), "", $this->TableVar, true);
        $pageId = ($this->isCopy()) ? "Copy" : "Add";
        $Breadcrumb->add("add", $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) {
                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;
    }
}
