<?php

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

/* 	
 * 	Author 	: Tagor / Tanggal : 14-08-2014
 * 	Revisi 	: Fachri / 26 /03/2015
 * 	Revisi 	: Dhidhik / 22 /03/2016, array in model system
 */

class Items extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 262;
    public $code = "Item Code";
    public $name = "Item 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_items');
        $this->load->model('m_item_categories');
        $this->load->model('setup/m_branchinfo');
        $this->load->model('m_purchase_requisition');
        $this->load->model('m_purchase_order');
        $this->load->model('m_job_costing');
        $this->load->model('m_roll_over');
        $this->load->model('m_production_amount');
		$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');

                    /* // pengecekan otoritas
                      $group_menu = $this->session->userdata('group_menu');
                      $arr_group_id = $this->m_menu->get_menu_by_group($group_menu);
                      $data['available_menu'] = array_unique($arr_group_id);

                      if(!in_array($this->menu_id, $data['available_menu'])) {
                      redirect(base_url() . 'error', 'refresh');
                      } */

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

                    //Get Item Category, by Ferry at 30-10-2014
                    $data['list_item_category'] = $this->m_item_categories->get_all();

                    $this->load->view('v_header');
                    $this->load->view('items/v_items', $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');

                    /*
                      $arr_group_id = $this->m_menu->get_menu_by_group($group_menu);
                      $data['available_menu'] = array_unique($arr_group_id);

                      if(!in_array($this->menu_id, $data['available_menu'])) {
                      redirect(base_url() . 'error', 'refresh');
                      } */

                    // 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('items/v_new_items', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    // Function Insert

    public function insert() {
        try {
            $id_aset = $this->input->post('id_aset');
            $txt_itemno = str_replace(' ', '-', $this->input->post('txt_itemno'));
            $txt_item_no = strtoupper($txt_itemno);
            $txa_desctiption = strtoupper($this->input->post('txa_desctiption'));
            $cmb_category = $this->input->post('cmb_category');
            $txt_unit = $this->input->post('txt_unit');
            $dataSend = [];
            $dataSend['data_items_insert'] = [];
            $dataSend['data_items_detail_insert'] = [];

            $cmb_fixedasset = $this->input->post('cmb_fixedasset');
            if ($id_aset != 1) {
                $cmb_fixedasset = NULL;
            }

            if ($id_aset == 1) {
                $rdo_itemtype = $id_aset;
            } else {
                $rdo_itemtype = $this->input->post('rdo_itemtype');
            }

            $txt_customfieldmerk = $this->input->post('txt_customfieldmerk');
            $txt_customfieldesign = $this->input->post('txt_customfieldesign');
            $txt_customfieldcolour = $this->input->post('txt_customfieldcolour');
            $txt_customfieldsize = $this->input->post('txt_customfieldsize');
            $txt_customfieldquality = $this->input->post('txt_customfieldquality');
            $txt_customfieldtype = $this->input->post('txt_customfieldtype');
            $txt_customfieldshading = $this->input->post('txt_customfieldshading');
            $txt_customfieldgroup = $this->input->post('txt_customfieldgroup');
            $rd_pph = $this->input->post('rd_pph');
            if ($rd_pph == "") {
                $rd_pph = 3;
            }

            if (!regex_name($txt_itemno)) {
                // set nilai untuk ke form
                throw new Exception(msg_invalid_code($this->code));
            } else {
                // cek apakah kode sudah digunakan
                if ($this->m_items->check_code_exist($txt_itemno) == TRUE) {
                    // set nilai untuk ke form
                    throw new Exception(msg_already_used($this->code));
                } else {
                    // inisialisasi array
                    $dataSend['data_items_insert'] = array(
                        'ItemCode' => $txt_item_no,
                        'ItemCategoryID' => $cmb_category,
                        'ItemDesc' => $txa_desctiption,
                        'ItemTypeID' => $rdo_itemtype,
                        'ItemUnit' => $txt_unit,
                        'FixedAssetTypeID' => $cmb_fixedasset,
                        'ItemPPhType' => $rd_pph,
                        'TransStatus' => 5,
                        'LastUser' => $this->session->userdata("username")
                    );

                    $dataSend['data_items_detail_insert'] = array(
                        'ItemCode' => $txt_itemno,
                        'ItemMerk' => $txt_customfieldmerk,
                        'ItemDesign' => $txt_customfieldesign,
                        'ItemColour' => $txt_customfieldcolour,
                        'ItemSize' => $txt_customfieldsize,
                        'ItemQuality' => $txt_customfieldquality,
                        'ItemType' => $txt_customfieldtype,
                        'ItemShading' => $txt_customfieldshading,
                        'ItemGroup' => $txt_customfieldgroup,
                        'LastUser' => $this->session->userdata("username")
                    );
                    // insert database
                    //$this->m_items->insert($data, $detail);

                    $rstDataSend = $this->m_items->data_send_items_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() {

        $id_aset = $this->input->post('id_aset');
        $txt_itemno = str_replace(' ', '-', $this->input->post('txt_itemno'));
        $txt_item_no = strtoupper($txt_itemno);
        $txa_desctiption = strtoupper($this->input->post('txa_desctiption'));
        $cmb_category = $this->input->post('cmb_category');
        $txt_unit = $this->input->post('txt_unit');

        $cmb_fixedasset = $this->input->post('cmb_fixedasset');
        if ($id_aset != 1) {
            $cmb_fixedasset = NULL;
        }

        if ($id_aset == 1) {
            $rdo_itemtype = $id_aset;
        } else {
            $rdo_itemtype = $this->input->post('rdo_itemtype');
        }

        $txt_customfieldmerk = $this->input->post('txt_customfieldmerk');
        $txt_customfieldesign = $this->input->post('txt_customfieldesign');
        $txt_customfieldcolour = $this->input->post('txt_customfieldcolour');
        $txt_customfieldsize = $this->input->post('txt_customfieldsize');
        $txt_customfieldquality = $this->input->post('txt_customfieldquality');
        $txt_customfieldtype = $this->input->post('txt_customfieldtype');
        $txt_customfieldshading = $this->input->post('txt_customfieldshading');
        $txt_customfieldgroup = $this->input->post('txt_customfieldgroup');
        $rd_pph = $this->input->post('rd_pph');
        if ($rd_pph == "") {
            $rd_pph = 3;
        }

        if (!regex_name($txt_itemno)) {
            // set nilai untuk ke form
            $result['status'] = false;
            $result['message'] = msg_invalid_code($this->code);
        } else {
            // cek apakah kode sudah digunakan
            if ($this->m_items->check_code_exist($txt_itemno) == TRUE) {
                // set nilai untuk ke form
                $result['status'] = false;
                $result['message'] = msg_already_used($this->code);
            } else {
                // inisialisasi array
                $this->db->trans_begin();
                $data = array(
                    'ItemCode' => $txt_item_no,
                    'ItemCategoryID' => $cmb_category,
                    'ItemDesc' => $txa_desctiption,
                    'ItemTypeID' => $rdo_itemtype,
                    'ItemUnit' => $txt_unit,
                    'FixedAssetTypeID' => $cmb_fixedasset,
                    'ItemPPhType' => $rd_pph,
                    'TransStatus' => 5,
                    'LastUser' => $this->session->userdata("username")
                );

                $detail = array(
                    'ItemCode' => $txt_itemno,
                    'ItemMerk' => $txt_customfieldmerk,
                    'ItemDesign' => $txt_customfieldesign,
                    'ItemColour' => $txt_customfieldcolour,
                    'ItemSize' => $txt_customfieldsize,
                    'ItemQuality' => $txt_customfieldquality,
                    'ItemType' => $txt_customfieldtype,
                    'ItemShading' => $txt_customfieldshading,
                    'ItemGroup' => $txt_customfieldgroup,
                    'LastUser' => $this->session->userdata("username")
                );

                // insert database
                $this->m_items->insert($data, $detail);


                /* =============================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');

                    /* // pengecekan otoritas
                      $group_menu = $this->session->userdata('group_menu');
                      $arr_group_id = $this->m_menu->get_menu_by_group($group_menu);
                      $data['available_menu'] = array_unique($arr_group_id);

                      if(!in_array($this->menu_id, $data['available_menu'])) {
                      redirect(base_url() . 'error', 'refresh');
                      } */

                    // inisialisasi additional parameter
                    $id = $this->uri->segment(4);
                    $data['detail'] = $this->m_items->get_by_id($id);
                    $data['detail_trans'] = $this->m_items->get_by_id_by_me($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('items/v_edit_items', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    // Function Update
    public function update() {
        try {
            $rdo_itemtype = $this->input->post('rdo_itemtype');
            $txt_itemno = str_replace(' ', '-', $this->input->post('txt_itemno'));
            $txt_item_no = strtoupper($txt_itemno);
            $txa_desctiption = trim($this->input->post('txa_desctiption'));
            $cmb_category = $this->input->post('cmb_category');
            $txt_unit = $this->input->post('txt_unit');
            $cmb_fixedasset = $this->input->post('cmb_fixedasset');
            $code_item_hidden = $this->input->post('code_item_hidden');

            if ($rdo_itemtype != 1) {
                $cmb_fixedasset = NULL;
            }

            $txt_customfieldmerk = $this->input->post('txt_customfieldmerk');
            $txt_customfieldesign = $this->input->post('txt_customfieldesign');
            $txt_customfieldcolour = $this->input->post('txt_customfieldcolour');
            $txt_customfieldsize = $this->input->post('txt_customfieldsize');
            $txt_customfieldquality = $this->input->post('txt_customfieldquality');
            $txt_customfieldtype = $this->input->post('txt_customfieldtype');
            $txt_customfieldshading = $this->input->post('txt_customfieldshading');
            $txt_customfieldgroup = $this->input->post('txt_customfieldgroup');
            $rd_pph = $this->input->post('rd_pph');

            $dataSend = [];
            $dataSend['data_items_update'] = [];
            $dataSend['data_items_detail_update'] = [];
            $dataSend['idcode'] = $code_item_hidden;

            //=========== Pemakaian Item yang status gantung =================//
            $get_inventory = $this->m_items->get_all_item_on_transaction($txt_itemno);
            if (!empty($get_inventory->item_code)) {
                throw new Exception('Maaf penggantian kategori gagal, masih ada transaksi di ' . $get_inventory->trans_type . ' untuk company ' . $get_inventory->company_code . ' yang gantung untuk kategori ini, No Transaksi : ' . $get_inventory->no_transaksi . '');
            }
            //=========== Pemakaian Item yang status gantung =================//
            // inisialisasi array
            $dataSend['data_items_update'] = array(
                'ItemCode' => $txt_item_no,
                'ItemCategoryID' => $cmb_category,
                'ItemDesc' => $txa_desctiption,
                'ItemTypeID' => $rdo_itemtype,
                'ItemUnit' => $txt_unit,
                'ItemPPhType' => $rd_pph,
                'FixedAssetTypeID' => $cmb_fixedasset,
                'LastUser' => $this->session->userdata("username")
            );
            $dataSend['data_items_detail_update'] = array(
                'ItemCode' => $txt_itemno,
                'ItemMerk' => $txt_customfieldmerk,
                'ItemDesign' => $txt_customfieldesign,
                'ItemColour' => $txt_customfieldcolour,
                'ItemSize' => $txt_customfieldsize,
                'ItemQuality' => $txt_customfieldquality,
                'ItemType' => $txt_customfieldtype,
                'ItemShading' => $txt_customfieldshading,
                'ItemGroup' => $txt_customfieldgroup,
                'LastUser' => $this->session->userdata("username")
            );

            // insert database
//            $this->m_items->update($data, $detail, $code_item_hidden);

            $rstDataSend = $this->m_items->data_send_items_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() {
        $rdo_itemtype = $this->input->post('rdo_itemtype');
        $txt_itemno = str_replace(' ', '-', $this->input->post('txt_itemno'));

        $txt_item_no = strtoupper($txt_itemno);
        $txa_desctiption = trim($this->input->post('txa_desctiption'));
        $cmb_category = $this->input->post('cmb_category');
        $txt_unit = $this->input->post('txt_unit');
        $cmb_fixedasset = $this->input->post('cmb_fixedasset');
        $code_item_hidden = $this->input->post('code_item_hidden');

        if ($rdo_itemtype != 1) {
            $cmb_fixedasset = NULL;
        }

        $txt_customfieldmerk = $this->input->post('txt_customfieldmerk');
        $txt_customfieldesign = $this->input->post('txt_customfieldesign');
        $txt_customfieldcolour = $this->input->post('txt_customfieldcolour');
        $txt_customfieldsize = $this->input->post('txt_customfieldsize');
        $txt_customfieldquality = $this->input->post('txt_customfieldquality');
        $txt_customfieldtype = $this->input->post('txt_customfieldtype');
        $txt_customfieldshading = $this->input->post('txt_customfieldshading');
        $txt_customfieldgroup = $this->input->post('txt_customfieldgroup');
        $rd_pph = $this->input->post('rd_pph');

        /*
          Pemakaian Item yang status gantung
         */
        $get_inventory = $this->m_items->get_all_item_on_transaction($txt_itemno);
        if (!empty($get_inventory->item_code)) {
            $result['status'] = false;
            $result['message'] = 'Maaf penggantian kategori gagal, masih ada transaksi di ' . $get_inventory->trans_type . ' untuk company ' . $get_inventory->company_code . ' yang gantung untuk kategori ini, No Transaksi : ' . $get_inventory->no_transaksi . '';
            echo json_encode($result);
            die();
        }
        /* ======================End=========================== */

        // inisialisasi array
        $data = array(
            'ItemCode' => $txt_item_no,
            'ItemCategoryID' => $cmb_category,
            'ItemDesc' => $txa_desctiption,
            'ItemTypeID' => $rdo_itemtype,
            'ItemUnit' => $txt_unit,
            'ItemPPhType' => $rd_pph,
            'FixedAssetTypeID' => $cmb_fixedasset,
            'LastUser' => $this->session->userdata("username")
        );

        $detail = array(
            'ItemCode' => $txt_itemno,
            'ItemMerk' => $txt_customfieldmerk,
            'ItemDesign' => $txt_customfieldesign,
            'ItemColour' => $txt_customfieldcolour,
            'ItemSize' => $txt_customfieldsize,
            'ItemQuality' => $txt_customfieldquality,
            'ItemType' => $txt_customfieldtype,
            'ItemShading' => $txt_customfieldshading,
            'ItemGroup' => $txt_customfieldgroup,
            'LastUser' => $this->session->userdata("username")
        );

        // insert database
        $this->m_items->update($data, $detail, $code_item_hidden);

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

    public function suspend_data() {
        try {
            $id = $this->input->post('id');
            $result_insert = 0;
            $dataSend = [];
            $dataSend['idcode'] = $id;
            //================ cek data di preq jika dia num rows > dari 0 maka data true jika < 0 data tidak ada ===========//
            $cek_transaksi_preq = $this->m_purchase_requisition->get_preq_detail_by_item($id);
            if ($cek_transaksi_preq == 1) {
                throw new Exception("Item tidak dapat di suspend, Terdapat item pada transaksi purchase requisition yg belum di approve / dalam process");
            }

            $cek_transaksi_pord = $this->m_purchase_order->get_pord_detail_by_item($id);
            if ($cek_transaksi_pord == 1) {
                throw new Exception("Item tidak bisa dihapus masih ada transaksi purchase order yg belum di approve / dalam process");
            }

            $cek_transaksi_job_cos = $this->m_job_costing->get_job_cos_detail_by_item($id);
            if ($cek_transaksi_job_cos == 1) {
                throw new Exception("Item tidak bisa dihapus masih ada transaksi job costing yg belum di approve");
            }

            $cek_transaksi_rol_over = $this->m_roll_over->get_rol_over_detail_by_item($id);
            if ($cek_transaksi_rol_over == 1) {
                throw new Exception("Item tidak bisa dihapus masih ada transaksi rol over yg belum di approve");
            }

            $cek_transaksi_daily_production = $this->m_production_amount->get_initial_amount_by_item($id);
            if ($cek_transaksi_daily_production == 1) {
                throw new Exception("Item tidak bisa dihapus masih ada transaksi initial amount yg belum di approve");
            }
            //================ end cek data di preq jika dia num rows > dari 0 maka data true jika < 0 data tidak ada ===========//
//            $result_insert = $this->m_items->suspended($id);

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

    public function suspend_data_LAMA() {
        $id = $this->input->post('id');
        $result_insert = 0;

        $this->db->trans_begin();
        /* ================cek data di preq jika dia num rows > dari 0 maka data true jiak < 0 data tidak ada=========== */
        $cek_transaksi_preq = $this->m_purchase_requisition->get_preq_detail_by_item($id);

        if ($cek_transaksi_preq == 1) {
            $result['status'] = false;
            $result['message'] = "Item tidak dapat di suspend, Terdapat item pada transaksi purchase requisition yg belum di approve / dalam process";
            echo json_encode($result);
            die();
        }

        $cek_transaksi_pord = $this->m_purchase_order->get_pord_detail_by_item($id);

        if ($cek_transaksi_pord == 1) {
            $result['status'] = false;
            $result['message'] = "Item tidak bisa dihapus masih ada transaksi purchase order yg belum di approve / dalam process";
            echo json_encode($result);
            die();
        }

        $cek_transaksi_job_cos = $this->m_job_costing->get_job_cos_detail_by_item($id);
        if ($cek_transaksi_job_cos == 1) {
            $result['status'] = false;
            $result['message'] = "Item tidak bisa dihapus masih ada transaksi job costing yg belum di approve";
            echo json_encode($result);
            die();
        }

        $cek_transaksi_rol_over = $this->m_roll_over->get_rol_over_detail_by_item($id);
        if ($cek_transaksi_rol_over == 1) {
            $result['status'] = false;
            $result['message'] = "Item tidak bisa dihapus masih ada transaksi rol over yg belum di approve";
            echo json_encode($result);
            die();
        }

        $cek_transaksi_daily_production = $this->m_production_amount->get_initial_amount_by_item($id);
        if ($cek_transaksi_daily_production == 1) {
            $result['status'] = false;
            $result['message'] = "Item tidak bisa dihapus masih ada transaksi initial amount yg belum di approve";
            echo json_encode($result);
            die();
        }
        /* ================================end=============================================================== */
        $result_insert = $this->m_items->suspended($id);

        if ($result_insert == 0) {
            $this->db->trans_rollback();
            $result['status'] = false;
            $result['message'] = get_notification('suspend', $result_insert);
        } else {
            $this->db->trans_commit();
            $result['status'] = true;
            $result['message'] = get_notification('suspend', $result_insert);
        }
        echo json_encode($result);
    }

    // Function Delete
    /* public function delete() {
      // pengecekan otoritas
      $group_menu = $this->session->userdata('group_menu');
      $arr_group_id = $this->m_menu->get_menu_by_group($group_menu);
      $data['available_menu'] = array_unique($arr_group_id);

      if(!in_array($this->menu_id, $data['available_menu'])) {
      redirect(base_url() . 'error', 'refresh');
      }

      // inisialisasi additional parameter
      $id = $this->input->post('id');
      $action = $this->m_items->suspended($id);

      if($action == 1) {
      $result['status'] = true;
      $result['message'] = get_notification('delete', 0);
      }
      else {
      $result['status'] = false;
      $result['message'] = get_notification('delete', 1);
      }
      echo json_encode($result);
      } */

    // Function Approval Direktur

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

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

            $rstDataSend = $this->m_items->data_send_items_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('txt_itemno'));

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

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

        $this->m_items->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('approval', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification('approval', 1);
        }
        /* ==================================end====================================================== */

        echo json_encode($result);
    }

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

        $cek_app_status_dir = $this->m_items->cek_status_app_dir($id);
        if (!empty($cek_app_status_dir)) {
            $TransStatus = 1;
        } 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_items->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);
    }

    //Function preview data
    public function to_preview($obj_string = null) {
//        $data['list'] = $this->m_items->get_all_print();

        $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_filter = arrayParamInUrlToStr($obj_string);
        $data['company_code'] = $data_filter['cmb_company'];
        $data['branch_code'] = $data_filter['cmb_branch'];
        $data['list'] = $this->m_items->get_all_to_print($data_filter);

        $this->load->view('v_header');
        $this->load->view('items/v_preview_items', $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_items->join_all();

        $this->load->view('v_header');
        $this->load->view('items/v_print_items', $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================================================ */
        $Code = $this->input->post('ItemCode') ? $this->input->post('ItemCode') : '';
        $Desc = $this->input->post('ItemDesc') ? $this->input->post('ItemDesc') : '';

        $TransStatus = $this->input->post('TransStatus') ? $this->input->post('TransStatus') : '';
        $ItemCategoryID = $this->input->post('ItemCategoryName') ? $this->input->post('ItemCategoryName') : '';
        $ItemTypeID = $this->input->post('ItemTypeID') ? $this->input->post('ItemTypeID') : '';
        /* ========================================end================================================== */

        /* ========================jika kondisi tidak sama dengan kosong di find lakukan proses di if============ */
        if ($Code != "") {
            $this->db->like('ItemCode', $Code);
        }
        if ($Desc != "") {
            $this->db->like('ItemDesc', $Desc);
        }
        if ($ItemCategoryID != "") {
            if ($ItemCategoryID == 'All') {
                
            } else {
                $this->db->like('am_item.ItemCategoryID', $ItemCategoryID);
            }
        }
        if ($ItemTypeID != '') {
            $this->db->where_in('am_itemtype.ItemTypeID', $ItemTypeID);
        }

        if ($TransStatus != '') {
            $this->db->where_in('am_item.TransStatus', $TransStatus);
        } else {
            /*
              default adalah 2,6. Finished dan Need Approval
             */
            $this->db->where_in('am_item.TransStatus', array(0, 1));
        }
        /* ==========================end================================================================= */
        $this->db->join('am_itemcategory', 'am_itemcategory.ItemCategoryID = am_item.ItemCategoryID', 'inner');
        $this->db->join('am_itemtype', 'am_itemtype.ItemTypeID = am_item.ItemTypeID', 'inner');
        $count_data = $this->db->count_all_results('am_item');

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

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

            $hasil[] = array(
                'TransNumber' => $result[$i]->ItemCode,
                'ItemDesc' => $result[$i]->ItemDesc,
                'ItemCategoryID' => $result[$i]->ItemCategoryID,
                'ItemTypeID' => $result[$i]->ItemTypeID,
                'unit' => $result[$i]->unit,
                'ItemCategoryName' => $result[$i]->ItemCategoryName,
                'ItemTypeName' => $result[$i]->ItemTypeName,
                'TransStatus' => $TransStatus
            );
        }

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

    /* Added by	: Hasan \ Tanggak  : 11-12-2014 */

    public function get_item() {
        $ItemID = $this->input->post("ItemID");
        $result = $this->m_items->get_by_id($ItemID);

        echo json_encode($result);
    }

    public function trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status'] = false;
        $result['message'] = get_notification_transaksi($this->name, $modus, 0);
        get_notification($this->name, 0);

        echo json_encode($result);
        die();
    }

    public function get_item_initial() {
        $item_kategori = $this->input->post("post_item_kategori");
        $dataitemcategori = $this->m_items->create_initial_code($item_kategori);

        $result['status'] = true;
        $result['number'] = $dataitemcategori;

        echo json_encode($result);
    }

}
