<?php

class Mditem extends MY_Controller
{
    var $db;

    function __construct()
    {
        parent::__construct();
    }

    function index()
    {
        echo "Mditem API";
    }

    function search()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $prm = $this->sys_input;
            $where = "M_ItemIsActive = 'Y'";

            // Filter by category
            // if (isset($prm['category_id']) && $prm['category_id'] != '' && intval($prm['category_id']) > 0) {
            //     $where .= " AND M_ItemItem_CategoryID = " . $prm['category_id'];
            // }

            // Filter by group
            if (isset($prm['group_id']) && $prm['group_id'] != '' && intval($prm['group_id']) > 0) {
                $where .= " AND M_ItemNat_GroupID = " . $prm['group_id'];
            }

            // Search by name
            if (isset($prm['search']) && trim($prm['search']) != '') {
                $search = trim($prm['search']);
                $where .= " AND M_ItemDesc LIKE '%" . $search . "%'";
            }

            // Pagination
            $number_limit = 20;
            $number_offset = 0;
            if (isset($prm['current_page']) && $prm['current_page'] > 0) {
                $number_offset = ($prm['current_page'] - 1) * $number_limit;
            }

            $sql = "SELECT
                    M_ItemID,
                    M_ItemCode,
                    M_ItemDesc,
                    M_ItemInventoryCode,
                    M_ItemItem_CategoryID,
                    M_ItemNat_GroupID,
                    M_ItemNat_SubGroupID,
                    M_ItemFa_ClassID,
                    M_ItemItem_UnitID,
                    itemCategoryID,
                    itemCategoryName,
                    Nat_GroupID,
                    Nat_GroupName,
                    Nat_SubGroupID,
                    Nat_SubGroupName,
                    Fa_ClassID,
                    Fa_ClassName,
                    Fa_ClassFlagType,
                    M_InventarisGolID,
                    M_InventarisGolName,
                    ItemUnitID,
                    ItemUnitCode,
                    GROUP_CONCAT(ItemUnitName) as ItemUnitName,
                    '' as satuan
                FROM m_item
                LEFT JOIN item_category  ON M_ItemItem_CategoryID = itemCategoryID
                LEFT JOIN nat_group ON M_ItemNat_GroupID = Nat_GroupID
                LEFT JOIN nat_subgroup ON M_ItemNat_SubGroupID = Nat_SubGroupID
                LEFT JOIN fa_class ON M_ItemFa_ClassID = Fa_ClassID
                LEFT JOIN m_inventaris_gol ON M_ItemM_InventarisGolID = M_InventarisGolID
                LEFT JOIN itemunitmap ON M_ItemID = ItemUnitMapM_ItemID
                AND ItemUnitMapIsActive = 'Y'
                LEFT JOIN itemunit ON ItemUnitMapItemUnitID = ItemUnitID
                AND ItemUnitIsActive = 'Y'
                WHERE $where
                GROUP BY M_ItemID
                ORDER BY M_ItemID DESC
                LIMIT $number_limit OFFSET $number_offset";

            $query = $this->db->query($sql);
            // echo $this->db->last_query();
            // exit;

            if (!$query) {
                $this->sys_error_db("item list", $this->db);
                exit;
            }

            $rows = $query->result_array();

            if (count($rows) > 0) {
                foreach ($rows as $key => $value) {
                    $sql = "SELECT ItemUnitMapID as id,
                    ItemUnitMapM_ItemID,
                    ItemUnitMapItemUnitID,
                    ItemUnitMapIsPurchase,
                    ItemUnitMapIsReport,
                    ItemUnitMapIsBase,
                    CASE
                        WHEN ItemUnitMapIsPurchase = 'Y' THEN 'purchase'
                        WHEN ItemUnitMapIsReport = 'Y' THEN 'report'
                        WHEN ItemUnitMapIsBase = 'Y' THEN 'base'
                    END as detail_tipe_itemunit,
                    ItemUnitName as item_unit_name,
                    ItemUnitID as item_unit_id,
                    ItemUnitID,
                    ItemUnitName,
                    ItemUnitMapMin as item_unit_min
                    from itemunitmap
                    JOIN itemunit
                        ON ItemUnitMapItemUnitID = ItemUnitID
                        AND ItemUnitIsActive = 'Y'
                    Where
                    ItemUnitMapIsActive = 'Y'
                    AND ItemUnitMapM_ItemID = ?";
                    $qry = $this->db->query($sql, array($value['M_ItemID']));
                    if ($qry) {
                        $rows_satuan = $qry->result_array();
                        $rows[$key]['satuan'] = $rows_satuan;
                    }
                }
            }

