<?php

namespace PHPMaker2021\gudang_ubi;

use Doctrine\DBAL\ParameterType;

/**
 * Table class for kedatangan
 */
class Kedatangan extends DbTable
{
    protected $SqlFrom = "";
    protected $SqlSelect = null;
    protected $SqlSelectList = null;
    protected $SqlWhere = "";
    protected $SqlGroupBy = "";
    protected $SqlHaving = "";
    protected $SqlOrderBy = "";
    public $UseSessionForListSql = true;
    public $UseCustomTemplate = false; // Use custom template

    // Column CSS classes
    public $LeftColumnClass = "col-sm-2 col-form-label ew-label";
    public $RightColumnClass = "col-sm-10";
    public $OffsetColumnClass = "col-sm-10 offset-sm-2";
    public $TableLeftColumnClass = "w-col-2";

    // Export
    public $ExportDoc;

    // Fields
    public $datang_id;
    public $datang_petugas;
    public $datang_tanggal;
    public $datang_varietas;
    public $datang_jumlah;
    public $datang_sup;
    public $datang_catatan;

    // Page ID
    public $PageID = ""; // To be overridden by subclass

    // Constructor
    public function __construct()
    {
        global $Language, $CurrentLanguage;
        parent::__construct();

        // Language object
        $Language = Container("language");
        $this->TableVar = 'kedatangan';
        $this->TableName = 'kedatangan';
        $this->TableType = 'TABLE';

        // Update Table
        $this->UpdateTable = "`kedatangan`";
        $this->Dbid = 'DB';
        $this->ExportAll = true;
        $this->ExportPageBreakCount = 0; // Page break per every n record (PDF only)
        $this->ExportPageOrientation = "portrait"; // Page orientation (PDF only)
        $this->ExportPageSize = "a4"; // Page size (PDF only)
        $this->ExportExcelPageOrientation = ""; // Page orientation (PhpSpreadsheet only)
        $this->ExportExcelPageSize = ""; // Page size (PhpSpreadsheet only)
        $this->ExportWordPageOrientation = "portrait"; // Page orientation (PHPWord only)
        $this->ExportWordColumnWidth = null; // Cell width (PHPWord only)
        $this->DetailAdd = false; // Allow detail add
        $this->DetailEdit = false; // Allow detail edit
        $this->DetailView = false; // Allow detail view
        $this->ShowMultipleDetails = false; // Show multiple details
        $this->GridAddRowCount = 5;
        $this->AllowAddDeleteRow = true; // Allow add/delete row
        $this->UserIDAllowSecurity = Config("DEFAULT_USER_ID_ALLOW_SECURITY"); // Default User ID allowed permissions
        $this->BasicSearch = new BasicSearch($this->TableVar);

        // datang_id
        $this->datang_id = new DbField('kedatangan', 'kedatangan', 'x_datang_id', 'datang_id', '`datang_id`', '`datang_id`', 3, 11, -1, false, '`datang_id`', false, false, false, 'FORMATTED TEXT', 'NO');
        $this->datang_id->IsAutoIncrement = true; // Autoincrement field
        $this->datang_id->IsPrimaryKey = true; // Primary key field
        $this->datang_id->Sortable = true; // Allow sort
        $this->datang_id->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->Fields['datang_id'] = &$this->datang_id;

        // datang_petugas
        $this->datang_petugas = new DbField('kedatangan', 'kedatangan', 'x_datang_petugas', 'datang_petugas', '`datang_petugas`', '`datang_petugas`', 3, 8, -1, false, '`datang_petugas`', false, false, false, 'FORMATTED TEXT', 'SELECT');
        $this->datang_petugas->Nullable = false; // NOT NULL field
        $this->datang_petugas->Sortable = true; // Allow sort
        $this->datang_petugas->UsePleaseSelect = true; // Use PleaseSelect by default
        $this->datang_petugas->PleaseSelectText = $Language->phrase("PleaseSelect"); // "PleaseSelect" text
        $this->datang_petugas->Lookup = new Lookup('datang_petugas', 'employees', false, 'EmployeeID', ["Name","","",""], [], [], [], [], [], [], '', '');
        $this->datang_petugas->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->Fields['datang_petugas'] = &$this->datang_petugas;

        // datang_tanggal
        $this->datang_tanggal = new DbField('kedatangan', 'kedatangan', 'x_datang_tanggal', 'datang_tanggal', '`datang_tanggal`', CastDateFieldForLike("`datang_tanggal`", 0, "DB"), 133, 10, 0, false, '`datang_tanggal`', false, false, false, 'FORMATTED TEXT', 'TEXT');
        $this->datang_tanggal->Nullable = false; // NOT NULL field
        $this->datang_tanggal->Required = true; // Required field
        $this->datang_tanggal->Sortable = true; // Allow sort
        $this->datang_tanggal->DefaultErrorMessage = str_replace("%s", $GLOBALS["DATE_FORMAT"], $Language->phrase("IncorrectDate"));
        $this->Fields['datang_tanggal'] = &$this->datang_tanggal;

        // datang_varietas
        $this->datang_varietas = new DbField('kedatangan', 'kedatangan', 'x_datang_varietas', 'datang_varietas', '`datang_varietas`', '`datang_varietas`', 3, 11, -1, false, '`datang_varietas`', false, false, false, 'FORMATTED TEXT', 'SELECT');
        $this->datang_varietas->Nullable = false; // NOT NULL field
        $this->datang_varietas->Required = true; // Required field
        $this->datang_varietas->Sortable = true; // Allow sort
        $this->datang_varietas->UsePleaseSelect = true; // Use PleaseSelect by default
        $this->datang_varietas->PleaseSelectText = $Language->phrase("PleaseSelect"); // "PleaseSelect" text
        $this->datang_varietas->Lookup = new Lookup('datang_varietas', 'varietas', false, 'var_id', ["var_nama","","",""], [], [], [], [], [], [], '', '');
        $this->datang_varietas->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->Fields['datang_varietas'] = &$this->datang_varietas;

        // datang_jumlah
        $this->datang_jumlah = new DbField('kedatangan', 'kedatangan', 'x_datang_jumlah', 'datang_jumlah', '`datang_jumlah`', '`datang_jumlah`', 131, 10, -1, false, '`datang_jumlah`', false, false, false, 'FORMATTED TEXT', 'TEXT');
        $this->datang_jumlah->Nullable = false; // NOT NULL field
        $this->datang_jumlah->Required = true; // Required field
        $this->datang_jumlah->Sortable = true; // Allow sort
        $this->datang_jumlah->DefaultDecimalPrecision = 2; // Default decimal precision
        $this->datang_jumlah->DefaultErrorMessage = $Language->phrase("IncorrectFloat");
        $this->Fields['datang_jumlah'] = &$this->datang_jumlah;

        // datang_sup
        $this->datang_sup = new DbField('kedatangan', 'kedatangan', 'x_datang_sup', 'datang_sup', '`datang_sup`', '`datang_sup`', 3, 11, -1, false, '`datang_sup`', false, false, false, 'FORMATTED TEXT', 'SELECT');
        $this->datang_sup->Nullable = false; // NOT NULL field
        $this->datang_sup->Required = true; // Required field
        $this->datang_sup->Sortable = true; // Allow sort
        $this->datang_sup->UsePleaseSelect = true; // Use PleaseSelect by default
        $this->datang_sup->PleaseSelectText = $Language->phrase("PleaseSelect"); // "PleaseSelect" text
        $this->datang_sup->Lookup = new Lookup('datang_sup', 'sup', false, 'sup_id', ["sup_nama","","",""], [], [], [], [], [], [], '', '');
        $this->datang_sup->DefaultErrorMessage = $Language->phrase("IncorrectInteger");
        $this->Fields['datang_sup'] = &$this->datang_sup;

        // datang_catatan
        $this->datang_catatan = new DbField('kedatangan', 'kedatangan', 'x_datang_catatan', 'datang_catatan', '`datang_catatan`', '`datang_catatan`', 201, 65535, -1, false, '`datang_catatan`', false, false, false, 'FORMATTED TEXT', 'TEXTAREA');
        $this->datang_catatan->Nullable = false; // NOT NULL field
        $this->datang_catatan->Required = true; // Required field
        $this->datang_catatan->Sortable = true; // Allow sort
        $this->Fields['datang_catatan'] = &$this->datang_catatan;
    }

