<?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 VolontaireEdit extends Volontaire
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

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

    // View file path
    public $View = null;

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

    // Rendering View
    public $RenderingView = false;

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

    // 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->volontaireID->Visible = false;
        $this->Carte_No->setVisibility();
        $this->NIP->setVisibility();
        $this->Nom->setVisibility();
        $this->Prenom->setVisibility();
        $this->Sexe->setVisibility();
        $this->DateNaissance->setVisibility();
        $this->Lieu->setVisibility();
        $this->Photo->setVisibility();
        $this->Unique_QR->setVisibility();
        $this->Groupe_Sanguin->setVisibility();
        $this->Delivree->setVisibility();
        $this->Expire->setVisibility();
        $this->Localite->setVisibility();
        $this->Prevenir->setVisibility();
        $this->Prevenir_Tel->setVisibility();
        $this->Reference->setVisibility();
        $this->EmployeeID->setVisibility();
        $this->Statut->setVisibility();
    }

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

        // 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 (volontaire)
        if (!isset($GLOBALS["volontaire"]) || get_class($GLOBALS["volontaire"]) == PROJECT_NAMESPACE . "volontaire") {
            $GLOBALS["volontaire"] = &$this;
        }

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

        // 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 == "volontaireview"; // 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['volontaireID'];
        }
        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->Sexe);
        $this->setupLookupOptions($this->EmployeeID);
        $this->setupLookupOptions($this->Statut);
		My_Global_Check(); // Modified by UDS Hub, October 6, 2021

        // Add Infinite-Scroll header
        AddHeader("Infinite-Scroll", "true");

        // 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("volontaireID") ?? Key(0) ?? Route(2)) !== null) {
                $this->volontaireID->setQueryStringValue($keyValue);
                $this->volontaireID->setOldValue($this->volontaireID->QueryStringValue);
            } elseif (Post("volontaireID") !== null) {
                $this->volontaireID->setFormValue(Post("volontaireID"));
                $this->volontaireID->setOldValue($this->volontaireID->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("volontaireID") ?? Route("volontaireID")) !== null) {
                    $this->volontaireID->setQueryStringValue($keyValue);
                    $loadByQuery = true;
                } else {
                    $this->volontaireID->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("volontairelist"); // 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->volontaireID->CurrentValue != null) {
                            while (!$rs->EOF) {
                                if (SameString($this->volontaireID->CurrentValue, $rs->fields['volontaireID'])) {
                                    $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("volontairelist"); // 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("volontairelist"); // No matching record, return to list
                        return;
                    }
                } // End modal checking
                break;
            case "update": // Update
                $returnUrl = "volontairelist";
                if (GetPageName($returnUrl) == "volontairelist") {
                    $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()) {
                    // Return list content for infinite scroll directly
                    if ($this->IsModal && $this->UseAjaxActions) {
                        $this->renderListContent($this->getRecordFilter());
                        $this->terminate();
                        return;
                    }

                    // Handle UseAjaxActions with return page
                    if ($this->IsModal && $this->UseAjaxActions) {
                        $this->IsModal = false;
                        if (GetPageName($returnUrl) != "volontairelist") {
                            Container("flash")->addMessage("Return-Url", $returnUrl); // Save return URL
                            $returnUrl = "volontairelist"; // 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 'Carte_No' first before field var 'x_Carte_No'
        $val = $CurrentForm->hasValue("Carte_No") ? $CurrentForm->getValue("Carte_No") : $CurrentForm->getValue("x_Carte_No");
        if (!$this->Carte_No->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->Carte_No->Visible = false; // Disable update for API request
            } else {
                $this->Carte_No->setFormValue($val);
            }
        }

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

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

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

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

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

        // Check field name 'Lieu' first before field var 'x_Lieu'
        $val = $CurrentForm->hasValue("Lieu") ? $CurrentForm->getValue("Lieu") : $CurrentForm->getValue("x_Lieu");
        if (!$this->Lieu->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->Lieu->Visible = false; // Disable update for API request
            } else {
                $this->Lieu->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 'Groupe_Sanguin' first before field var 'x_Groupe_Sanguin'
        $val = $CurrentForm->hasValue("Groupe_Sanguin") ? $CurrentForm->getValue("Groupe_Sanguin") : $CurrentForm->getValue("x_Groupe_Sanguin");
        if (!$this->Groupe_Sanguin->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->Groupe_Sanguin->Visible = false; // Disable update for API request
            } else {
                $this->Groupe_Sanguin->setFormValue($val);
            }
        }

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

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

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

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

        // Check field name 'Prevenir_Tel' first before field var 'x_Prevenir_Tel'
        $val = $CurrentForm->hasValue("Prevenir_Tel") ? $CurrentForm->getValue("Prevenir_Tel") : $CurrentForm->getValue("x_Prevenir_Tel");
        if (!$this->Prevenir_Tel->IsDetailKey) {
            if (IsApi() && $val === null) {
                $this->Prevenir_Tel->Visible = false; // Disable update for API request
            } else {
                $this->Prevenir_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);
            }
        }

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

        // Check field name 'volontaireID' first before field var 'x_volontaireID'
        $val = $CurrentForm->hasValue("volontaireID") ? $CurrentForm->getValue("volontaireID") : $CurrentForm->getValue("x_volontaireID");
        if (!$this->volontaireID->IsDetailKey) {
            $this->volontaireID->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->volontaireID->CurrentValue = $this->volontaireID->FormValue;
        $this->Carte_No->CurrentValue = $this->Carte_No->FormValue;
        $this->NIP->CurrentValue = $this->NIP->FormValue;
        $this->Nom->CurrentValue = $this->Nom->FormValue;
        $this->Prenom->CurrentValue = $this->Prenom->FormValue;
        $this->Sexe->CurrentValue = $this->Sexe->FormValue;
        $this->DateNaissance->CurrentValue = $this->DateNaissance->FormValue;
        $this->DateNaissance->CurrentValue = UnFormatDateTime($this->DateNaissance->CurrentValue, $this->DateNaissance->formatPattern());
        $this->Lieu->CurrentValue = $this->Lieu->FormValue;
        $this->Unique_QR->CurrentValue = $this->Unique_QR->FormValue;
        $this->Groupe_Sanguin->CurrentValue = $this->Groupe_Sanguin->FormValue;
        $this->Delivree->CurrentValue = $this->Delivree->FormValue;
        $this->Delivree->CurrentValue = UnFormatDateTime($this->Delivree->CurrentValue, $this->Delivree->formatPattern());
        $this->Expire->CurrentValue = $this->Expire->FormValue;
        $this->Expire->CurrentValue = UnFormatDateTime($this->Expire->CurrentValue, $this->Expire->formatPattern());
        $this->Localite->CurrentValue = $this->Localite->FormValue;
        $this->Prevenir->CurrentValue = $this->Prevenir->FormValue;
        $this->Prevenir_Tel->CurrentValue = $this->Prevenir_Tel->FormValue;
        $this->Reference->CurrentValue = $this->Reference->FormValue;
        $this->EmployeeID->CurrentValue = $this->EmployeeID->FormValue;
        $this->Statut->CurrentValue = $this->Statut->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->volontaireID->setDbValue($row['volontaireID']);
        $this->Carte_No->setDbValue($row['Carte_No']);
        $this->NIP->setDbValue($row['NIP']);
        $this->Nom->setDbValue($row['Nom']);
        $this->Prenom->setDbValue($row['Prenom']);
        $this->Sexe->setDbValue($row['Sexe']);
        $this->DateNaissance->setDbValue($row['DateNaissance']);
        $this->Lieu->setDbValue($row['Lieu']);
        $this->Photo->Upload->DbValue = $row['Photo'];
        $this->Photo->setDbValue($this->Photo->Upload->DbValue);
        $this->Unique_QR->setDbValue($row['Unique_QR']);
        $this->Groupe_Sanguin->setDbValue($row['Groupe_Sanguin']);
        $this->Delivree->setDbValue($row['Delivree']);
        $this->Expire->setDbValue($row['Expire']);
        $this->Localite->setDbValue($row['Localite']);
        $this->Prevenir->setDbValue($row['Prevenir']);
        $this->Prevenir_Tel->setDbValue($row['Prevenir_Tel']);
        $this->Reference->setDbValue($row['Reference']);
        $this->EmployeeID->setDbValue($row['EmployeeID']);
        $this->Statut->setDbValue($row['Statut']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $row = [];
        $row['volontaireID'] = $this->volontaireID->DefaultValue;
        $row['Carte_No'] = $this->Carte_No->DefaultValue;
        $row['NIP'] = $this->NIP->DefaultValue;
        $row['Nom'] = $this->Nom->DefaultValue;
        $row['Prenom'] = $this->Prenom->DefaultValue;
        $row['Sexe'] = $this->Sexe->DefaultValue;
        $row['DateNaissance'] = $this->DateNaissance->DefaultValue;
        $row['Lieu'] = $this->Lieu->DefaultValue;
        $row['Photo'] = $this->Photo->DefaultValue;
        $row['Unique_QR'] = $this->Unique_QR->DefaultValue;
        $row['Groupe_Sanguin'] = $this->Groupe_Sanguin->DefaultValue;
        $row['Delivree'] = $this->Delivree->DefaultValue;
        $row['Expire'] = $this->Expire->DefaultValue;
        $row['Localite'] = $this->Localite->DefaultValue;
        $row['Prevenir'] = $this->Prevenir->DefaultValue;
        $row['Prevenir_Tel'] = $this->Prevenir_Tel->DefaultValue;
        $row['Reference'] = $this->Reference->DefaultValue;
        $row['EmployeeID'] = $this->EmployeeID->DefaultValue;
        $row['Statut'] = $this->Statut->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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Lieu
            $this->Lieu->ViewValue = $this->Lieu->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 = "";
            }

            // Unique_QR
            $this->Unique_QR->ViewValue = $this->Unique_QR->CurrentValue;
            $this->Unique_QR->ImageAlt = $this->Unique_QR->alt();
                $this->Unique_QR->ImageCssClass = "ew-image";

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

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

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

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

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

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

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

            // EmployeeID
            $curVal = strval($this->EmployeeID->CurrentValue);
            if ($curVal != "") {
                $this->EmployeeID->ViewValue = $this->EmployeeID->lookupCacheOption($curVal);
                if ($this->EmployeeID->ViewValue === null) { // Lookup from database
                    $filterWrk = SearchFilter("`EmployeeID`", "=", $curVal, DATATYPE_NUMBER, "");
                    $sqlWrk = $this->EmployeeID->Lookup->getSql(false, $filterWrk, '', $this, true, true);
                    $conn = Conn();
                    $config = $conn->getConfiguration();
                    $config->setResultCacheImpl($this->Cache);
                    $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $arwrk = $this->EmployeeID->Lookup->renderViewRow($rswrk[0]);
                        $this->EmployeeID->ViewValue = $this->EmployeeID->displayValue($arwrk);
                    } else {
                        $this->EmployeeID->ViewValue = FormatNumber($this->EmployeeID->CurrentValue, $this->EmployeeID->formatPattern());
                    }
                }
            } else {
                $this->EmployeeID->ViewValue = null;
            }

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

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

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

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

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

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

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

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

            // 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"] = "_self"; // 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;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Lieu
            $this->Lieu->setupEditAttributes();
            if (!$this->Lieu->Raw) {
                $this->Lieu->CurrentValue = HtmlDecode($this->Lieu->CurrentValue);
            }
            $this->Lieu->EditValue = HtmlEncode($this->Lieu->CurrentValue);
            $arwrk = [];
            $arwrk["lf"] = $this->Lieu->CurrentValue;
            $arwrk["df"] = $this->Lieu->CurrentValue;
            $arwrk = $this->Lieu->Lookup->renderViewRow($arwrk, $this);
            $dispVal = $this->Lieu->displayValue($arwrk);
            if ($dispVal != "") {
                $this->Lieu->EditValue = $dispVal;
            }
            $this->Lieu->PlaceHolder = RemoveHtml($this->Lieu->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);
            }

            // 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);
            $arwrk = [];
            $arwrk["lf"] = $this->Unique_QR->CurrentValue;
            $arwrk["df"] = $this->Unique_QR->CurrentValue;
            $arwrk = $this->Unique_QR->Lookup->renderViewRow($arwrk, $this);
            $dispVal = $this->Unique_QR->displayValue($arwrk);
            if ($dispVal != "") {
                $this->Unique_QR->EditValue = $dispVal;
            }
            $this->Unique_QR->PlaceHolder = RemoveHtml($this->Unique_QR->caption());

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

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

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

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

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

            // Prevenir_Tel
            $this->Prevenir_Tel->setupEditAttributes();
            if (!$this->Prevenir_Tel->Raw) {
                $this->Prevenir_Tel->CurrentValue = HtmlDecode($this->Prevenir_Tel->CurrentValue);
            }
            $this->Prevenir_Tel->EditValue = HtmlEncode($this->Prevenir_Tel->CurrentValue);
            $this->Prevenir_Tel->PlaceHolder = RemoveHtml($this->Prevenir_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();
            $curVal = strval($this->EmployeeID->CurrentValue);
            if ($curVal != "") {
                $this->EmployeeID->EditValue = $this->EmployeeID->lookupCacheOption($curVal);
                if ($this->EmployeeID->EditValue === null) { // Lookup from database
                    $filterWrk = SearchFilter("`EmployeeID`", "=", $curVal, DATATYPE_NUMBER, "");
                    $sqlWrk = $this->EmployeeID->Lookup->getSql(false, $filterWrk, '', $this, true, true);
                    $conn = Conn();
                    $config = $conn->getConfiguration();
                    $config->setResultCacheImpl($this->Cache);
                    $rswrk = $conn->executeCacheQuery($sqlWrk, [], [], $this->CacheProfile)->fetchAll();
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $arwrk = $this->EmployeeID->Lookup->renderViewRow($rswrk[0]);
                        $this->EmployeeID->EditValue = $this->EmployeeID->displayValue($arwrk);
                    } else {
                        $this->EmployeeID->EditValue = FormatNumber($this->EmployeeID->CurrentValue, $this->EmployeeID->formatPattern());
                    }
                }
            } else {
                $this->EmployeeID->EditValue = null;
            }

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

            // Edit refer script

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

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

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

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

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

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

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

            // 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"] = "_self"; // 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;

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

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

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

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

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

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

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

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

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

            // Statut
            $this->Statut->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->Carte_No->Required) {
            if (!$this->Carte_No->IsDetailKey && EmptyValue($this->Carte_No->FormValue)) {
                $this->Carte_No->addErrorMessage(str_replace("%s", $this->Carte_No->caption(), $this->Carte_No->RequiredErrorMessage));
            }
        }
        if ($this->NIP->Required) {
            if (!$this->NIP->IsDetailKey && EmptyValue($this->NIP->FormValue)) {
                $this->NIP->addErrorMessage(str_replace("%s", $this->NIP->caption(), $this->NIP->RequiredErrorMessage));
            }
        }
        if ($this->Nom->Required) {
            if (!$this->Nom->IsDetailKey && EmptyValue($this->Nom->FormValue)) {
                $this->Nom->addErrorMessage(str_replace("%s", $this->Nom->caption(), $this->Nom->RequiredErrorMessage));
            }
        }
        if ($this->Prenom->Required) {
            if (!$this->Prenom->IsDetailKey && EmptyValue($this->Prenom->FormValue)) {
                $this->Prenom->addErrorMessage(str_replace("%s", $this->Prenom->caption(), $this->Prenom->RequiredErrorMessage));
            }
        }
        if ($this->Sexe->Required) {
            if ($this->Sexe->FormValue == "") {
                $this->Sexe->addErrorMessage(str_replace("%s", $this->Sexe->caption(), $this->Sexe->RequiredErrorMessage));
            }
        }
        if ($this->DateNaissance->Required) {
            if (!$this->DateNaissance->IsDetailKey && EmptyValue($this->DateNaissance->FormValue)) {
                $this->DateNaissance->addErrorMessage(str_replace("%s", $this->DateNaissance->caption(), $this->DateNaissance->RequiredErrorMessage));
            }
        }
        if (!CheckDate($this->DateNaissance->FormValue, $this->DateNaissance->formatPattern())) {
            $this->DateNaissance->addErrorMessage($this->DateNaissance->getErrorMessage(false));
        }
        if ($this->Lieu->Required) {
            if (!$this->Lieu->IsDetailKey && EmptyValue($this->Lieu->FormValue)) {
                $this->Lieu->addErrorMessage(str_replace("%s", $this->Lieu->caption(), $this->Lieu->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->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->Groupe_Sanguin->Required) {
            if (!$this->Groupe_Sanguin->IsDetailKey && EmptyValue($this->Groupe_Sanguin->FormValue)) {
                $this->Groupe_Sanguin->addErrorMessage(str_replace("%s", $this->Groupe_Sanguin->caption(), $this->Groupe_Sanguin->RequiredErrorMessage));
            }
        }
        if ($this->Delivree->Required) {
            if (!$this->Delivree->IsDetailKey && EmptyValue($this->Delivree->FormValue)) {
                $this->Delivree->addErrorMessage(str_replace("%s", $this->Delivree->caption(), $this->Delivree->RequiredErrorMessage));
            }
        }
        if (!CheckDate($this->Delivree->FormValue, $this->Delivree->formatPattern())) {
            $this->Delivree->addErrorMessage($this->Delivree->getErrorMessage(false));
        }
        if ($this->Expire->Required) {
            if (!$this->Expire->IsDetailKey && EmptyValue($this->Expire->FormValue)) {
                $this->Expire->addErrorMessage(str_replace("%s", $this->Expire->caption(), $this->Expire->RequiredErrorMessage));
            }
        }
        if (!CheckDate($this->Expire->FormValue, $this->Expire->formatPattern())) {
            $this->Expire->addErrorMessage($this->Expire->getErrorMessage(false));
        }
        if ($this->Localite->Required) {
            if (!$this->Localite->IsDetailKey && EmptyValue($this->Localite->FormValue)) {
                $this->Localite->addErrorMessage(str_replace("%s", $this->Localite->caption(), $this->Localite->RequiredErrorMessage));
            }
        }
        if ($this->Prevenir->Required) {
            if (!$this->Prevenir->IsDetailKey && EmptyValue($this->Prevenir->FormValue)) {
                $this->Prevenir->addErrorMessage(str_replace("%s", $this->Prevenir->caption(), $this->Prevenir->RequiredErrorMessage));
            }
        }
        if ($this->Prevenir_Tel->Required) {
            if (!$this->Prevenir_Tel->IsDetailKey && EmptyValue($this->Prevenir_Tel->FormValue)) {
                $this->Prevenir_Tel->addErrorMessage(str_replace("%s", $this->Prevenir_Tel->caption(), $this->Prevenir_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 ($this->Statut->Required) {
            if (!$this->Statut->IsDetailKey && EmptyValue($this->Statut->FormValue)) {
                $this->Statut->addErrorMessage(str_replace("%s", $this->Statut->caption(), $this->Statut->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 = [];

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

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

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

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

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

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

        // Lieu
        $this->Lieu->setDbValueDef($rsnew, $this->Lieu->CurrentValue, $this->Lieu->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 = 488; // Resize width
            $this->Photo->ImageHeight = 600; // Resize height
        }

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

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

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

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

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

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

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

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

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

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

        // Check field with unique index (Carte_No)
        if ($this->Carte_No->CurrentValue != "") {
            $filterChk = "(`Carte_No` = '" . AdjustSql($this->Carte_No->CurrentValue, $this->Dbid) . "')";
            $filterChk .= " AND NOT (" . $filter . ")";
            $this->CurrentFilter = $filterChk;
            $sqlChk = $this->getCurrentSql();
            $rsChk = $conn->executeQuery($sqlChk);
            if (!$rsChk) {
                return false;
            }
            if ($rsChk->fetch()) {
                $idxErrMsg = str_replace("%f", $this->Carte_No->caption(), $Language->phrase("DupIndex"));
                $idxErrMsg = str_replace("%v", $this->Carte_No->CurrentValue, $idxErrMsg);
                $this->setFailureMessage($idxErrMsg);
                return false;
            }
        }

        // Check field with unique index (NIP)
        if ($this->NIP->CurrentValue != "") {
            $filterChk = "(`NIP` = '" . AdjustSql($this->NIP->CurrentValue, $this->Dbid) . "')";
            $filterChk .= " AND NOT (" . $filter . ")";
            $this->CurrentFilter = $filterChk;
            $sqlChk = $this->getCurrentSql();
            $rsChk = $conn->executeQuery($sqlChk);
            if (!$rsChk) {
                return false;
            }
            if ($rsChk->fetch()) {
                $idxErrMsg = str_replace("%f", $this->NIP->caption(), $Language->phrase("DupIndex"));
                $idxErrMsg = str_replace("%v", $this->NIP->CurrentValue, $idxErrMsg);
                $this->setFailureMessage($idxErrMsg);
                return false;
            }
        }

        // Check field with unique index (Unique_QR)
        if ($this->Unique_QR->CurrentValue != "") {
            $filterChk = "(`Unique_QR` = '" . AdjustSql($this->Unique_QR->CurrentValue, $this->Dbid) . "')";
            $filterChk .= " AND NOT (" . $filter . ")";
            $this->CurrentFilter = $filterChk;
            $sqlChk = $this->getCurrentSql();
            $rsChk = $conn->executeQuery($sqlChk);
            if (!$rsChk) {
                return false;
            }
            if ($rsChk->fetch()) {
                $idxErrMsg = str_replace("%f", $this->Unique_QR->caption(), $Language->phrase("DupIndex"));
                $idxErrMsg = str_replace("%v", $this->Unique_QR->CurrentValue, $idxErrMsg);
                $this->setFailureMessage($idxErrMsg);
                return false;
            }
        }

        // Check field with unique index (Prevenir_Tel)
        if ($this->Prevenir_Tel->CurrentValue != "") {
            $filterChk = "(`Prevenir_Tel` = '" . AdjustSql($this->Prevenir_Tel->CurrentValue, $this->Dbid) . "')";
            $filterChk .= " AND NOT (" . $filter . ")";
            $this->CurrentFilter = $filterChk;
            $sqlChk = $this->getCurrentSql();
            $rsChk = $conn->executeQuery($sqlChk);
            if (!$rsChk) {
                return false;
            }
            if ($rsChk->fetch()) {
                $idxErrMsg = str_replace("%f", $this->Prevenir_Tel->caption(), $Language->phrase("DupIndex"));
                $idxErrMsg = str_replace("%v", $this->Prevenir_Tel->CurrentValue, $idxErrMsg);
                $this->setFailureMessage($idxErrMsg);
                return false;
            }
        }

        // 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['Carte_No']); // Carte_No
        $hash .= GetFieldHash($row['NIP']); // NIP
        $hash .= GetFieldHash($row['Nom']); // Nom
        $hash .= GetFieldHash($row['Prenom']); // Prenom
        $hash .= GetFieldHash($row['Sexe']); // Sexe
        $hash .= GetFieldHash($row['DateNaissance']); // DateNaissance
        $hash .= GetFieldHash($row['Lieu']); // Lieu
        $hash .= GetFieldHash($row['Photo']); // Photo
        $hash .= GetFieldHash($row['Unique_QR']); // Unique_QR
        $hash .= GetFieldHash($row['Groupe_Sanguin']); // Groupe_Sanguin
        $hash .= GetFieldHash($row['Delivree']); // Delivree
        $hash .= GetFieldHash($row['Expire']); // Expire
        $hash .= GetFieldHash($row['Localite']); // Localite
        $hash .= GetFieldHash($row['Prevenir']); // Prevenir
        $hash .= GetFieldHash($row['Prevenir_Tel']); // Prevenir_Tel
        $hash .= GetFieldHash($row['Reference']); // Reference
        $hash .= GetFieldHash($row['Statut']); // Statut
        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("volontairelist"), "", $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_Carte_No":
                    break;
                case "x_NIP":
                    break;
                case "x_Nom":
                    break;
                case "x_Sexe":
                    break;
                case "x_Lieu":
                    break;
                case "x_Unique_QR":
                    break;
                case "x_Localite":
                    break;
                case "x_EmployeeID":
                    break;
                case "x_Statut":
                    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;
    }
}
