<?php
class Itemdivision extends MY_Controller {

    var $db_onedev;
    public function index()
    {
        echo "AUTH API";
    }

    public function __construct()
    {
        parent::__construct();
        $this->db_onedev = $this->load->database("onedev", true);
    }

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

            $search_item = isset($prm['search_item']) ? trim($prm['search_item']) : '';

            $where_search = '%'.$search_item.'%';
            $itemCategoryID = isset($prm['itemCategoryID']) ? (int) $prm['itemCategoryID'] : (int) 0;
    
            $where_item_category_id = ($itemCategoryID > 0) ? "AND itemCategoryID = '$itemCategoryID'" : "";
            // $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * 20 : 0;
            // $number_limit = 2;
            $number_limit = 10;
            $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * $number_limit : 0;
    
            $sql = "SELECT 
                    M_ItemID,
                    IFNULL(itemCategoryName, '') AS itemCategoryName, 
                    IFNULL(M_ItemCode, '') AS M_ItemCode,
                    IFNULL(M_ItemDesc, '') AS M_ItemDesc
                    from m_item
                    join item_category 
                        ON M_ItemItem_CategoryID = itemCategoryID
                        AND itemCategoryIsActive = 'Y'
                    WHERE M_ItemIsActive = 'Y'
                        $where_item_category_id
                        AND (
                            M_ItemDesc LIKE '$where_search'
                            OR M_ItemCode LIKE '$where_search'
                        )
                    ORDER BY M_ItemID ASC";

            $sql_total = "SELECT count(*) as total FROM ($sql) as x";
            $qry_total = $this->db_onedev->query($sql_total);

            $totalCount = 0;
            $totalPage = 0;
            if ($qry_total) {
                $totalCount = $qry_total->result_array()[0]["total"];
                $totalPage = ceil($totalCount / $number_limit);
            } else {
                $this->sys_error_db("select m_item count error", $this->db_onedev);;
                exit;
            }

            $sql_select = $sql . " LIMIT $number_limit OFFSET $number_offset";
            
            $qry = $this->db_onedev->query($sql_select);

            if(!$qry){
                $this->db_onedev->trans_rollback();
                $this->sys_error_db("select m_item error", $this->db_onedev);
                exit;
            }

            $rows = $qry->result_array();
    
            $response = [
                "total" => $totalPage,
                "totalFilter" => $totalCount,
                "records" => $rows,
                "sql" => $this->db_onedev->last_query()
            ];
            
