<?php

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

/* 	
 * 	Author 	: Fachri
 * 	Tanggal : 27-03-2015	
 * 	Revisi 	: 
 */

class Transfer_item extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 407;
    public $code = "Batch Number";
    public $name = "Transfer Item";
    public $trans_data = array();

    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->helper('message');
        $this->load->helper('status');
        $this->load->helper('convert_date');
        $this->load->helper('approval');

        $this->load->model('m_menu');
        $this->load->model('m_transfer_item');
        $this->load->model('m_transfer_item');
        $this->load->model('m_items');
        $this->load->model('m_inventories');
        $this->load->model('m_item_price');
        $this->load->model('m_delivery_order');
        $this->load->model('custom/m_custom');
        $this->load->model('m_account_journal');
		$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();
			}
		}
    }

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

    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======= */

        /* =================================post dari find di kiri==================================================== */
        $param = $this->input->post('param');
        $Number = isset($param['txt_IDNumber']) ? $param['txt_IDNumber'] : '';
        $Desc = isset($param['txt_Description']) ? $param['txt_Description'] : '';

        $DateFrom = isset($param['txt_DateFrom']) ? $param['txt_DateFrom'] : '';
        $DateTo = isset($param['txt_DateTo']) ? $param['txt_DateTo'] : '';
        $TransStatus = isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
        $BranchCode = isset($param['cmb_branch']) ? $param['cmb_branch'] : '';
        /* ============================================end============================================================ */
        /* ========================jika kondisi tidak sama dengan kosong di find lakukan proses di if================= */
        if ($BranchCode != "") {
            $this->db->where('BranchCode', $BranchCode);
        } else {
            $this->db->where('BranchCode', $this->session->userdata('branch'));
        }

        if ($Number != "") {
            $this->db->like('ProdNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('ProdDesc', $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, 4, 5, 6, 7));
        }


        if ((($DateFrom != '') && ($DateTo != ''))) {
            if ($DateFrom <= $DateTo) {
                $this->db->where('at_transfer_item.ProdDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('at_transfer_item.ProdDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }
        /* ==========================end================================================================= */

        $count_data = $this->db->count_all_results('at_transfer_item');
        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_transfer_item->get_all();


        for ($i = 0; $i <= ($rows - 1); $i++) {
            // kalau master ambil dari get_status_master(), kalau transaksi get_status()
            $TransStatus = get_status($result[$i]->TransStatus);

            $hasil[] = array(
                'BranchName' => $result[$i]->BranchName,
                'BranchNameTo' => $result[$i]->BranchNameTo,
                'TransNumber' => $result[$i]->ProdNumber,
                'ProdDate' => $result[$i]->ProdDate,
                'ProdDesc' => $result[$i]->ProdDesc,
                'TransStatus' => $TransStatus,
                'EmployeeName' => $result[$i]->EmployeeName,
            );
        }

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

    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);
                    $BranchCode = $this->session->userdata('branch');
                    $data['date_now'] = date('d-m-Y');

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

    public function get_prod_emoun_number() {
        $prod_date = $this->input->post('prod_af_date') == '' ? date('d-m-Y') : $this->input->post('prod_af_date');
        $prod_no = $this->m_transfer_item->create_prod_amount_number($prod_date);

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

        echo json_encode($result);
    }

    //Function Form Insert
    public function insert() {
        /* =======================deklar varaibel====================================== */
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $txt_date = $this->input->post('txt_date');

        /* =====================================ia number========================================== */
        $txt_no = $this->m_transfer_item->create_ia_number($txt_date);
        /* ========================================================================================== */

        $txa_description = $this->input->post('txa_description');
        $cmb_branch = $this->input->post('cmb_branch');
        $BranchCode = $this->session->userdata('branch');
        $CategoryAmount = "";
        $item_code = "";
        $result_insert = 0;
        /* ====================================end======================================= */

        if (count($detail) > 0) {

            // $this->db->trans_begin();

            /* =========================insert group========================================== */
            $insert_group = $this->insert_group($BranchCode, $cmb_branch, $txt_date, $txa_description, $txt_no);
            /* =================================end=========================================== */

            /* ==========================insert detail======================================== */
            $insert_detail = $this->insert_detail($detail, $txt_no, $txt_date,$BranchCode);
            /* =============================end=============================================== */

            $result_return = $this->m_transfer_item->insert_transsaction($this->trans_data);

            $this->trans_data = [];

            if ($result_return) {
                $result['status'] = true;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 1, $txt_no);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $txt_no);
            }

            echo json_encode($result);
        } else {
            $result['status'] = false;
            $result['message'] = msg_qty_not_nol();
            echo json_encode($result);
        }
    }

    /* =====================insert_group================================================= */

    function insert_group($BranchCode, $cmb_branch, $txt_date, $txa_description, $txt_no) {
        $data = array(
            'BranchCode' => $BranchCode,
            'BranchFor' => $cmb_branch,
            'ProdNumber' => $txt_no,
            'ProdDate' => date("Y-m-d", strtotime($txt_date)),
            'ProdDesc' => $txa_description,
            'TransStatus' => 4,
            'CreatedBy' => $this->session->userdata("username"),
            'CreatedAt' => date("Y-m-d"),
            'LastUser' => $this->session->userdata("username")
        );

        //$this->m_transfer_item->insert($data);
        $this->trans_data['insert_group']['data'] = $data;
    }

    /* ======================end========================================================= */

    /* =====================insert_detail================================================= */

    function insert_detail($detail, $txt_no, $txt_date, $BranchCode) {
        $jurnal_amount = 0;
        foreach ($detail as $row) {

            $get_data_avereg = $this->m_transfer_item->get_item_price($row->ItemCode,$BranchCode);

            $detail_data = array(
                'ProdNumber' => $txt_no,
                'ItemCode' => $row->ItemCode,
                'itemUnit' => $row->ItemUnit,
                'itemQty' => $row->ItemQty,
                'ItemAmount' => $get_data_avereg->ItemAverage,
                'itemDesc' => $row->Description,
                'LastUser' => $this->session->userdata("username")
            );

            //$this->m_transfer_item->insert_detail($detail_data);
            $this->trans_data['insert_detail']['data'][] = $detail_data;

            // get item average dari inventories
            $tmp_jurnal_amount = doubleval($get_data_avereg->ItemAverage) * $row->ItemQty;
            $jurnal_amount = doubleval($jurnal_amount) + doubleval($tmp_jurnal_amount);

            @$CategoryAmount[$row->ItemCategoryID] += $tmp_jurnal_amount;
            @$SubTotal[$txt_no] += $jurnal_amount;
        }

        $get_journal_debet_credit = $this->journal_debet_credit($CategoryAmount, $txt_date, $txt_no, $jurnal_amount);
    }

    /* =====================end========================================================== */

    /* =====================insert_journal================================================= */

    function journal_debet_credit($CategoryAmount, $txt_date, $txt_no, $jurnal_amount) {

        $PersediaanArea = $this->m_account_journal->get_account_name('Persediaan Barang Area');

        if ($PersediaanArea == false) {
            $result['status'] = false;
            $result['message'] = 'Persediaan Barang Area belum tersedia, silahkan lihat Chart Of Account';
            echo json_encode($result);
            die;
        } else {
            $data_journal_credit = array(
                'ProdDate' => date("Y-m-d", strtotime($txt_date)),
                'ProdNumber' => $txt_no,
                'ProdAccountNumber' => $PersediaanArea->AccountNumber,
                'ProdSaldoDebet' => $jurnal_amount,
                'ProdSaldoCredit' => 0,
                'ProdSignStatus' => 0,
                'LastUser' => $this->session->userdata('username')
            );

            //$this->m_transfer_item->insert_journal_credit($data_journal_credit);
            $this->trans_data['insert_journal']['data'][] = $data_journal_credit;
        }

        foreach ($CategoryAmount as $key => $value) {
            $InventoryAccount = $this->m_account_journal->get_cat_item_account('Inventory', $key, 'IDR');

            if ($InventoryAccount == false) {
                $result['status'] = false;
                $result['message'] = 'Settingan preference untuk item inventory belum lengakap, silahkan setting ulang';
                echo json_encode($result);
                die;
            } else {
                $data_journal_debet = array(
                    'ProdDate' => date("Y-m-d", strtotime($txt_date)),
                    'ProdNumber' => $txt_no,
                    'ProdAccountNumber' => $InventoryAccount->AccountNumber,
                    'ProdSaldoDebet' => 0,
                    'ProdSaldoCredit' => $value,
                    'ProdSignStatus' => 1,
                    'LastUser' => $this->session->userdata('username')
                );

                //$this->m_transfer_item->insert_journal_credit($data_journal_debet);
                $this->trans_data['insert_journal']['data'][] = $data_journal_debet;
            }
        }        
    }

    /* ========================end========================================================= */

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

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

                    // inisialisasi additional parameter
                    $id = str_replace($data['menu_link'] . '/edit/', "", $this->uri->uri_string());
                    $data['detail'] = $this->m_transfer_item->get_detail($id);

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

    public function update() {
        /* =======================================deklar variabel ================================== */
        $txt_batch_no = $this->input->post('txt_Prod_no');
        $txt_date = $this->input->post('txt_date');
        $txa_description = $this->input->post('txa_description');
        $cmb_branch = $this->input->post('cmb_branch');
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);

        $detail_id = $this->input->post('detail_id');
        $detail_id = json_decode($detail_id);
        /* ==================================end=================================================== */

        //$this->db->trans_begin();

        /* ====================insert group========================================================= */
        $update_group = $this->update_group($cmb_branch, $txt_batch_no, $txt_date, $txa_description);
        /* ===========================end=========================================================== */

        /* ===========================delete detail================================================================= */
        $this->trans_data['delete_detail']['total'] = count($detail_id);
        if (count($detail_id) > 0) {
            foreach ($detail_id as $ProdDetailID) {
                //$this->m_transfer_item->delete_detail_by_id($ProdDetailID);
                $this->trans_data['delete_detail']['ProdDetailID'][] = $ProdDetailID;
            }
        }
        /* =============================end========================================================================== */

        /* =============================insert detail=============================================== */
        $update_detail = $this->update_detail($detail, $txt_batch_no, $txt_date);
        /* ==================================end==================================================== */

        $result_return = $this->m_transfer_item->update_transsaction($this->trans_data);

        $this->trans_data = [];

        if ($result_return) {
            $result['status'] = true;
            $result['message'] = get_notification_transaksi($this->name, 'update', 1, $txt_batch_no);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification_transaksi($this->name, 'update', 0, $txt_batch_no);
        }

        echo json_encode($result);
    }

    /* ====================function update group========================================== */

    function update_group($cmb_branch, $txt_batch_no, $txt_date, $txa_description) {
        $data = array(
            'BranchFor' => $cmb_branch,
            'ProdNumber' => $txt_batch_no,
            'ProdDate' => date("Y-m-d", strtotime($txt_date)),
            'ProdDesc' => $txa_description,
            'LastUser' => $this->session->userdata("username")
        );

        //$this->m_transfer_item->update($data, $txt_batch_no);
        $this->trans_data['update_group']['data'] = $data;
        $this->trans_data['update_group']['TransNumber'] = $txt_batch_no;
    }

    /* ============================end===================================================== */

    function update_detail($detail, $txt_batch_no, $txt_date) {

        $jurnal_amount = 0;
        foreach ($detail as $row) {

            $RowStatus = $row->flag;
            $ProdDetailID = $row->ProdDetailID;

            $detail_data = array(
                'ProdNumber' => $txt_batch_no,
                'ItemCode' => $row->ItemCode,
                'ItemUnit' => $row->ItemUnit,
                'ItemQty' => $row->ItemQty,
                'ItemAmount' => $row->ItemAmount,
                'ItemDesc' => $row->ItemDesc,
                'LastEdited' => $this->session->userdata("username")
            );

            //$this->m_transfer_item->update_detail($detail_data, $row->ProdDetailID);
            $this->trans_data['update_detail']['data'][] = $detail_data;
            $this->trans_data['update_detail']['ProdDetailID'][] = $row->ProdDetailID;

            if ($RowStatus == 3) {
                //$this->m_transfer_item->delete_detail_by_id($ProdDetailID);
                $this->trans_data['delete_detail']['ProdDetailID'][] = $ProdDetailID;
            } else {
                // get item average dari inventories
                $tmp_jurnal_amount = doubleval($row->ItemAmount) * $row->ItemQty;
                $jurnal_amount = doubleval($jurnal_amount) + doubleval($tmp_jurnal_amount);

                @$CategoryAmount[$row->ItemCategoryID] += $tmp_jurnal_amount;
                @$SubTotal[$txt_no] += $jurnal_amount;
            }
        }

        /* =======================suming dari category amount credit======================================================= */
        $get_data_journal = $this->m_transfer_item->get_journal_by_number($txt_batch_no);
        foreach ($get_data_journal as $row_jurnal) {
            /* ==========================delete all for jurnal============================================================= */
            //$this->m_transfer_item->delete_detail_jurnal_by_id($txt_batch_no);
            $this->trans_data['delete_journal']['TransNumber'] = $txt_batch_no;
            /* ===================================end===================================================================== */
        }

        $get_journal_debet_credit = $this->journal_debet_credit($CategoryAmount, $txt_date, $txt_batch_no, $jurnal_amount);
    }

    function get_branch_data() {
        $result = $this->m_transfer_item->get_branch();
        echo json_encode($result);
    }

    function get_area_data() {
        $result = $this->m_transfer_item->get_area();
        echo json_encode($result);
    }

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

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

    public function ajax_item() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $id = str_replace($data['menu_link'] . '/ajax_item/', "", $this->uri->uri_string());

        $result = $this->m_transfer_item->get_detail_item($id);
        foreach ($result as $row) {
			if($row->ItemTypeID == 1){
				$status = 1;
			}
			else{
				$status = 0;
			}
			
            $hasil[] = array(
                'ProdDetailID' => $row->ProdDetailID,
                'ProdNumber' => $row->ProdNumber,
                'ItemCode' => $row->ItemCode,
                'ItemQty' => $row->ItemQty,
                'ItemUnit' => $row->ItemUnit,
                'ItemDesc' => $row->ItemDesc,
                //'ProdJurnal_id' 	=> $row->ProdAccountNumber,
                'ItemAmount' => $row->ItemAmount,
                'flag' => $row->status_remove,
                'ItemCategoryID' => $row->ItemCategoryID,
				'ItemStatus' => $status,
				'ItemType' => $row->ItemType
            );
        }

        echo json_encode($hasil);
    }

    function to_preview_journal() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        // set data 
        $id = str_replace($data['menu_link'] . '/to_preview_journal/', "", $this->uri->uri_string());

        $data['detail'] = $this->m_transfer_item->get_detail($id);
        $data['list'] = $this->m_transfer_item->get_journal_by_number($id);
        $data['list_detail'] = $this->m_transfer_item->get_detail_journal($id);

        $this->load->view('v_header');
        $this->load->view('daily_production_amount/v_preview_journal_dailyproduction_amount', $data);
        $this->load->view('v_footer');
    }
	
    public function approval_mgr() {
        /* ================deklar variabel========================================= */
        $id = $this->input->post('id');
        $detail = $this->input->post('detail');
        $cmb_branch = $this->input->post('cmb_branch');
        $detail = json_decode($detail);
        /* ===========================end=========================================== */

        $txt_date = $this->m_transfer_item->get_date_by_id($id);
        $result_approv_mgr = 0;

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

        //$this->db->trans_begin();
        foreach ($detail as $row) {
            // get item average dari inventories
            $get_invetori = $this->m_transfer_item->get_inventoris($row->ItemCode, $cmb_branch);

            if ($get_invetori == true) {
                $result['status'] = false;
                $result['message'] = 'Item ' . $row->ItemCode . ' Sudah Tersedia Di Inventori, Sistem Tidak Memasukan Data Yang Sudah Ada';
                echo json_encode($result);
                die;
            } else {

                //$this->m_transfer_item->update($data, $id);
                $this->trans_data['update_group']['data'] = $data;
                $this->trans_data['update_group']['TransNumber'] = $id;

                $tmp_jurnal_amount = doubleval($row->ItemAmount) * $row->ItemQty;
                $data_inventori = array(
                    'BranchCode' => $cmb_branch,
                    'ItemCode' => $row->ItemCode,
                    'ItemQty' => $row->ItemQty,
                    'ItemValue' => $tmp_jurnal_amount,
                    'ItemAverage' => $row->ItemAmount,
                    'LastUser' => $this->session->userdata("username")
                );
                //$this->m_transfer_item->insert_inventori($data_inventori);
                $this->trans_data['insert_inventori']['data'][] = $data_inventori;
            }
        }

        $result_return = $this->m_transfer_item->approve_transsaction($this->trans_data);

        $this->trans_data = [];

        if ($result_return) {
            $result['status'] = true;
            $result['message'] = get_notification_transaksi($this->name, 'approve', 1, $id);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification_transaksi($this->name, 'approve', 0, $id);
        }

        echo json_encode($result);
    }
	
	function reverse_data_detail() {
		try {
			$production_number = $this->input->post('id');
			$cmb_branch 		= $this->input->post('cmb_branch');
			$detail_post		= $this->input->post('detail');
			$detail				= json_decode($detail_post);
			
			$date_transaction 	= check_end_periode($production_number);
			$get_end_periode = $this->m_custom->check_period_end_custom($date_transaction);
			if ($get_end_periode) {
                throw new Exception(get_notification('reverse_in_period', 0)); //sudah di end periode atau belum
            }
			
			foreach($detail as $row_detail){
				$ItemCode = $row_detail->ItemCode;
				/*
					Check av_item_already ada yang pakai atau tidak, jika tidak ada di av_item_already
					item langsung reverse dan delete inventory
				*/
				$get_item_already_used = $this->m_custom->check_item_already_used($ItemCode, $cmb_branch,'Initial Amount');
				
				if ($get_item_already_used != false) {
					throw new Exception("Transaksi tidak bisa direverse, karena item ".$get_item_already_used->ItemCode." ini sudah dipakai di ".$get_item_already_used->TransName." dengan No Transaksi ".$get_item_already_used->TransNumber); //sudah di end periode atau belum
				}
				
				$this->transaction['delete_inventory']['ItemCode'][] = $ItemCode;
				$this->transaction['delete_inventory']['BranchCode'][] = $cmb_branch;
			}
			
			$data = array(
				'AppLevel1Status' => 0,
				'AppFinished' => 0,
				'TransStatus' => 4,
				'AppLevel1Code' => NULL,
				'AppLevel1Date' => NULL,
				'LastUser' => $this->session->userdata("username")
			);
			
			$this->transaction['update_group']['data'] = $data;
            $this->transaction['update_group']['ProdNumber'] = $production_number;
			
			/* =============================trans roll back dan trans commit============================/ */
            $result_approve = $this->m_transfer_item->reverse_trasaction($this->transaction);
            $this->transaction = [];

            if ($result_approve == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $production_number);
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $production_number);
            }
            /* ==================================end====================================================== */

            echo json_encode($result);
		}
		catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
	}
	
    public function suspend_data() {
        $id = $this->input->post('id');

        $data = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata('username')
        );

        //$this->m_transfer_item->update_trans_status($id, $data);
        $this->trans_data['suspend_data']['data'] = $data;
        $this->trans_data['suspend_data']['TransNumber'] = $id;

        $result_return = $this->m_transfer_item->suspend_transsaction($this->trans_data);

        $this->trans_data = [];

        if ($result_return) {
            $result['status'] = true;
            $result['message'] = get_notification('suspend', 1);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('suspend', 0);
        }

        echo json_encode($result);
    }

    public function delete_row() {
        /* ================================deklar variabel================================= */
        $id = $this->input->post('id');
        $txt_date = $this->input->post('txt_date');
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $result_delete = 0;
        /* =============================end============================================== */

        /* ===========================update detail function ini dipake juga di update data and calculate journal======================================= */
        $delete_detail = $this->update_detail($detail, $id, $txt_date);
        /* =============================end====================================================================================== */

        /* =============================trans roll back dan trans commit============================/ */
        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);
        }
        /* ==================================end====================================================== */

        echo json_encode($result);
    }

    // Function Print
    function to_print_detail() {
        // get link from tbl_menu 
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

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

        // set data
        $id = str_replace($data['menu_link'] . '/to_print_detail/', "", $this->uri->uri_string());

        if ($id != "") {
            $data['detail'] = $this->m_transfer_item->get_detail_print($id);
            $data['list'] = $this->m_transfer_item->get_detail_item_print($data['detail']->ProdNumber);

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

    /* ============================pencarian dari master item by kategori and all kategori waktu pop up======================================= */
    /*
      baru dipake di modul inventori initial amount
     */

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


        /* =================================post dari find di atas pop up==================================================== */
        $param = $this->input->post('param');
        $ItemCategoryID = isset($param['cmb_ItemCategoryID']) ? $param['cmb_ItemCategoryID'] : '';
        $ItemCode = isset($param['txt_ItemCode']) ? $param['txt_ItemCode'] : '';
        $ItemDesc = isset($param['txt_ItemDesc']) ? $param['txt_ItemDesc'] : '';
        /* ============================================end============================================================ */

        /* ===========================count data tabel job costing================================== */
        if ($ItemCode != '') {
            $BranchCode_Cmb = isset($param['txt_Branch']) ? $param['txt_Branch'] : '';
            $ItemCodeAnd = "AND am_item.ItemCode LIKE '%$ItemCode%'";
        } else {
            $ItemCodeAnd = "";
            $BranchCode_Cmb = $this->input->post('branch');
        }

        if ($ItemDesc != '') {
            $ItemDescAnd = "AND am_item.ItemDesc LIKE '%$ItemDesc%'";
            $BranchCode_Cmb = isset($param['txt_Branch']) ? $param['txt_Branch'] : '';
        } else {
            $ItemDescAnd = "";
            $BranchCode_Cmb = $this->input->post('branch');
        }

        if ($ItemCategoryID != '') {
            if ($ItemCategoryID == "All") {
                $ItemCategoryIDAnd = "";
            } else {
                $ItemCategoryIDAnd = "AND am_item.ItemCategoryID = '$ItemCategoryID'";
            }
            $BranchCode_Cmb = isset($param['txt_Branch']) ? $param['txt_Branch'] : '';
        } else {
            $BranchCode_Cmb = $this->input->post('branch');
            $ItemCategoryIDAnd = "";
        }

        $not_in = "SELECT COUNT(am_item.ItemCode) as Total
					FROM am_itemcategory 
					INNER JOIN am_item
						ON am_item.ItemCategoryID=am_itemcategory.ItemCategoryID
                    INNER JOIN at_inventories
                        ON at_inventories.ItemCode=am_item.ItemCode
					WHERE am_item.TransStatus IN (0,1) $ItemCodeAnd $ItemDescAnd $ItemCategoryIDAnd";
        $query = $this->db->query($not_in);

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $Total = $row->Total;
            }

            $count_data = $Total;
        } else {
            $result['status'] = false;
            $result['message'] = "Maaf data tidak ditemukan";
            die();
            echo json_encode($result);
        }
        /* ======================================end================================================ */

        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }

        /* ===============ambil data dari model search_job_costing============================ */
        $result = $this->m_custom->search_all_item_master_by_kategori($BranchCode_Cmb);
        //echo $this->db->last_query();
        /* ======================end================================= */

        for ($i = 0; $i <= ($rows - 1); $i++) {

            $hasil[] = array(
                'ItemCode' => $result[$i]->ItemCode,
                'ItemDesc' => $result[$i]->ItemDesc,
                'ItemUnit' => $result[$i]->ItemUnit,
                'ItemCategoryID' => $result[$i]->ItemCategoryID,
				'ItemCategoryName' => $result[$i]->ItemCategoryName,
				'ItemTypeID' => $result[$i]->ItemTypeID,
                'ItemAverage' => $result[$i]->ItemAverage
            );
        }
        /* ===================jika kondisi kosong dari array $hasil======================= */
        if (empty($hasil)) {
            $emptyVar = array();
            echo json_encode($emptyVar);
        } else {
            $result = array();
            $result['total'] = $count_data;
            $result['rows'] = $hasil;
            echo json_encode($result);
        }
        /* ==============================end=========================================== */
    }

    /* ====================================end============================================================================== */

    // Function Print
    public function to_preview($obj_string = null) {
//        $CompanyCode = $this->uri->segment(4);
//        $BranchCode = $this->uri->segment(5);
        // 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_adjustment->get_all_to_print($BranchCode);
//        $obj_string = arrayInUrlToStr($data_grid);
//        
        $data_filter            = arrayParamInUrlToStr($obj_string);
        $data['company_code']   = $data_filter['cmb_company'];
        $data['branch_code']    = $data_filter['cmb_branch'];
//        echo "cmb_company = ".$data_filter['cmb_company'];
        $data['list']           = $this->m_transfer_item->get_all_to_print($data_filter);

        $this->load->view('v_header');
        $this->load->view('list/daily_production_amount/v_print_daily_production_amount', $data);
        $this->load->view('v_footer');
    }

}
