<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* 	
 * 	Author 	: Fachri
 * 	Tanggal : 30-04-2015	
 * 	Revisi 	: 
 */

class Roll_over extends CI_Controller {

    public $menu_id = 269;
    public $menu_model = 'm_roll_over';
    public $name = 'Roll Over';
    public $trans_data = array();

    public function __construct() {
        parent::__construct();
        $this->load->model('m_roll_over');
        $this->load->model('m_job_costing');
        $this->load->model('m_inventories');
        $this->load->model('custom/m_custom');
        $this->load->model('m_account_journal');

        $this->load->helper('message_helper');
        $this->load->helper('status');
        $this->load->helper('custom_string_helper');
		$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_menu->get_menulink($this->menu_id);

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

    //Function Menampilkan Data Pada Data Grid View
    //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('ROvrNumber', $Number);
        } //change
        if ($Desc != "") {
            $this->db->like('ROvrDesc', $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_rollover.ROvrDate >=', date("Y-m-d", strtotime($DateFrom))); //change
                $this->db->where('at_rollover.ROvrDate <=', date("Y-m-d", strtotime($DateTo))); //change
            }
        }
        /* ==========================end================================================================= */

        $count_data = $this->db->count_all_results('at_rollover'); //change
        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_roll_over->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]->TransStatus);

            $hasil[] = array(
                'TransNumber' => $result[$i]->ROvrNumber,
                'ROvrDesc' => $result[$i]->ROvrDesc,
                'ROvrDate' => $result[$i]->ROvrDate,
                'JCostNumber' => $result[$i]->JCostNumber,
                'JCostSubTotal' => $result[$i]->JCostSubTotal,
                'TransStatus' => $TransStatus,
                'CreatedBy' => $result[$i]->CreatedBy,
                'TransStatus_Code' => $result[$i]->TransStatus,
                '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_id'] = $this->menu_id;
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $data['date_now'] = date('d-m-Y');

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

    public function insert() {
        /* ==================================deklar variabel===================================== */
        $batch_no = $this->input->post('cmb_roll_over');
        $txt_date = $this->input->post('txt_date');

        /* =====================================jcos number========================================== */
        $rov_no = $this->m_roll_over->create_ro_number($txt_date);
        /* ========================================================================================== */

        $akun_no = $this->input->post('txt_jobcostaccountno');
        $akun_name = $this->input->post('txt_jobcostaccountnodesc');
        $desc = $this->input->post('txt_jobcostdesc');
        $Status_Tab = $this->input->post('Status_Tab');
        if ($Status_Tab == 0) {
            $total = $this->input->post('txt_totaljobcost_no_koma');
        } else {
            $total = $this->input->post('txt_amount_allocated');
        }
        $JCostSubTotal = $this->input->post('txt_totaljobcost_no_koma');

        $rov_date = $this->input->post('txt_rolloverdate');
        $detail_post = $this->input->post('detail');
        $detail = json_decode($detail_post);
        $Status_Tab = $this->input->post('Status_Tab');
        /* ======================================end============================================= */
        if (count($detail) > 0) {

            /* =========================insert group================================================= */
            $insert_group = $this->insert_group($rov_date, $rov_no, $batch_no, $akun_no, $total, $desc, $Status_Tab, $txt_date, $JCostSubTotal);
            /* ============================end======================================================= */

            /* =========================insert detail================================================= */
            $insert_detail = $this->insert_detail($detail, $rov_no, $Status_Tab, $akun_no, $total, $desc, $rov_date, $JCostSubTotal);
            /* ============================end======================================================= */

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

            $this->trans_data = [];

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

            echo json_encode($result);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('no_count', 0);
            echo json_encode($result);
        }
    }

    function insert_group($rov_date, $rov_no, $batch_no, $akun_no, $total, $desc, $Status_Tab, $txt_date, $JCostSubTotal) {
        /* ===========================================sunction insert gtroup============================= */
        $data = array(
            'BranchCode' => $this->session->userdata("branch"),
            'ROvrDate' => date("Y-m-d", strtotime($rov_date)),
            'ROvrNumber' => $rov_no,
            'JCostNumber' => $batch_no,
            'JCostDate' => date("Y-m-d", strtotime($txt_date)),
            'ROvrDesc' => $desc,
            'ROvrAccountNumber' => $akun_no,
            'ROvrTotalAmount' => $total,
            'JCostSubTotal' => $JCostSubTotal,
            'TransStatus' => 4,
            'ROvrStatus' => $Status_Tab,
            'LockStatus' => 0,
            'CreatedBy' => $this->session->userdata("username"),
            'CreatedAt' => date('Y-m-d'),
            'LastUser' => $this->session->userdata("username")
        );

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

    function insert_detail($detail, $rov_no, $Status_Tab, $akun_no, $total, $desc, $rov_date, $JCostSubTotal) {

        $this->trans_data['status_tab'] = $Status_Tab;

        foreach ($detail as $row) {
            /* ================================deklar variabel===================================== */
            if ($Status_Tab == 0) {
                $akun_grid = $row->AccountNo;
                $Department = $row->DepartmentCode;

                $data_detail = array(
                    'ROvrNumber' => $rov_no,
                    'AccountNumber' => $akun_grid,
                    'DepartmentCode' => $Department,
                    'LastUser' => $this->session->userdata("username")
                );
                //$this->m_roll_over->insert_detail($data_detail);
                $this->trans_data['insert_detail']['data'][] = $data_detail;

                $get_insert_journal = $this->insert_journal_to_akun($rov_no, $akun_no, $JCostSubTotal, $desc, $akun_grid, $rov_date);
            } else {
                /*
                  Perhitungan allocated value untuk hpp baru di inventori
                 */
                $total_allocated = ($total * $row->Allocated) / 100;

                $ItemCode = $row->ItemCode;
                $ItemUnit = $row->ItemUnit;
                $ItemDesc = $row->ItemDesc;
                $ItemQty = $row->ItemQty;
                $AllocatedValue = $row->Allocated;
                $ItemCategoryID = $row->ItemCategoryID;
                $HPPNew = $row->HPPNew_Los;

                $data_detail = array(
                    'ROvrNumber' => $rov_no,
                    'ItemCode' => $ItemCode,
                    'ItemQty' => $ItemQty,
                    'ItemUnit' => $ItemUnit,
                    'ItemDesc' => $ItemDesc,
                    'HPPNew' => $HPPNew,
                    'AllocatedValue' => $AllocatedValue,
                    'LastUser' => $this->session->userdata("username")
                );

                //$this->m_roll_over->insert_detail($data_detail);
                $this->trans_data['insert_detail']['data'][] = $data_detail;
                @$CategoryAmount[$ItemCategoryID] += $total_allocated;
            }
            /* ================================end=================================================== */
        }

        if ($Status_Tab == 1) {
            $get_insert_journal = $this->insert_journal_to_item($CategoryAmount, $rov_no, $akun_no, $total, $desc, $rov_date);
        }
    }

    /* ================================================insert jurnal to akun============================================ */

    function insert_journal_to_akun($rov_no, $akun_no, $JCostSubTotal, $desc, $akun_grid, $rov_date) {
        $data_jurnal_credit = array(
            'ROvrDate' => date("Y-m-d", strtotime($rov_date)),
            'ROvrNumber' => $rov_no,
            'ROvrAccountNumber' => $akun_no,
            'ROvrSaldoDebet' => 0,
            'ROvrSaldoCredit' => $JCostSubTotal,
            'ROvrDesc' => $desc,
            'ROvrSignStatus' => 1,
            'LastUser' => $this->session->userdata("username")
        );

        //$this->m_roll_over->insert_jurnal($data_jurnal_credit);
        $this->trans_data['insert_journal_to_akun']['data'][] = $data_jurnal_credit;

        $data_jurnal_debet = array(
            'ROvrDate' => date("Y-m-d", strtotime($rov_date)),
            'ROvrNumber' => $rov_no,
            'ROvrAccountNumber' => $akun_grid,
            'ROvrSaldoDebet' => $JCostSubTotal,
            'ROvrSaldoCredit' => 0,
            'ROvrDesc' => $desc,
            'ROvrSignStatus' => 0,
            'LastUser' => $this->session->userdata("username")
        );

        //$this->m_roll_over->insert_jurnal($data_jurnal_debet);
        $this->trans_data['insert_journal_to_akun']['data'][] = $data_jurnal_debet;
    }

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

    function insert_journal_to_item($CategoryAmount, $rov_no, $akun_no, $total, $desc, $rov_date) {
        foreach ($CategoryAmount as $key => $value) {
            $InventoriAccount = $this->m_account_journal->get_cat_item_account('Inventory', $key, 'IDR');

            if ($InventoriAccount == false) {
                $result['status'] = false;
                $result['message'] = 'Settingan inventory di preferences belum lengkap , silahkan setting ulang';

                echo json_encode($result);
                die;
            } else {
                $data_jurnal_debet = array(
                    'ROvrDate' => date("Y-m-d", strtotime($rov_date)),
                    'ROvrNumber' => $rov_no,
                    'ROvrAccountNumber' => $InventoriAccount->AccountNumber,
                    'ROvrSaldoDebet' => $value,
                    'ROvrSaldoCredit' => 0,
                    'ROvrDesc' => $desc,
                    'ROvrSignStatus' => 0,
                    'LastUser' => $this->session->userdata("username")
                );
                //$this->m_roll_over->insert_jurnal($data_jurnal_debet);
                $this->trans_data['insert_journal_to_item']['data'][] = $data_jurnal_debet;
            }
        }

        $data_jurnal_credit = array(
            'ROvrDate' => date("Y-m-d", strtotime($rov_date)),
            'ROvrNumber' => $rov_no,
            'ROvrAccountNumber' => $akun_no,
            'ROvrSaldoDebet' => 0,
            'ROvrSaldoCredit' => $total,
            'ROvrDesc' => $desc,
            'ROvrSignStatus' => 1,
            'LastUser' => $this->session->userdata("username")
        );

        //$this->m_roll_over->insert_jurnal($data_jurnal_credit);
        $this->trans_data['insert_journal_to_item']['data'][] = $data_jurnal_credit;
    }

    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_id'] = $this->menu_id;
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

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

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

                    $cek_rovr_type_status = $this->m_roll_over->get_roll_over_group($id);
                    $data['detail'] = $this->m_roll_over->get_detail($id, $cek_rovr_type_status->ROvrStatus);

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

    public function update() {

        /* =====================================deklar variabel ================================== */
        $batch_no = $this->input->post('cmb_roll_over');
        $desc = $this->input->post('txt_jobcostdesc');
        $akun_no = $this->input->post('txt_jobcostaccountno');
        $total = $this->input->post('txt_amount_allocated');
        $JCostSubTotal = $this->input->post('txt_totaljobcost_no_koma');

        $rov_date = $this->input->post('txt_rolloverdate');
        $roll_over_no = $this->input->post('txt_rol_over_no');

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

        $Status_Tab = $this->input->post('Status_Tab');

        $detail_id = $this->input->post('detail_id');
        $detail_id = json_decode($detail_id);
        /* ======================================end=============================================== */
        if (count($detail) > 0) {

            /* ===============================update group============================================ */
            $update_group = $this->update_group($roll_over_no, $desc, $total);
            /* ==================================end================================================== */

            /* ===============================update detail=========================================== */
            $update_detail = $this->update_detail($roll_over_no, $Status_Tab, $detail, $total, $akun_no, $desc, $rov_date, $JCostSubTotal);
            /* ================================end==================================================== */

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

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

            $this->trans_data = [];

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

            echo json_encode($result);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('no_count', 0);
            echo json_encode($result);
        }
    }

    function update_group($roll_over_no, $desc, $total) {
        /* ===========================================sunction update gtroup============================= */
        $data = array(
            'ROvrDesc' => $desc,
            'ROvrTotalAmount' => $total,
            'LastUser' => $this->session->userdata("username")
        );

        //$this->m_roll_over->update_app($data, $roll_over_no);
        $this->trans_data['update_group']['data'] = $data;
        $this->trans_data['update_group']['TransNumber'] = $roll_over_no;
        /* ==============================================end================================================ */
    }

    function update_detail($roll_over_no, $Status_Tab, $detail, $total, $akun_no, $desc, $rov_date, $JCostSubTotal) {
        $this->trans_data['status_tab'] = $Status_Tab;
        $sub_total_roll_over = 0;
        foreach ($detail as $row) {
            if ($Status_Tab == 0) {
                /* ==========================deklar variabel======================== */
                $akun_grid = $row->AccountNumber;
                $ROvrDetailID = $row->ROvrDetailID;
                $RowStatus = $row->RowStatus;
                /* ============================end================================== */

                $data_detail = array(
                    'ROvrNumber' => $roll_over_no,
                    'AccountNumber' => $row->AccountNumber,
                    'DepartmentCode' => $row->DepartmentCode,
                    'LastUser' => $this->session->userdata("username")
                );

                /* ================================kondisi jika dia flag grid status 3 delete per grid========================== */
                //$this->m_roll_over->update_detail($data_detail, $ROvrDetailID);
                $this->trans_data['update_detail']['data'][] = $data_detail;
                $this->trans_data['update_detail']['ROvrDetailID'][] = $ROvrDetailID;

                $get_insert_journal = $this->update_journal_to_akun($roll_over_no, $akun_no, $JCostSubTotal, $desc, $akun_grid, $rov_date);
                /* =========================================end================================================================= */
            } else {
                /*
                  Perhitungan allocated value untuk hpp baru di inventori
                 */
                $total_allocated = ($total * $row->Allocated) / 100;

                $ItemCode = $row->ItemCode;
                $ItemUnit = $row->ItemUnit;
                $ItemDesc = $row->ItemDesc;
                $ItemQty = $row->ItemQty;
                $AllocatedValue = $row->Allocated;
                $ItemCategoryID = $row->ItemCategoryID;
                $ROvrDetailID = $row->ROvrDetailID;
                $HPPNew = $row->HPPNew_Los;
                $RowStatus = $row->RowStatus;

                $data_detail = array(
                    'ROvrNumber' => $roll_over_no,
                    'ItemCode' => $ItemCode,
                    'ItemQty' => $ItemQty,
                    'ItemUnit' => $ItemUnit,
                    'ItemDesc' => $ItemDesc,
                    'HPPNew' => $HPPNew,
                    'AllocatedValue' => $AllocatedValue,
                    'LastUser' => $this->session->userdata("username")
                );

                /* ================================kondisi jika dia flag grid status 3 delete per grid========================== */
                //$this->m_roll_over->update_detail($data_detail, $ROvrDetailID);
                $this->trans_data['update_detail']['data'][] = $data_detail;
                $this->trans_data['update_detail']['ROvrDetailID'][] = $ROvrDetailID;

                @$CategoryAmount[$ItemCategoryID] += $total_allocated;
                $sub_total_roll_over = $sub_total_roll_over + $total_allocated;
                /* =========================================end================================================================= */
            }
        }

        if ($Status_Tab == 1) {
            $get_insert_journal = $this->update_journal_to_item($CategoryAmount, $roll_over_no, $akun_no, $total, $desc, $rov_date, $sub_total_roll_over);
        }
    }

    /* ================================================update jurnal to akun============================================ */

    function update_journal_to_akun($rov_no, $akun_no, $JCostSubTotal, $desc, $akun_grid, $rov_date) {

        //$delete_journal 	= $this->m_roll_over->delete_journal($rov_no);
        $this->trans_data['delete_journal_to_akun']['TransNumber'] = $rov_no;

        $data_jurnal_credit = array(
            'ROvrDate' => date("Y-m-d", strtotime($rov_date)),
            'ROvrNumber' => $rov_no,
            'ROvrAccountNumber' => $akun_no,
            'ROvrSaldoDebet' => 0,
            'ROvrSaldoCredit' => $JCostSubTotal,
            'ROvrDesc' => $desc,
            'ROvrSignStatus' => 1,
            'LastUser' => $this->session->userdata("username")
        );

        //$this->m_roll_over->insert_jurnal($data_jurnal_credit);
        $this->trans_data['insert_journal_to_akun']['data'][] = $data_jurnal_credit;

        $data_jurnal_debet = array(
            'ROvrDate' => date("Y-m-d", strtotime($rov_date)),
            'ROvrNumber' => $rov_no,
            'ROvrAccountNumber' => $akun_grid,
            'ROvrSaldoDebet' => $JCostSubTotal,
            'ROvrSaldoCredit' => 0,
            'ROvrDesc' => $desc,
            'ROvrSignStatus' => 0,
            'LastUser' => $this->session->userdata("username")
        );

        //$this->m_roll_over->insert_jurnal($data_jurnal_debet);
        $this->trans_data['insert_journal_to_akun']['data'][] = $data_jurnal_debet;
    }

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

    function update_journal_to_item($CategoryAmount, $roll_over_no, $akun_no, $total, $desc, $rov_date, $sub_total_roll_over) {
        /* =======================suming dari category amount credit======================================================= */
        $get_data_journal = $this->m_roll_over->get_journal_by_number($roll_over_no);
        $this->trans_data['delete_journal_to_item']['total'] = count($get_data_journal);
        foreach ($get_data_journal as $row_jurnal) {
            /* ==========================delete all for jurnal============================================================= */
            //$this->m_roll_over->delete_journal($roll_over_no);
            $this->trans_data['delete_journal_to_item']['TransNumber'] = $roll_over_no;
            /* ===================================end===================================================================== */
        }

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

            if ($InventoriAccount == false) {
                $result['status'] = false;
                $result['message'] = 'Settingan expanse akun belum lengakap, silahkan setting ulang';

                echo json_encode($result);
                die;
            } else {
                $data_jurnal_debet = array(
                    'ROvrDate' => date("Y-m-d", strtotime($rov_date)),
                    'ROvrNumber' => $roll_over_no,
                    'ROvrAccountNumber' => $InventoriAccount->AccountNumber,
                    'ROvrSaldoDebet' => $value,
                    'ROvrSaldoCredit' => 0,
                    'ROvrDesc' => $desc,
                    'ROvrSignStatus' => 0,
                    'LastUser' => $this->session->userdata("username")
                );
                //$this->m_roll_over->insert_jurnal($data_jurnal_debet);
                $this->trans_data['insert_journal_to_item']['data'][] = $data_jurnal_debet;
            }
        }

        $data_jurnal_credit = array(
            'ROvrDate' => date("Y-m-d", strtotime($rov_date)),
            'ROvrNumber' => $roll_over_no,
            'ROvrAccountNumber' => $akun_no,
            'ROvrSaldoDebet' => 0,
            'ROvrSaldoCredit' => $sub_total_roll_over,
            'ROvrDesc' => $desc,
            'ROvrSignStatus' => 1,
            'LastUser' => $this->session->userdata("username")
        );

        //$this->m_roll_over->insert_jurnal($data_jurnal_credit);
        $this->trans_data['insert_journal_to_item']['data'][] = $data_jurnal_credit;
    }

    public function get_all() {
        $sess_company = $this->session->userdata('company');
        $sess_branch = $this->session->userdata('branch');

        $result = $this->m_roll_over->get_all_data($sess_company, $sess_branch);

        foreach ($result as $row) {
            $TransStatus = get_status($row->TransStatus);

            $hasil[] = array(
                'ROvrNumber' => $row->ROvrNumber,
                'ROvrDate' => $row->ROvrDate,
                'JCostNumber' => $row->JCostNumber,
                'ROvrTotalAmount' => $row->ROvrTotalAmount,
                'TransStatus' => $TransStatus,
                'TransStatus_Code' => $row->TransStatus,
                'ROvrStatus' => $row->ROvrStatus
            );
        }

        if (!empty($hasil)) {
            echo json_encode($hasil);
        } else {
            $emptyVar = array();
            echo json_encode($emptyVar);
        }
    }

    function get_edit_grid() {
        $uri4 = $this->uri->segment(4);
        $uri5 = $this->uri->segment(5);
        $uri6 = $this->uri->segment(6);
        $uri7 = $this->uri->segment(7);

        $id = $uri4 . "/" . $uri5 . "/" . $uri6;

        $payment_detail = $this->m_roll_over->get_dg_roll_edit($id, $uri4, $uri7);
        echo json_encode($payment_detail);
    }

    /* ============================pencarian dari job costing waktu pop up======================================= */

    function get_akun_rol_over() {
        $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');
        $AccountNumber = isset($param['txt_AccountNumber']) ? $param['txt_AccountNumber'] : '';
        $AccountName = isset($param['txt_AccountName']) ? $param['txt_AccountName'] : '';
        /* ============================================end============================================================ */

        /* ===========================count data tabel job costing================================== */
        $this->db->where('at_compaccountgl.BranchCode', $this->session->userdata('branch'));
        $this->db->where('at_compaccountgl.CompanyCode', $this->session->userdata('company'));
        $this->db->where_in('at_compaccountgl.TransStatus', array(2));
        $this->db->where_in('am_accounttype.AccountTypeName', array('Expense', 'COGS / COGM (Cost Of Goods Made)', 'Other Expense'));
        $this->db->where('am_accountgl.AccountChild', 1);

        if ($AccountNumber != "") {
            $this->db->like('am_accountgl.AccountNumber', $AccountNumber);
        }
        if ($AccountName != "") {
            $this->db->like('am_accountgl.AccountName', $AccountName);
        }


        $this->db->join('am_accountsubtype', 'am_accountsubtype.AccountSubTypeID = am_accountgl.AccountSubTypeID', 'inner');
        $this->db->join('am_accounttype', 'am_accounttype.AccountTypeID = am_accountsubtype.AccountTypeID', 'inner');
        $this->db->join('at_compaccountgl', 'at_compaccountgl.AccountNumber = am_accountgl.AccountNumber', 'inner');
        $count_data = $this->db->count_all_results('am_accountgl');
        /* ======================================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_roll_over->get_persediaan_akun();
        /* ======================end================================= */

        for ($i = 0; $i <= ($rows - 1); $i++) {
            $hasil[] = array(
                'AccountNumber' => $result[$i]->AccountNumber,
                'AccountName' => $result[$i]->AccountName
            );
        }
        /* ===================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============================================================================== */

    public function department($company) {
        $result = $this->m_roll_over->get_department($company);
        echo json_encode($result);
    }

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

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

    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_roll_over->get_detail_jurnal($id);
        $data['list'] = $this->m_roll_over->get_journal_by_number($id);
        $this->load->view('v_header');
        $this->load->view('roll_over/v_journal_roll_over', $data);
        $this->load->view('v_footer');
    }

    public function approval_mgr() {
        /* ==============deklar variabel======================================= */
        $rol_over_no = $this->input->post('id');
        $Status_Tab = $this->input->post('Status_Tab');
        $BrancCode = $this->session->userdata('branch');
        $JCostNumber = $this->input->post('JCostNumber');
        $data_transstatus = 2;
        $data_transstatus_job_cos = 2;

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

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

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

        /*
          Ket : Status_Tab 0 = To Account, 1 = To Item
         */

        /*
          lock status jika ada no job cos yang sama tetapi salah satu sudah di approve , yg ke dua
          mau di approve maka yg ke dua tidak bisa di approve lagi
         */
        $get_rol_over_group = $this->m_roll_over->get_roll_over_by_jcos_number($JCostNumber);
        foreach ($get_rol_over_group as $row_jcost_number) {
            if ($row_jcost_number->LockStatus == 1) {
                $result['status'] = false;
                $result['message'] = 'Maaf No Job Costing ' . $JCostNumber . ' sudah di approve pada tanggal ' . $row_jcost_number->AppLevel1Date . '';

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

        $this->trans_data['status_tab'] = $Status_Tab;

        if ($Status_Tab == 1) {

            $this->trans_data['detail_item']['total'] = count($detail);

            foreach ($detail as $row) {
                $get_inventori_code = $this->m_job_costing->get_inventori_by_item($row->ItemCode, $BrancCode);

                /* =============================chek jika ada item yang di adjus maka proses dihentikan========================= */
                if (!empty($get_inventori_code->ItemCode)) {
                    if ($get_inventori_code->LockStatus == 1) {
                        $result['status'] = false;
                        $result['message'] = 'Item ' . $get_inventori_code->ItemCode . ' sedang di Adjustment, Silhakan Lihat kembali form anda';

                        echo json_encode($result);
                        die();
                    }
                }
                /* ==============================================end=========================================================== */
                $this->trans_data['detail_item']['inventori_code'][] = !empty($get_inventori_code->ItemCode) ? $get_inventori_code->ItemCode : null;
                if (!empty($get_inventori_code->ItemCode)) {
                    /*
                      Perhitungan allocated value untuk hpp baru di inventori
                     */
                    $total_allocated = ($txt_totaljobcost * $row->Allocated) / 100;

                    /* ===================================akumulasi inventori dan hpp============================================== */
                    $total_inventori = $get_inventori_code->ItemQty + $row->ItemQty;

                    /*
                      Akumulasi dari inventori, item average dikali qty inventori
                     */
                    $item_value_inventori = $get_inventori_code->ItemValue;
                    /* ===================================end================================================== */

                    /*
                      Akumulasi dari grid item price di grid dikali item qty di grid
                     */
                    $item_value_rol_over = $row->HPPNew_Los;
                    /* =================end============================================ */


                    /*
                      hitung hpp baru untuk di inventori dan value baru
                     */
                    $item_average = ($item_value_inventori + $item_value_rol_over) / $total_inventori;
                    $item_value_new = ($item_average * $total_inventori);
                    /* ===========================================end====================================== */

                    $data_inventori = array(
                        'ItemQty' => $total_inventori,
                        'ItemValue' => $item_value_new,
                        'ItemAverage' => $item_average,
                        'LastUser' => $this->session->userdata("username")
                            //'ItemBooks' 	=> $total_qty_book
                    );

                    //$result_approve = $this->m_inventories->update_average($data_inventori, $row->ItemCode, $BrancCode);
                    $this->trans_data['update_average']['data'][] = $data_inventori;
                    $this->trans_data['update_average']['ItemCode'][] = $row->ItemCode;
                    $this->trans_data['update_average']['branch'][] = $BrancCode;
                } else {
                    $data_inventori = array(
                        'BranchCode' => $BrancCode,
                        'ItemCode' => $row->ItemCode,
                        'ItemQty' => $row->ItemQty,
                        'ItemValue' => $row->HPPNew_Los,
                        'ItemAverage' => $row->HPPNew_Los / $row->ItemQty,
                        'LastUser' => $this->session->userdata("username")
                    );

                    //$result_approve = $this->m_inventories->insert($data_inventori);
                    $this->trans_data['insert']['data'][] = $data_inventori;
                }

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

        //$this->m_roll_over->update_app($data, $rol_over_no);
        $this->trans_data['update_app']['data'] = $data;
        $this->trans_data['update_app']['TransNumber'] = $rol_over_no;

        /* ================update trans status di roll over=================================== */
        //$this->m_roll_over->set_trans_status($rol_over_no, $data_transstatus);
        $this->trans_data['set_trans_status']['data'] = $data_transstatus;
        $this->trans_data['set_trans_status']['TransNumber'] = $rol_over_no;
        /* ========================end======================================================= */

        /* ===================update trans status job costing jadi 2========================== */
        //$this->m_roll_over->set_trans_status_job_cos($JCostNumber, $data_transstatus_job_cos);
        $this->trans_data['set_trans_status_job_cos']['data'] = $data_transstatus_job_cos;
        $this->trans_data['set_trans_status_job_cos']['TransNumber'] = $JCostNumber;
        /* ===========================end===================================================== */

        $check_jobcosting = $this->m_roll_over->check_status_jobcosting($JCostNumber);

        if ($check_jobcosting) {

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

            $this->trans_data = [];

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

            echo json_encode($result);
        } else {
            $result['status'] = false;
            $result['message'] = 'JobCosting Status belum di approved';
            echo json_encode($result);
        }
    }

    public function reverse_data_detail() {

        /* ===================================Deklarasi Variabel untuk proses insert atau update=================================== */
        $no_rollover = $this->input->post('id');
        $no_jobcosting = $this->input->post('cmb_roll_over');
		
        $Status_Tab = $this->input->post('Status_Tab');
        $branch = $this->session->userdata('branch');

        $date_transaction 	= check_end_periode($no_rollover);

        $data = array(
            'TransStatus' => 4,
            'AppLevel1Status' => 0,
            'AppFinished' => 0,
            'LockStatus' => 0,
            'LastUser' => $this->session->userdata("username")
        );

        $data_jobcosting = array("TransStatus" => 1);

        /* ============================== check period end ======================================== */
        $get_end_periode = $this->m_custom->check_period_end_custom($date_transaction);

        if ($get_end_periode == false) {

            $this->trans_data['status_tab'] = $Status_Tab;

            if ($Status_Tab == 0) {
                /* =================== reverse Job Costing ============================= */
                $this->trans_data['reverse_jobcosting']['data'] = $data_jobcosting;
                $this->trans_data['reverse_jobcosting']['TransNumber'] = $no_jobcosting;
                /* =================== end reverse job costing ======================== */

                /* =================== reverse roll over ============================= */
                $this->trans_data['reverse_rollover']['data'] = $data;
                $this->trans_data['reverse_rollover']['TransNumber'] = $no_rollover;
                /* =================== end reverse roll over ========================= */
            } else {

                /* ================ recalculate HPP =========================== */
                $this->reverse_inventori($no_rollover, $branch);

                /* =================== reverse Job Costing ============================= */
                $this->trans_data['reverse_jobcosting']['data'] = $data_jobcosting;
                $this->trans_data['reverse_jobcosting']['TransNumber'] = $no_jobcosting;
                /* =================== end reverse job costing ======================== */

                /* =================== reverse roll over ============================= */
                $this->trans_data['reverse_rollover']['data'] = $data;
                $this->trans_data['reverse_rollover']['TransNumber'] = $no_rollover;
                /* =================== end reverse roll over ========================= */
            }

            $result_return = $this->m_roll_over->reverse_transsaction($this->trans_data);

            $this->trans_data = [];

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

            echo json_encode($result);
        } else {

            $result['status'] = false;
            $result['message'] = get_notification('reverse_in_period', 0);
            echo json_encode($result);
        }
    }

    function reverse_inventori($no_rollover, $branch) {

        $detail = $this->m_roll_over->get_rollover_detail($no_rollover, $branch);

        $this->trans_data['update_inventori']['total'] = count($detail);

        foreach ($detail as $row) {

            $ItemCode = $row->ItemCode;
            $QtyRO = doubleval($row->ItemQty);
            $ValueRO = doubleval($row->HPPNew);
            $ItemAmount = $ValueRO / $QtyRO;

            /* ================================= check lock unlock inventories ============================ */
            $LockStatus = $this->m_roll_over->check_lock_status_inventories($ItemCode, $branch, 0);

            $this->trans_data['update_inventori']['LockStatus'][] = $LockStatus;
            /* ================== if LockStatus true -> Item inventory unlock ====================== */
            if ($LockStatus) {

                $get_inventori = $this->m_roll_over->get_data_inventories($ItemCode, $branch);

                $Average = doubleval($get_inventori->ItemAverage);
                $Qtyinv = doubleval($get_inventori->ItemQty);
                $Bookinv = doubleval($get_inventori->ItemBooks);

                $TotalQTY = $Qtyinv - $QtyRO;
                if (($TotalQTY == 0)) {
					$HPP = 0;
				} else {
					$HPP = (($Qtyinv * $Average) - ($ItemAmount)) / $TotalQTY;
				}
                $ItemValue = $HPP * $TotalQTY;
				$data_inventori = array('ItemQty' => $TotalQTY, 'ItemAverage' => $HPP, 'ItemValue' => $ItemValue);

                $this->trans_data['update_inventori']['data'][] = $data_inventori;
                $this->trans_data['update_inventori']['ItemCode'][] = $ItemCode;
                $this->trans_data['update_inventori']['branch'][] = $branch;
            }
        }
    }

    public function get_no_job_cos() {
        $result = $this->m_roll_over->get_no_job_cos($this->session->userdata('branch'));

        echo json_encode($result);
    }

    public function suspend_data() {
        /* =================================deklar variabel================== */
        $id = $this->input->post('id');
        $hasil = 0;

        //$get_rol_over_group = $this->m_roll_over->get_roll_over_group($id);
        //$get_rol_over_detail = $this->m_roll_over->get_roll_over_detail($id);

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

        /*
          =============================perhitungan item book==================
         */
        //if($get_rol_over_group->ROvrStatus == 1){
//			foreach($get_rol_over_detail as $row){
//				$get_inventori_code = $this->m_job_costing->get_inventori_by_item($row->ItemCode, $get_rol_over_group->BranchCode);
//				/*===================================akumulasi inventori dan hpp==============================================*/
//				$total_qty_book 	= $row->ItemQty - $get_inventori_code->ItemBooks;
//				/*===========================================end==============================================================*/
//				
//				$data_inventori = array(
//					'ItemBooks' 	=> $total_qty_book
//				);
//				
//				$result_approve = $this->m_inventories->update_average($data_inventori, $row->ItemCode, $get_rol_over_group->BranchCode);
//			}
//		}
        /* =====================================end=================================================================== */

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

        //$hasil = $this->m_roll_over->suspend($data, $id);
        $this->trans_data['suspend_data']['data'] = $data;
        $this->trans_data['suspend_data']['TransNumber'] = $id;

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

        $this->trans_data = [];

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

        echo json_encode($result);
    }

    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_roll_over->get_detail_print($id);
            $data['list'] = $this->m_roll_over->get_detail_item_print($data['detail']->ROvrNumber);
            // echo $this->db->last_query();   
            $this->load->view('v_header');
            $this->load->view('roll_over/v_print_detail_roll_over', $data);
            $this->load->view('v_footer');
        }
    }

    function to_print_detail_akun() {
        $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_akun/', "", $this->uri->uri_string());

        if ($id != "") {
            $data['detail'] = $this->m_roll_over->get_detail_print($id);
            $data['list'] = $this->m_roll_over->get_detail_item_print_akun($data['detail']->ROvrNumber);

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

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

//        $data['list'] = $this->m_roll_over->get_all_print_list($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_roll_over->get_all_to_print($data_filter);
//        echo"list = ".  json_encode($data['list']);
        $this->load->view('v_header');
        $this->load->view('roll_over/v_print_roll_over', $data);
        $this->load->view('v_footer');
    }

    /* ============================pencarian dari job costing waktu pop up======================================= */

    function search_roll_over() {
        $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================================== */
        $this->db->where_in('am_item.TransStatus', array(0, 1));
        $this->db->where('am_item.ItemTypeID !=', 1);

        if ($ItemCategoryID != "") {
            if ($ItemCategoryID == "All") {
                
            } else {
                $this->db->like('am_item.ItemCategoryID', $ItemCategoryID);
            }
        }
        if ($ItemCode != "") {
            $this->db->like('am_item.ItemCode', $ItemCode);
        }
        if ($ItemDesc != "") {
            $this->db->like('am_item.ItemDesc', $ItemDesc);
        }

        $this->db->join('am_item', 'am_item.ItemCategoryID = am_itemcategory.ItemCategoryID', 'inner');
        $count_data = $this->db->count_all_results('am_itemcategory');
        /* ======================================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_roll_over->search_roll_over();

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