            // Get total count
            $sql_count = "SELECT COUNT(*) as total FROM (
                        SELECT M_ItemID
                        FROM m_item
                        LEFT JOIN item_category  ON M_ItemItem_CategoryID = itemCategoryID
                        LEFT JOIN nat_group ON M_ItemNat_GroupID = Nat_GroupID
                        LEFT JOIN nat_subgroup ON M_ItemNat_SubGroupID = Nat_SubGroupID
                        LEFT JOIN fa_class ON M_ItemFa_ClassID = Fa_ClassID
                        LEFT JOIN m_inventaris_gol ON M_ItemM_InventarisGolID = M_InventarisGolID
                        LEFT JOIN itemunitmap ON M_ItemID = ItemUnitMapM_ItemID
                        AND ItemUnitMapIsActive = 'Y'
                        LEFT JOIN itemunit ON ItemUnitMapItemUnitID = ItemUnitID
                        AND ItemUnitIsActive = 'Y'
                        WHERE $where
                            GROUP BY M_ItemID
                        ) x";

            $query_count = $this->db->query($sql_count);
            $total = 0;
            if ($query_count) {
                $total = $query_count->row()->total;
                $total_page = ceil($total / $number_limit);
            } else {
                $this->sys_error_db("item count", $this->db);
                exit;
            }

            $result = array(
                "total" => $total,
                "total_page" => $total_page,
                "records" => $rows
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function get_category()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $prm = $this->sys_input;
            $search = $prm["search"];

            $where = "itemCategoryIsActive = 'Y'";
            if (!empty($search)) {
                $where .= " AND itemCategoryName LIKE '%$search%'";
            }

            $sql = "SELECT
                    itemCategoryID,
                    itemCategoryName
                FROM item_category
                WHERE $where
                ORDER BY itemCategoryID ASC";

            $query = $this->db->query($sql);

            if (!$query) {
                $this->sys_error_db("category list", $this->db);
                exit;
            }

            $rows = $query->result_array();

            $result = array(
                "records" => $rows
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function get_group_filter()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $prm = $this->sys_input;
            // $search = $prm["search"];

            // $where = "Nat_GroupIsActive = 'Y'";
            // if (!empty($search)) {
            //     $where .= " AND Nat_GroupName LIKE '%$search%'";
            // }

            $sql = "SELECT
                    Nat_GroupID,
                    Nat_GroupName
                FROM nat_group
                WHERE Nat_GroupIsActive = 'Y'
                ORDER BY Nat_GroupID DESC";

            $query = $this->db->query($sql);

            if (!$query) {
                $this->sys_error_db("group list", $this->db);
                exit;
            }

            $rows = $query->result_array();

            if ($rows) {
                array_push($rows, ["Nat_GroupID" => "0", "Nat_GroupName" => "All"]);
            }

            $result = array(
                "records" => $rows
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function get_group()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $prm = $this->sys_input;
            $search = $prm["search"];

            $where = "Nat_GroupIsActive = 'Y'";
            if (!empty($search)) {
                $where .= " AND Nat_GroupName LIKE '%$search%'";
            }

            $sql = "SELECT
                    Nat_GroupID,
                    Nat_GroupCode,
                    Nat_GroupName
                FROM nat_group
                WHERE Nat_GroupIsActive = 'Y'
                ORDER BY Nat_GroupID ASC";

            $query = $this->db->query($sql);

            if (!$query) {
                $this->sys_error_db("group list", $this->db);
                exit;
            }

            $rows = $query->result_array();

            $result = array(
                "records" => $rows
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function get_subgroup()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $prm = $this->sys_input;
            $search = isset($prm["search"]) ? $prm["search"] : "";
            $groupId = $prm["group_id"];

            $sql = "SELECT
                    Nat_SubGroupID,
                    Nat_SubGroupNat_GroupID,
                    Nat_SubGroupCode,
                    Nat_SubGroupName,
                    Nat_SubGroupLangName,
                    Nat_SubGroupIsResult,
                    Nat_SubGroupReportTitle
                FROM nat_subgroup
                WHERE Nat_SubGroupIsActive = 'Y'
                AND Nat_SubGroupName LIKE '%$search%'
                AND Nat_SubGroupNat_GroupID = $groupId
                ORDER BY Nat_SubGroupID DESC";

            $query = $this->db->query($sql);

            if (!$query) {
                $this->sys_error_db("subgroup list", $this->db);
                exit;
            }

            $rows = $query->result_array();

            $result = array(
                "records" => $rows,
                "sql" => $this->db->last_query()
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    public function get_fa_class()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $prm = $this->sys_input;
            $search = isset($prm["search"]) ? $prm["search"] : "";
            $flag_type = isset($prm["flag_type"]) ? $prm["flag_type"] : "";

            $sql = "SELECT
                    Fa_ClassID,
                    Fa_ClassName,
                    Fa_ClassFlagType,
                    Fa_ClassCoaID,
                    Fa_ClassCoaAccountNo,
                    Fa_ClassCoaDesc,
                    Fa_ClassDepreCorp,
                    Fa_ClassDepreGov,
                    Fa_ClassAccumDepreCoaID,
                    Fa_ClassAccumDepreCoaAccountNo,
                    Fa_ClassAccumDepreCoaDesc,
                    Fa_ClassAccumNote,
                    Fa_ClassAccumCreated,
                    Fa_ClassAccumLastUpdated,
                    Fa_ClassIsActive,
                    Fa_ClassM_UserID
                FROM fa_class
                WHERE Fa_ClassIsActive = 'Y'
                AND Fa_ClassFlagType = '{$flag_type}'
                AND Fa_ClassName LIKE '%$search%'
                ORDER BY Fa_ClassID DESC";

            $query = $this->db->query($sql);
            // echo $this->db->last_query();
            // exit;

            if (!$query) {
                $this->sys_error_db("fa class list", $this->db);
                exit;
            }

            $rows = $query->result_array();

            $result = array(
                "records" => $rows,
                "sql" => $this->db->last_query()
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function get_inventaris_gol()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $prm = $this->sys_input;
            $search = isset($prm["search"]) ? $prm["search"] : "";

            $sql = "SELECT
                    M_InventarisGolID,
                    M_InventarisGolName,
                    M_InventarisGolCreated,
                    M_InventarisGolLastUpdated,
                    M_InventarisGolIsActive,
                    M_InventarisGolUserID
                FROM m_inventaris_gol
                WHERE M_InventarisGolIsActive = 'Y'
                ORDER BY M_InventarisGolID DESC";

            $query = $this->db->query($sql);

            if (!$query) {
                $this->sys_error_db("m inventaris gol list", $this->db);
                exit;
            }

            $rows = $query->result_array();

            $result = array(
                "records" => $rows,
                "sql" => $this->db->last_query()
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function get_unit()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $prm = $this->sys_input;
            $search = isset($prm["search"]) ? $prm["search"] : "";

            $sql = "SELECT
                    ItemUnitID,
                    ItemUnitCode,
                    ItemUnitName,
                    ItemUnitCreated,
                    ItemUnitLastUpdated,
                    ItemUnitIsActive,
                    ItemUnitUserID
                FROM itemunit
                WHERE ItemUnitIsActive = 'Y'
                AND ItemUnitName LIKE '%$search%'
                ORDER BY ItemUnitID DESC";

            $query = $this->db->query($sql);

            if (!$query) {
                $this->sys_error_db("item unit list", $this->db);
                exit;
            }

            $rows = $query->result_array();

            $result = array(
                "records" => $rows,
                "sql" => $this->db->last_query()
            );

            $this->sys_ok($result);
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function save_item()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $this->db->trans_begin();
            $prm = $this->sys_input;
            $userid = $this->sys_user["M_UserID"];

            $item_group_id = $prm['itemgroupid'];
            $item_sub_group_id = $prm['itemsubgroupid'];
            $item_fa_class_id = $prm['itemfaclassid'];
            $item_fa_inventaris_id = $prm['itemfainventarisid'];
            $item_name = $prm['itemname'];
            $inventory_code = $prm['inventory_code'];
            $item_category_id = $prm['itemcategoryid'];

            $item_name_search = "";
            $item_name = "";
            if (isset($prm['itemname'])) {
                $item_name_search = trim($prm["itemname"]);
                $item_name = trim($prm['itemname']);
                if ($item_name_search != "") {
                    $item_name_search = $prm['itemname'];
                }
            }

            $sql_count = "SELECT COUNT(*) as exist
            FROM m_item
            WHERE M_ItemIsActive = 'Y'
            AND M_ItemDesc = ?";

            $query_count = $this->db->query($sql_count, [
                $item_name_search
            ]);

            if (!$query_count) {
                $this->db->trans_rollback();
                $this->sys_error_db("item search & count by name");
                exit;
            }

            $get_count = $query_count->row_array();
            if ($get_count['exist'] == 0) {
                // Continue with insert logic
                $sqlfn = "SELECT fn_numbering('I') as item";
                $queryfn = $this->db->query($sqlfn);

                if (!$queryfn) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("item call sp");
                    exit;
                } else {
                    $get_item_code = $queryfn->result_array()[0]["item"];
                }

                $sql_insert = "INSERT INTO m_item (
                    M_ItemCode,
                    M_ItemDesc,
                    M_ItemItem_CategoryID,
                    M_ItemInventoryCode,
                    M_ItemNat_GroupID,
                    M_ItemNat_SubGroupID,
                    M_ItemFa_ClassID,
                    M_ItemM_InventarisGolID,
                    M_ItemIsActive,
                    M_ItemCreated,
                    M_ItemLastUpdated,
                    M_ItemM_UserID
                ) VALUES (
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    'Y',
                    NOW(),
                    NOW(),
                    ?
                )";

                $query_insert = $this->db->query($sql_insert, [
                    $get_item_code,
                    $item_name,
                    $item_category_id,
                    $inventory_code,
                    $item_group_id,
                    $item_sub_group_id,
                    $item_fa_class_id,
                    $item_fa_inventaris_id,
                    $userid
                ]);

                if (!$query_insert) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Failed to insert item");
                    exit;
                }

                $last_id = $this->db->insert_id();

                // Insert batch item unit map
                if (isset($prm['satuan']) && count($prm['satuan']) > 0) {
                    foreach ($prm['satuan'] as $key => $value) {
                        $ItemUnitMapItemUnitID = trim($value['item_unit_id']);
                        $itemunitpurchase = 'N';
                        $itemunitbase = 'N';
                        $itemunitreport = 'N';
                        $item_unit_min = trim($value['item_unit_min']);

                        if ($value['detail_tipe_itemunit'] == "purchase") {
                            $itemunitpurchase = 'Y';
                        } else if ($value['detail_tipe_itemunit'] == "base") {
                            $itemunitbase = 'Y';
                        } else if ($value['detail_tipe_itemunit'] == "report") {
                            $itemunitreport = 'Y';
                        }

                        $sql = "INSERT INTO itemunitmap(
                            ItemUnitMapM_ItemID,
                            ItemUnitMapItemUnitID,
                            ItemUnitMapIsPurchase,
                            ItemUnitMapIsReport,
                            ItemUnitMapIsBase,
                            ItemUnitMapMin,
                            ItemUnitMapIsActive,
                            ItemUnitMapCreated,
                            ItemUnitMapLastUpdated,
                            ItemUnitMapUserID
                        ) VALUES (
                            ?,?,?,?,?,?,?,NOW(),NOW(),?
                        )";

                        $query = $this->db->query($sql, [
                            $last_id,
                            $ItemUnitMapItemUnitID,
                            $itemunitpurchase,
                            $itemunitreport,
                            $itemunitbase,
                            $item_unit_min,
                            'Y',
                            $userid
                        ]);

                        if (!$query) {
                            $this->db->trans_rollback();
                            $this->sys_error_db("Failed to insert item unit map");
                            exit;
                        }
                    }
                }

                $this->db->trans_commit();
                $result = array(
                    "total" => 1,
                    "records" => array(
                        "M_ItemCode" => $get_item_code,
                        "M_ItemDesc" => $item_name
                    )
                );
                $this->sys_ok($result);
            } else {
                $errors = array();
                array_push($errors, array(
                    'field' => 'name',
                    'msg' => 'Nama ' . $item_name . ' sudah ada'
                ));

                $result = array(
                    "total" => -1,
                    "errors" => $errors,
                    "records" => 0
                );
                $this->sys_ok($result);
            }
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function update_item()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
            $this->db->trans_begin();
            $prm = $this->sys_input;
            $userid = $this->sys_user["M_UserID"];

            $item_group_id = $prm['itemgroupid'];
            $item_sub_group_id = $prm['itemsubgroupid'];
            $item_fa_class_id = $prm['itemfaclassid'];
            $item_fa_inventaris_id = $prm['itemfainventarisid'];
            $item_name = $prm['itemname'];
            $inventory_code = $prm['inventory_code'];
            $item_category_id = $prm['itemcategoryid'];
            $item_id = $prm['itemid'];

            $item_name_search = "";
            $item_name = "";
            if (isset($prm['itemname'])) {
                $item_name_search = trim($prm["itemname"]);
                $item_name = trim($prm['itemname']);
                if ($item_name_search != "") {
                    $item_name_search = $prm['itemname'];
                }
            }

            $sql_count = "SELECT COUNT(*) as exist
            FROM m_item
            WHERE M_ItemIsActive = 'Y'
            AND M_ItemDesc = ?";

            $query_count = $this->db->query($sql_count, [
                $item_name_search
            ]);

            if (!$query_count) {
                $this->db->trans_rollback();
                $this->sys_error_db("item search & count by name");
                exit;
            } else {

                // $get_count = $query_count->row_array();
                // if ($get_count['exist'] == 0) {

                $sql_update = "UPDATE m_item SET
                    M_ItemDesc = ?,
                    M_ItemItem_CategoryID = ?,
                    M_ItemInventoryCode = ?,
                    M_ItemNat_GroupID = ?,
                    M_ItemNat_SubGroupID = ?,
                    M_ItemFa_ClassID = ?,
                    M_ItemM_InventarisGolID = ?,
                    M_ItemIsActive = 'Y',
                    M_ItemLastUpdated = NOW(),
                    M_ItemM_UserID = ?
                WHERE M_ItemID = ?";

                $query_update = $this->db->query($sql_update, [
                    $item_name,
                    $item_category_id,
                    $inventory_code,
                    $item_group_id,
                    $item_sub_group_id,
                    $item_fa_class_id,
                    $item_fa_inventaris_id,
                    $userid,
                    $item_id
                ]);


                if (!$query_update) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Failed to update item");
                    exit;
                }

                $sql_update_itemunitmap = "UPDATE itemunitmap SET
                ItemUnitMapIsActive = 'N'
                WHERE ItemUnitMapM_ItemID = ?";
                $query_update_itemunitmap = $this->db->query($sql_update_itemunitmap, [
                    $item_id
                ]);

                if (!$query_update_itemunitmap) {
                    $this->db->trans_rollback();
                    $this->sys_error_db("Failed to update item unit map");
                    exit;
                }

                // Insert batch item unit map
                if (isset($prm['satuan']) && count($prm['satuan']) > 0) {
                    foreach ($prm['satuan'] as $key => $value) {
                        $ItemUnitMapItemUnitID = trim($value['item_unit_id']);
                        $itemunitpurchase = 'N';
                        $itemunitbase = 'N';
                        $itemunitreport = 'N';
                        $item_unit_min = trim($value['item_unit_min']);

                        if ($value['detail_tipe_itemunit'] == "purchase") {
                            $itemunitpurchase = 'Y';
                        } else if ($value['detail_tipe_itemunit'] == "base") {
                            $itemunitbase = 'Y';
                        } else if ($value['detail_tipe_itemunit'] == "report") {
                            $itemunitreport = 'Y';
                        }

                        if (intval($value['id']) > 0) {
                            // update
                            $sql = "UPDATE itemunitmap SET
                            ItemUnitMapItemUnitID = ?,
                            ItemUnitMapIsPurchase = ?,
                            ItemUnitMapIsReport = ?,
                            ItemUnitMapIsBase = ?,
                            ItemUnitMapMin = ?,
                            ItemUnitMapIsActive = 'Y',
                            ItemUnitMapLastUpdated = NOW(),
                            ItemUnitMapUserID = ?
                            WHERE ItemUnitMapID = ?";

                            $query = $this->db->query($sql, [
                                $ItemUnitMapItemUnitID,
                                $itemunitpurchase,
                                $itemunitreport,
                                $itemunitbase,
                                $item_unit_min,
                                $userid,
                                $value['id']
                            ]);

                            if (!$query) {
                                $this->db->trans_rollback();
                                $this->sys_error_db("Failed to update item unit map");
                                exit;
                            }
                        } else {
                            // insert
                            $sql = "INSERT INTO itemunitmap(
                                ItemUnitMapM_ItemID,
                                ItemUnitMapItemUnitID,
                                ItemUnitMapIsPurchase,
                                ItemUnitMapIsReport,
                                ItemUnitMapIsBase,
                                ItemUnitMapMin,
                                ItemUnitMapIsActive,
                                ItemUnitMapCreated,
                                ItemUnitMapLastUpdated,
                                ItemUnitMapUserID
                            ) VALUES (
                                ?,?,?,?,?,?,?,NOW(),NOW(),?
                            )";

                            $query = $this->db->query($sql, [
                                $prm['itemid'],
                                $ItemUnitMapItemUnitID,
                                $itemunitpurchase,
                                $itemunitreport,
                                $itemunitbase,
                                $item_unit_min,
                                'Y',
                                $userid
                            ]);

                            if (!$query) {
                                $this->db->trans_rollback();
                                $this->sys_error_db("Failed to insert item unit map");
                                exit;
                            }
                        }
                    }
                }

                $this->db->trans_commit();
                $result = array(
                    "total" => 1,
                    "records" => array(
                        "M_ItemDesc" => $item_name
                    )
                );
                $this->sys_ok($result);
                // } else {
                //     $errors = array();
                //     array_push($errors, array(
                //         'field' => 'name',
                //         'msg' => 'Nama ' . $item_name . ' sudah ada'
                //     ));

                //     $result = array(
                //         "total" => -1,
                //         "errors" => $errors,
                //         "records" => 0
                //     );
                //     $this->sys_ok($result);
                // }
            }
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    function delete_item()
    {
        try {
            if (!$this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $prm = $this->sys_input;
            $item_id = $prm['itemid'];
            $userid = $this->sys_user["M_UserID"];

            $sql_delete = "UPDATE m_item SET
            M_ItemIsActive = 'N',
            M_ItemLastUpdated = NOW(),
            M_ItemM_UserID = ?
            WHERE M_ItemID = ?";

            $query_delete = $this->db->query($sql_delete, [
                $userid,
                $item_id
            ]);

            if (!$query_delete) {
                $this->sys_error_db("Failed to delete item");
                exit;
            }

            $sql_delete_itemunitmap = "UPDATE itemunitmap SET
            ItemUnitMapIsActive = 'N',
            ItemUnitMapLastUpdated = NOW(),
            ItemUnitMapUserID = ?
            WHERE ItemUnitMapM_ItemID = ?";
            $query_delete_itemunitmap = $this->db->query($sql_delete_itemunitmap, [
                $userid,
                $item_id
            ]);

            if (!$query_delete_itemunitmap) {
                $this->sys_error_db("Failed to delete item unit map");
                exit;
            }

            $this->sys_ok(array(
                "total" => 1,
                "records" => array(
                    "M_ItemID" => $item_id
                )
            ));
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }
}
