<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/* 	
 * 	Author 	: Tagor
 * 	Tanggal : 06-08-2014	
 * 	Revisi 	: Dhidhik, 22 Maret 2016, array in model proccess system
 */

class Item_Categories extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 178;
    public $code = "Item Categories Code";
    public $name = "Item Categories Name";

    public function __construct() {
        parent::__construct();
        $this->load->helper('regex');
        $this->load->helper('message');
        $this->load->helper('status');
        $this->load->helper('custom_string_helper');

        $this->load->model('m_menu');
        $this->load->model('m_item_categories');
        $this->load->model('m_items');
        $this->load->model('m_fixed_asset_type');
        $this->load->model('setup/m_branchinfo');
        $this->load->model('setup/m_preference');
		$this->load->model('login/m_login');
	
		$is_login = $this->m_login->get_session_id($this->session->userdata('session_id'),$this->session->userdata('username'));
		if($is_login){

		}else{
			$username       = $this->session->userdata('username');
			$session_id     = $this->session->userdata('session_id');
			$this->m_login->delete_session($username,$session_id);
			$this->session->sess_destroy();

			$uri_func = $this->uri->segment(3);
			if(($uri_func === FALSE) || ($uri_func =='add') || ($uri_func =='edit')){
				redirect(base_url() . 'login', 'refresh');
			}else if(in_array($uri_func,array('approve_data','approved_mgr','approved_dir','approve','approve_transsaction','reverse_data','reversed_data','reverse_transsaction','save','save_data','insert','update','update_data','suspend','suspend_data','suspend_transsaction','suspend_mgr','suspend_dir'))){
				$result['status']   = 'session';
				$result['message']  = get_notification('session_destroy',0);
				echo json_encode($result);
				die();
			}
		}
    }

    // Function Index	
    public function index() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

                    // set data
                    $data['menu_id'] = $this->menu_id;

                    // get link from tbl_menu 
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $this->load->view('v_header');
                    $this->load->view('item_categories/v_item_categories', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    // Function Add
    public function add() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            /*
              untuk di index/list = get_menu_by_group,
              untuk di add = get_menu_by_group_add
              untuk di edit = get_menu_by_group_edit
             */
            $arr_group_id = $this->m_menu->get_menu_by_group_add($group_menu, $this->menu_id);
            //--------------------------end-----------------------------------------------------------
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    /*
                      modul untuk akses add masing masing modul berebda
                      jangan lupa copy $data nya (jika dia bener langsung ke add)
                     */
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

                    // set data
                    $data['menu_id'] = $this->menu_id;

                    // get link from tbl_menu 
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $this->load->view('v_header');
                    $this->load->view('item_categories/v_new_item_categories', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    // Function Insert

    public function insert() {
        try {
            $txt_name = trim($this->input->post('txt_name'));
            $txt_desc = trim($this->input->post('txt_desc'));
            $txt_initial = trim($this->input->post('txt_name_initial'));

            // cek suspended
            $chk_suspended = $this->input->post('chk_suspended');
            if ($chk_suspended == 1) {
                $chk_suspended = 3;
            } else {
                $chk_suspended = 5;
            }

            if (!regex_name($txt_name)) {
                // set nilai untuk ke form
                throw new Exception(msg_invalid_name($this->name));
            } else {
                $dataSend = [];
                $dataSend['data_itemcategory_insert'] = [];
                // cek apakah kode sudah digunakan
                if ($this->m_item_categories->check_code_exist($txt_name) == TRUE) {
                    // set nilai untuk ke form
                    throw new Exception(msg_already_used($this->name));
                } else if ($this->m_item_categories->check_code_initial_exist($txt_initial) == TRUE) {
                    // set nilai untuk ke form
                    throw new Exception("Initial Name Category sudah digunakan silahkan mengganti dengan yang lain");
                } else {
                    // inisialisasi array
                    $dataSend['data_itemcategory_insert'] = array(
                        'ItemCategoryName' => strtoupper($txt_name),
                        'InitialCategory' => strtoupper($txt_initial),
                        'ItemCategoryDesc' => $txt_desc,
                        'TransStatus' => $chk_suspended,
                        'LastUser' => $this->session->userdata("username")
                    );

                    // insert database
//                    $action = $this->m_item_categories->insert($data);

                    $rstDataSend = $this->m_item_categories->data_send_itemcategory_insert($dataSend);
                    if ($rstDataSend) {
                        $result['status'] = true;
                        $result['message'] = get_notification('insert', 1);
                    } else {
                        $result['status'] = false;
                        $result['message'] = get_notification('insert', 0);
                    }
                    echo json_encode($result);
                }
            }
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function insert_LAMA() {
        $txt_name = trim($this->input->post('txt_name'));
        $txt_desc = trim($this->input->post('txt_desc'));
        $txt_initial = trim($this->input->post('txt_name_initial'));

        // cek suspended
        $chk_suspended = $this->input->post('chk_suspended');
        if ($chk_suspended == 1) {
            $chk_suspended = 3;
        } else {
            $chk_suspended = 5;
        }
        $this->db->trans_begin();

        if (!regex_name($txt_name)) {
            // set nilai untuk ke form
            $result['status'] = false;
            $result['message'] = msg_invalid_name($this->name);
        } else {
            // cek apakah kode sudah digunakan
            if ($this->m_item_categories->check_code_exist($txt_name) == TRUE) {
                // set nilai untuk ke form
                $result['status'] = false;
                $result['message'] = msg_already_used($this->name);
            } else if ($this->m_item_categories->check_code_initial_exist($txt_initial) == TRUE) {
                // set nilai untuk ke form
                $result['status'] = false;
                $result['message'] = "Initial Name Category sudah digunakan silahkan mengganti dengan yang lain";
            } else {
                // inisialisasi array
                $data = array(
                    'ItemCategoryName' => strtoupper($txt_name),
                    'InitialCategory' => strtoupper($txt_initial),
                    'ItemCategoryDesc' => $txt_desc,
                    'TransStatus' => $chk_suspended,
                    'LastUser' => $this->session->userdata("username")
                );

                // insert database
                $action = $this->m_item_categories->insert($data);
                /* =============================trans roll back dan trans commit============================/ */
                if ($this->db->trans_status() === FALSE) {
                    $this->db->trans_rollback();
                    $result['status'] = FALSE;
                    $result['message'] = get_notification('insert', 0);
                } else {
                    $this->db->trans_commit();
                    $result['status'] = TRUE;
                    $result['message'] = get_notification('insert', 1);
                }
                /* ==================================end====================================================== */
            }
        }

        echo json_encode($result);
    }

    // Function Edit
    public function edit() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            /*
              untuk di index/list = get_menu_by_group,
              untuk di add = get_menu_by_group_add
              untuk di edit = get_menu_by_group_edit
             */
            $arr_group_id = $this->m_menu->get_menu_by_group_edit($group_menu, $this->menu_id);
            //--------------------------end-----------------------------------------------------------
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    /*
                      modul untuk akses add masing masing modul berebda
                      jangan lupa copy $data nya (jika dia bener langsung ke add)
                     */
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

                    // inisialisasi additional parameter
                    $id = $this->uri->segment(4);
                    $data['detail'] = $this->m_item_categories->get_detail($id);

                    // set data
                    $data['menu_id'] = $this->menu_id;

                    // get link from tbl_menu 
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $this->load->view('v_header');
                    $this->load->view('item_categories/v_edit_item_categories', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    // Function Update

    public function update() {
        try {
            $id = $this->input->post('id');
            $txt_name = trim($this->input->post('txt_name'));
            $txt_desc = trim($this->input->post('txt_desc'));
            $AssetStatus = $this->input->post('AssetStatus');
            $kategori_name = $this->input->post('kategori_name');
            $txt_initial = trim($this->input->post('txt_name_initial'));
            $dataSend = [];
            $dataSend['data_itemcategory_update'] = [];
            $dataSend['data_asset_update'] = [];
            $dataSend['idcode'] = $id;
            $dataSend['kategori_name'] = $kategori_name;

            // inisialisasi array
            $dataSend['data_itemcategory_update'] = array(
                'ItemCategoryName' => strtoupper($txt_name),
                'InitialCategory' => strtoupper($txt_initial),
                'ItemCategoryDesc' => $txt_desc,
                'LastUser' => $this->session->userdata("username")
            );
            if ($AssetStatus == 1) {
                $dataSend['data_asset_update'][] = array(
                    'FixedAssetType' => strtoupper($txt_name),
                    'FixedAssetDesc' => $txt_desc,
                    'LastUser' => $this->session->userdata("username")
                );
//                $this->m_fixed_asset_type->update_from_category($data_asset, $kategori_name);//masuk ke model
            }
            // update database
//		$action = $this->m_item_categories->update($data, $id);

            $rstDataSend = $this->m_item_categories->data_send_itemcategory_update($dataSend);
            if ($rstDataSend) {
                $result['status'] = true;
                $result['message'] = get_notification('update', 1);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('update', 0);
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function update_LAMA() {
        $id = $this->input->post('id');
        $txt_name = trim($this->input->post('txt_name'));
        $txt_desc = trim($this->input->post('txt_desc'));
        $AssetStatus = $this->input->post('AssetStatus');
        $kategori_name = $this->input->post('kategori_name');
        $txt_initial = trim($this->input->post('txt_name_initial'));

        $this->db->trans_begin();
        // inisialisasi array
        $data = array(
            'ItemCategoryName' => strtoupper($txt_name),
            'InitialCategory' => strtoupper($txt_initial),
            'ItemCategoryDesc' => $txt_desc,
            'LastUser' => $this->session->userdata("username")
        );

        if ($AssetStatus == 1) {
            $data_asset = array(
                'FixedAssetType' => strtoupper($txt_name),
                'FixedAssetDesc' => $txt_desc,
                'LastUser' => $this->session->userdata("username")
            );
            $this->m_fixed_asset_type->update_from_category($data_asset, $kategori_name);
        }

        // insert database
        $action = $this->m_item_categories->update($data, $id);
        /* =============================trans roll back dan trans commit============================/ */
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
            $result['message'] = get_notification('update', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification('update', 1);
        }
        /* ==================================end====================================================== */

        echo json_encode($result);
    }

    // Function Delete/suspend

    public function suspend_data() {
        try {
            // inisialisasi additional parameter
            $id = $this->input->post('id');
            $get_detail_categories = $this->m_item_categories->get_detail_row($id);
            $dataSend = [];
            $dataSend['data_sys_item_delete'] = [];
            $dataSend['data_sys_sales_delete'] = [];
            $dataSend['data_sys_purchase_delete'] = [];
            $dataSend['idcode'] = $id;
            $dataSend['byname'] = "";

            //========== Cek apakah kategori ini ternaksud fix asset yg di asset type =============================//
            $get_fix_asset_type = $this->m_fixed_asset_type->check_as_assets($get_detail_categories->ItemCategoryName);
            if ($get_fix_asset_type == 1) {
                throw new Exception("Gagal di suspend karena kategori ini termaksud dalam fixed asset type, silahkan suspend di menu fixed asset type");
            }
            //========== End Cek apakah kategori ini ternaksud fix asset yg di asset type =============================//
            // 2 means active
            if ($get_detail_categories->TransStatus == 1) {
                //============================ cek item yang di suspend =================================//
                $cek_item_master = $this->m_items->get_item_by_categori($id);
                // 1 means there is data.
                if ($cek_item_master == 1) {
                    throw new Exception("Gagal di suspend karena masih ada item di master belum disuspend");
                } else {
                    /* else ini cek trans status 3, yg trans status 0,1 di ifnya */
                    //========================== cek item by kategroi untuk status yg suspend ===============//
                    $cek_item_by_kategori = $this->m_items->get_item_suspend_by_categori($id);
                    if (!empty($cek_item_by_kategori)) {
                        foreach ($cek_item_by_kategori as $row_data) {
                            if ($row_data->ItemQty != 0) {
                                throw new Exception("Gagal di suspend karena masih ada qty di inventori");
                            }
                        }
                    }
                    //========================== end cek item by kategroi untuk status yg suspend ===============//
                }
                //============================ end cek item yang di suspend =================================//
                //=================== delete permanen yang ada kategori yg di suspen ======================//
                $cek_sys_item = $this->m_preference->get_sys_item_categories_suspen($id);
                if (!empty($cek_sys_item)) {
                    foreach ($cek_sys_item as $row_sys_item) {
                        $SysItemCategoryID = $row_sys_item->SysItemCategoryID;
                        $dataSend['data_sys_item_delete'][] = array(
                            'idcode' => $id,
                            'SysItemCategoryID' => $SysItemCategoryID
                        );
//                        $action 		= $this->m_preference->delete_sys_item($id,$SysItemCategoryID);// masuk ke model
                    }
                }

                $cek_sys_sales = $this->m_preference->get_sys_sales_categories_suspen($id);
                if (!empty($cek_sys_item)) {
                    foreach ($cek_sys_sales as $row_sys_sales) {
                        $SysSalesCategoryID = $row_sys_sales->SysSalesCategoryID;
                        $dataSend['data_sys_sales_delete'][] = array(
                            'idcode' => $id,
                            'SysSalesCategoryID' => $SysSalesCategoryID
                        );
//                        $action 		= $this->m_preference->delete_sys_sales($id,$SysSalesCategoryID);//masuk ke model
                    }
                }

                $cek_sys_purchases = $this->m_preference->get_sys_purchases_categories_suspen($id);
                if (!empty($cek_sys_purchases)) {
                    foreach ($cek_sys_purchases as $row_sys_purchase) {
                        $SysPurchaseCategoryID = $row_sys_purchase->SysPurchaseCategoryID;
                        $dataSend['data_sys_purchase_delete'][] = array(
                            'idcode' => $id,
                            'SysPurchaseCategoryID' => $SysPurchaseCategoryID
                        );
//                        $action 		= $this->m_preference->delete_sys_purchase($id,$SysPurchaseCategoryID);
                    }
                }
                //=================== end delete permanen yang ada kategori yg di suspen ======================//

                $name = $this->m_item_categories->get_name_by_id($id);
                $dataSend['byname'] = $name;
                /* ====================================================================================== */
                /*
                  action suspen jika suspen, kategori langsung otomatis suspen
                  dan jika dia kategori ini adalah khusus aset maka di type asset langsung ke suspend juga
                 */
//                $action_assetb 	= $this->m_fixed_asset_type->suspended_by_name($name);  //masuk ke model
//                $action               = $this->m_item_categories->suspended($id);             //masuk ke model
                /* ======================================================================================== */
            } else if ($get_detail_categories->TransStatus == 5) {
                //=================== delete permanen yang ada kategori yg di suspen ======================//
                $cek_sys_item = $this->m_preference->get_sys_item_categories_suspen($id);
                if (!empty($cek_sys_item)) {
                    foreach ($cek_sys_item as $row_sys_item) {
                        $SysItemCategoryID = $row_sys_item->SysItemCategoryID;
                        $dataSend['data_sys_item_delete'][] = array(
                            'idcode' => $id,
                            'SysItemCategoryID' => $SysItemCategoryID
                        );
//                        $action 		= $this->m_preference->delete_sys_item($id,$SysItemCategoryID);//masuk ke model
                    }
                }

                $cek_sys_sales = $this->m_preference->get_sys_sales_categories_suspen($id);
                if (!empty($cek_sys_item)) {
                    foreach ($cek_sys_sales as $row_sys_sales) {
                        $SysSalesCategoryID = $row_sys_sales->SysSalesCategoryID;
                        $dataSend['data_sys_sales_delete'][] = array(
                            'idcode' => $id,
                            'SysSalesCategoryID' => $SysSalesCategoryID
                        );
//                        $action 		= $this->m_preference->delete_sys_sales($id,$SysSalesCategoryID);
                    }
                }

                $cek_sys_purchases = $this->m_preference->get_sys_purchases_categories_suspen($id);
                if (!empty($cek_sys_purchases)) {
                    foreach ($cek_sys_purchases as $row_sys_purchase) {
                        $SysPurchaseCategoryID = $row_sys_purchase->SysPurchaseCategoryID;
                        $dataSend['data_sys_purchase_delete'][] = array(
                            'idcode' => $id,
                            'SysPurchaseCategoryID' => $SysPurchaseCategoryID
                        );
//                        $action 		= $this->m_preference->delete_sys_purchase($id,$SysPurchaseCategoryID);
                    }
                }
                //=================== end delete permanen yang ada kategori yg di suspen ======================//

                $name = $this->m_item_categories->get_name_by_id($id);
                $dataSend['byname'] = $name;
                /* ====================================================================================== */
                /*
                  action suspen jika suspen, kategori langsung otomatis suspen
                  dan jika dia kategori ini adalah khusus aset maka di type asset langsung ke suspend juga
                 */
//                $action_assetb 	= $this->m_fixed_asset_type->suspended_by_name($name);  //Masuk ke model
//                $action 		= $this->m_item_categories->suspended($id);             //masuk ke model
                /* ======================================================================================== */
            }

            $rstDataSend = $this->m_item_categories->data_send_itemcategory_suspend($dataSend);
            if ($rstDataSend) {
                $result['status'] = true;
                $result['message'] = get_notification('delete', 1);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('delete', 0);
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function suspend_data_LAMA() {

        // inisialisasi additional parameter
        $id = $this->input->post('id');
        $get_detail_categories = $this->m_item_categories->get_detail_row($id);

        $this->db->trans_begin();

        /*
          Cek apakah kategori ini ternaksud fix asset yg di asset type
         */
        $get_fix_asset_type = $this->m_fixed_asset_type->check_as_assets($get_detail_categories->ItemCategoryName);
        if ($get_fix_asset_type == 1) {
            $result['status'] = false;
            $result['message'] = "Gagal di suspend karena kategori ini termaksud dalam fixed asset type, silahkan suspend di menu fixed asset type";
            echo json_encode($result);
            die();
        }
        /* =================End====================================== */

        // 2 means active
        if ($get_detail_categories->TransStatus == 1) {
            /* ============================cek item yang di suspend================================= */
            $cek_item_master = $this->m_items->get_item_by_categori($id);
            // 1 means there is data.
            if ($cek_item_master == 1) {
                $result['status'] = false;
                $result['message'] = "Gagal di suspend karena masih ada item di master belum disuspend";
                echo json_encode($result);
                die();
            } else {
                /*
                  else ini cek trans status 3, yg trans status 0,1 di ifnya
                 */
                /* ==========================cek item by kategroi untuk status yg suspend=============== */
                $cek_item_by_kategori = $this->m_items->get_item_suspend_by_categori($id);

                if (!empty($cek_item_by_kategori)) {
                    foreach ($cek_item_by_kategori as $row_data) {
                        if ($row_data->ItemQty != 0) {
                            $result['status'] = false;
                            $result['message'] = "Gagal di suspend karena masih ada qty di inventori";
                            echo json_encode($result);
                            die();
                        }
                    }
                }
                /* =======================================end============================================ */
            }
            /* =======================================end============================================ */

            /* ===================delete permanen yang ada kategori yg di suspen====================== */
            $cek_sys_item = $this->m_preference->get_sys_item_categories_suspen($id);
            if (!empty($cek_sys_item)) {
                foreach ($cek_sys_item as $row_sys_item) {
                    $SysItemCategoryID = $row_sys_item->SysItemCategoryID;
                    $action = $this->m_preference->delete_sys_item($id, $SysItemCategoryID);
                }
            }

            $cek_sys_sales = $this->m_preference->get_sys_sales_categories_suspen($id);
            if (!empty($cek_sys_item)) {
                foreach ($cek_sys_sales as $row_sys_sales) {
                    $SysSalesCategoryID = $row_sys_sales->SysSalesCategoryID;
                    $action = $this->m_preference->delete_sys_sales($id, $SysSalesCategoryID);
                }
            }

            $cek_sys_purchases = $this->m_preference->get_sys_purchases_categories_suspen($id);
            if (!empty($cek_sys_purchases)) {
                foreach ($cek_sys_purchases as $row_sys_purchase) {
                    $SysPurchaseCategoryID = $row_sys_purchase->SysPurchaseCategoryID;
                    $action = $this->m_preference->delete_sys_purchase($id, $SysPurchaseCategoryID);
                }
            }
            /* ===============================end==================================================== */

            $name = $this->m_item_categories->get_name_by_id($id);
            /* ====================================================================================== */
            /*
              action suspen jika suspen, kategori langsung otomatis suspen
              dan jika dia kategori ini adalah khusus aset maka di type asset langsung ke suspend juga
             */
            $action_assetb = $this->m_fixed_asset_type->suspended_by_name($name);
            $action = $this->m_item_categories->suspended($id);
            /* ======================================================================================== */
        } else if ($get_detail_categories->TransStatus == 5) {

            /* ===================delete permanen yang ada kategori yg di suspen====================== */
            $cek_sys_item = $this->m_preference->get_sys_item_categories_suspen($id);
            if (!empty($cek_sys_item)) {
                foreach ($cek_sys_item as $row_sys_item) {
                    $SysItemCategoryID = $row_sys_item->SysItemCategoryID;
                    $action = $this->m_preference->delete_sys_item($id, $SysItemCategoryID);
                }
            }

            $cek_sys_sales = $this->m_preference->get_sys_sales_categories_suspen($id);
            if (!empty($cek_sys_item)) {
                foreach ($cek_sys_sales as $row_sys_sales) {
                    $SysSalesCategoryID = $row_sys_sales->SysSalesCategoryID;
                    $action = $this->m_preference->delete_sys_sales($id, $SysSalesCategoryID);
                }
            }

            $cek_sys_purchases = $this->m_preference->get_sys_purchases_categories_suspen($id);
            if (!empty($cek_sys_purchases)) {
                foreach ($cek_sys_purchases as $row_sys_purchase) {
                    $SysPurchaseCategoryID = $row_sys_purchase->SysPurchaseCategoryID;
                    $action = $this->m_preference->delete_sys_purchase($id, $SysPurchaseCategoryID);
                }
            }
            /* ===============================end==================================================== */

            $name = $this->m_item_categories->get_name_by_id($id);
            /* ====================================================================================== */
            /*
              action suspen jika suspen, kategori langsung otomatis suspen
              dan jika dia kategori ini adalah khusus aset maka di type asset langsung ke suspend juga
             */
            $action_assetb = $this->m_fixed_asset_type->suspended_by_name($name);
            $action = $this->m_item_categories->suspended($id);
            /* ======================================================================================== */
        }

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
            $result['message'] = get_notification('delete', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification('delete', 1);
        }
        echo json_encode($result);
    }

    //Function preview data
    public function to_preview($obj_string = null) {
        // set data
        $data['menu_id'] = $this->menu_id;
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

//        $data['list'] = $this->m_item_categories->get_all();

        $data_filter            = arrayParamInUrlToStr($obj_string);
        $data['company_code']   = $data_filter['cmb_company'];
        $data['branch_code']    = $data_filter['cmb_branch'];
        $data['list']           = $this->m_item_categories->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('item_categories/v_preview_item_categories', $data);
        $this->load->view('v_footer');
    }

    //Function To Print
    public function to_print() {
        // set data
        $data['menu_id'] = $this->menu_id;
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        $data['list'] = $this->m_item_categories->get_all();

        $this->load->view('v_header');
        $this->load->view('item_categories/v_print_item_categories', $data);
        $this->load->view('v_footer');
    }

    public function ajax() {
        $page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;

        $hasil = array();
        /* ===========rows*page tidak boleh melebihi dari jumlah data======= */

        /* ===========================declar post by find================================================ */
        $Name = $this->input->post('ItemCategoryName') ? $this->input->post('ItemCategoryName') : '';
        $Desc = $this->input->post('ItemCategoryDesc') ? $this->input->post('ItemCategoryDesc') : '';

        $TransStatus = $this->input->post('TransStatus') ? $this->input->post('TransStatus') : '';
        /* ========================================end================================================== */
        /* ========================jika kondisi tidak sama dengan kosong di find lakukan proses di if============ */

        if ($Name != "") {
            $this->db->like('ItemCategoryName', $Name);
        }
        if ($Desc != "") {
            $this->db->like('ItemCategoryDesc', $Desc);
        }

        if ($TransStatus != '') {
            $this->db->where_in('TransStatus', $TransStatus);
        } else {
            /*
              default adalah 2,6. Finished dan Need Approval
             */
            $this->db->where_in('TransStatus', array(0, 1));
        }
        /* ==========================end================================================================= */

        $count_data = $this->db->count_all_results('am_itemcategory');

        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_item_categories->get_all();

        for ($i = 0; $i <= ($rows - 1); $i++) {
            $TransStatus = get_status_master($result[$i]->Status);

            $hasil[] = array(
                'TransNumber' => $result[$i]->ItemCategoryID,
                'InitialCategory' => $result[$i]->InitialCategory,
                'ItemCategoryName' => $result[$i]->ItemCategoryName,
                'ItemCategoryDesc' => $result[$i]->ItemCategoryDesc,
                'TransStatus' => $TransStatus
            );
        }

        if ($hasil == "") {
            $result = array();
            echo json_encode($result);
        } else {
            $result = array();
            $result['total'] = $count_data;
            $result['rows'] = $hasil;
            echo json_encode($result);
        }
    }

    public function approval_dir() {
        try {
            $id = trim($this->input->post('id'));
            $TransStatus = 1;
            $dataSend = [];
            $dataSend['data_itemcategory_update'] = [];
            $dataSend['idcode'] = $id;

            $dataSend['data_itemcategory_update'] = array(
                'TransStatus' => $TransStatus,
                'AppLevel2Status' => 1,
                'AppLevel2Code' => $this->session->userdata("username"),
                'AppLevel2Date' => date("Y-m-d"),
                'LastUser' => $this->session->userdata("username")
            );

//            $action = $this->m_item_categories->update($data, $id);//masuk ke mobel

            $rstDataSend = $this->m_item_categories->data_send_itemcategory_app_dir($dataSend);
            if ($rstDataSend) {
                $result['status'] = true;
                $result['message'] = get_notification('approval', 1);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification('approval', 0);
            }
            echo json_encode($result);
        } catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    public function approval_dir_LAMA() {
        $id = trim($this->input->post('id'));

        //$cek_app_status_dir = $this->m_item_categories->cek_status_app_mgr($id);
        //if(!empty($cek_app_status_dir)){
        //$TransStatus = 1; 
        //} else {
        //$TransStatus = 4;
        $TransStatus = 1;
        //}		

        $data = array(
            'TransStatus' => $TransStatus,
            'AppLevel2Status' => 1,
            'AppLevel2Code' => $this->session->userdata("username"),
            'AppLevel2Date' => date("Y-m-d"),
            'LastUser' => $this->session->userdata("username")
        );

        $this->db->trans_begin();
        $action = $this->m_item_categories->update($data, $id);
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
            $result['message'] = get_notification('approval', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification('approval', 1);
        }

        echo json_encode($result);
    }

    // Function Approval Manager
    public function approval_mgr() {
        $id = $this->input->post('id');

        $cek_app_status_dir = $this->m_item_categories->cek_status_app_dir($id);

        if (!empty($cek_app_status_dir)) {
            $TransStatus = 0;
        } else {
            $TransStatus = 5;
        }

        $data = array(
            'TransStatus' => $TransStatus,
            'AppLevel1Status' => 1,
            'AppLevel1Code' => $this->session->userdata("username"),
            'AppLevel1Date' => date("Y-m-d"),
            'LastUser' => $this->session->userdata("username")
        );

        $action = $this->m_item_categories->update($data, $id);
        if ($action == 0) {
            $result['status'] = false;
            $result['message'] = get_notification('approval', 0);
        } else {
            $result['status'] = true;
            $result['message'] = get_notification('approval', 1);
        }

        echo json_encode($result);
    }

}