    // Field Visibility
    public function getFieldVisibility($fldParm)
    {
        global $Security;
        return $this->$fldParm->Visible; // Returns original value
    }

    // Set left column class (must be predefined col-*-* classes of Bootstrap grid system)
    public function setLeftColumnClass($class)
    {
        if (preg_match('/^col\-(\w+)\-(\d+)$/', $class, $match)) {
            $this->LeftColumnClass = $class . " col-form-label ew-label";
            $this->RightColumnClass = "col-" . $match[1] . "-" . strval(12 - (int)$match[2]);
            $this->OffsetColumnClass = $this->RightColumnClass . " " . str_replace("col-", "offset-", $class);
            $this->TableLeftColumnClass = preg_replace('/^col-\w+-(\d+)$/', "w-col-$1", $class); // Change to w-col-*
        }
    }

    // Single column sort
    public function updateSort(&$fld)
    {
        if ($this->CurrentOrder == $fld->Name) {
            $sortField = $fld->Expression;
            $lastSort = $fld->getSort();
            if (in_array($this->CurrentOrderType, ["ASC", "DESC", "NO"])) {
                $curSort = $this->CurrentOrderType;
            } else {
                $curSort = $lastSort;
            }
            $fld->setSort($curSort);
            $orderBy = in_array($curSort, ["ASC", "DESC"]) ? $sortField . " " . $curSort : "";
            $this->setSessionOrderBy($orderBy); // Save to Session
        } else {
            $fld->setSort("");
        }
    }

    // Table level SQL
    public function getSqlFrom() // From
    {
        return ($this->SqlFrom != "") ? $this->SqlFrom : "`kedatangan`";
    }

    public function sqlFrom() // For backward compatibility
    {
        return $this->getSqlFrom();
    }