            $this->sys_ok($response);
        } catch (Exception $exc) {
            $this->sys_error($exc->getMessage());
        }
    }

    // dropdown item_category
    function dropdown_item_category()
    {
        $prm = $this->sys_input;
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $sql = "SELECT 
                itemCategoryID,
                itemCategoryName
            FROM item_category
            WHERE itemCategoryIsActive = 'Y'
            ORDER BY itemCategoryID ASC";

            // echo $sql;
            // die();
            $qry = $this->db_onedev->query($sql, array());

            if (!$qry) {
                // $this->db->trans_rollback();
                $this->sys_error_db("Error get dropdown item_category");
                exit;
            }
            
            $rows = $qry->result_array();
            if(count($rows) > 0){
                $response = [
                    "records" => $rows,
                    "sql" => $this->db_onedev->last_query()
                ];
                
                $this->sys_ok($response);
            } else {
                $rows[] = [
                    "M_ItemID" => 0,
                    "itemCategoryName" => "Item Tidak Ada",
                    "M_ItemCode" => "",
                    "M_ItemDesc" => ""
                ];
                
                $response = [
                    "records" => $rows,
                    "sql" => $this->db_onedev->last_query()
                ];
                
                $this->sys_ok($response);
            }
        } catch (Exception $exc) {
            $message = $exc->getMessage();
            $this->sys_error($message);
        }
    }

    // item division list
    function item_division_list()
    {
        try {
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }
    
            $prm = $this->sys_input;
            $M_ItemID = isset($prm['M_ItemID']) ? (int) $prm['M_ItemID'] : (int) 0;
    
            $where_item_id = ($M_ItemID > 0) ? "AND M_ItemDivisionM_ItemID = '$M_ItemID'" : "";
            // $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * 20 : 0;
            // $number_limit = 2;
            $number_limit = 10;
            $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * $number_limit : 0;
    
            $sql = "SELECT  
                    IFNULL(M_ItemDivisionID, 0) AS M_ItemDivisionID,
                    IFNULL(M_ItemDivisionM_ItemID, 0) AS M_ItemDivisionM_ItemID,
                    DivisionName,
                    IFNULL(DivisionID, 0) AS DivisionID,
                    CASE
                    WHEN M_ItemDivisionIsActive = 'Y' 
                        THEN 1
                        ELSE 0
                    END as IsChecked
                    from division
                    left join m_itemdivision
                        ON DivisionID = M_ItemDivisionID
                    $where_item_id
                    where DivisionIsActive = 'Y'
                    ORDER BY DivisionID asc";

            $sql_total = "SELECT count(*) as total FROM ($sql) as x";
            $qry_total = $this->db_onedev->query($sql_total);

            $totalCount = 0;
            $totalPage = 0;
            if ($qry_total) {
                $totalCount = $qry_total->result_array()[0]["total"];
                $totalPage = ceil($totalCount / $number_limit);
            } else {
                $this->sys_error_db("select m_itemdivision count error", $this->db_onedev);;
                exit;
            }

            // $sql_select = $sql . " LIMIT $number_limit OFFSET $number_offset";
            $sql_select = $sql;
            
            $qry = $this->db_onedev->query($sql_select);

            if(!$qry){
                $this->db_onedev->trans_rollback();
                $this->sys_error_db("select m_itemdivision error", $this->db_onedev);
                exit;
            }

            $rows = $qry->result_array();
    
            $response = [
                "total" => $totalPage,
                "totalFilter" => $totalCount,
                "records" => $rows,
                "sql" => $this->db_onedev->last_query()
            ];
            
            $this->sys_ok($response);
        } catch (Exception $exc) {
            $this->sys_error($exc->getMessage());
        }
    }

    // update m_itemdivision
    function update_item_division()
    {
        try {
            // Cek token valid
            if (! $this->isLogin) {
                $this->sys_error("Invalid Token");
                exit;
            }

            $this->db_onedev->trans_begin();
            $prm = $this->sys_input;
            
            $userid = $this->sys_user["M_UserID"];
            $M_ItemDivisionID = isset($prm['M_ItemDivisionID']) ? $prm['M_ItemDivisionID'] : [];
            $M_ItemID = isset($prm['M_ItemID']) ? (int) $prm['M_ItemID'] : (int) 0;
            $where_item_id = ($M_ItemID > 0) ? "AND M_ItemDivisionM_ItemID = '$M_ItemID'" : "";

            // $sql_u = "";

            // var_dump($M_ItemDivisionID);

            if(count($M_ItemDivisionID) > 0){
                foreach ($M_ItemDivisionID as $row) {
                    $id = $row['M_ItemDivisionID'];
                    
                    $M_ItemDivisionDivisionID = $row['DivisionID'];
                    // $M_ItemDivisionM_ItemID = $row['M_ItemDivisionM_ItemID'];

                    $flag = ($row['IsChecked'] === "1") ? "Y" : "N";

                    // check data jika ada update jika tidak ada insert
                    $sql_c = "SELECT * 
                    FROM m_itemdivision 
                    WHERE M_ItemDivisionID = '$id'";
                    
                    $qry_c = $this->db_onedev->query($sql_c);
                    if(!$qry_c){
                       $this->db_onedev->trans_rollback();
                        $this->sys_error_db("query check data m_itemdivision", $this->db_onedev);
                        exit;
                    }

                    $rc = $qry_c->result_array();
                    if(count($rc) > 0) {
                        // update
                        $sql_u = "UPDATE m_itemdivision SET 
                        M_ItemDivisionIsActive = '$flag',
                        M_ItemDivisionLastUpdatedUserID = '$userid',
                        M_ItemDivisionLastUpdated = NOW()
                        WHERE M_ItemDivisionID = '$id'";
                    
                        // echo $sql_u;
                        $query_u = $this->db_onedev->query($sql_u);
                        if(!$query_u){
                        $this->db_onedev->trans_rollback();
                            $this->sys_error_db("query m_itemdivision update", $this->db_onedev);
                            exit;
                        }
                    } else{
                        // insert
                        $sql_i = "INSERT INTO m_itemdivision (
                            M_ItemDivisionM_ItemID,
                            M_ItemDivisionDivisionID,
                            M_ItemDivisionIsActive,
                            M_ItemDivisionCreated,
                            M_ItemDivisionCreatedUserID
                        ) VALUES (
                            '$M_ItemID',
                            '$M_ItemDivisionDivisionID',
                            'Y',
                            NOW(),
                            $userid
                        )";

                        $query_i = $this->db_onedev->query($sql_i);
                        if(!$query_i){
                        $this->db_onedev->trans_rollback();
                            $this->sys_error_db("query m_itemdivision insert", $this->db_onedev);
                            exit;
                        }
                    }
                }
            }

            $number_limit = 10;
            $number_offset = ($prm["current_page"] > 0) ? ($prm["current_page"] - 1) * $number_limit : 0;
    
            $sql = "SELECT  
                    IFNULL(M_ItemDivisionID, 0) AS M_ItemDivisionID,
                    IFNULL(M_ItemDivisionM_ItemID, 0) AS M_ItemDivisionM_ItemID,
                    DivisionName,
                    IFNULL(DivisionID, 0) AS DivisionID,
                    CASE
                    WHEN M_ItemDivisionIsActive = 'Y' 
                        THEN 1
                        ELSE 0
                    END as IsChecked
                    from division
                    left join m_itemdivision
                        ON DivisionID = M_ItemDivisionID
                    $where_item_id
                    where DivisionIsActive = 'Y'
                    ORDER BY DivisionID asc";

            $sql_total = "SELECT count(*) as total FROM ($sql) as x";
            $qry_total = $this->db_onedev->query($sql_total);

            $totalCount = 0;
            $totalPage = 0;
            if ($qry_total) {
                $totalCount = $qry_total->result_array()[0]["total"];
                $totalPage = ceil($totalCount / $number_limit);
            } else {
                $this->sys_error_db("select m_itemdivision count error", $this->db_onedev);;
                exit;
            }

            $sql_select = $sql;
            $qry = $this->db_onedev->query($sql_select);

            if(!$qry){
                $this->db_onedev->trans_rollback();
                $this->sys_error_db("select m_itemdivision error", $this->db_onedev);
                exit;
            }

            $this->db_onedev->trans_commit();
            $rows = $qry->result_array();
    
            $response = [
                "total" => $totalPage,
                "totalFilter" => $totalCount,
                "records" => $rows,
                "sql" => $this->db_onedev->last_query()
            ];
            
            $this->sys_ok($response);
        } catch (Exception $exc) {
            $this->sys_error($exc->getMessage());
        }
    }
}