<?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 StudentEdit extends Student
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

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

    // Rendering View
    public $RenderingView = false;

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

    // Audit Trail
    public $AuditTrailOnAdd = true;
    public $AuditTrailOnEdit = true;
    public $AuditTrailOnDelete = true;
    public $AuditTrailOnView = false;
    public $AuditTrailOnViewData = false;
    public $AuditTrailOnSearch = false;

    // 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->studentID->setVisibility();
        $this->PIN->setVisibility();
        $this->Last_Name->setVisibility();
        $this->First_Name->setVisibility();
        $this->Gender->setVisibility();
        $this->Date_Of_Birth->setVisibility();
        $this->Place_Of_Birth->setVisibility();
        $this->Card_No->setVisibility();
        $this->Unique_QR->setVisibility();
        $this->Photo->setVisibility();
        $this->Address->setVisibility();
        $this->Start_Date->setVisibility();
        $this->Expiry_Date->setVisibility();
        $this->SClass->setVisibility();
        $this->Contact_Incase->setVisibility();
        $this->Contact_Tel->setVisibility();
        $this->Reference->setVisibility();
        $this->EmployeeID->setVisibility();
        $this->Status->setVisibility();
    }

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

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

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

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

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

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

        // 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 == "studentview"; // 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
                $this->Photo->OldUploadPath = $this->Photo->getUploadPath(); // PHP
                $this->Photo->UploadPath = $this->Photo->OldUploadPath;
                $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['studentID'];
        }
        return $key;
    }

    /**
     * Hide fields for add/edit
     *
     * @return void
     */
    protected function hideFieldsForAddEdit()
    {
    }

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

    // Properties
    public $FormClassName = "ew-form ew-edit-form overlay-wrapper";
    public $IsModal = false;
    public $IsMobileOrModal = false;
    public $DbMasterFilter;
    public $DbDetailFilter;
    public $HashValue; // Hash Value
    public $DisplayRecords = 1;
    public $StartRecord;
    public $StopRecord;
    public $TotalRecords = 0;
    public $RecordRange = 10;
    public $RecordCount;
    public $MultiPages; // Multi pages object

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

        // Set up multi page object
        $this->setupMultiPages();

        // 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->Gender);
        $this->setupLookupOptions($this->Status);
		My_Global_Check(); // Modified by Unique Digital Solutions Ltd, October 6, 2021

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

        // Load record by position
        $loadByPosition = false;
        $loaded = false;
        $postBack = false;

        // Set up current action and primary key
        if (IsApi()) {
            // Load key values
            $loaded = true;
            if (($keyValue = Get("studentID") ?? Key(0) ?? Route(2)) !== null) {
                $this->studentID->setQueryStringValue($keyValue);
                $this->studentID->setOldValue($this->studentID->QueryStringValue);
            } elseif (Post("studentID") !== null) {
                $this->studentID->setFormValue(Post("studentID"));
                $this->studentID->setOldValue($this->studentID->FormValue);
            } else {
                $loaded = false; // Unable to load key
            }

            // Load record
            if ($loaded) {
                $loaded = $this->loadRow();
            }
            if (!$loaded) {
                $this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
                $this->terminate();
                return;
            }
            $this->CurrentAction = "update"; // Update record directly
            $this->OldKey = $this->getKey(true); // Get from CurrentValue
            $postBack = true;
        } else {
            if (Post("action", "") !== "") {
                $this->CurrentAction = Post("action"); // Get action code
                if (!$this->isShow()) { // Not reload record, handle as postback
                    $postBack = true;
                }

                // Get key from Form
                $this->setKey(Post($this->OldKeyName), $this->isShow());
            } else {
                $this->CurrentAction = "show"; // Default action is display

                // Load key from QueryString
                $loadByQuery = false;
                if (($keyValue = Get("studentID") ?? Route("studentID")) !== null) {
                    $this->studentID->setQueryStringValue($keyValue);
                    $loadByQuery = true;
                } else {
                    $this->studentID->CurrentValue = null;
                }
                if (!$loadByQuery || Get(Config("TABLE_START_REC")) !== null || Get(Config("TABLE_PAGE_NUMBER")) !== null) {
                    $loadByPosition = true;
                }
            }

            // Load recordset
            if ($this->isShow()) {
                if (!$this->IsModal) { // Normal edit page
                    $this->StartRecord = 1; // Initialize start position
                    if ($rs = $this->loadRecordset()) { // Load records
                        $this->TotalRecords = $rs->recordCount(); // Get record count
                    }
                    if ($this->TotalRecords <= 0) { // No record found
                        if ($this->getSuccessMessage() == "" && $this->getFailureMessage() == "") {
                            $this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
                        }
                        $this->terminate("studentlist"); // Return to list page
                        return;
                    } elseif ($loadByPosition) { // Load record by position
                        $this->setupStartRecord(); // Set up start record position
                        // Point to current record
                        if ($this->StartRecord <= $this->TotalRecords) {
                            $rs->move($this->StartRecord - 1);
                            // Redirect to correct record
                            $this->loadRowValues($rs);
                            $url = $this->getCurrentUrl();
                            $this->terminate($url);
                            return;
                        }
                    } else { // Match key values
                        if ($this->studentID->CurrentValue != null) {
                            while (!$rs->EOF) {
                                if (SameString($this->studentID->CurrentValue, $rs->fields['studentID'])) {
                                    $this->setStartRecordNumber($this->StartRecord); // Save record position
                                    $loaded = true;
                                    break;
                                } else {
                                    $this->StartRecord++;
                                    $rs->moveNext();
                                }
                            }
                        }
                    }

                    // Load current row values
                    if ($loaded) {
                        $this->loadRowValues($rs);
                    }
                } else {
                    // Load current record
                    $loaded = $this->loadRow();
                } // End modal checking
                $this->OldKey = $loaded ? $this->getKey(true) : ""; // Get from CurrentValue
            }
        }

        // Process form if post back
        if ($postBack) {
            $this->loadFormValues(); // Get form values

            // Overwrite record, reload hash value
            if ($this->isOverwrite()) {
                $this->loadRowHash();
                $this->CurrentAction = "confirm";
            }
        }

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

        // Perform current action
        switch ($this->CurrentAction) {
            case "show": // Get a record to display
                if (!$this->IsModal) { // Normal edit page
                    if (!$loaded) {
                        if ($this->getSuccessMessage() == "" && $this->getFailureMessage() == "") {
                            $this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
                        }
                        $this->terminate("studentlist"); // Return to list page
                        return;
                    } else {
                        $this->HashValue = $this->getRowHash($rs); // Get hash value for record
                    }
                } else { // Modal edit page
                    if (!$loaded) { // Load record based on key
                        if ($this->getFailureMessage() == "") {
                            $this->setFailureMessage($Language->phrase("NoRecord")); // No record found
                        }
                        $this->terminate("studentlist"); // No matching record, return to list
                        return;
                    }
                } // End modal checking
                break;
            case "update": // Update
                $returnUrl = "studentlist";
                if (GetPageName($returnUrl) == "studentlist") {
                    $returnUrl = $this->addMasterUrl($returnUrl); // List page, return to List page with correct master key if necessary
                }
                $this->SendEmail = true; // Send email on update success
                if ($this->editRow()) {
                    // Handle UseAjaxActions with return page
                    if ($this->IsModal && $this->UseAjaxActions) {
                        $this->IsModal = false;
                        if (GetPageName($returnUrl) != "studentlist") {
                            Container("flash")->addMessage("Return-Url", $returnUrl); // Save return URL
                            $returnUrl = "studentlist"; // Return list page content
                        }
                    }
                    if ($this->getSuccessMessage() == "") {
                        $this->setSuccessMessage($Language->phrase("UpdateSuccess")); // Update success
                    }
                    if (IsJsonResponse()) {
                        $this->terminate(true);
                        return;
                    } else {
                        $this->terminate($returnUrl); // Return to caller
                        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;
                } elseif ($this->getFailureMessage() == $Language->phrase("NoRecord")) {
                    $this->terminate($returnUrl); // Return to caller
                    return;
                } else {
                    $this->EventCancelled = true; // Event cancelled
                    $this->restoreFormValues(); // Restore form values if update failed
                }
        }

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

        // Render the record
        if ($this->isConfirm()) { // Confirm page
            $this->RowType = ROWTYPE_VIEW; // Render as View
        } else {
            $this->RowType = ROWTYPE_EDIT; // Render as Edit
        }
        $this->resetAttributes();
        $this->renderRow();
        if (!$this->IsModal) { // Normal view page
            $this->Pager = new PrevNextPager($this, $this->StartRecord, $this->DisplayRecords, $this->TotalRecords, "", $this->RecordRange, $this->AutoHidePager, false, false);
            $this->Pager->PageNumberName = Config("TABLE_PAGE_NUMBER");
            $this->Pager->PagePhraseId = "Record"; // Show as record
        }

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

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

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

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

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

// Get upload files
    protected function getUploadFiles()
    {
        global $CurrentForm, $Language;
        $this->Photo->Upload->Index = $CurrentForm->Index;
        $this->Photo->Upload->uploadFile();
        $this->Photo->CurrentValue = $this->Photo->Upload->FileName;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // Check field name 'Status' first before field var 'x_Status'
        $val = $CurrentForm->hasValue("Status") ? $CurrentForm->getValue("Status") : $CurrentForm->getValue("x_Status");
        if (!$this->Status->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->Status->Visible = false; // Disable update for API request
            } else {
                $this->Status->setFormValue($val);
            }
        }
		$this->Photo->OldUploadPath = $this->Photo->getUploadPath(); // PHP
		$this->Photo->UploadPath = $this->Photo->OldUploadPath;
        $this->getUploadFiles(); // Get upload files
        if (!$this->isOverwrite()) {
            $this->HashValue = $CurrentForm->getValue("k_hash");
        }
    }

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->studentID->CurrentValue = $this->studentID->FormValue;
        $this->PIN->CurrentValue = $this->PIN->FormValue;
        $this->Last_Name->CurrentValue = $this->Last_Name->FormValue;
        $this->First_Name->CurrentValue = $this->First_Name->FormValue;
        $this->Gender->CurrentValue = $this->Gender->FormValue;
        $this->Date_Of_Birth->CurrentValue = $this->Date_Of_Birth->FormValue;
        $this->Date_Of_Birth->CurrentValue = UnFormatDateTime($this->Date_Of_Birth->CurrentValue, $this->Date_Of_Birth->formatPattern());
        $this->Place_Of_Birth->CurrentValue = $this->Place_Of_Birth->FormValue;
        $this->Card_No->CurrentValue = $this->Card_No->FormValue;
        $this->Unique_QR->CurrentValue = $this->Unique_QR->FormValue;
        $this->Address->CurrentValue = $this->Address->FormValue;
        $this->Start_Date->CurrentValue = $this->Start_Date->FormValue;
        $this->Start_Date->CurrentValue = UnFormatDateTime($this->Start_Date->CurrentValue, $this->Start_Date->formatPattern());
        $this->Expiry_Date->CurrentValue = $this->Expiry_Date->FormValue;
        $this->Expiry_Date->CurrentValue = UnFormatDateTime($this->Expiry_Date->CurrentValue, $this->Expiry_Date->formatPattern());
        $this->SClass->CurrentValue = $this->SClass->FormValue;
        $this->Contact_Incase->CurrentValue = $this->Contact_Incase->FormValue;
        $this->Contact_Tel->CurrentValue = $this->Contact_Tel->FormValue;
        $this->Reference->CurrentValue = $this->Reference->FormValue;
        $this->EmployeeID->CurrentValue = $this->EmployeeID->FormValue;
        $this->Status->CurrentValue = $this->Status->FormValue;
        if (!$this->isOverwrite()) {
            $this->HashValue = $CurrentForm->getValue("k_hash");
        }
    }

    // Load recordset
    public function loadRecordset($offset = -1, $rowcnt = -1)
    {
        // Load List page SQL (QueryBuilder)
        $sql = $this->getListSql();

        // Load recordset
        if ($offset > -1) {
            $sql->setFirstResult($offset);
        }
        if ($rowcnt > 0) {
            $sql->setMaxResults($rowcnt);
        }
        $result = $sql->execute();
        $rs = new Recordset($result, $sql);

        // Call Recordset Selected event
        $this->recordsetSelected($rs);
        return $rs;
    }

    // Load records as associative array
    public function loadRows($offset = -1, $rowcnt = -1)
    {
        // Load List page SQL (QueryBuilder)
        $sql = $this->getListSql();

        // Load recordset
        if ($offset > -1) {
            $sql->setFirstResult($offset);
        }
        if ($rowcnt > 0) {
            $sql->setMaxResults($rowcnt);
        }
        $result = $sql->execute();
        return $result->fetchAllAssociative();
    }

    /**
     * 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
            if (!$this->EventCancelled) {
                $this->HashValue = $this->getRowHash($row); // Get hash value for record
            }
        }
        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->studentID->setDbValue($row['studentID']);
        $this->PIN->setDbValue($row['PIN']);
        $this->Last_Name->setDbValue($row['Last_Name']);
        $this->First_Name->setDbValue($row['First_Name']);
        $this->Gender->setDbValue($row['Gender']);
        $this->Date_Of_Birth->setDbValue($row['Date_Of_Birth']);
        $this->Place_Of_Birth->setDbValue($row['Place_Of_Birth']);
        $this->Card_No->setDbValue($row['Card_No']);
        $this->Unique_QR->setDbValue($row['Unique_QR']);
        $this->Photo->Upload->DbValue = $row['Photo'];
        $this->Photo->setDbValue($this->Photo->Upload->DbValue);
        $this->Address->setDbValue($row['Address']);
        $this->Start_Date->setDbValue($row['Start_Date']);
        $this->Expiry_Date->setDbValue($row['Expiry_Date']);
        $this->SClass->setDbValue($row['SClass']);
        $this->Contact_Incase->setDbValue($row['Contact_Incase']);
        $this->Contact_Tel->setDbValue($row['Contact_Tel']);
        $this->Reference->setDbValue($row['Reference']);
        $this->EmployeeID->setDbValue($row['EmployeeID']);
        $this->Status->setDbValue($row['Status']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $row = [];
        $row['studentID'] = $this->studentID->DefaultValue;
        $row['PIN'] = $this->PIN->DefaultValue;
        $row['Last_Name'] = $this->Last_Name->DefaultValue;
        $row['First_Name'] = $this->First_Name->DefaultValue;
        $row['Gender'] = $this->Gender->DefaultValue;
        $row['Date_Of_Birth'] = $this->Date_Of_Birth->DefaultValue;
        $row['Place_Of_Birth'] = $this->Place_Of_Birth->DefaultValue;
        $row['Card_No'] = $this->Card_No->DefaultValue;
        $row['Unique_QR'] = $this->Unique_QR->DefaultValue;
        $row['Photo'] = $this->Photo->DefaultValue;
        $row['Address'] = $this->Address->DefaultValue;
        $row['Start_Date'] = $this->Start_Date->DefaultValue;
        $row['Expiry_Date'] = $this->Expiry_Date->DefaultValue;
        $row['SClass'] = $this->SClass->DefaultValue;
        $row['Contact_Incase'] = $this->Contact_Incase->DefaultValue;
        $row['Contact_Tel'] = $this->Contact_Tel->DefaultValue;
        $row['Reference'] = $this->Reference->DefaultValue;
        $row['EmployeeID'] = $this->EmployeeID->DefaultValue;
        $row['Status'] = $this->Status->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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Gender
            if (strval($this->Gender->CurrentValue) != "") {
                $this->Gender->ViewValue = $this->Gender->optionCaption($this->Gender->CurrentValue);
            } else {
                $this->Gender->ViewValue = null;
            }

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

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

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

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

            // Photo
            $this->Photo->UploadPath = $this->Photo->getUploadPath(); // PHP
            if (!EmptyValue($this->Photo->Upload->DbValue)) {
                $this->Photo->ImageWidth = 100;
                $this->Photo->ImageHeight = 100;
                $this->Photo->ImageAlt = $this->Photo->alt();
                $this->Photo->ImageCssClass = "ew-image";
                $this->Photo->ViewValue = $this->Photo->Upload->DbValue;
            } else {
                $this->Photo->ViewValue = "";
            }

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

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

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

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

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

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

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

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

            // Status
            if (strval($this->Status->CurrentValue) != "") {
                $this->Status->ViewValue = $this->Status->optionCaption($this->Status->CurrentValue);
            } else {
                $this->Status->ViewValue = null;
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Status
            $this->Status->HrefValue = "";
        } elseif ($this->RowType == ROWTYPE_EDIT) {
            // studentID
            $this->studentID->setupEditAttributes();
            $this->studentID->EditValue = HtmlEncode($this->studentID->CurrentValue);
            $this->studentID->PlaceHolder = RemoveHtml($this->studentID->caption());

            // PIN
            $this->PIN->setupEditAttributes();
            if (!$this->PIN->Raw) {
                $this->PIN->CurrentValue = HtmlDecode($this->PIN->CurrentValue);
            }
            $this->PIN->EditValue = HtmlEncode($this->PIN->CurrentValue);
            $arwrk = [];
            $arwrk["lf"] = $this->PIN->CurrentValue;
            $arwrk["df"] = $this->PIN->CurrentValue;
            $arwrk = $this->PIN->Lookup->renderViewRow($arwrk, $this);
            $dispVal = $this->PIN->displayValue($arwrk);
            if ($dispVal != "") {
                $this->PIN->EditValue = $dispVal;
            }
            $this->PIN->PlaceHolder = RemoveHtml($this->PIN->caption());

            // Last_Name
            $this->Last_Name->setupEditAttributes();
            if (!$this->Last_Name->Raw) {
                $this->Last_Name->CurrentValue = HtmlDecode($this->Last_Name->CurrentValue);
            }
            $this->Last_Name->EditValue = HtmlEncode($this->Last_Name->CurrentValue);
            $arwrk = [];
            $arwrk["lf"] = $this->Last_Name->CurrentValue;
            $arwrk["df"] = $this->Last_Name->CurrentValue;
            $arwrk = $this->Last_Name->Lookup->renderViewRow($arwrk, $this);
            $dispVal = $this->Last_Name->displayValue($arwrk);
            if ($dispVal != "") {
                $this->Last_Name->EditValue = $dispVal;
            }
            $this->Last_Name->PlaceHolder = RemoveHtml($this->Last_Name->caption());

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

            // Gender
            $this->Gender->setupEditAttributes();
            $this->Gender->EditValue = $this->Gender->options(true);
            $this->Gender->PlaceHolder = RemoveHtml($this->Gender->caption());

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

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

            // Card_No
            $this->Card_No->setupEditAttributes();
            if (!$this->Card_No->Raw) {
                $this->Card_No->CurrentValue = HtmlDecode($this->Card_No->CurrentValue);
            }
            $this->Card_No->EditValue = HtmlEncode($this->Card_No->CurrentValue);
            $arwrk = [];
            $arwrk["lf"] = $this->Card_No->CurrentValue;
            $arwrk["df"] = $this->Card_No->CurrentValue;
            $arwrk = $this->Card_No->Lookup->renderViewRow($arwrk, $this);
            $dispVal = $this->Card_No->displayValue($arwrk);
            if ($dispVal != "") {
                $this->Card_No->EditValue = $dispVal;
            }
            $this->Card_No->PlaceHolder = RemoveHtml($this->Card_No->caption());

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

            // Photo
            $this->Photo->setupEditAttributes();
            $this->Photo->UploadPath = $this->Photo->getUploadPath(); // PHP
            if (!EmptyValue($this->Photo->Upload->DbValue)) {
                $this->Photo->ImageWidth = 100;
                $this->Photo->ImageHeight = 100;
                $this->Photo->ImageAlt = $this->Photo->alt();
                $this->Photo->ImageCssClass = "ew-image";
                $this->Photo->EditValue = $this->Photo->Upload->DbValue;
            } else {
                $this->Photo->EditValue = "";
            }
            if (!EmptyValue($this->Photo->CurrentValue)) {
                $this->Photo->Upload->FileName = $this->Photo->CurrentValue;
            }
            if ($this->isShow()) {
                RenderUploadField($this->Photo);
            }

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

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

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

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

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

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

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

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

            // Status
            $this->Status->setupEditAttributes();
            $this->Status->EditValue = $this->Status->options(true);
            $this->Status->PlaceHolder = RemoveHtml($this->Status->caption());

            // Edit refer script

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Status
            $this->Status->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->studentID->Required) {
            if (!$this->studentID->IsDetailKey && EmptyValue($this->studentID->FormValue)) {
                $this->studentID->addErrorMessage(str_replace("%s", $this->studentID->caption(), $this->studentID->RequiredErrorMessage));
            }
        }
        if (!CheckInteger($this->studentID->FormValue)) {
            $this->studentID->addErrorMessage($this->studentID->getErrorMessage(false));
        }
        if ($this->PIN->Required) {
            if (!$this->PIN->IsDetailKey && EmptyValue($this->PIN->FormValue)) {
                $this->PIN->addErrorMessage(str_replace("%s", $this->PIN->caption(), $this->PIN->RequiredErrorMessage));
            }
        }
        if ($this->Last_Name->Required) {
            if (!$this->Last_Name->IsDetailKey && EmptyValue($this->Last_Name->FormValue)) {
                $this->Last_Name->addErrorMessage(str_replace("%s", $this->Last_Name->caption(), $this->Last_Name->RequiredErrorMessage));
            }
        }
        if ($this->First_Name->Required) {
            if (!$this->First_Name->IsDetailKey && EmptyValue($this->First_Name->FormValue)) {
                $this->First_Name->addErrorMessage(str_replace("%s", $this->First_Name->caption(), $this->First_Name->RequiredErrorMessage));
            }
        }
        if ($this->Gender->Required) {
            if (!$this->Gender->IsDetailKey && EmptyValue($this->Gender->FormValue)) {
                $this->Gender->addErrorMessage(str_replace("%s", $this->Gender->caption(), $this->Gender->RequiredErrorMessage));
            }
        }
        if ($this->Date_Of_Birth->Required) {
            if (!$this->Date_Of_Birth->IsDetailKey && EmptyValue($this->Date_Of_Birth->FormValue)) {
                $this->Date_Of_Birth->addErrorMessage(str_replace("%s", $this->Date_Of_Birth->caption(), $this->Date_Of_Birth->RequiredErrorMessage));
            }
        }
        if (!CheckDate($this->Date_Of_Birth->FormValue, $this->Date_Of_Birth->formatPattern())) {
            $this->Date_Of_Birth->addErrorMessage($this->Date_Of_Birth->getErrorMessage(false));
        }
        if ($this->Place_Of_Birth->Required) {
            if (!$this->Place_Of_Birth->IsDetailKey && EmptyValue($this->Place_Of_Birth->FormValue)) {
                $this->Place_Of_Birth->addErrorMessage(str_replace("%s", $this->Place_Of_Birth->caption(), $this->Place_Of_Birth->RequiredErrorMessage));
            }
        }
        if ($this->Card_No->Required) {
            if (!$this->Card_No->IsDetailKey && EmptyValue($this->Card_No->FormValue)) {
                $this->Card_No->addErrorMessage(str_replace("%s", $this->Card_No->caption(), $this->Card_No->RequiredErrorMessage));
            }
        }
        if ($this->Unique_QR->Required) {
            if (!$this->Unique_QR->IsDetailKey && EmptyValue($this->Unique_QR->FormValue)) {
                $this->Unique_QR->addErrorMessage(str_replace("%s", $this->Unique_QR->caption(), $this->Unique_QR->RequiredErrorMessage));
            }
        }
        if ($this->Photo->Required) {
            if ($this->Photo->Upload->FileName == "" && !$this->Photo->Upload->KeepFile) {
                $this->Photo->addErrorMessage(str_replace("%s", $this->Photo->caption(), $this->Photo->RequiredErrorMessage));
            }
        }
        if ($this->Address->Required) {
            if (!$this->Address->IsDetailKey && EmptyValue($this->Address->FormValue)) {
                $this->Address->addErrorMessage(str_replace("%s", $this->Address->caption(), $this->Address->RequiredErrorMessage));
            }
        }
        if ($this->Start_Date->Required) {
            if (!$this->Start_Date->IsDetailKey && EmptyValue($this->Start_Date->FormValue)) {
                $this->Start_Date->addErrorMessage(str_replace("%s", $this->Start_Date->caption(), $this->Start_Date->RequiredErrorMessage));
            }
        }
        if (!CheckDate($this->Start_Date->FormValue, $this->Start_Date->formatPattern())) {
            $this->Start_Date->addErrorMessage($this->Start_Date->getErrorMessage(false));
        }
        if ($this->Expiry_Date->Required) {
            if (!$this->Expiry_Date->IsDetailKey && EmptyValue($this->Expiry_Date->FormValue)) {
                $this->Expiry_Date->addErrorMessage(str_replace("%s", $this->Expiry_Date->caption(), $this->Expiry_Date->RequiredErrorMessage));
            }
        }
        if (!CheckDate($this->Expiry_Date->FormValue, $this->Expiry_Date->formatPattern())) {
            $this->Expiry_Date->addErrorMessage($this->Expiry_Date->getErrorMessage(false));
        }
        if ($this->SClass->Required) {
            if (!$this->SClass->IsDetailKey && EmptyValue($this->SClass->FormValue)) {
                $this->SClass->addErrorMessage(str_replace("%s", $this->SClass->caption(), $this->SClass->RequiredErrorMessage));
            }
        }
        if ($this->Contact_Incase->Required) {
            if (!$this->Contact_Incase->IsDetailKey && EmptyValue($this->Contact_Incase->FormValue)) {
                $this->Contact_Incase->addErrorMessage(str_replace("%s", $this->Contact_Incase->caption(), $this->Contact_Incase->RequiredErrorMessage));
            }
        }
        if ($this->Contact_Tel->Required) {
            if (!$this->Contact_Tel->IsDetailKey && EmptyValue($this->Contact_Tel->FormValue)) {
                $this->Contact_Tel->addErrorMessage(str_replace("%s", $this->Contact_Tel->caption(), $this->Contact_Tel->RequiredErrorMessage));
            }
        }
        if ($this->Reference->Required) {
            if (!$this->Reference->IsDetailKey && EmptyValue($this->Reference->FormValue)) {
                $this->Reference->addErrorMessage(str_replace("%s", $this->Reference->caption(), $this->Reference->RequiredErrorMessage));
            }
        }
        if ($this->EmployeeID->Required) {
            if (!$this->EmployeeID->IsDetailKey && EmptyValue($this->EmployeeID->FormValue)) {
                $this->EmployeeID->addErrorMessage(str_replace("%s", $this->EmployeeID->caption(), $this->EmployeeID->RequiredErrorMessage));
            }
        }
        if (!CheckInteger($this->EmployeeID->FormValue)) {
            $this->EmployeeID->addErrorMessage($this->EmployeeID->getErrorMessage(false));
        }
        if ($this->Status->Required) {
            if (!$this->Status->IsDetailKey && EmptyValue($this->Status->FormValue)) {
                $this->Status->addErrorMessage(str_replace("%s", $this->Status->caption(), $this->Status->RequiredErrorMessage));
            }
        }

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

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

    // Update record based on key values
    protected function editRow()
    {
        global $Security, $Language;
        $oldKeyFilter = $this->getRecordFilter();
        $filter = $this->applyUserIDFilters($oldKeyFilter);
        $conn = $this->getConnection();

        // Load old row
        $this->CurrentFilter = $filter;
        $sql = $this->getCurrentSql();
        $rsold = $conn->fetchAssociative($sql);
        if (!$rsold) {
            $this->setFailureMessage($Language->phrase("NoRecord")); // Set no record message
            return false; // Update Failed
        } else {
            // Save old values
            $this->loadDbValues($rsold);
            $this->Photo->OldUploadPath = $this->Photo->getUploadPath(); // PHP
            $this->Photo->UploadPath = $this->Photo->OldUploadPath;
        }

        // Set new row
        $rsnew = [];

        // studentID
        $this->studentID->setDbValueDef($rsnew, $this->studentID->CurrentValue, $this->studentID->ReadOnly);

        // PIN
        $this->PIN->setDbValueDef($rsnew, $this->PIN->CurrentValue, $this->PIN->ReadOnly);

        // Last_Name
        $this->Last_Name->setDbValueDef($rsnew, $this->Last_Name->CurrentValue, $this->Last_Name->ReadOnly);

        // First_Name
        $this->First_Name->setDbValueDef($rsnew, $this->First_Name->CurrentValue, $this->First_Name->ReadOnly);

        // Gender
        $this->Gender->setDbValueDef($rsnew, $this->Gender->CurrentValue, $this->Gender->ReadOnly);

        // Date_Of_Birth
        $this->Date_Of_Birth->setDbValueDef($rsnew, UnFormatDateTime($this->Date_Of_Birth->CurrentValue, $this->Date_Of_Birth->formatPattern()), $this->Date_Of_Birth->ReadOnly);

        // Place_Of_Birth
        $this->Place_Of_Birth->setDbValueDef($rsnew, $this->Place_Of_Birth->CurrentValue, $this->Place_Of_Birth->ReadOnly);

        // Card_No
        $this->Card_No->setDbValueDef($rsnew, $this->Card_No->CurrentValue, $this->Card_No->ReadOnly);

        // Unique_QR
        $this->Unique_QR->setDbValueDef($rsnew, $this->Unique_QR->CurrentValue, $this->Unique_QR->ReadOnly);

        // Photo
        if ($this->Photo->Visible && !$this->Photo->ReadOnly && !$this->Photo->Upload->KeepFile) {
            $this->Photo->Upload->DbValue = $rsold['Photo']; // Get original value
            if ($this->Photo->Upload->FileName == "") {
                $rsnew['Photo'] = null;
            } else {
                $rsnew['Photo'] = $this->Photo->Upload->FileName;
            }
            $this->Photo->ImageWidth = 283; // Resize width
            $this->Photo->ImageHeight = 425; // Resize height
        }

        // Address
        $this->Address->setDbValueDef($rsnew, $this->Address->CurrentValue, $this->Address->ReadOnly);

        // Start_Date
        $this->Start_Date->setDbValueDef($rsnew, UnFormatDateTime($this->Start_Date->CurrentValue, $this->Start_Date->formatPattern()), $this->Start_Date->ReadOnly);

        // Expiry_Date
        $this->Expiry_Date->setDbValueDef($rsnew, UnFormatDateTime($this->Expiry_Date->CurrentValue, $this->Expiry_Date->formatPattern()), $this->Expiry_Date->ReadOnly);

        // SClass
        $this->SClass->setDbValueDef($rsnew, $this->SClass->CurrentValue, $this->SClass->ReadOnly);

        // Contact_Incase
        $this->Contact_Incase->setDbValueDef($rsnew, $this->Contact_Incase->CurrentValue, $this->Contact_Incase->ReadOnly);

        // Contact_Tel
        $this->Contact_Tel->setDbValueDef($rsnew, $this->Contact_Tel->CurrentValue, $this->Contact_Tel->ReadOnly);

        // Reference
        $this->Reference->setDbValueDef($rsnew, $this->Reference->CurrentValue, $this->Reference->ReadOnly);

        // EmployeeID
        $this->EmployeeID->setDbValueDef($rsnew, $this->EmployeeID->CurrentValue, $this->EmployeeID->ReadOnly);

        // Status
        $this->Status->setDbValueDef($rsnew, $this->Status->CurrentValue, $this->Status->ReadOnly);

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

        // Check hash value
        $rowHasConflict = (!IsApi() && $this->getRowHash($rsold) != $this->HashValue);

        // Call Row Update Conflict event
        if ($rowHasConflict) {
            $rowHasConflict = $this->rowUpdateConflict($rsold, $rsnew);
        }
        if ($rowHasConflict) {
            $this->setFailureMessage($Language->phrase("RecordChangedByOtherUser"));
            $this->UpdateConflict = "U";
            return false; // Update Failed
        }
        if ($this->Photo->Visible && !$this->Photo->Upload->KeepFile) {
            $this->Photo->UploadPath = $this->Photo->getUploadPath(); // PHP
            $oldFiles = EmptyValue($this->Photo->Upload->DbValue) ? [] : [$this->Photo->htmlDecode($this->Photo->Upload->DbValue)];
            if (!EmptyValue($this->Photo->Upload->FileName)) {
                $newFiles = [$this->Photo->Upload->FileName];
                $NewFileCount = count($newFiles);
                for ($i = 0; $i < $NewFileCount; $i++) {
                    if ($newFiles[$i] != "") {
                        $file = $newFiles[$i];
                        $tempPath = UploadTempPath($this->Photo, $this->Photo->Upload->Index);
                        if (file_exists($tempPath . $file)) {
                            if (Config("DELETE_UPLOADED_FILES")) {
                                $oldFileFound = false;
                                $oldFileCount = count($oldFiles);
                                for ($j = 0; $j < $oldFileCount; $j++) {
                                    $oldFile = $oldFiles[$j];
                                    if ($oldFile == $file) { // Old file found, no need to delete anymore
                                        array_splice($oldFiles, $j, 1);
                                        $oldFileFound = true;
                                        break;
                                    }
                                }
                                if ($oldFileFound) { // No need to check if file exists further
                                    continue;
                                }
                            }
                            $file1 = UniqueFilename($this->Photo->physicalUploadPath(), $file); // Get new file name
                            if ($file1 != $file) { // Rename temp file
                                while (file_exists($tempPath . $file1) || file_exists($this->Photo->physicalUploadPath() . $file1)) { // Make sure no file name clash
                                    $file1 = UniqueFilename([$this->Photo->physicalUploadPath(), $tempPath], $file1, true); // Use indexed name
                                }
                                rename($tempPath . $file, $tempPath . $file1);
                                $newFiles[$i] = $file1;
                            }
                        }
                    }
                }
                $this->Photo->Upload->DbValue = empty($oldFiles) ? "" : implode(Config("MULTIPLE_UPLOAD_SEPARATOR"), $oldFiles);
                $this->Photo->Upload->FileName = implode(Config("MULTIPLE_UPLOAD_SEPARATOR"), $newFiles);
                $this->Photo->setDbValueDef($rsnew, $this->Photo->Upload->FileName, $this->Photo->ReadOnly);
            }
        }

        // Call Row Updating event
        $updateRow = $this->rowUpdating($rsold, $rsnew);

        // Check for duplicate key when key changed
        if ($updateRow) {
            $newKeyFilter = $this->getRecordFilter($rsnew);
            if ($newKeyFilter != $oldKeyFilter) {
                $rsChk = $this->loadRs($newKeyFilter)->fetch();
                if ($rsChk !== false) {
                    $keyErrMsg = str_replace("%f", $newKeyFilter, $Language->phrase("DupKey"));
                    $this->setFailureMessage($keyErrMsg);
                    $updateRow = false;
                }
            }
        }
        if ($updateRow) {
            if (count($rsnew) > 0) {
                $this->CurrentFilter = $filter; // Set up current filter
                $editRow = $this->update($rsnew, "", $rsold);
                if (!$editRow && !EmptyValue($this->DbErrorMessage)) { // Show database error
                    $this->setFailureMessage($this->DbErrorMessage);
                }
            } else {
                $editRow = true; // No field to update
            }
            if ($editRow) {
                if ($this->Photo->Visible && !$this->Photo->Upload->KeepFile) {
                    $oldFiles = EmptyValue($this->Photo->Upload->DbValue) ? [] : [$this->Photo->htmlDecode($this->Photo->Upload->DbValue)];
                    if (!EmptyValue($this->Photo->Upload->FileName)) {
                        $newFiles = [$this->Photo->Upload->FileName];
                        $newFiles2 = [$this->Photo->htmlDecode($rsnew['Photo'])];
                        $newFileCount = count($newFiles);
                        for ($i = 0; $i < $newFileCount; $i++) {
                            if ($newFiles[$i] != "") {
                                $file = UploadTempPath($this->Photo, $this->Photo->Upload->Index) . $newFiles[$i];
                                if (file_exists($file)) {
                                    if (@$newFiles2[$i] != "") { // Use correct file name
                                        $newFiles[$i] = $newFiles2[$i];
                                    }
                                    if (!$this->Photo->Upload->ResizeAndSaveToFile($this->Photo->ImageWidth, $this->Photo->ImageHeight, 100, $newFiles[$i], true, $i)) {
                                        $this->setFailureMessage($Language->phrase("UploadError7"));
                                        return false;
                                    }
                                }
                            }
                        }
                    } else {
                        $newFiles = [];
                    }
                    if (Config("DELETE_UPLOADED_FILES")) {
                        foreach ($oldFiles as $oldFile) {
                            if ($oldFile != "" && !in_array($oldFile, $newFiles)) {
                                @unlink($this->Photo->oldPhysicalUploadPath() . $oldFile);
                            }
                        }
                    }
                }
            }
        } 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("UpdateCancelled"));
            }
            $editRow = false;
        }

        // Call Row_Updated event
        if ($editRow) {
            $this->rowUpdated($rsold, $rsnew);
        }
        if ($editRow) {
            if ($this->SendEmail) {
                $this->sendEmailOnEdit($rsold, $rsnew);
            }
        }

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

    // Load row hash
    protected function loadRowHash()
    {
        $filter = $this->getRecordFilter();

        // Load SQL based on filter
        $this->CurrentFilter = $filter;
        $sql = $this->getCurrentSql();
        $conn = $this->getConnection();
        $row = $conn->fetchAssociative($sql);
        $this->HashValue = $row ? $this->getRowHash($row) : ""; // Get hash value for record
    }

    // Get Row Hash
    public function getRowHash(&$rs)
    {
        if (!$rs) {
            return "";
        }
        $row = ($rs instanceof Recordset) ? $rs->fields : $rs;
        $hash = "";
        $hash .= GetFieldHash($row['studentID']); // studentID
        $hash .= GetFieldHash($row['PIN']); // PIN
        $hash .= GetFieldHash($row['Last_Name']); // Last_Name
        $hash .= GetFieldHash($row['First_Name']); // First_Name
        $hash .= GetFieldHash($row['Gender']); // Gender
        $hash .= GetFieldHash($row['Date_Of_Birth']); // Date_Of_Birth
        $hash .= GetFieldHash($row['Place_Of_Birth']); // Place_Of_Birth
        $hash .= GetFieldHash($row['Card_No']); // Card_No
        $hash .= GetFieldHash($row['Unique_QR']); // Unique_QR
        $hash .= GetFieldHash($row['Photo']); // Photo
        $hash .= GetFieldHash($row['Address']); // Address
        $hash .= GetFieldHash($row['Start_Date']); // Start_Date
        $hash .= GetFieldHash($row['Expiry_Date']); // Expiry_Date
        $hash .= GetFieldHash($row['SClass']); // SClass
        $hash .= GetFieldHash($row['Contact_Incase']); // Contact_Incase
        $hash .= GetFieldHash($row['Contact_Tel']); // Contact_Tel
        $hash .= GetFieldHash($row['Reference']); // Reference
        $hash .= GetFieldHash($row['EmployeeID']); // EmployeeID
        $hash .= GetFieldHash($row['Status']); // Status
        return md5($hash);
    }

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

    // Set up multi pages
    protected function setupMultiPages()
    {
        $pages = new SubPages();
        $pages->Style = "tabs";
        $pages->add(0);
        $pages->add(1);
        $pages->add(2);
        $pages->add(3);
        $pages->add(4);
        $pages->add(5);
        $this->MultiPages = $pages;
    }

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

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

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

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

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

    // Set up starting record parameters
    public function setupStartRecord()
    {
        if ($this->DisplayRecords == 0) {
            return;
        }
        $pageNo = Get(Config("TABLE_PAGE_NUMBER"));
        $startRec = Get(Config("TABLE_START_REC"));
        $infiniteScroll = false;
        $recordNo = $pageNo ?? $startRec; // Record number = page number or start record
        if ($recordNo !== null && is_numeric($recordNo)) {
            $this->StartRecord = $recordNo;
        } else {
            $this->StartRecord = $this->getStartRecordNumber();
        }

        // Check if correct start record counter
        if (!is_numeric($this->StartRecord) || intval($this->StartRecord) <= 0) { // Avoid invalid start record counter
            $this->StartRecord = 1; // Reset start record counter
        } elseif ($this->StartRecord > $this->TotalRecords) { // Avoid starting record > total records
            $this->StartRecord = (int)(($this->TotalRecords - 1) / $this->DisplayRecords) * $this->DisplayRecords + 1; // Point to last page first record
        } elseif (($this->StartRecord - 1) % $this->DisplayRecords != 0) {
            $this->StartRecord = (int)(($this->StartRecord - 1) / $this->DisplayRecords) * $this->DisplayRecords + 1; // Point to page boundary
        }
        if (!$infiniteScroll) {
            $this->setStartRecordNumber($this->StartRecord);
        }
    }

    // Get page count
    public function pageCount() {
        return ceil($this->TotalRecords / $this->DisplayRecords);
    }

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