    public function setSqlFrom($v)
    {
        $this->SqlFrom = $v;
    }

    public function getSqlSelect() // Select
    {
        return $this->SqlSelect ?? $this->getQueryBuilder()->select("*");
    }

    public function sqlSelect() // For backward compatibility
    {
        return $this->getSqlSelect();
    }

    public function setSqlSelect($v)
    {
        $this->SqlSelect = $v;
    }

    public function getSqlWhere() // Where
    {
        $where = ($this->SqlWhere != "") ? $this->SqlWhere : "";
        $this->DefaultFilter = "";
        AddFilter($where, $this->DefaultFilter);
        return $where;
    }

    public function sqlWhere() // For backward compatibility
    {
        return $this->getSqlWhere();
    }

    public function setSqlWhere($v)
    {
        $this->SqlWhere = $v;
    }

    public function getSqlGroupBy() // Group By
    {
        return ($this->SqlGroupBy != "") ? $this->SqlGroupBy : "";
    }

    public function sqlGroupBy() // For backward compatibility
    {
        return $this->getSqlGroupBy();
    }

    public function setSqlGroupBy($v)
    {
        $this->SqlGroupBy = $v;
    }

    public function getSqlHaving() // Having
    {
        return ($this->SqlHaving != "") ? $this->SqlHaving : "";
    }

    public function sqlHaving() // For backward compatibility
    {
        return $this->getSqlHaving();
    }

    public function setSqlHaving($v)
    {
        $this->SqlHaving = $v;
    }

    public function getSqlOrderBy() // Order By
    {
        return ($this->SqlOrderBy != "") ? $this->SqlOrderBy : $this->DefaultSort;
    }

    public function sqlOrderBy() // For backward compatibility
    {
        return $this->getSqlOrderBy();
    }

    public function setSqlOrderBy($v)
    {
        $this->SqlOrderBy = $v;
    }

    // Apply User ID filters
    public function applyUserIDFilters($filter)
    {
        return $filter;
    }

    // Check if User ID security allows view all
    public function userIDAllow($id = "")
    {
        $allow = $this->UserIDAllowSecurity;
        switch ($id) {
            case "add":
            case "copy":
            case "gridadd":
            case "register":
            case "addopt":
                return (($allow & 1) == 1);
            case "edit":
            case "gridedit":
            case "update":
            case "changepassword":
            case "resetpassword":
                return (($allow & 4) == 4);
            case "delete":
                return (($allow & 2) == 2);
            case "view":
                return (($allow & 32) == 32);
            case "search":
                return (($allow & 64) == 64);
            default:
                return (($allow & 8) == 8);
        }
    }

    /**
     * Get record count
     *
     * @param string|QueryBuilder $sql SQL or QueryBuilder
     * @param mixed $c Connection
     * @return int
     */
    public function getRecordCount($sql, $c = null)
    {
        $cnt = -1;
        $rs = null;
        if ($sql instanceof \Doctrine\DBAL\Query\QueryBuilder) { // Query builder
            $sql = $sql->resetQueryPart("orderBy")->getSQL();
        }
        $pattern = '/^SELECT\s([\s\S]+)\sFROM\s/i';
        // Skip Custom View / SubQuery / SELECT DISTINCT / ORDER BY
        if (
            ($this->TableType == 'TABLE' || $this->TableType == 'VIEW' || $this->TableType == 'LINKTABLE') &&
            preg_match($pattern, $sql) && !preg_match('/\(\s*(SELECT[^)]+)\)/i', $sql) &&
            !preg_match('/^\s*select\s+distinct\s+/i', $sql) && !preg_match('/\s+order\s+by\s+/i', $sql)
        ) {
            $sqlwrk = "SELECT COUNT(*) FROM " . preg_replace($pattern, "", $sql);
        } else {
            $sqlwrk = "SELECT COUNT(*) FROM (" . $sql . ") COUNT_TABLE";
        }
        $conn = $c ?? $this->getConnection();
        $rs = $conn->executeQuery($sqlwrk);
        $cnt = $rs->fetchColumn();
        if ($cnt !== false) {
            return (int)$cnt;
        }

        // Unable to get count by SELECT COUNT(*), execute the SQL to get record count directly
        return ExecuteRecordCount($sql, $conn);
    }

    // Get SQL
    public function getSql($where, $orderBy = "")
    {
        return $this->buildSelectSql(
            $this->getSqlSelect(),
            $this->getSqlFrom(),
            $this->getSqlWhere(),
            $this->getSqlGroupBy(),
            $this->getSqlHaving(),
            $this->getSqlOrderBy(),
            $where,
            $orderBy
        )->getSQL();
    }

    // Table SQL
    public function getCurrentSql()
    {
        $filter = $this->CurrentFilter;
        $filter = $this->applyUserIDFilters($filter);
        $sort = $this->getSessionOrderBy();
        return $this->getSql($filter, $sort);
    }

