<?php

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

/* 	
 * 	Author 	: Tagor
 * 	Tanggal : 07-08-2014	
 * 	Revisi 	: Fachri
 */

class Adjustment extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 177;
    public $menu_model = 'm_adjustment';
    public $name = "Adjustment";
    public $trans_data = array();
    // inisialisasi otomatis
    public $add = "add";
    public $edit = "edit";
    public $delete = "delete";
    public $to_preview = "to_preview";
    public $to_pdf = "to_pdf";
    public $to_excel = "to_excel";

    public function __construct() {
        parent::__construct();
        $this->load->model('m_adjustment');
        $this->load->helper('message_helper');
        $this->load->helper('status');
        $this->load->helper('custom_string_helper');
        $this->load->model('list/m_inventories');
        $this->load->model('m_account_journal');
		$this->load->model('custom/m_custom');
		
		$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');

                    $data['menu_id'] = $this->menu_id;
                    $data['menu_model'] = $this->menu_model;

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

                    $data['menu_link'] = $this->m_adjustment->get_menulink($this->menu_id);
                    $this->load->view('v_header');
                    $this->load->view('adjustment/v_adjustment', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    //function get data to grid
    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('IAdjNumber', $Number);
        } //change
        if ($Desc != "") {
            $this->db->like('IAdjDesc', $Desc);
        } //change
        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_inventadjustment.IAdjDate >=', date("Y-m-d", strtotime($DateFrom))); //change
                $this->db->where('at_inventadjustment.IAdjDate <=', date("Y-m-d", strtotime($DateTo))); //change
            }
        }
        /* ==========================end================================================================= */

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

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

            $hasil[] = array(
                'IAdjDate' => $result[$i]->IAdjDate,
                'TransNumber' => $result[$i]->IAdjNumber,
                'AccountName' => $result[$i]->AccountName,
                'IAdjDesc' => $result[$i]->IAdjDesc,
                'CreatedBy' => $result[$i]->CreatedBy,
                'TransStatus' => $TransStatus,
                'BranchName'    => $result[$i]->BranchName,
                'EmployeeName'    => $result[$i]->EmployeeName,
                'Status'    => $TransStatus
            );
        }

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

                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    $data['menu_link'] = $this->m_adjustment->get_menulink($this->menu_id);
                    $sess_brach = $this->session->userdata('branch');

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

                    $inv_adjustment_no = $this->m_adjustment->get_latest_inv_adjustment_no($sess_brach);

                    if (!empty($inv_adjustment_no) || $inv_adjustment_no != null) {
                        foreach ($inv_adjustment_no as $row) {
                            $number = $row->IAdjNumber;
                            $explode_number = explode("/", $number);
                            $last_index = (count($explode_number) - 1);
                            $last_number = $explode_number[$last_index];
                            if (empty($last_index)) {
                                $pay_numb3 = '001';
                            } else {
                                $pay_numb3 = $last_number + 1;
                            }
                        }

                        $count_paynumb = strlen($pay_numb3);
                        if ($count_paynumb == 1) {
                            $data['next_inv_adj_numb'] = '00' . $pay_numb3;
                        } elseif ($count_paynumb == 2) {
                            $data['next_inv_adj_numb'] = '0' . $pay_numb3;
                        } elseif ($count_paynumb == 3) {
                            $data['next_inv_adj_numb'] = $pay_numb3;
                        }
                        $data['branch_param1'] = $sess_brach;
                    } else {
                        $data['branch_param1'] = $sess_brach;
                        $data['next_inv_adj_numb'] = '001';
                    }

                    //$data['adjust_no']  = $this->m_adjustment->create_adjust_number(date('d-m-Y'));

                    $data['date_now'] = date('d-m-Y');
                    $this->load->view('v_header');
                    $this->load->view('adjustment/v_new_adjustment', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function insert() {
        /* ===================deklar varaibel========================================================= */
        $branch_code = $this->session->userdata('branch');
        $company_code = $this->session->userdata('company');

        $txt_adjustment_date = $this->input->post('txt_date');
		$txa_description = $this->input->post('txa_description');
		
        /* =====================================adj number========================================== */
        $txt_no = $this->m_adjustment->create_adj_number($txt_adjustment_date);
        /* ========================================================================================== */

        $cmb_adj_account = $this->input->post('cmb_adj_account');
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $check = $this->input->post('Status_Tab');
        $result_insert = 0;
        /* =====================end=================================================================== */

        if (count($detail) > 0) {

            /* ================insert data group=========================================== */
            $this->insert_group($txa_description, $branch_code, $txt_adjustment_date, $txt_no, $cmb_adj_account, $check);
            /* ===================end====================================================== */

            /* ================insert data detail=========================================== */
            $this->insert_detail($check, $detail, $txt_no, $branch_code, $cmb_adj_account, $txt_adjustment_date);
            /* ===================end====================================================== */

            $result_return = $this->m_adjustment->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($txa_description, $branch_code, $txt_adjustment_date, $txt_no, $cmb_adj_account, $check) {
        $data = array(
            'BranchCode' => $branch_code,
            'IAdjDate' => date("Y-m-d", strtotime($txt_adjustment_date)),
            'IAdjNumber' => $txt_no,
			'IAdjDesc' => $txa_description,
            'IAdjAccountNumber' => $cmb_adj_account,
            'StatusCheck' => $check,
            'TransStatus' => 5,
            'CreatedBy' => $this->session->userdata("username"),
            'CreatedAt' => date('Y-m-d'),
            'LastUser' => $this->session->userdata("username")
        );

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

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

    /* ===================================insert detail============================================== */

    function insert_detail($check, $detail, $txt_no, $branch_code, $cmb_adj_account, $txt_adjustment_date) {
        /*
          $check = 1 is value
          $check = 0 is qty
         */
        $sub_total = 0;

        $total_persediaan_plus = 0;
        $total_persediaan_minus = 0;

        $nilai_persediaan_plus = 0;
        $nilai_persediaan_minus = 0;
        $CategoryMinus = 0;
        $CategoryPlus = 0;

        $CategoryMinus = array();
        $CategoryPlus = array();

        $update_inv_data = array(
            'LockStatus' => 1
        );

        /* ===============================================the adjusted value only=================== */
        if ($check == 1) {
            $arResult = array();

            foreach ($detail as $row) {
                $ItemCode = $row->ItemCode;
                $ItemUnit = $row->ItemUnit;
                $ItemDesc = $row->Description;
                //$Qty 		= $row->Qty;

                $Value = $row->Value;
                $CtrlValue = $row->ControlValue;
                $ItemCategoryID = $row->ItemCategoryID;

                $nilai_persediaan_plus = 0;
                $nilai_persediaan_minus = 0;

                if ($Value > $CtrlValue) {
                    /* ======perhitungan jika value lebih besar dari ctrl value============================== */
                    $nilai_persediaan_minus = $Value - $CtrlValue;
                    $nilai_jurnal = $Value - $CtrlValue;
                } else {
                    /* ======perhitungan jika value lebih besar dari ctrl value============================== */
                    $nilai_persediaan_plus = $CtrlValue - $Value;
                    $nilai_jurnal = $CtrlValue - $Value;
                    /* ==================end============================================================= */
                }

                /*
                  Cek lock status adjustment
                 */
                $check_inventories_adjustment = $this->m_adjustment->get_inventories_adjustment($ItemCode, $branch_code);
                if ($check_inventories_adjustment->LockStatus == 1) {
                    $result['status'] = false;
                    $result['message'] = 'Maaf transaksi gagal item sedang di adjustment, silahkan selesaikan adjustment untuk item ' . $ItemDesc . '';

                    echo json_encode($result);
                    die;
                }
                /* ======================End================================================================================== */

                $detail_data = array(
                    'IAdjNumber' => $txt_no,
                    'ItemCode' => $ItemCode,
                    'ItemDesc' => $ItemDesc,
                    'ItemUnit' => $ItemUnit,
                    'ItemValue' => $Value,
                    'ItemNewValue' => $CtrlValue,
                    'LastUser' => $this->session->userdata("username")
                );

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

                //$this->m_adjustment->update_inventories($update_inv_data, $ItemCode, $branch_code);	
                $this->trans_data['update_inventories']['data'][] = $update_inv_data;
                $this->trans_data['update_inventories']['ItemCode'][] = $ItemCode;
                $this->trans_data['update_inventories']['branch'][] = $branch_code;

                //================== persiapan array untuk journal ================//
                $indexCategory = $this->checkIndex($arResult, "CategoryCode", $row->ItemCategoryID);

                if ($indexCategory > -1) { //di array result udah ada
                    $arResult[$indexCategory]["SumPlus"] += $nilai_persediaan_plus;
                    $arResult[$indexCategory]["SumMinus"] += $nilai_persediaan_minus;
                } else { //di array result belum ada
                    $arData = array(
                        "CategoryCode" => $row->ItemCategoryID,
                        "SumPlus" => $nilai_persediaan_plus,
                        "SumMinus" => $nilai_persediaan_minus
                    );
                    $arResult[] = $arData;
                }
                //================== END persiapan array untuk journal ================//
            }
            $CategoryAmount = $arResult;
            $this->jurnal_debet_credit($check, $CategoryAmount, $cmb_adj_account, $txt_no, $txt_adjustment_date, $Value, $CtrlValue);
        }
        /* =====================================end value=================================================== */ else {
            /* ===============================================the adjusted qty only=================== */
            $arResult = array();
            foreach ($detail as $row) {
                $ItemCode = $row->ItemCode;
                $ItemUnit = $row->ItemUnit;
                $ItemDesc = $row->Description;
                $ItemAverage = $row->Hpp;

                $Qty = $row->Qty;
                $CtrlQty = $row->ControlQty;
                $ItemCategoryID = $row->ItemCategoryID;

                $nilai_persediaan_plus = 0;
                $nilai_persediaan_minus = 0;

                if ($Qty > $CtrlQty) {
                    /* ======perhitungan jika qty lebih besar dari ctrl qty============================== */
                    $selisih_qty = $Qty - $CtrlQty;
                    $new_value = $CtrlQty * $ItemAverage;
                    $nilai_persediaan_minus = $selisih_qty * $ItemAverage;
                    $nilai_jurnal = $selisih_qty * $ItemAverage;
                    /* ==================end============================================================= */
                } else {
                    /* ======perhitungan jika qty lebih kecil dari ctrl qty============================== */
                    $selisih_qty = $CtrlQty - $Qty;
                    $new_value = $CtrlQty * $ItemAverage;
                    $nilai_persediaan_plus = $selisih_qty * $ItemAverage;
                    $nilai_jurnal = $selisih_qty * $ItemAverage;
                    /* ===========================end====================================================== */
                }

                /*
                  Cek lock status adjustment
                 */
                $check_inventories_adjustment = $this->m_adjustment->get_inventories_adjustment($ItemCode, $branch_code);
                if ($check_inventories_adjustment->LockStatus == 1) {
                    $result['status'] = false;
                    $result['message'] = 'Maaf transaksi gagal item sedang di adjustment, silahkan selesaikan adjustment untuk item ' . $ItemDesc . '';

                    echo json_encode($result);
                    die;
                }
                /* ======================End================================================================================== */

                $detail_data = array(
                    'IAdjNumber' => $txt_no,
                    'ItemCode' => $ItemCode,
                    'ItemDesc' => $ItemDesc,
                    'ItemUnit' => $ItemUnit,
                    'ItemQty' => $Qty,
                    'ItemNewQty' => $CtrlQty,
                    'LastUser' => $this->session->userdata("username")
                );

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

                //$this->m_adjustment->update_inventories($update_inv_data, $ItemCode, $branch_code);
                $this->trans_data['update_inventories']['data'][] = $update_inv_data;
                $this->trans_data['update_inventories']['ItemCode'][] = $ItemCode;
                $this->trans_data['update_inventories']['branch'][] = $branch_code;

                //================== persiapan array untuk journal ================//
                $indexCategory = $this->checkIndex($arResult, "CategoryCode", $row->ItemCategoryID);

                if ($indexCategory > -1) { //di array result udah ada
                    $arResult[$indexCategory]["SumPlus"] += $nilai_persediaan_plus;
                    $arResult[$indexCategory]["SumMinus"] += $nilai_persediaan_minus;
                } else { //di array result belum ada
                    $arData = array(
                        "CategoryCode" => $row->ItemCategoryID,
                        "SumPlus" => $nilai_persediaan_plus,
                        "SumMinus" => $nilai_persediaan_minus
                    );
                    $arResult[] = $arData;
                }
                //================== END persiapan array untuk journal ================//	
            }

            $CategoryAmount = $arResult;
            $this->jurnal_debet_credit($check, $CategoryAmount, $cmb_adj_account, $txt_no, $txt_adjustment_date, $Qty, $CtrlQty);
        }
        /* =====================================end qty=================================================== */
    }

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

    /*
      New Data = New Qty / New Value
      Old Data = Current Qty / Cureen Value
     */

    function jurnal_debet_credit($check, $CategoryAmount, $cmb_adj_account, $txt_no, $txt_adjustment_date, $OldData, $NewData) {

        if ($check == 1) {
            /* ======================insert journal credit=================================================== */
            foreach ($CategoryAmount as $key => $value) {
                if ($value['SumPlus'] > $value['SumMinus']) {
                    $InventoryAccount = $this->m_account_journal->get_cat_item_account('Inventory', $value['CategoryCode'], 'IDR');
                    $BiayaSelisih = $this->m_account_journal->get_account_name('Biaya Selisih Stock');
                    $SumTotal = $value['SumPlus'] - $value['SumMinus'];

                    if ($InventoryAccount == false) {
                        $result['status'] = false;
                        $result['message'] = 'Settingan Preference untuk Item Category Inventory Belum Lengkap, Silahkan Setting Ulang';

                        echo json_encode($result);
                        die;
                    } else {
                        $credit_journal = array(
                            'IAdjDate' => date("Y-m-d", strtotime($txt_adjustment_date)),
                            'IAdjNumber' => $txt_no,
                            'IAdjAccountNumber' => $InventoryAccount->AccountNumber,
                            'IAdjSaldoDebet' => abs($SumTotal),
                            'IAdjSaldoCredit' => 0,
                            'IAdjSignStatus' => 0,
                            'LastUser' => $this->session->userdata('username')
                        );
                        //$this->m_adjustment->insert_tojournal_kredit($credit_journal);
                        $this->trans_data['insert_journal']['data'][] = $credit_journal;
                    }

                    if ($BiayaSelisih == false) {
                        $result['status'] = false;
                        $result['message'] = 'Settingan Preference untuk Biaya Selisih Stock Belum Lengkap, Silahkan Setting Ulang';

                        echo json_encode($result);
                        die;
                    } else {
                        $debet_journal = array(
                            'IAdjDate' => date("Y-m-d", strtotime($txt_adjustment_date)),
                            'IAdjNumber' => $txt_no,
                            'IAdjAccountNumber' => $BiayaSelisih->AccountNumber,
                            'IAdjSaldoDebet' => 0,
                            'IAdjSaldoCredit' => abs($SumTotal),
                            'IAdjSignStatus' => 1,
                            'LastUser' => $this->session->userdata('username')
                        );
                        //$this->m_adjustment->insert_tojournal_kredit($debet_journal);
                        $this->trans_data['insert_journal']['data'][] = $debet_journal;
                    }
                } else {
                    $InventoryAccount = $this->m_account_journal->get_cat_item_account('Inventory', $value['CategoryCode'], 'IDR');
                    $BiayaSelisih = $this->m_account_journal->get_account_name('Biaya Selisih Stock');
                    $SumTotal = $value['SumPlus'] - $value['SumMinus'];

                    if ($InventoryAccount == false) {
                        $result['status'] = false;
                        $result['message'] = 'Settingan Preference untuk Item Category Inventory Belum Lengkap, Silahkan Setting Ulang';

                        echo json_encode($result);
                        die;
                    } else {
                        $credit_journal = array(
                            'IAdjDate' => date("Y-m-d", strtotime($txt_adjustment_date)),
                            'IAdjNumber' => $txt_no,
                            'IAdjAccountNumber' => $InventoryAccount->AccountNumber,
                            'IAdjSaldoDebet' => 0,
                            'IAdjSaldoCredit' => abs($SumTotal),
                            'IAdjSignStatus' => 1,
                            'LastUser' => $this->session->userdata('username')
                        );
                        //$this->m_adjustment->insert_tojournal_kredit($credit_journal);
                        $this->trans_data['insert_journal']['data'][] = $credit_journal;
                    }

                    if ($BiayaSelisih == false) {
                        $result['status'] = false;
                        $result['message'] = 'Settingan Preference untuk Biaya Selisih Stock Belum Lengkap, Silahkan Setting Ulang';

                        echo json_encode($result);
                        die;
                    } else {
                        $debet_journal = array(
                            'IAdjDate' => date("Y-m-d", strtotime($txt_adjustment_date)),
                            'IAdjNumber' => $txt_no,
                            'IAdjAccountNumber' => $BiayaSelisih->AccountNumber,
                            'IAdjSaldoDebet' => abs($SumTotal),
                            'IAdjSaldoCredit' => 0,
                            'IAdjSignStatus' => 0,
                            'LastUser' => $this->session->userdata('username')
                        );
                        //$this->m_adjustment->insert_tojournal_kredit($debet_journal);
                        $this->trans_data['insert_journal']['data'][] = $debet_journal;
                    }
                }
            }
            /* ===============================end============================================================= */
        } else {
            foreach ($CategoryAmount as $key => $value) {
                if ($value['SumPlus'] > $value['SumMinus']) {
                    $InventoryAccount = $this->m_account_journal->get_cat_item_account('Inventory', $value['CategoryCode'], 'IDR');
                    $BiayaSelisih = $this->m_account_journal->get_account_name('Biaya Selisih Stock');
                    $SumTotal = $value['SumPlus'] - $value['SumMinus'];

                    if ($InventoryAccount == false) {
                        $result['status'] = false;
                        $result['message'] = 'Settingan Preference untuk Item Category Inventory Belum Lengkap, Silahkan Setting Ulang';

                        echo json_encode($result);
                        die;
                    } else {
                        $credit_journal = array(
                            'IAdjDate' => date("Y-m-d", strtotime($txt_adjustment_date)),
                            'IAdjNumber' => $txt_no,
                            'IAdjAccountNumber' => $InventoryAccount->AccountNumber,
                            'IAdjSaldoDebet' => abs($SumTotal),
                            'IAdjSaldoCredit' => 0,
                            'IAdjSignStatus' => 0,
                            'LastUser' => $this->session->userdata('username')
                        );
                        //$this->m_adjustment->insert_tojournal_kredit($credit_journal);
                        $this->trans_data['insert_journal']['data'][] = $credit_journal;
                    }

                    if ($BiayaSelisih == false) {
                        $result['status'] = false;
                        $result['message'] = 'Settingan Preference untuk Biaya Selisih Stock Belum Lengkap, Silahkan Setting Ulang';

                        echo json_encode($result);
                        die;
                    } else {
                        $debet_journal = array(
                            'IAdjDate' => date("Y-m-d", strtotime($txt_adjustment_date)),
                            'IAdjNumber' => $txt_no,
                            'IAdjAccountNumber' => $BiayaSelisih->AccountNumber,
                            'IAdjSaldoDebet' => 0,
                            'IAdjSaldoCredit' => abs($SumTotal),
                            'IAdjSignStatus' => 1,
                            'LastUser' => $this->session->userdata('username')
                        );
                        //$this->m_adjustment->insert_tojournal_kredit($debet_journal);
                        $this->trans_data['insert_journal']['data'][] = $debet_journal;
                    }
                } else {
                    $InventoryAccount = $this->m_account_journal->get_cat_item_account('Inventory', $value['CategoryCode'], 'IDR');
                    $BiayaSelisih = $this->m_account_journal->get_account_name('Biaya Selisih Stock');
                    $SumTotal = $value['SumPlus'] - $value['SumMinus'];

                    if ($InventoryAccount == false) {
                        $result['status'] = false;
                        $result['message'] = 'Settingan Preference untuk Item Category Inventory Belum Lengkap, Silahkan Setting Ulang';

                        echo json_encode($result);
                        die;
                    } else {
                        $credit_journal = array(
                            'IAdjDate' => date("Y-m-d", strtotime($txt_adjustment_date)),
                            'IAdjNumber' => $txt_no,
                            'IAdjAccountNumber' => $InventoryAccount->AccountNumber,
                            'IAdjSaldoDebet' => 0,
                            'IAdjSaldoCredit' => abs($SumTotal),
                            'IAdjSignStatus' => 1,
                            'LastUser' => $this->session->userdata('username')
                        );
                        //$this->m_adjustment->insert_tojournal_kredit($credit_journal);
                        $this->trans_data['insert_journal']['data'][] = $credit_journal;
                    }

                    if ($BiayaSelisih == false) {
                        $result['status'] = false;
                        $result['message'] = 'Settingan Preference untuk Biaya Selisih Stock Belum Lengkap, Silahkan Setting Ulang';

                        echo json_encode($result);
                        die;
                    } else {
                        $debet_journal = array(
                            'IAdjDate' => date("Y-m-d", strtotime($txt_adjustment_date)),
                            'IAdjNumber' => $txt_no,
                            'IAdjAccountNumber' => $BiayaSelisih->AccountNumber,
                            'IAdjSaldoDebet' => abs($SumTotal),
                            'IAdjSaldoCredit' => 0,
                            'IAdjSignStatus' => 0,
                            'LastUser' => $this->session->userdata('username')
                        );
                        //$this->m_adjustment->insert_tojournal_kredit($debet_journal);
                        $this->trans_data['insert_journal']['data'][] = $debet_journal;
                    }
                }
            }
            /* ===============================end============================================================= */
        }
    }

    public function get_account_bycompany() {
        $result = $this->m_adjustment->akun_biaya_adjustment($this->session->userdata('company'));

        echo json_encode($result);
    }

    public function get_itemcategory() {
        $data['menu_link'] = $this->m_adjustment->get_menulink($this->menu_id);

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


        $result = $this->m_adjustment->get_itemcategory($AccountNumber, $this->session->userdata('company'));

        echo json_encode($result);
    }

    public function items() {
        $result = $this->m_adjustment->items();
        echo json_encode($result);
    }

    /* public function ajax_list_item_group($CategoryID){
      $sess_branch = $this->session->userdata('branch');
      //select ke am account gl dan di explode by itemkategori id di am account gl

      $list_item_group =  $this->m_adjustment->get_list_item_group($CategoryID,$sess_branch);
      echo json_encode($list_item_group);
      } */

    function ajax_list_item_group() {
        $result = $this->m_adjustment->get_list_item_group();
        //echo $this->db->last_query();
        $hasil = '';
        foreach ($result as $row) {
            if ($row->IsLock == 1) {
                $Status = "Item Lock";
            } else {
                $Status = "Item UnLock";
            }
            $hasil[] = array(
                'ItemCode' => $row->ItemCode,
                'ItemDesc' => $row->ItemDesc,
                'ItemUnit' => $row->ItemUnit,
                'ItemAverage' => $row->ItemAverage,
                'ItemValue' => $row->ItemValue,
                'ItemCategoryID' => $row->ItemCategoryID,
                'ItemQty' => $row->ItemQty,
                'IsLock' => $Status,
                'ItemLockId' => $row->IsLock
            );
        }
        echo json_encode($hasil);
    }

    public function get_item($item_code) {
        $result = $this->m_adjustment->get_item_bycode($item_code);
        echo json_encode($result);
    }

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

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

                    $id = str_replace($data['menu_link'] . '/edit/', "", $this->uri->uri_string());
                    $data['adjustment'] = $this->m_adjustment->get_by_id($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('adjustment/v_edit_adjustment', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function chek_update($nilai_n) {
        // inisialisasi additional parameter
        $id = $this->input->post('txt_adjust_number');
        $data = array(
            'StatusCheck' => $nilai_n
        );

        $this->m_adjustment->update_chek($data, $id);
    }

    public function update() {

        /* ====================deklar varabel============================ */
        $branch_code = $this->input->post('branch_code_hidden');
        $get_company = $this->m_adjustment->company_name($branch_code);

        $txt_adjustment_date = $this->input->post('txt_date');
        $txt_adjust_number = $this->input->post('txt_adjust_number');
        $txa_description = $this->input->post('txa_description');

        $cmb_adj_account = $this->input->post('cmb_adj_account');
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $chk_value_adjustment = $this->input->post('Status_Tab');

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

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

        if (count($detail) > 0) {

            /* ==========================delete all for jurnal============================================================= */
            //$this->m_adjustment->delete_jurnal($txt_adjust_number);
            $this->trans_data['delete_journal']['TransNumber'] = $txt_adjust_number;
            /* ===================================end===================================================================== */

            /* ======================update group============================ */
            $update_group = $this->update_group($branch_code, $txt_adjustment_date, $txt_adjust_number, $cmb_adj_account, $txa_description);
            /* =====================end====================================== */

            /* ===========================delete detail================================================================= */
            $this->trans_data['delete_detail']['total'] = count($detail_id);

            if (count($detail_id) > 0) {
                foreach ($detail_id as $IAdjDetailID) {

                    //$this->m_adjustment->delete_data_grid($IAdjDetailID);
                    $this->trans_data['delete_detail']['IAdjDetailID'][] = $IAdjDetailID;

                    $update_inv_data = array(
                        'LockStatus' => 0
                    );

                    //$this->m_adjustment->update_inventories($update_inv_data, $detail_item[1], $branch_code);
                    $this->trans_data['update_inventories']['data'][] = $update_inv_data;
                    $this->trans_data['update_inventories']['ItemCode'][] = $detail_item[1];
                    $this->trans_data['update_inventories']['branch'][] = $branch_code;
                }
            }
            /* =============================end========================================================================== */

            /* ======================update detail========================== */
            $update_detail = $this->update_detail($chk_value_adjustment, $detail, $cmb_adj_account, $txt_adjust_number, $txt_adjustment_date);
            /* ========================end================================= */

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

            $this->trans_data = [];

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

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

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

    function update_group($branch_code, $txt_adjustment_date, $txt_adjust_number, $cmb_adj_account, $txa_description) {
        $data = array(
            'BranchCode' => $branch_code,
            'IAdjDate' => date("Y-m-d", strtotime($txt_adjustment_date)),
            'IAdjNumber' => $txt_adjust_number,
            'IAdjAccountNumber' => $cmb_adj_account,
            'IAdjDesc' => $txa_description,
            'LastUser' => $this->session->userdata("username")
        );
        //$this->m_adjustment->update($data, $txt_adjust_number);
        $this->trans_data['update_group']['data'] = $data;
        $this->trans_data['update_group']['TransNumber'] = $txt_adjust_number;
    }

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

    function checkIndex($dataMaster, $name, $value) {
        $indexFound = -1;
        $noIndex = 0;
        foreach ($dataMaster as $dataLoop) {
            if ($dataLoop[$name] == $value) {
                $indexFound = $noIndex;
                return $indexFound;
            }
            $noIndex++;
        }
        return $indexFound;
    }

    /* ======================function upda detail============================================= */

    function update_detail($chk_value_adjustment, $detail, $cmb_adj_account, $txt_adjust_number, $txt_adjustment_date) {
        /*
          chk value = 1 for value
          chk value = 0 for qty
         */
        $total_persediaan_plus = 0;
        $total_persediaan_minus = 0;

        $nilai_persediaan_plus = 0;
        $nilai_persediaan_minus = 0;
        $CategoryMinus = 0;
        $CategoryPlus = 0;

        $CategoryMinus = array();
        $CategoryPlus = array();


        if ($chk_value_adjustment == 1) {
            $arResult = array();

            foreach ($detail as $row) {
                $IAdjDetailID = $row->IAdjDetailID;
                $ItemCode = $row->ItemCode;
                $ItemDesc = $row->Description;
                $ItemUnit = $row->ItemUnit;

                $Value = $row->Value;
                $ControlValue = $row->ControlValue;

                $RowStatus = $row->RowStatus;

                $ItemCategoryID = $row->ItemCategoryID;

                $nilai_persediaan_plus = 0;
                $nilai_persediaan_minus = 0;

                if ($Value > $ControlValue) {
                    //$new_hpp 				= $ControlValue / $Qty;
                    $nilai_persediaan_minus = $Value - $ControlValue;
                    $nilai_jurnal = $Value - $ControlValue;
                } else {
                    //$new_hpp 				= $ControlValue / $Qty;
                    $nilai_persediaan_plus = $ControlValue - $Value;
                    $nilai_jurnal = $ControlValue - $Value;
                }

                $detail_data = array(
                    'ItemNewValue' => $ControlValue,
                    'LastUser' => $this->session->userdata("username")
                );

                //$this->m_adjustment->update_fromgrid($detail_data, $IAdjDetailID);
                $this->trans_data['update_detail']['data'][] = $detail_data;
                $this->trans_data['update_detail']['IAdjDetailID'][] = $IAdjDetailID;

                //================== persiapan array untuk journal ================//
                $indexCategory = $this->checkIndex($arResult, "CategoryCode", $row->ItemCategoryID);

                if ($indexCategory > -1) { //di array result udah ada
                    $arResult[$indexCategory]["SumPlus"] += $nilai_persediaan_plus;
                    $arResult[$indexCategory]["SumMinus"] += $nilai_persediaan_minus;
                } else { //di array result belum ada
                    $arData = array(
                        "CategoryCode" => $row->ItemCategoryID,
                        "SumPlus" => $nilai_persediaan_plus,
                        "SumMinus" => $nilai_persediaan_minus
                    );
                    $arResult[] = $arData;
                }
                //================== END persiapan array untuk journal ================//
            }
            $CategoryAmount = $arResult;
            $get_journal_debet_credit = $this->jurnal_debet_credit($chk_value_adjustment, $CategoryAmount, $cmb_adj_account, $txt_adjust_number, $txt_adjustment_date, $Value, $ControlValue);
        } else {
            $arResult = array();

            foreach ($detail as $row) {
                $IAdjDetailID = $row->IAdjDetailID;
                $ItemCode = $row->ItemCode;
                $ItemUnit = $row->ItemUnit;
                $ItemDesc = $row->Description;
                $ItemAverage = $row->Hpp;

                $Qty = $row->Qty;
                $CtrlQty = $row->ControlQty;
                $RowStatus = $row->RowStatus;
                $ItemCategoryID = $row->ItemCategoryID;

                $nilai_persediaan_plus = 0;
                $nilai_persediaan_minus = 0;

                if ($Qty > $CtrlQty) {
                    /* ======perhitungan jika qty lebih besar dari ctrl qty============================== */
                    $selisih_qty = $Qty - $CtrlQty;

                    $new_value = $CtrlQty * $ItemAverage;

                    //masuk nilai jurnal
                    $nilai_persediaan_minus = $selisih_qty * $ItemAverage;
                    $nilai_jurnal = $selisih_qty * $ItemAverage;
                    /* ==================end============================================================= */
                } else {
                    /* ======perhitungan jika qty lebih kecil dari ctrl qty============================== */
                    $selisih_qty = $CtrlQty - $Qty;

                    $new_value = $CtrlQty * $ItemAverage;

                    //masuk nilai jurnal
                    $nilai_persediaan_plus = $selisih_qty * $ItemAverage;
                    $nilai_jurnal = $selisih_qty * $ItemAverage;
                    /* ===========================end====================================================== */
                }

                $detail_data = array(
                    'ItemNewQty' => $CtrlQty,
                    'LastUser' => $this->session->userdata("username")
                );

                //$this->m_adjustment->update_fromgrid($detail_data, $IAdjDetailID);
                $this->trans_data['update_detail']['data'][] = $detail_data;
                $this->trans_data['update_detail']['IAdjDetailID'][] = $IAdjDetailID;

                //================== persiapan array untuk journal ================//
                $indexCategory = $this->checkIndex($arResult, "CategoryCode", $row->ItemCategoryID);

                if ($indexCategory > -1) { //di array result udah ada
                    $arResult[$indexCategory]["SumPlus"] += $nilai_persediaan_plus;
                    $arResult[$indexCategory]["SumMinus"] += $nilai_persediaan_minus;
                } else { //di array result belum ada
                    $arData = array(
                        "CategoryCode" => $row->ItemCategoryID,
                        "SumPlus" => $nilai_persediaan_plus,
                        "SumMinus" => $nilai_persediaan_minus
                    );
                    $arResult[] = $arData;
                }
                //================== END persiapan array untuk journal ================//
            }

            //echo $total_persediaan_minus .'+'. $nilai_persediaan_minus.'<br>';
            $CategoryAmount = $arResult;
            $get_journal_debet_credit = $this->jurnal_debet_credit($chk_value_adjustment, $CategoryAmount, $cmb_adj_account, $txt_adjust_number, $txt_adjustment_date, $Qty, $CtrlQty);
        }
    }

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

    //function get data to grid
    function get_data_grid() {
        $data['menu_link'] = $this->m_adjustment->get_menulink($this->menu_id);

        $IAdjNumber = str_replace($data['menu_link'] . '/get_data_grid/', "", $this->uri->uri_string());
        $result = $this->m_adjustment->get_data_grid($IAdjNumber);
        echo json_encode($result);
    }
	
	function reverse_data_detail() {
        try {
			$txt_adjust_number = $this->input->post('txt_adjust_number');
			$branch_code = $this->session->userdata("branch");
			$check 		= $this->input->post('Status_Tab');
			
			$detail = $this->input->post('detail');
        	$detail = json_decode($detail);
		
			/*Check End Periode*/
			$date_transaction 	= check_end_periode($txt_adjust_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;
				$get_item_already_used = $this->m_custom->check_item_already_used($ItemCode, $branch_code,'Adjustment');
				
				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
				}
				
				if($check == 0){//This adjust Qty
					/*
					  Check Adjustment
					*/
					$item_lock_status = $this->m_inventories->get_inventori_by_item($ItemCode, $branch_code);
					if ($item_lock_status->LockStatus == 1) {
						throw new Exception(('Tidak bisa dilakukan proses Reverse, karena item ' . $row_detail->ItemCode . ' pada listing sedang dilakukan proses Adjustment')); //item adjust
					}
					/* =================END============================== */
					$ItemAverage 	= $row_detail->Hpp;
					$Qty 		 	= $row_detail->Qty;
					$CtrlQty 	 	= $row_detail->ControlQty;
					$Value 		 	= $row_detail->ValueInv;
					$RowStatus 	 	= $row_detail->RowStatus;
					$ItemCategoryID = $row_detail->ItemCategoryID;
		
					$new_value = $Qty * $ItemAverage;
		
					$update_inv_data = array(
						'ItemQty' => $Qty,
						'ItemValue' => $new_value,
						'LockStatus' => 1
					);
		
					//$this->m_adjustment->update_inventories($update_inv_data, $ItemCode, $branch_code);
					$this->trans_data['update_inventory']['data'][] = $update_inv_data;
					$this->trans_data['update_inventory']['ItemCode'][] = $ItemCode;
				}
				else{//this adjust value
					/*
					  Check Adjustment
					*/
					$item_lock_status = $this->m_inventories->get_inventori_by_item($ItemCode, $branch_code);
					if ($item_lock_status->LockStatus == 1) {
						throw new Exception(('Tidak bisa dilakukan proses Reverse, karena item ' . $row_detail->ItemCode . ' pada listing sedang dilakukan proses Adjustment')); //item adjust
					}
					/* =================END============================== */
					
					if(($item_lock_status->ItemValue == $row_detail->ControlValue)){
						$ItemCode 		= $row_detail->ItemCode;
						$Value 			= $row_detail->Value;
						$ControlValue 	= $row_detail->ControlValue;
						$Qty 			= $row_detail->QtyInv;
						$RowStatus	 	= $row_detail->RowStatus;
		
						$ItemCategoryID = $row_detail->ItemCategoryID;
		
						/* ==================rumus new hpp======================== */
						$new_hpp = $Value / $Qty;
						/* =======================end============================= */
		
						$update_inv_data = array(
							'ItemValue' => $Value,
							'ItemAverage' => $new_hpp,
							'LockStatus' => 1
						);
		
						//$this->m_adjustment->update_inventories($update_inv_data, $ItemCode, $branch_code);
						$this->trans_data['update_inventory']['data'][] = $update_inv_data;
						$this->trans_data['update_inventory']['ItemCode'][] = $ItemCode;
					}
					else{
						throw new Exception(('Tidak bisa dilakukan proses Reverse, karena item ' . $row_detail->ItemCode . ' pada listing sedang dilakukan proses Adjustment')); //item adjust
					}
				}
			}
			
			$status_and_approval = array(
				'TransStatus' => 5,
				'AppLevel2Status' => NULL,
				'AppLevel2Code' => NULL,
				'AppLevel2Date' => NULL,
				'AppFinished' => 0
			);

			//$this->m_adjustment->update_status($status_and_approval, $txt_adjust_number);
			$this->trans_data['update_status']['data'] = $status_and_approval;
			$this->trans_data['update_status']['TransNumber'] = $txt_adjust_number;
			
			$result_approve = $this->m_adjustment->reverse_transsaction($this->trans_data);
            $this->trans_data = [];

            if ($result_approve) {
				$result['status'] = true;
				$result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $txt_adjust_number);
			} else {
				$result['status'] = false;
				$result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $txt_adjust_number);
			}
            /* ==================================end====================================================== */
			echo json_encode($result);
		}
		catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
	}
	
    public function approve_dir() {
        /* ===================deklar varabel============================================= */
        $code_appdir = $this->input->post('code_appdir');
        $branch_code = $this->input->post('branch_code_hidden');
        $txt_adjust_number = $this->input->post('txt_adjust_number');
        $status_checked = $this->input->post('Status_Tab');
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);

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

        $status_and_approval = array(
            'TransStatus' => 2,
            'AppLevel2Status' => 1,
            'AppLevel2Code' => $this->session->userdata('username'),
            'AppLevel2Date' => date('Y-m-d'),
            'AppFinished' => 1
        );

        //$this->m_adjustment->update_status($status_and_approval, $txt_adjust_number);
        $this->trans_data['update_status']['data'] = $status_and_approval;
        $this->trans_data['update_status']['TransNumber'] = $txt_adjust_number;

        /*
          status checked = 1 is value
          status checked = 0 is qty
         */
        if ($status_checked == 1) {
            foreach ($detail as $row) {
                $ItemCode = $row->ItemCode;
                $ItemDesc = $row->Description;
                $ItemUnit = $row->ItemUnit;

                $Value = $row->Value;
                $ControlValue = $row->ControlValue;
                $Qty = $row->QtyInv;
                $RowStatus = $row->RowStatus;

                $ItemCategoryID = $row->ItemCategoryID;

                /* ==================rumus new hpp======================== */
                $new_hpp = $ControlValue / $Qty;
                /* =======================end============================= */

                $update_inv_data = array(
                    'ItemValue' => $ControlValue,
                    'ItemAverage' => $new_hpp,
                    'LockStatus' => 0
                );

                //$this->m_adjustment->update_inventories($update_inv_data, $ItemCode, $branch_code);
                $this->trans_data['update_inventories']['data'][] = $update_inv_data;
                $this->trans_data['update_inventories']['ItemCode'][] = $ItemCode;
                $this->trans_data['update_inventories']['branch'][] = $branch_code;
            }
        } else {
            foreach ($detail as $row) {
                $ItemCode = $row->ItemCode;
                $ItemUnit = $row->ItemUnit;
                $ItemDesc = $row->Description;
                $ItemAverage = $row->Hpp;

                $Qty = $row->Qty;
                $CtrlQty = $row->ControlQty;
                $Value = $row->ValueInv;

                $RowStatus = $row->RowStatus;
                $ItemCategoryID = $row->ItemCategoryID;

                $new_value = $CtrlQty * $ItemAverage;

                $update_inv_data = array(
                    'ItemQty' => $CtrlQty,
                    'ItemValue' => $new_value,
                    'LockStatus' => 0
                );

                //$this->m_adjustment->update_inventories($update_inv_data, $ItemCode, $branch_code);
                $this->trans_data['update_inventories']['data'][] = $update_inv_data;
                $this->trans_data['update_inventories']['ItemCode'][] = $ItemCode;
                $this->trans_data['update_inventories']['branch'][] = $branch_code;
            }
        }

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

        $this->trans_data = [];

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

        echo json_encode($result);
    }

    public function suspend_data() {
        /* ======================deklarr variabel========================== */
        $adjust_number = $this->input->post('id');
        /* =======================end====================================== */

        /* ===================change trans status from table group=============== */
        $data = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata('username')
        );
        /* ========================end========================================== */

        //$this->m_adjustment->suspend($data, $adjust_number);
        $this->trans_data['suspend_data']['data'] = $data;
        $this->trans_data['suspend_data']['TransNumber'] = $adjust_number;

        /* ========================update inventori by branch and item code===================== */
        $cek_branch = $this->m_adjustment->get_by_id_suspend($adjust_number);
        $branch_code = $cek_branch->BranchCode;

        $cek_detail = $this->m_adjustment->get_tabel_detail($adjust_number);
        /* =====================end============================================================ */

        foreach ($cek_detail as $row_data) {
            $item_code = $row_data->ItemCode;
            $update_inv_data = array(
                'LockStatus' => 0
            );

            //$this->m_adjustment->update_inventories($update_inv_data, $item_code, $branch_code);
            $this->trans_data['update_inventories']['data'][] = $update_inv_data;
            $this->trans_data['update_inventories']['ItemCode'][] = $item_code;
            $this->trans_data['update_inventories']['branch'][] = $branch_code;
        }

        $result_return = $this->m_adjustment->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);
    }

    function get_status_transaki() {
        $trans_number = $this->input->post('number');
        $get_number = $this->m_adjustment->get_all_by_no($trans_number);

        foreach ($get_number as $row) {
            $adjust_numbstatus[] = $row->TransStatus;
        }

        $data = array(
            'number_adjuststatus' => $adjust_numbstatus
        );
        echo json_encode($data);
    }

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

        $sess_company = $this->session->userdata('company');
        $sess_branch = $this->session->userdata('branch');

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


        $akun_persediaan_number = $this->m_adjustment->get_account_persediaan($adjust_number);

        $data['account_number_adjustment'] = $this->m_adjustment->account_number_adjustment($adjust_number);
        //$data['account_name_adjustment']	= $this->m_adjustment->account_name_adjustment($adjust_number);


        $data['account_inv_adjustment'] = $this->m_adjustment->account_inv_adjustment();


        $data['branch_by_company'] = $akun_persediaan_number->IAdjNumber;

        $data['company_name'] = $this->m_adjustment->company_name($this->session->userdata('branch'));

        $data['detail_to_journal'] = $this->m_adjustment->detail_to_journal($adjust_number);

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

    // Function Print
    public function to_preview($obj_string = null) {
//        $CompanyCode = $this->uri->segment(4);
//        $BranchCode = $this->uri->segment(5);
        // set data
//        $data['company_code'] = $CompanyCode;
//        $data['branch_code'] = $BranchCode;

//        $data['list'] = $this->m_adjustment->get_all_to_print($BranchCode);
//        $obj_string     = arrayInUrlToStr($data_grid); 
//        $data['list']   = json_decode($obj_string);
        $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_adjustment->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('list/adjustment/v_print_adjustment', $data);
        $this->load->view('v_footer');
    }

    function to_print_detail() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
        $companyCode = $this->session->userdata('company');

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

        if ($id != "") {
            $data['detail'] = $this->m_adjustment->get_detail_print($id);
            $data['list'] = $this->m_adjustment->get_detail_item_print($data['detail']->IAdjNumber);
            // echo $this->db->last_query();   
            $this->load->view('v_header');
            $this->load->view('list/adjustment/v_print_detail_adjustment', $data);
            $this->load->view('v_footer');
        }
    }

    public function to_pdf() {
        $this->load->library('html2pdf');
        $this->html2pdf->folder('./asset/pdfs/');
        $this->html2pdf->filename('List Adjustment.pdf');
        $this->html2pdf->paper('a4', 'portrait');

        $data['company'] = $this->m_adjustment->get_company_by_branch($this->session->userdata('branch'));
        $data['list'] = $this->m_adjustment->get_all_to_print($this->session->userdata('branch'));

        $this->html2pdf->html($this->load->view('adjustment/v_print_adjustment', $data, true));
        $this->html2pdf->create();
    }

    public function to_excel() {
        $this->load->library('export');

        $sql = $this->m_adjustment->view_all();
        $header = array(
            'MenuId' => 'ID',
            'MenuLabel' => 'Name',
            'MenuLink' => 'Rate',
            'MenuLevel' => 'Country'
        );
        $this->export->to_excel($sql, 'List Adjustment', $header);
    }

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

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

    public function get_number_adjust() {
        $adjust_date_model = $this->input->post('adjust_date') == '' ? date('d-m-Y') : $this->input->post('adjust_date');
        $adjustment_number = $this->m_adjustment->create_adjust_number($adjust_date_model);

        $result['status'] = true;
        $result['number'] = $adjustment_number;
        echo json_encode($result);
    }

    function get_asset() {

        $sess_branch = $this->session->userdata('branch');
        $item_code = $this->input->post('ItemCode');

        if (!empty($item_code)) {
            echo json_encode($this->m_adjustment->asset($sess_branch, $item_code));
        } else {
            echo '[]';
        }
    }

    /* ==================function from new adjustmen pop up================================== */

    public function ajax_item() {
        $ItemCode = $this->input->post('ItemCode');
        $branch = $this->session->userdata('branch');
        if (!empty($ItemCode)) {
            echo json_encode($this->m_inventories->get_item_inventori_by_branch($ItemCode, $branch));
        } else {
            echo '[]';
        }
    }

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

    function delete_row() {
        /* ====================================deklar variabel from delete grid================================ */
        $branch_code = $this->input->post('branch_code_hidden');
        $get_company = $this->m_adjustment->company_name($branch_code);

        $txt_adjustment_date = $this->input->post('txt_date');
        $txt_adjust_number = $this->input->post('txt_adjust_number');
        $cmb_adj_account = $this->input->post('cmb_adj_account');
        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $chk_value_adjustment = $this->input->post('status_checked');

        /* =====================================end========================================================= */
        $this->db->trans_begin();

        /* ===========================update detail function ini dipake juga di update data======================================= */
        $delete_detail = $this->update_detail($chk_value_adjustment, $detail, $cmb_adj_account, $txt_adjust_number, $txt_adjustment_date);
        /* =============================end====================================================================================== */

        /* =====================function buka lock status di inventories================================================ */
        foreach ($detail as $row_data) {
            $item_code = $row_data->ItemCode;
            $RowStatus = $row_data->RowStatus;

            if ($RowStatus == 3) {
                $update_inv_data = array(
                    'LockStatus' => 0
                );

                $this->m_adjustment->update_inventories($update_inv_data, $item_code, $branch_code);
            }
        }
        /* ======================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);
    }

}
