<?php

namespace PHPMaker2021\rkm21;

use Doctrine\DBAL\ParameterType;

/**
 * Page class
 */
class PenilaianP5Add extends PenilaianP5
{
    use MessagesTrait;

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

    // Project ID
    public $ProjectID = PROJECT_ID;

    // Table name
    public $TableName = 'penilaian_p5';

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

    // Rendering View
    public $RenderingView = false;

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

    // 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()
    {
        $url = ScriptName() . "?";
        if ($this->UseTokenInUrl) {
            $url .= "t=" . $this->TableVar . "&"; // Add page token
        }
        return $url;
    }

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

    // Validate page request
    protected function isPageRequest()
    {
        global $CurrentForm;
        if ($this->UseTokenInUrl) {
            if ($CurrentForm) {
                return ($this->TableVar == $CurrentForm->getValue("t"));
            }
            if (Get("t") !== null) {
                return ($this->TableVar == Get("t"));
            }
        }
        return true;
    }

    // Constructor
    public function __construct()
    {
        global $Language, $DashboardReport, $DebugTimer;
        global $UserTable;

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

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

        // Parent constuctor
        parent::__construct();

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

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

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

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

        // Debug message
        LoadDebugMessage();

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

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

    // Get content from stream
    public function getContents($stream = null): 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 $ExportFileName, $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();

        // Export
        if ($this->CustomExport && $this->CustomExport == $this->Export && array_key_exists($this->CustomExport, Config("EXPORT_CLASSES"))) {
            $content = $this->getContents();
            if ($ExportFileName == "") {
                $ExportFileName = $this->TableVar;
            }
            $class = PROJECT_NAMESPACE . Config("EXPORT_CLASSES." . $this->CustomExport);
            if (class_exists($class)) {
                $doc = new $class(Container("penilaian_p5"));
                $doc->Text = @$content;
                if ($this->isExport("email")) {
                    echo $this->exportEmail($doc->Text);
                } else {
                    $doc->export();
                }
                DeleteTempImages(); // Delete temp images
                return;
            }
        }
        if (!IsApi() && method_exists($this, "pageRedirecting")) {
            $this->pageRedirecting($url);
        }

        // Close connection
        CloseConnections();

        // Return for API
        if (IsApi()) {
            $res = $url === true;
            if (!$res) { // Show error
                WriteJson(array_merge(["success" => false], $this->getMessages()));
            }
            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
            if ($this->IsModal) { // Show as modal
                $row = ["url" => GetUrl($url), "modal" => "1"];
                $pageName = GetPageName($url);
                if ($pageName != $this->getListUrl()) { // Not List page
                    $row["caption"] = $this->getModalCaption($pageName);
                    if ($pageName == "PenilaianP5View") {
                        $row["view"] = "1";
                    }
                } else { // List page should not be shown as modal => error
                    $row["error"] = $this->getFailureMessage();
                    $this->clearFailureMessage();
                }
                WriteJson($row);
            } else {
                SaveDebugMessage();
                Redirect(GetUrl($url));
            }
        }
        return; // Return to controller
    }

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

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

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

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

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

        // Get lookup object
        $fieldName = Post("field");
        $lookup = $this->Fields[$fieldName]->Lookup;