    /**
     * Table SQL with List page filter
     *
     * @return QueryBuilder
     */
    public function getListSql()
    {
        $filter = $this->UseSessionForListSql ? $this->getSessionWhere() : "";
        AddFilter($filter, $this->CurrentFilter);
        $filter = $this->applyUserIDFilters($filter);
        $this->recordsetSelecting($filter);
        $select = $this->getSqlSelect();
        $from = $this->getSqlFrom();
        $sort = $this->UseSessionForListSql ? $this->getSessionOrderBy() : "";
        $this->Sort = $sort;
        return $this->buildSelectSql(
            $select,
            $from,
            $this->getSqlWhere(),
            $this->getSqlGroupBy(),
            $this->getSqlHaving(),
            $this->getSqlOrderBy(),
            $filter,
            $sort
        );
    }

    // Get ORDER BY clause
    public function getOrderBy()
    {
        $orderBy = $this->getSqlOrderBy();
        $sort = $this->getSessionOrderBy();
        if ($orderBy != "" && $sort != "") {
            $orderBy .= ", " . $sort;
        } elseif ($sort != "") {
            $orderBy = $sort;
        }
        return $orderBy;
    }

    // Get record count based on filter (for detail record count in master table pages)
    public function loadRecordCount($filter)
    {
        $origFilter = $this->CurrentFilter;
        $this->CurrentFilter = $filter;
        $this->recordsetSelecting($this->CurrentFilter);
        $select = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlSelect() : $this->getQueryBuilder()->select("*");
        $groupBy = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlGroupBy() : "";
        $having = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlHaving() : "";
        $sql = $this->buildSelectSql($select, $this->getSqlFrom(), $this->getSqlWhere(), $groupBy, $having, "", $this->CurrentFilter, "");
        $cnt = $this->getRecordCount($sql);
        $this->CurrentFilter = $origFilter;
        return $cnt;
    }

    // Get record count (for current List page)
    public function listRecordCount()
    {
        $filter = $this->getSessionWhere();
        AddFilter($filter, $this->CurrentFilter);
        $filter = $this->applyUserIDFilters($filter);
        $this->recordsetSelecting($filter);
        $select = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlSelect() : $this->getQueryBuilder()->select("*");
        $groupBy = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlGroupBy() : "";
        $having = $this->TableType == 'CUSTOMVIEW' ? $this->getSqlHaving() : "";
        $sql = $this->buildSelectSql($select, $this->getSqlFrom(), $this->getSqlWhere(), $groupBy, $having, "", $filter, "");
        $cnt = $this->getRecordCount($sql);
        return $cnt;
    }