        // Get lookup parameters
        $lookupType = Post("ajax", "unknown");
        $pageSize = -1;
        $offset = -1;
        $searchValue = "";
        if (SameText($lookupType, "modal")) {
            $searchValue = Post("sv", "");
            $pageSize = Post("recperpage", 10);
            $offset = Post("start", 0);
        } elseif (SameText($lookupType, "autosuggest")) {
            $searchValue = Param("q", "");
            $pageSize = Param("n", -1);
            $pageSize = is_numeric($pageSize) ? (int)$pageSize : -1;
            if ($pageSize <= 0) {
                $pageSize = Config("AUTO_SUGGEST_MAX_ENTRIES");
            }
            $start = Param("start", -1);
            $start = is_numeric($start) ? (int)$start : -1;
            $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(Post("s", ""));
        $userFilter = Decrypt(Post("f", ""));
        $userOrderBy = Decrypt(Post("o", ""));
        $keys = Post("keys");
        $lookup->LookupType = $lookupType; // Lookup type
        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[] = Post("v0", Post("lookupValue", ""));
        }
        $cnt = is_array($lookup->FilterFields) ? count($lookup->FilterFields) : 0;
        for ($i = 1; $i <= $cnt; $i++) {
            $lookup->FilterValues[] = 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;
        }
        $lookup->toJson($this); // Use settings from current page
    }
    public $FormClassName = "ew-horizontal ew-form ew-add-form";
    public $IsModal = false;
    public $IsMobileOrModal = false;
    public $DbMasterFilter = "";
    public $DbDetailFilter = "";
    public $StartRecord;
    public $Priv = 0;
    public $OldRecordset;
    public $CopyRecord;

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

        // Is modal
        $this->IsModal = Param("modal") == "1";

        // Create form object
        $CurrentForm = new HttpForm();
        $this->CurrentAction = Param("action"); // Set up current action
        $this->nilai_p5->Visible = false;
        $this->project_id->setVisibility();
        $this->kelas->setVisibility();
        $this->nis->setVisibility();
        $this->proyek->setVisibility();
        $this->dimensi->setVisibility();
        $this->sub_elemen->setVisibility();
        $this->nilai->setVisibility();
        $this->tapel_id->setVisibility();
        $this->hideFieldsForAddEdit();

        // Do not use lookup cache
        $this->setUseLookupCache(false);

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

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

        // Set up lookup cache
        $this->setupLookupOptions($this->nis);

        // Check modal
        if ($this->IsModal) {
            $SkipHeaderFooter = true;
        }
        $this->IsMobileOrModal = IsMobile() || $this->IsModal;
        $this->FormClassName = "ew-form ew-add-form ew-horizontal";
        $postBack = false;

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

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

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

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

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

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

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

        // Render row
        $this->resetAttributes();
        $this->renderRow();

        // Set LoginStatus / Page_Rendering / Page_Render
        if (!IsApi() && !$this->isTerminated()) {
            // Pass table and field properties to client side
            $this->toClientVar(["tableCaption"], ["caption", "Visible", "Required", "IsInvalid", "Raw"]);

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

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

    // Load default values
    protected function loadDefaultValues()
    {
        $this->nilai_p5->CurrentValue = null;
        $this->nilai_p5->OldValue = $this->nilai_p5->CurrentValue;
        $this->project_id->CurrentValue = null;
        $this->project_id->OldValue = $this->project_id->CurrentValue;
        $this->kelas->CurrentValue = CurrentUserID();
        $this->nis->CurrentValue = null;
        $this->nis->OldValue = $this->nis->CurrentValue;
        $this->proyek->CurrentValue = null;
        $this->proyek->OldValue = $this->proyek->CurrentValue;
        $this->dimensi->CurrentValue = null;
        $this->dimensi->OldValue = $this->dimensi->CurrentValue;
        $this->sub_elemen->CurrentValue = null;
        $this->sub_elemen->OldValue = $this->sub_elemen->CurrentValue;
        $this->nilai->CurrentValue = null;
        $this->nilai->OldValue = $this->nilai->CurrentValue;
        $this->tapel_id->CurrentValue = null;
        $this->tapel_id->OldValue = $this->tapel_id->CurrentValue;
    }

    // Load form values
    protected function loadFormValues()
    {
        // Load from form
        global $CurrentForm;

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

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

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

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

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

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

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

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

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

    // Restore form values
    public function restoreFormValues()
    {
        global $CurrentForm;
        $this->project_id->CurrentValue = $this->project_id->FormValue;
        $this->kelas->CurrentValue = $this->kelas->FormValue;
        $this->nis->CurrentValue = $this->nis->FormValue;
        $this->proyek->CurrentValue = $this->proyek->FormValue;
        $this->dimensi->CurrentValue = $this->dimensi->FormValue;
        $this->sub_elemen->CurrentValue = $this->sub_elemen->FormValue;
        $this->nilai->CurrentValue = $this->nilai->FormValue;
        $this->tapel_id->CurrentValue = $this->tapel_id->FormValue;
    }

    /**
     * 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->fetchAssoc($sql);
        if ($row) {
            $res = true;
            $this->loadRowValues($row); // Load row values
        }

        // Check if valid User ID
        if ($res) {
            $res = $this->showOptionLink("add");
            if (!$res) {
                $userIdMsg = DeniedMessage();
                $this->setFailureMessage($userIdMsg);
            }
        }
        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();
        }

        // Call Row Selected event
        $this->rowSelected($row);
        if (!$rs) {
            return;
        }
        $this->nilai_p5->setDbValue($row['nilai_p5']);
        $this->project_id->setDbValue($row['project_id']);
        $this->kelas->setDbValue($row['kelas']);
        $this->nis->setDbValue($row['nis']);
        $this->proyek->setDbValue($row['proyek']);
        $this->dimensi->setDbValue($row['dimensi']);
        $this->sub_elemen->setDbValue($row['sub_elemen']);
        $this->nilai->setDbValue($row['nilai']);
        $this->tapel_id->setDbValue($row['tapel_id']);
    }

    // Return a row with default values
    protected function newRow()
    {
        $this->loadDefaultValues();
        $row = [];
        $row['nilai_p5'] = $this->nilai_p5->CurrentValue;
        $row['project_id'] = $this->project_id->CurrentValue;
        $row['kelas'] = $this->kelas->CurrentValue;
        $row['nis'] = $this->nis->CurrentValue;
        $row['proyek'] = $this->proyek->CurrentValue;
        $row['dimensi'] = $this->dimensi->CurrentValue;
        $row['sub_elemen'] = $this->sub_elemen->CurrentValue;
        $row['nilai'] = $this->nilai->CurrentValue;
        $row['tapel_id'] = $this->tapel_id->CurrentValue;
        return $row;
    }

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

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

        // nilai_p5

        // project_id

        // kelas

        // nis

        // proyek

        // dimensi

        // sub_elemen

        // nilai

        // tapel_id
        if ($this->RowType == ROWTYPE_VIEW) {
            // nilai_p5
            $this->nilai_p5->ViewValue = $this->nilai_p5->CurrentValue;
            $this->nilai_p5->ViewCustomAttributes = "";

            // project_id
            $this->project_id->ViewValue = $this->project_id->CurrentValue;
            $this->project_id->ViewValue = FormatNumber($this->project_id->ViewValue, 0, -2, -2, -2);
            $this->project_id->ViewCustomAttributes = "";

            // kelas
            $this->kelas->ViewValue = $this->kelas->CurrentValue;
            $this->kelas->ViewCustomAttributes = "";

            // nis
            $this->nis->ViewValue = $this->nis->CurrentValue;
            $curVal = trim(strval($this->nis->CurrentValue));
            if ($curVal != "") {
                $this->nis->ViewValue = $this->nis->lookupCacheOption($curVal);
                if ($this->nis->ViewValue === null) { // Lookup from database
                    $filterWrk = "\"nis\"" . SearchString("=", $curVal, DATATYPE_MEMO, "");
                    $sqlWrk = $this->nis->Lookup->getSql(false, $filterWrk, '', $this, true, true);
                    $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $arwrk = $this->nis->Lookup->renderViewRow($rswrk[0]);
                        $this->nis->ViewValue = $this->nis->displayValue($arwrk);
                    } else {
                        $this->nis->ViewValue = $this->nis->CurrentValue;
                    }
                }
            } else {
                $this->nis->ViewValue = null;
            }
            $this->nis->ViewCustomAttributes = "";

            // proyek
            $this->proyek->ViewValue = $this->proyek->CurrentValue;
            $this->proyek->ViewCustomAttributes = "";

            // dimensi
            $this->dimensi->ViewValue = $this->dimensi->CurrentValue;
            $this->dimensi->ViewCustomAttributes = "";

            // sub_elemen
            $this->sub_elemen->ViewValue = $this->sub_elemen->CurrentValue;
            $this->sub_elemen->ViewCustomAttributes = "";

            // nilai
            $this->nilai->ViewValue = $this->nilai->CurrentValue;
            $this->nilai->ViewCustomAttributes = "";

            // tapel_id
            $this->tapel_id->ViewValue = $this->tapel_id->CurrentValue;
            $this->tapel_id->ViewCustomAttributes = "";

            // project_id
            $this->project_id->LinkCustomAttributes = "";
            $this->project_id->HrefValue = "";
            $this->project_id->TooltipValue = "";

            // kelas
            $this->kelas->LinkCustomAttributes = "";
            $this->kelas->HrefValue = "";
            $this->kelas->TooltipValue = "";

            // nis
            $this->nis->LinkCustomAttributes = "";
            $this->nis->HrefValue = "";
            $this->nis->TooltipValue = "";

            // proyek
            $this->proyek->LinkCustomAttributes = "";
            $this->proyek->HrefValue = "";
            $this->proyek->TooltipValue = "";

            // dimensi
            $this->dimensi->LinkCustomAttributes = "";
            $this->dimensi->HrefValue = "";
            $this->dimensi->TooltipValue = "";

            // sub_elemen
            $this->sub_elemen->LinkCustomAttributes = "";
            $this->sub_elemen->HrefValue = "";
            $this->sub_elemen->TooltipValue = "";

            // nilai
            $this->nilai->LinkCustomAttributes = "";
            $this->nilai->HrefValue = "";
            $this->nilai->TooltipValue = "";

            // tapel_id
            $this->tapel_id->LinkCustomAttributes = "";
            $this->tapel_id->HrefValue = "";
            $this->tapel_id->TooltipValue = "";
        } elseif ($this->RowType == ROWTYPE_ADD) {
            // project_id
            $this->project_id->EditAttrs["class"] = "form-control";
            $this->project_id->EditCustomAttributes = "";
            $this->project_id->EditValue = HtmlEncode($this->project_id->CurrentValue);

            // kelas
            $this->kelas->EditAttrs["class"] = "form-control";
            $this->kelas->EditCustomAttributes = "";
            if (!$Security->isAdmin() && $Security->isLoggedIn() && !$this->userIDAllow("add")) { // Non system admin
                $this->kelas->CurrentValue = CurrentUserID();
                $this->kelas->EditValue = $this->kelas->CurrentValue;
                $this->kelas->ViewCustomAttributes = "";
            } else {
                if (!$this->kelas->Raw) {
                    $this->kelas->CurrentValue = HtmlDecode($this->kelas->CurrentValue);
                }
                $this->kelas->EditValue = HtmlEncode($this->kelas->CurrentValue);
            }

            // nis
            $this->nis->EditAttrs["class"] = "form-control";
            $this->nis->EditCustomAttributes = "";
            if (!$this->nis->Raw) {
                $this->nis->CurrentValue = HtmlDecode($this->nis->CurrentValue);
            }
            $this->nis->EditValue = HtmlEncode($this->nis->CurrentValue);
            $curVal = trim(strval($this->nis->CurrentValue));
            if ($curVal != "") {
                $this->nis->EditValue = $this->nis->lookupCacheOption($curVal);
                if ($this->nis->EditValue === null) { // Lookup from database
                    $filterWrk = "\"nis\"" . SearchString("=", $curVal, DATATYPE_MEMO, "");
                    $sqlWrk = $this->nis->Lookup->getSql(false, $filterWrk, '', $this, true, true);
                    $rswrk = Conn()->executeQuery($sqlWrk)->fetchAll(\PDO::FETCH_BOTH);
                    $ari = count($rswrk);
                    if ($ari > 0) { // Lookup values found
                        $arwrk = $this->nis->Lookup->renderViewRow($rswrk[0]);
                        $this->nis->EditValue = $this->nis->displayValue($arwrk);
                    } else {
                        $this->nis->EditValue = HtmlEncode($this->nis->CurrentValue);
                    }
                }
            } else {
                $this->nis->EditValue = null;
            }

            // proyek
            $this->proyek->EditAttrs["class"] = "form-control";
            $this->proyek->EditCustomAttributes = "";
            if (!$this->proyek->Raw) {
                $this->proyek->CurrentValue = HtmlDecode($this->proyek->CurrentValue);
            }
            $this->proyek->EditValue = HtmlEncode($this->proyek->CurrentValue);

            // dimensi
            $this->dimensi->EditAttrs["class"] = "form-control";
            $this->dimensi->EditCustomAttributes = "";
            if (!$this->dimensi->Raw) {
                $this->dimensi->CurrentValue = HtmlDecode($this->dimensi->CurrentValue);
            }
            $this->dimensi->EditValue = HtmlEncode($this->dimensi->CurrentValue);

            // sub_elemen
            $this->sub_elemen->EditAttrs["class"] = "form-control";
            $this->sub_elemen->EditCustomAttributes = "";
            if (!$this->sub_elemen->Raw) {
                $this->sub_elemen->CurrentValue = HtmlDecode($this->sub_elemen->CurrentValue);
            }
            $this->sub_elemen->EditValue = HtmlEncode($this->sub_elemen->CurrentValue);

            // nilai
            $this->nilai->EditAttrs["class"] = "form-control";
            $this->nilai->EditCustomAttributes = "";
            if (!$this->nilai->Raw) {
                $this->nilai->CurrentValue = HtmlDecode($this->nilai->CurrentValue);
            }
            $this->nilai->EditValue = HtmlEncode($this->nilai->CurrentValue);

            // tapel_id
            $this->tapel_id->EditAttrs["class"] = "form-control";
            $this->tapel_id->EditCustomAttributes = "";
            if (!$this->tapel_id->Raw) {
                $this->tapel_id->CurrentValue = HtmlDecode($this->tapel_id->CurrentValue);
            }
            $this->tapel_id->EditValue = HtmlEncode($this->tapel_id->CurrentValue);

            // Add refer script

            // project_id
            $this->project_id->LinkCustomAttributes = "";
            $this->project_id->HrefValue = "";

            // kelas
            $this->kelas->LinkCustomAttributes = "";
            $this->kelas->HrefValue = "";

            // nis
            $this->nis->LinkCustomAttributes = "";
            $this->nis->HrefValue = "";

            // proyek
            $this->proyek->LinkCustomAttributes = "";
            $this->proyek->HrefValue = "";

            // dimensi
            $this->dimensi->LinkCustomAttributes = "";
            $this->dimensi->HrefValue = "";

            // sub_elemen
            $this->sub_elemen->LinkCustomAttributes = "";
            $this->sub_elemen->HrefValue = "";

            // nilai
            $this->nilai->LinkCustomAttributes = "";
            $this->nilai->HrefValue = "";

            // tapel_id
            $this->tapel_id->LinkCustomAttributes = "";
            $this->tapel_id->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;

        // Check if validation required
        if (!Config("SERVER_VALIDATE")) {
            return true;
        }
        if ($this->project_id->Required) {
            if (!$this->project_id->IsDetailKey && EmptyValue($this->project_id->FormValue)) {
                $this->project_id->addErrorMessage(str_replace("%s", $this->project_id->caption(), $this->project_id->RequiredErrorMessage));
            }
        }
        if (!CheckInteger($this->project_id->FormValue)) {
            $this->project_id->addErrorMessage($this->project_id->getErrorMessage(false));
        }
        if ($this->kelas->Required) {
            if (!$this->kelas->IsDetailKey && EmptyValue($this->kelas->FormValue)) {
                $this->kelas->addErrorMessage(str_replace("%s", $this->kelas->caption(), $this->kelas->RequiredErrorMessage));
            }
        }
        if ($this->nis->Required) {
            if (!$this->nis->IsDetailKey && EmptyValue($this->nis->FormValue)) {
                $this->nis->addErrorMessage(str_replace("%s", $this->nis->caption(), $this->nis->RequiredErrorMessage));
            }
        }
        if ($this->proyek->Required) {
            if (!$this->proyek->IsDetailKey && EmptyValue($this->proyek->FormValue)) {
                $this->proyek->addErrorMessage(str_replace("%s", $this->proyek->caption(), $this->proyek->RequiredErrorMessage));
            }
        }
        if ($this->dimensi->Required) {
            if (!$this->dimensi->IsDetailKey && EmptyValue($this->dimensi->FormValue)) {
                $this->dimensi->addErrorMessage(str_replace("%s", $this->dimensi->caption(), $this->dimensi->RequiredErrorMessage));
            }
        }
        if ($this->sub_elemen->Required) {
            if (!$this->sub_elemen->IsDetailKey && EmptyValue($this->sub_elemen->FormValue)) {
                $this->sub_elemen->addErrorMessage(str_replace("%s", $this->sub_elemen->caption(), $this->sub_elemen->RequiredErrorMessage));
            }
        }
        if ($this->nilai->Required) {
            if (!$this->nilai->IsDetailKey && EmptyValue($this->nilai->FormValue)) {
                $this->nilai->addErrorMessage(str_replace("%s", $this->nilai->caption(), $this->nilai->RequiredErrorMessage));
            }
        }
        if ($this->tapel_id->Required) {
            if (!$this->tapel_id->IsDetailKey && EmptyValue($this->tapel_id->FormValue)) {
                $this->tapel_id->addErrorMessage(str_replace("%s", $this->tapel_id->caption(), $this->tapel_id->RequiredErrorMessage));
            }
        }

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

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

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

        // Check if valid User ID
        $validUser = false;
        if ($Security->currentUserID() != "" && !EmptyValue($this->kelas->CurrentValue) && !$Security->isAdmin()) { // Non system admin
            $validUser = $Security->isValidUserID($this->kelas->CurrentValue);
            if (!$validUser) {
                $userIdMsg = str_replace("%c", CurrentUserID(), $Language->phrase("UnAuthorizedUserID"));
                $userIdMsg = str_replace("%u", $this->kelas->CurrentValue, $userIdMsg);
                $this->setFailureMessage($userIdMsg);
                return false;
            }
        }
        $conn = $this->getConnection();

        // Load db values from rsold
        $this->loadDbValues($rsold);
        if ($rsold) {
        }
        $rsnew = [];

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

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

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

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

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

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

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

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

        // Call Row Inserting event
        $insertRow = $this->rowInserting($rsold, $rsnew);
        $addRow = false;
        if ($insertRow) {
            try {
                $addRow = $this->insert($rsnew);
            } catch (\Exception $e) {
                $this->setFailureMessage($e->getMessage());
            }
            if ($addRow) {
            }
        } else {
            if ($this->getSuccessMessage() != "" || $this->getFailureMessage() != "") {
                // Use the message, do nothing
            } elseif ($this->CancelMessage != "") {
                $this->setFailureMessage($this->CancelMessage);
                $this->CancelMessage = "";
            } else {
                $this->setFailureMessage($Language->phrase("InsertCancelled"));
            }
            $addRow = false;
        }
        if ($addRow) {
            // Call Row Inserted event
            $this->rowInserted($rsold, $rsnew);
        }

        // Clean upload path if any
        if ($addRow) {
        }

        // Write JSON for API request
        if (IsApi() && $addRow) {
            $row = $this->getRecordsFromRecordset([$rsnew], true);
            WriteJson(["success" => true, $this->TableVar => $row]);
        }
        return $addRow;
    }

    // Show link optionally based on User ID
    protected function showOptionLink($id = "")
    {
        global $Security;
        if ($Security->isLoggedIn() && !$Security->isAdmin() && !$this->userIDAllow($id)) {
            return $Security->isValidUserID($this->kelas->CurrentValue);
        }
        return true;
    }

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

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

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

            // Set up lookup SQL and connection
            switch ($fld->FieldVar) {
                case "x_nis":
                    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->UseLookupCache && $sql != "" && count($fld->Lookup->Options) == 0) {
                $totalCnt = $this->getRecordCount($sql, $conn);
                if ($totalCnt > $fld->LookupCacheCount) { // Total count > cache count, do not cache
                    return;
                }
                $rows = $conn->executeQuery($sql)->fetchAll(\PDO::FETCH_BOTH);
                $ar = [];
                foreach ($rows as $row) {
                    $row = $fld->Lookup->renderViewRow($row);
                    $ar[strval($row[0])] = $row;
                }
                $fld->Lookup->Options = $ar;
            }
        }
    }

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

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

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

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

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

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

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

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