    /**
     * INSERT statement
     *
     * @param mixed $rs
     * @return QueryBuilder
     */
    protected function insertSql(&$rs)
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->insert($this->UpdateTable);
        foreach ($rs as $name => $value) {
            if (!isset($this->Fields[$name]) || $this->Fields[$name]->IsCustom) {
                continue;
            }
            $type = GetParameterType($this->Fields[$name], $value, $this->Dbid);
            $queryBuilder->setValue($this->Fields[$name]->Expression, $queryBuilder->createPositionalParameter($value, $type));
        }
        return $queryBuilder;
    }

    // Insert
    public function insert(&$rs)
    {
        $conn = $this->getConnection();
        $success = $this->insertSql($rs)->execute();
        if ($success) {
            // Get insert id if necessary
            $this->datang_id->setDbValue($conn->lastInsertId());
            $rs['datang_id'] = $this->datang_id->DbValue;
        }
        return $success;
    }

    /**
     * UPDATE statement
     *
     * @param array $rs Data to be updated
     * @param string|array $where WHERE clause
     * @param string $curfilter Filter
     * @return QueryBuilder
     */
    protected function updateSql(&$rs, $where = "", $curfilter = true)
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->update($this->UpdateTable);
        foreach ($rs as $name => $value) {
            if (!isset($this->Fields[$name]) || $this->Fields[$name]->IsCustom || $this->Fields[$name]->IsAutoIncrement) {
                continue;
            }
            $type = GetParameterType($this->Fields[$name], $value, $this->Dbid);
            $queryBuilder->set($this->Fields[$name]->Expression, $queryBuilder->createPositionalParameter($value, $type));
        }
        $filter = ($curfilter) ? $this->CurrentFilter : "";
        if (is_array($where)) {
            $where = $this->arrayToFilter($where);
        }
        AddFilter($filter, $where);
        if ($filter != "") {
            $queryBuilder->where($filter);
        }
        return $queryBuilder;
    }

    // Update
    public function update(&$rs, $where = "", $rsold = null, $curfilter = true)
    {
        // If no field is updated, execute may return 0. Treat as success
        $success = $this->updateSql($rs, $where, $curfilter)->execute();
        $success = ($success > 0) ? $success : true;
        return $success;
    }

    /**
     * DELETE statement
     *
     * @param array $rs Key values
     * @param string|array $where WHERE clause
     * @param string $curfilter Filter
     * @return QueryBuilder
     */
    protected function deleteSql(&$rs, $where = "", $curfilter = true)
    {
        $queryBuilder = $this->getQueryBuilder();
        $queryBuilder->delete($this->UpdateTable);
        if (is_array($where)) {
            $where = $this->arrayToFilter($where);
        }
        if ($rs) {
            if (array_key_exists('datang_id', $rs)) {
                AddFilter($where, QuotedName('datang_id', $this->Dbid) . '=' . QuotedValue($rs['datang_id'], $this->datang_id->DataType, $this->Dbid));
            }
        }
        $filter = ($curfilter) ? $this->CurrentFilter : "";
        AddFilter($filter, $where);
        return $queryBuilder->where($filter != "" ? $filter : "0=1");
    }

    // Delete
    public function delete(&$rs, $where = "", $curfilter = false)
    {
        $success = true;
        if ($success) {
            $success = $this->deleteSql($rs, $where, $curfilter)->execute();
        }
        return $success;
    }

    // Load DbValue from recordset or array
    protected function loadDbValues($row)
    {
        if (!is_array($row)) {
            return;
        }
        $this->datang_id->DbValue = $row['datang_id'];
        $this->datang_petugas->DbValue = $row['datang_petugas'];
        $this->datang_tanggal->DbValue = $row['datang_tanggal'];
        $this->datang_varietas->DbValue = $row['datang_varietas'];
        $this->datang_jumlah->DbValue = $row['datang_jumlah'];
        $this->datang_sup->DbValue = $row['datang_sup'];
        $this->datang_catatan->DbValue = $row['datang_catatan'];
    }

    // Delete uploaded files
    public function deleteUploadedFiles($row)
    {
        $this->loadDbValues($row);
    }

    // Record filter WHERE clause
    protected function sqlKeyFilter()
    {
        return "`datang_id` = @datang_id@";
    }

    // Get record filter
    public function getRecordFilter($row = null)
    {
        $keyFilter = $this->sqlKeyFilter();
        if (is_array($row)) {
            $val = array_key_exists('datang_id', $row) ? $row['datang_id'] : null;
        } else {
            $val = $this->datang_id->OldValue !== null ? $this->datang_id->OldValue : $this->datang_id->CurrentValue;
        }
        if (!is_numeric($val)) {
            return "0=1"; // Invalid key
        }
        if ($val === null) {
            return "0=1"; // Invalid key
        } else {
            $keyFilter = str_replace("@datang_id@", AdjustSql($val, $this->Dbid), $keyFilter); // Replace key value
        }
        return $keyFilter;
    }

    // Return page URL
    public function getReturnUrl()
    {
        $name = PROJECT_NAME . "_" . $this->TableVar . "_" . Config("TABLE_RETURN_URL");
        // Get referer URL automatically
        if (ReferUrl() != "" && ReferPageName() != CurrentPageName() && ReferPageName() != "login") { // Referer not same page or login page
            $_SESSION[$name] = ReferUrl(); // Save to Session
        }
        if (@$_SESSION[$name] != "") {
            return $_SESSION[$name];
        } else {
            return GetUrl("KedatanganList");
        }
    }

    public function setReturnUrl($v)
    {
        $_SESSION[PROJECT_NAME . "_" . $this->TableVar . "_" . Config("TABLE_RETURN_URL")] = $v;
    }

    // Get modal caption
    public function getModalCaption($pageName)
    {
        global $Language;
        if ($pageName == "KedatanganView") {
            return $Language->phrase("View");
        } elseif ($pageName == "KedatanganEdit") {
            return $Language->phrase("Edit");
        } elseif ($pageName == "KedatanganAdd") {
            return $Language->phrase("Add");
        } else {
            return "";
        }
    }

    // List URL
    public function getListUrl()
    {
        return "KedatanganList";
    }

    // View URL
    public function getViewUrl($parm = "")
    {
        if ($parm != "") {
            $url = $this->keyUrl("KedatanganView", $this->getUrlParm($parm));
        } else {
            $url = $this->keyUrl("KedatanganView", $this->getUrlParm(Config("TABLE_SHOW_DETAIL") . "="));
        }
        return $this->addMasterUrl($url);
    }

    // Add URL
    public function getAddUrl($parm = "")
    {
        if ($parm != "") {
            $url = "KedatanganAdd?" . $this->getUrlParm($parm);
        } else {
            $url = "KedatanganAdd";
        }
        return $this->addMasterUrl($url);
    }

    // Edit URL
    public function getEditUrl($parm = "")
    {
        $url = $this->keyUrl("KedatanganEdit", $this->getUrlParm($parm));
        return $this->addMasterUrl($url);
    }

    // Inline edit URL
    public function getInlineEditUrl()
    {
        $url = $this->keyUrl(CurrentPageName(), $this->getUrlParm("action=edit"));
        return $this->addMasterUrl($url);
    }

    // Copy URL
    public function getCopyUrl($parm = "")
    {
        $url = $this->keyUrl("KedatanganAdd", $this->getUrlParm($parm));
        return $this->addMasterUrl($url);
    }

    // Inline copy URL
    public function getInlineCopyUrl()
    {
        $url = $this->keyUrl(CurrentPageName(), $this->getUrlParm("action=copy"));
        return $this->addMasterUrl($url);
    }

    // Delete URL
    public function getDeleteUrl()
    {
        return $this->keyUrl("KedatanganDelete", $this->getUrlParm());
    }

    // Add master url
    public function addMasterUrl($url)
    {
        return $url;
    }

    public function keyToJson($htmlEncode = false)
    {
        $json = "";
        $json .= "datang_id:" . JsonEncode($this->datang_id->CurrentValue, "number");
        $json = "{" . $json . "}";
        if ($htmlEncode) {
            $json = HtmlEncode($json);
        }
        return $json;
    }

    // Add key value to URL
    public function keyUrl($url, $parm = "")
    {
        if ($this->datang_id->CurrentValue !== null) {
            $url .= "/" . rawurlencode($this->datang_id->CurrentValue);
        } else {
            return "javascript:ew.alert(ew.language.phrase('InvalidRecord'));";
        }
        if ($parm != "") {
            $url .= "?" . $parm;
        }
        return $url;
    }

    // Render sort
    public function renderSort($fld)
    {
        $classId = $fld->TableVar . "_" . $fld->Param;
        $scriptId = str_replace("%id%", $classId, "tpc_%id%");
        $scriptStart = $this->UseCustomTemplate ? "<template id=\"" . $scriptId . "\">" : "";
        $scriptEnd = $this->UseCustomTemplate ? "</template>" : "";
        $jsSort = " class=\"ew-pointer\" onclick=\"ew.sort(event, '" . $this->sortUrl($fld) . "', 1);\"";
        if ($this->sortUrl($fld) == "") {
            $html = <<<NOSORTHTML
{$scriptStart}<div class="ew-table-header-caption">{$fld->caption()}</div>{$scriptEnd}
NOSORTHTML;
        } else {
            if ($fld->getSort() == "ASC") {
                $sortIcon = '<i class="fas fa-sort-up"></i>';
            } elseif ($fld->getSort() == "DESC") {
                $sortIcon = '<i class="fas fa-sort-down"></i>';
            } else {
                $sortIcon = '';
            }
            $html = <<<SORTHTML
{$scriptStart}<div{$jsSort}><div class="ew-table-header-btn"><span class="ew-table-header-caption">{$fld->caption()}</span><span class="ew-table-header-sort">{$sortIcon}</span></div></div>{$scriptEnd}
SORTHTML;
        }
        return $html;
    }

    // Sort URL
    public function sortUrl($fld)
    {
        if (
            $this->CurrentAction || $this->isExport() ||
            in_array($fld->Type, [128, 204, 205])
        ) { // Unsortable data type
                return "";
        } elseif ($fld->Sortable) {
            $urlParm = $this->getUrlParm("order=" . urlencode($fld->Name) . "&amp;ordertype=" . $fld->getNextSort());
            return $this->addMasterUrl(CurrentPageName() . "?" . $urlParm);
        } else {
            return "";
        }
    }

    // Get record keys from Post/Get/Session
    public function getRecordKeys()
    {
        $arKeys = [];
        $arKey = [];
        if (Param("key_m") !== null) {
            $arKeys = Param("key_m");
            $cnt = count($arKeys);
        } else {
            if (($keyValue = Param("datang_id") ?? Route("datang_id")) !== null) {
                $arKeys[] = $keyValue;
            } elseif (IsApi() && (($keyValue = Key(0) ?? Route(2)) !== null)) {
                $arKeys[] = $keyValue;
            } else {
                $arKeys = null; // Do not setup
            }

            //return $arKeys; // Do not return yet, so the values will also be checked by the following code
        }
        // Check keys
        $ar = [];
        if (is_array($arKeys)) {
            foreach ($arKeys as $key) {
                if (!is_numeric($key)) {
                    continue;
                }
                $ar[] = $key;
            }
        }
        return $ar;
    }

    // Get filter from record keys
    public function getFilterFromRecordKeys($setCurrent = true)
    {
        $arKeys = $this->getRecordKeys();
        $keyFilter = "";
        foreach ($arKeys as $key) {
            if ($keyFilter != "") {
                $keyFilter .= " OR ";
            }
            if ($setCurrent) {
                $this->datang_id->CurrentValue = $key;
            } else {
                $this->datang_id->OldValue = $key;
            }
            $keyFilter .= "(" . $this->getRecordFilter() . ")";
        }
        return $keyFilter;
    }

    // Load recordset based on filter
    public function &loadRs($filter)
    {
        $sql = $this->getSql($filter); // Set up filter (WHERE Clause)
        $conn = $this->getConnection();
        $stmt = $conn->executeQuery($sql);
        return $stmt;
    }

    // Load row values from record
    public function loadListRowValues(&$rs)
    {
        if (is_array($rs)) {
            $row = $rs;
        } elseif ($rs && property_exists($rs, "fields")) { // Recordset
            $row = $rs->fields;
        } else {
            return;
        }
        $this->datang_id->setDbValue($row['datang_id']);
        $this->datang_petugas->setDbValue($row['datang_petugas']);
        $this->datang_tanggal->setDbValue($row['datang_tanggal']);
        $this->datang_varietas->setDbValue($row['datang_varietas']);
        $this->datang_jumlah->setDbValue($row['datang_jumlah']);
        $this->datang_sup->setDbValue($row['datang_sup']);
        $this->datang_catatan->setDbValue($row['datang_catatan']);
    }

    // Render list row values
    public function renderListRow()
    {
        global $Security, $CurrentLanguage, $Language;

        // Call Row Rendering event
        $this->rowRendering();

        // Common render codes

        // datang_id

        // datang_petugas

        // datang_tanggal

        // datang_varietas

        // datang_jumlah

        // datang_sup

        // datang_catatan

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

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

        // datang_tanggal
        $this->datang_tanggal->ViewValue = $this->datang_tanggal->CurrentValue;
        $this->datang_tanggal->ViewValue = FormatDateTime($this->datang_tanggal->ViewValue, 0);
        $this->datang_tanggal->ViewCustomAttributes = "";

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

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

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

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

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

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

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

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

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

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

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

        // Call Row Rendered event
        $this->rowRendered();

        // Save data for Custom Template
        $this->Rows[] = $this->customTemplateFieldValues();
    }

    // Render edit row values
    public function renderEditRow()
    {
        global $Security, $CurrentLanguage, $Language;

        // Call Row Rendering event
        $this->rowRendering();

        // datang_id
        $this->datang_id->EditAttrs["class"] = "form-control";
        $this->datang_id->EditCustomAttributes = "";
        $this->datang_id->EditValue = $this->datang_id->CurrentValue;
        $this->datang_id->EditValue = FormatNumber($this->datang_id->EditValue, 0, -2, -2, -2);
        $this->datang_id->ViewCustomAttributes = "";

        // datang_petugas

        // datang_tanggal
        $this->datang_tanggal->EditAttrs["class"] = "form-control";
        $this->datang_tanggal->EditCustomAttributes = "";
        $this->datang_tanggal->EditValue = FormatDateTime($this->datang_tanggal->CurrentValue, 8);
        $this->datang_tanggal->PlaceHolder = RemoveHtml($this->datang_tanggal->caption());

        // datang_varietas
        $this->datang_varietas->EditAttrs["class"] = "form-control";
        $this->datang_varietas->EditCustomAttributes = "";
        $this->datang_varietas->PlaceHolder = RemoveHtml($this->datang_varietas->caption());

        // datang_jumlah
        $this->datang_jumlah->EditAttrs["class"] = "form-control";
        $this->datang_jumlah->EditCustomAttributes = "";
        $this->datang_jumlah->EditValue = $this->datang_jumlah->CurrentValue;
        $this->datang_jumlah->PlaceHolder = RemoveHtml($this->datang_jumlah->caption());
        if (strval($this->datang_jumlah->EditValue) != "" && is_numeric($this->datang_jumlah->EditValue)) {
            $this->datang_jumlah->EditValue = FormatNumber($this->datang_jumlah->EditValue, -2, -2, -2, -2);
        }

        // datang_sup
        $this->datang_sup->EditAttrs["class"] = "form-control";
        $this->datang_sup->EditCustomAttributes = "";
        $this->datang_sup->PlaceHolder = RemoveHtml($this->datang_sup->caption());

        // datang_catatan
        $this->datang_catatan->EditAttrs["class"] = "form-control";
        $this->datang_catatan->EditCustomAttributes = "";
        $this->datang_catatan->EditValue = $this->datang_catatan->CurrentValue;
        $this->datang_catatan->PlaceHolder = RemoveHtml($this->datang_catatan->caption());

        // Call Row Rendered event
        $this->rowRendered();
    }

    // Aggregate list row values
    public function aggregateListRowValues()
    {
    }

    // Aggregate list row (for rendering)
    public function aggregateListRow()
    {
        // Call Row Rendered event
        $this->rowRendered();
    }

    // Export data in HTML/CSV/Word/Excel/Email/PDF format
    public function exportDocument($doc, $recordset, $startRec = 1, $stopRec = 1, $exportPageType = "")
    {
        if (!$recordset || !$doc) {
            return;
        }
        if (!$doc->ExportCustom) {
            // Write header
            $doc->exportTableHeader();
            if ($doc->Horizontal) { // Horizontal format, write header
                $doc->beginExportRow();
                if ($exportPageType == "view") {
                    $doc->exportCaption($this->datang_id);
                    $doc->exportCaption($this->datang_petugas);
                    $doc->exportCaption($this->datang_tanggal);
                    $doc->exportCaption($this->datang_varietas);
                    $doc->exportCaption($this->datang_jumlah);
                    $doc->exportCaption($this->datang_sup);
                    $doc->exportCaption($this->datang_catatan);
                } else {
                    $doc->exportCaption($this->datang_id);
                    $doc->exportCaption($this->datang_petugas);
                    $doc->exportCaption($this->datang_tanggal);
                    $doc->exportCaption($this->datang_varietas);
                    $doc->exportCaption($this->datang_jumlah);
                    $doc->exportCaption($this->datang_sup);
                }
                $doc->endExportRow();
            }
        }

        // Move to first record
        $recCnt = $startRec - 1;
        $stopRec = ($stopRec > 0) ? $stopRec : PHP_INT_MAX;
        while (!$recordset->EOF && $recCnt < $stopRec) {
            $row = $recordset->fields;
            $recCnt++;
            if ($recCnt >= $startRec) {
                $rowCnt = $recCnt - $startRec + 1;

                // Page break
                if ($this->ExportPageBreakCount > 0) {
                    if ($rowCnt > 1 && ($rowCnt - 1) % $this->ExportPageBreakCount == 0) {
                        $doc->exportPageBreak();
                    }
                }
                $this->loadListRowValues($row);

                // Render row
                $this->RowType = ROWTYPE_VIEW; // Render view
                $this->resetAttributes();
                $this->renderListRow();
                if (!$doc->ExportCustom) {
                    $doc->beginExportRow($rowCnt); // Allow CSS styles if enabled
                    if ($exportPageType == "view") {
                        $doc->exportField($this->datang_id);
                        $doc->exportField($this->datang_petugas);
                        $doc->exportField($this->datang_tanggal);
                        $doc->exportField($this->datang_varietas);
                        $doc->exportField($this->datang_jumlah);
                        $doc->exportField($this->datang_sup);
                        $doc->exportField($this->datang_catatan);
                    } else {
                        $doc->exportField($this->datang_id);
                        $doc->exportField($this->datang_petugas);
                        $doc->exportField($this->datang_tanggal);
                        $doc->exportField($this->datang_varietas);
                        $doc->exportField($this->datang_jumlah);
                        $doc->exportField($this->datang_sup);
                    }
                    $doc->endExportRow($rowCnt);
                }
            }

            // Call Row Export server event
            if ($doc->ExportCustom) {
                $this->rowExport($row);
            }
            $recordset->moveNext();
        }
        if (!$doc->ExportCustom) {
            $doc->exportTableFooter();
        }
    }

    // Get file data
    public function getFileData($fldparm, $key, $resize, $width = 0, $height = 0, $plugins = [])
    {
        // No binary fields
        return false;
    }

    // Table level events

    // Recordset Selecting event
    public function recordsetSelecting(&$filter)
    {
        // Enter your code here
    }

    // Recordset Selected event
    public function recordsetSelected(&$rs)
    {
        //Log("Recordset Selected");
    }

    // Recordset Search Validated event
    public function recordsetSearchValidated()
    {
        // Example:
        //$this->MyField1->AdvancedSearch->SearchValue = "your search criteria"; // Search value
    }

    // Recordset Searching event
    public function recordsetSearching(&$filter)
    {
        // Enter your code here
    }

    // Row_Selecting event
    public function rowSelecting(&$filter)
    {
        // Enter your code here
    }

    // Row Selected event
    public function rowSelected(&$rs)
    {
        //Log("Row Selected");
    }

    // Row Inserting event
    public function rowInserting($rsold, &$rsnew)
    {
        // Enter your code here
        // To cancel, set return value to false
        return true;
    }

    // Row Inserted event
    public function rowInserted($rsold, &$rsnew)
    {
        //Log("Row Inserted");
    }

    // Row Updating event
    public function rowUpdating($rsold, &$rsnew)
    {
        // Enter your code here
        // To cancel, set return value to false
        return true;
    }

    // Row Updated event
    public function rowUpdated($rsold, &$rsnew)
    {
        //Log("Row Updated");
    }

    // Row Update Conflict event
    public function rowUpdateConflict($rsold, &$rsnew)
    {
        // Enter your code here
        // To ignore conflict, set return value to false
        return true;
    }

    // Grid Inserting event
    public function gridInserting()
    {
        // Enter your code here
        // To reject grid insert, set return value to false
        return true;
    }

    // Grid Inserted event
    public function gridInserted($rsnew)
    {
        //Log("Grid Inserted");
    }

    // Grid Updating event
    public function gridUpdating($rsold)
    {
        // Enter your code here
        // To reject grid update, set return value to false
        return true;
    }

    // Grid Updated event
    public function gridUpdated($rsold, $rsnew)
    {
        //Log("Grid Updated");
    }

    // Row Deleting event
    public function rowDeleting(&$rs)
    {
        // Enter your code here
        // To cancel, set return value to False
        return true;
    }

    // Row Deleted event
    public function rowDeleted(&$rs)
    {
        //Log("Row Deleted");
    }

    // Email Sending event
    public function emailSending($email, &$args)
    {
        //var_dump($email); var_dump($args); exit();
        return true;
    }

    // Lookup Selecting event
    public function lookupSelecting($fld, &$filter)
    {
        //var_dump($fld->Name, $fld->Lookup, $filter); // Uncomment to view the filter
        // Enter your code here
    }

    // Row Rendering event
    public function rowRendering()
    {
        // Enter your code here
    }

    // Row Rendered event
    public function rowRendered()
    {
        // To view properties of field class, use:
        //var_dump($this-><FieldName>);
    }

    // User ID Filtering event
    public function userIdFiltering(&$filter)
    {
        // Enter your code here
    }
}
