<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* 	
 * 	Author 	: Fachri
 * 	Tanggal : 06-10-2014	
 * 	Revisi 	: 
 */

class Job_costing extends CI_Controller {

    public $menu_id = 123;
    public $menu_model = 'm_job_costing';
    public $name = "Job Costing";
    public $trans_data = array();

    public function __construct() {
        parent::__construct();
        $this->load->model('m_job_costing');
        $this->load->model('m_inventories');
		$this->load->model('custom/m_custom');
        $this->load->helper('message_helper');
        $this->load->helper('status');
        $this->load->helper('custom_string_helper');
		$this->load->model('login/m_login');
		$this->load->model('m_account_journal');
	
		$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('job_costing/v_job_costing', $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('JCostNumber', $Number);
        } //change
        if ($Desc != "") {
            $this->db->like('JCostDesc', $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_jobcosting.JCostDate >=', date("Y-m-d", strtotime($DateFrom))); //change
                $this->db->where('at_jobcosting.JCostDate <=', date("Y-m-d", strtotime($DateTo))); //change
            }
        }
        /* ==========================end================================================================= */

        $count_data = $this->db->count_all_results('at_jobcosting'); //change
        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_job_costing->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]->JCostNumber,
                'JCostDate' => $result[$i]->JCostDate,
                'JCostDesc' => $result[$i]->JCostDesc,
                'JCostSubTotal' => $result[$i]->JCostSubTotal,
                //'ItemAmount' 		=>	$row->Total,
                'TransStatus' => $TransStatus,
                'CreatedBy' => $result[$i]->CreatedBy,
                'TransStatus_Code' => $result[$i]->TransStatus,
				'DepartmentName' => $result[$i]->DepartmentName,
                '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 get_persedian_bahan_baku() {
        $CompanyCode = $this->session->userdata('company');
        $BranchCode = $this->session->userdata('branch');
        $get_persediaan_dalam_proses = $this->m_job_costing->get_persedian_bahan_baku($CompanyCode, $BranchCode);
        echo"$get_persediaan_dalam_proses";
    }

    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_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($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);
                    $data['date_now'] = date('d-m-Y');
                    //$data['pay_number']  			= $this->m_payment->create_pay_number(date('d-m-Y'));
                    $this->load->view('v_header');
                    $this->load->view('job_costing/v_add_job_costing', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    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_menu->get_menulink($this->menu_id);


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

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

                    $data['detail'] = $this->m_job_costing->get_edit_jobcost($jcos_number, $BranchCode);
                    $data['j_cost_detail'] = $this->m_job_costing->get_edit_jobcost_detail($jcos_number, $BranchCode);

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

    function detail_jobcost($payment_number) {
        /* ================================ambil uri segmen di grid saat edit untuk menampilkan item====================== */
        $uri4 = $this->uri->segment(4);
        $uri5 = $this->uri->segment(5);
        $uri6 = $this->uri->segment(6);
        $id = $uri4 . '/' . $uri5 . '/' . $uri6;
        /* ===============================end============================================================================= */

        $detail = $this->m_job_costing->get_edit_jobcost_detail($id, $uri4);

        echo json_encode($detail);
    }

    public function insert() {


        /* =======================deklar variabel saat insert========================= */
        $cmb_jcost = $this->input->post('cmb_jcost');
        $txt_date = date("Y-m-d", strtotime($this->input->post('txt_date')));

        /* =====================================jcos number========================================== */
        $txt_no = $this->m_job_costing->create_jc_number($txt_date);
        /* ========================================================================================== */

        $cmb_department = $this->input->post('cmb_department');
        $sub_total = $this->input->post('sub_total_koma');
        $detail = $this->input->post('detail');


        $result_insert = 0;
        $kategori_id = "";
        $total_amount = 0;
        $detail = json_decode($detail);
        /* ======================================================================= */

        if (count($detail) > 0) {
            /* ==================function insert group================================================ */
            $insert_group = $this->insert_group($txt_no, $cmb_jcost, $cmb_department, $sub_total, $txt_date);
            /* ===========================end========================================================= */

            /* ==================function insert detail================================================ */
            $insert_detail = $this->insert_detail($detail, $txt_no, $cmb_jcost, $cmb_department, $sub_total, $txt_date);
            /* =========================end=========================================================== */

            $result_return = $this->m_job_costing->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'] = get_notification('no_count', 0);
            echo json_encode($result);
        }
    }

    /* ======================================insert grroup=============================================================== */

    function insert_group($txt_no, $cmb_jcost, $cmb_department, $sub_total, $txt_date) {

        $data = array(
            'BranchCode' => $this->session->userdata('branch'),
            'JCostNumber' => $txt_no,
            'JCostDate' => date("Y-m-d", strtotime($txt_date)),
            'JCostAccount' => $cmb_jcost,
            'JCostDesc' => $this->input->post('txa_description'),
            'DepartmentCode' => $cmb_department,
            'JCostSubTotal' => $sub_total,
            'TransStatus' => 4,
            'CreatedBy' => $this->session->userdata("username"),
            'CreatedAt' => date('Y-m-d'),
            'LastUser' => $this->session->userdata("username")
        );

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

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

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

    function insert_detail($detail, $txt_no, $cmb_jcost, $cmb_department, $sub_total, $txt_date) {
        if ($detail) {
            foreach ($detail as $row) {
                $sess_branch = $this->session->userdata('branch');
                $item_code = $row->ItemCode;
                $ItemKategori = $row->ItemKategori;
                $Amount_item = $row->Amount_item;
				$ItemType = $row->ItemType;

                /* ================ Added By Prawira Tgl 18 September 2015 ================================
                  Variable Convention: Inventory, Amount, ItemCategory, ItemCode, ItemAmount, AmountItem
                  Function Name "get_inventori"" is Wrong. It Should be GetItemHpp($sess_branch, $item_code);
                  Variable $get_invent should be $item_hpp_inventory
                  If Fix, put a note in this commment, fixed by $Name, $Date
                  =========================================================================================== */
                $get_invent = $this->m_job_costing->get_inventori($sess_branch, $item_code);
                
				if($ItemType == 0){
					$Item_amounth = $row->Qty * $get_invent;
				}
				else{
					$Item_amounth = $Amount_item;
				}
				
                //insert to detail -------------------------------------------------

                /* ================================item book inventories=============================== */
                $update_item_book = $this->inventori_book($row->ItemCode, $row->Qty, "Insert");
                /* ==================================end=============================================== */

                $date = date("Y-m-d", strtotime($row->DateJob));
                $detail_data = array(
                    'JCostNumber' => $txt_no,
                    'JcostDetailDate' => date("Y-m-d", strtotime($row->DateJob)),
                    'ItemCode' => $row->ItemCode,
                    'ItemQty' => $row->Qty,
                    'ItemUnit' => $row->ItemUnit,
                    'JCostDetailDesc' => $row->Description,
                    'ItemAmount' 	=> $Item_amounth,
					'ItemHPP' 		=> $row->ItemAverage_Real,
					'ItemType' 		=> $row->ItemType,
					'ItemStatus' 	 => $row->ItemStatus,
					'ItemCategoryID' => $row->ItemKategori,
                    'LastUser' => $this->session->userdata("username")
                );
                //$this->m_job_costing->insert_fromgrid($detail_data);

                $this->trans_data['insert_detail']['data'][] = $detail_data;

                @$CategoryAmount[$row->ItemKategori] += ($row->ItemAverage_Real * $row->Qty);
				@$CategoryType[$row->ItemKategori] 	 = $row->ItemType;
            }
        }
        /* ===========================function get journal debet credit================================ */
        $get_journal_debet_credit = $this->insert_journal_debet_credit($CategoryType, $CategoryAmount, $txt_no, $txt_date, $cmb_jcost, $sub_total);
        /* ==========================end=============================================================== */
    }

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

    function insert_journal_debet_credit($CategoryType, $CategoryAmount, $txt_no, $txt_date, $cmb_jcost, $sub_total) {
        /* =======================suming dari category amount journal credit======================================================= */
        foreach ($CategoryAmount as $key => $value) {
            if($CategoryType[$key] == 0){
				$get_coa_persedian_brang = $this->m_job_costing->get_item_account('Inventory', $key);
				if($get_coa_persedian_brang == false) {
					$result['status'] = false;
					$result['message'] = 'Settingan Preference untuk Item Category Belum Lengkap, Silahkan Setting Ulang';
	
					echo json_encode($result);
					die;
				}
			}
			else if($CategoryType[$key] == 1){
				$get_coa_persedian_brang = $this->m_account_journal->get_sys_service_account('Expense', 'IDR', $key); // Jasa / Service
				if($get_coa_persedian_brang == false) {
					$result['status'] = false;
					$result['message'] = 'Settingan Preference untuk Expense Belum Lengkap, Silahkan Setting Ulang untuk Expense Account';
	
					echo json_encode($result);
					die;
				}
			}
			
            $data_credit = array(
				'JCostNumber' => $txt_no,
				'JCostDate' => $txt_date,
				'JCostAccountNumber' => $get_coa_persedian_brang->AccountNumber,
				'JCostSaldoDebet' => 0,
				'JCostSaldoCredit' => $value,
				'JCostSignStatus' => 1,
				'LastUser' => $this->session->userdata("username")
			);
			//$this->m_job_costing->insert_tojournal_credit($data_credit);
			$this->trans_data['insert_journal']['data'][] = $data_credit;
        }
        /* ==================================================end======================================================== */

        /* ===================================data debet jobcosting===================================================== */
        $data_debet = array(
            'JCostNumber' => $txt_no,
            'JCostDate' => $txt_date,
            'JCostAccountNumber' => $cmb_jcost,
            'JCostSaldoDebet' => $sub_total,
            'JCostSaldoCredit' => 0,
            'JCostSignStatus' => 0,
            'LastUser' => $this->session->userdata("username")
        );
        //$this->m_job_costing->insert_tojournal_debet($data_debet);
        $this->trans_data['insert_journal']['data'][] = $data_debet;
        /* ====================================end======================================================================= */
    }

    function inventori_book($ItemCode, $ItemQty, $action) {
        /* ================================item book inventories=============================== */
        if ($action == "Insert") {
            $item_booked = $this->m_inventories->get_item_booked($ItemCode);
            $new_item_books = $item_booked + $ItemQty;
        }
        //$this->m_inventories->update(array('ItemBooks'=>$new_item_books), $ItemCode);

        $this->trans_data['inventori_book']['ItemBooks'][] = array('ItemBooks' => $new_item_books);
        $this->trans_data['inventori_book']['ItemCode'][] = $ItemCode;

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

    function inventori_book_minus($ItemCode, $ItemQty) {
        /* ================================item book inventories=============================== */
        $item_booked = $this->m_inventories->get_item_booked($ItemCode);
        $new_item_books = $item_booked - $ItemQty;

        //$this->m_inventories->update(array('ItemBooks'=>$new_item_books), $ItemCode);
        $this->trans_data['inventori_book']['ItemBooks'][] = array('ItemBooks' => $new_item_books);
        $this->trans_data['inventori_book']['ItemCode'][] = $ItemCode;
        /* ==================================end=============================================== */
    }

    public function update() {
        /* =================================declar variabel======================================================== */
        $cmb_jcost = $this->input->post('cmb_jcost');
        $txt_no = $this->input->post('txt_no');
        $txt_date = date("Y-m-d", strtotime($this->input->post('txt_date')));
        $txt_no_hidden = $this->input->post('txt_no_hidden');
        $cmb_department = $this->input->post('cmb_departement');
        $txt_item_code = $this->input->post('item_code');
        $txa_desc = $this->input->post('txa_description');
        $detail = $this->input->post('detail');
        $sub_total = $this->input->post('sub_total_koma');
        $cmb_jcost = $this->input->post('cmb_jcost');
        $sess_branch = $this->session->userdata('branch');
        $result_update = 0;
        $kategori_id = "";
        $detail = json_decode($detail);

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

        /* ============================count jika data di grid nelum di isi maka akan menampilkan error function di UI=================== */
        if (count($detail) > 0) {

            /* ===========================update group=================================================================== */
            $update_group = $this->update_group($txt_no_hidden, $cmb_jcost, $txt_date, $cmb_department, $txa_desc, $sub_total, $txt_no);
            /* =============================end========================================================================== */

            /* ===========================update detail=================================================================== */
            $update_detail = $this->update_detail($detail, $txt_no_hidden, $sess_branch, $txt_no, $cmb_jcost, $txt_date, $sub_total);
            /* =============================end========================================================================== */

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

                    $this->inventori_book_minus($detail_item[1], $detail_item[2]);
                }
            }
            /* =============================end========================================================================== */

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

            $this->trans_data = [];

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

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

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

    function update_group($txt_no_hidden, $cmb_jcost, $txt_date, $cmb_department, $txa_desc, $sub_total, $txt_no) {
        $data = array(
            'JCostDate' => date("Y-m-d", strtotime($txt_date)),
            'JCostNumber' => $txt_no_hidden,
            'JCostAccount' => $cmb_jcost,
            'DepartmentCode' => $cmb_department,
            'JCostDesc' => $txa_desc,
            'JCostSubTotal' => $sub_total,
            'LastEdited' => $this->session->userdata("username")
        );

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

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

    /* ==========================update detail============================================================== */

    function update_detail($detail, $txt_no_hidden, $sess_branch, $txt_no, $cmb_jcost, $txt_date, $sub_total) {
        $sub_total_job_cost = 0;
        if ($detail) {
            foreach ($detail as $row) {
                /* ============================deklar variabel dari grid================ */
                $item_code = $row->ItemCode;
                $JCostDetailID = $row->JCostDetailID;
                $ItemKategori = $row->ItemCategoryID;
                $Amount_item = $row->ItemAmount;

				$ItemType = $row->ItemType;

                /* ================ Added By Prawira Tgl 18 September 2015 ================================
                  Variable Convention: Inventory, Amount, ItemCategory, ItemCode, ItemAmount, AmountItem
                  Function Name "get_inventori"" is Wrong. It Should be GetItemHpp($sess_branch, $item_code);
                  Variable $get_invent should be $item_hpp_inventory
                  If Fix, put a note in this commment, fixed by $Name, $Date
                  =========================================================================================== */
                $get_invent = $this->m_job_costing->get_inventori($sess_branch, $item_code);
               	if($ItemType == 0){
					$Item_amounth = $row->ItemQty * $get_invent;
				}
				else{
					$Item_amounth = $Amount_item;
				}
				
                $RowStatus = $row->RowStatus;

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

                /* ================================item book inventories=============================== */
                //$update_item_book 		= $this->inventori_book($row->ItemCode, $row->ItemQty, "Update");

                $item_booked = $this->m_inventories->get_item_booked($item_code);
                $new_item_books = ($item_booked - $row->OldQty) + $row->ItemQty;

                //$this->m_inventories->update(array('ItemBooks'=>$new_item_books), $item_code);
                $this->trans_data['inventori_book']['ItemBooks'][] = array('ItemBooks' => $new_item_books);
                $this->trans_data['inventori_book']['ItemCode'][] = $item_code;
                /* ==================================end=============================================== */

                //insert to detail -------------------------------------------------
                $date = date("Y-m-d", strtotime($row->JcostDetailDate));
                $detail_data = array(
                    'JCostNumber' => $txt_no_hidden,
                    'JcostDetailDate' => date("Y-m-d", strtotime($row->JcostDetailDate)),
                    'ItemCode' => $row->ItemCode,
                    'ItemQty' => $row->ItemQty,
                    'ItemUnit' => $row->ItemUnit,
                    'JCostDetailDesc' => $row->JCostDetailDesc,
					'ItemHPP' => $row->ItemAverage_Real,
                    'ItemAmount' => $Item_amounth,
                    'LastEdited' => $this->session->userdata("username")
                );
                /* ================================kondisi jika dia flag grid status 3 delete per grid========================== */
                //$this->m_job_costing->update_detail($detail_data, $JCostDetailID);
                $this->trans_data['update_detail']['data'][] = $detail_data;
                $this->trans_data['update_detail']['JCostDetailID'][] = $JCostDetailID;

                @$CategoryAmount[$row->ItemCategoryID] += ($row->ItemAverage_Real * $row->ItemQty);
				@$CategoryType[$row->ItemCategoryID] 	 = $row->ItemType;
				
                $sub_total_job_cost = $sub_total_job_cost + $row->ItemAmount;
                /* =========================================end================================================================= */
            }
        }
        $get_update_journal_debet_credit = $this->update_journal_debet_credit($CategoryType, $CategoryAmount, $txt_no, $cmb_jcost, $txt_date, $sub_total_job_cost);
    }

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

    /* ===============================update journal======================================================= */

    function update_journal_debet_credit($CategoryType, $CategoryAmount, $txt_no, $cmb_jcost, $txt_date, $sub_total_job_cost) {
        /* =======================suming dari category amount credit======================================================= */
        $get_data_journal = $this->m_job_costing->get_journal_by_number($txt_no);

        $this->trans_data['delete_journal']['total'] = count($get_data_journal);
        foreach ($get_data_journal as $row_jurnal) {
            /* ==========================delete all for jurnal============================================================= */
            //$this->m_job_costing->delete_jurnal($txt_no);
            $this->trans_data['delete_journal']['TransNumber'] = $txt_no;
            /* ===================================end===================================================================== */
        }

        foreach ($CategoryAmount as $key => $value) {
            
			if($CategoryType[$key] == 0){
				$get_coa_persedian_brang = $this->m_job_costing->get_item_account('Inventory', $key);
				if($get_coa_persedian_brang == false) {
					$result['status'] = false;
					$result['message'] = 'Settingan Preference untuk Item Category Belum Lengkap, Silahkan Setting Ulang';
	
					echo json_encode($result);
					die;
				}
			}
			else if($CategoryType[$key] == 1){
				$get_coa_persedian_brang = $this->m_account_journal->get_sys_service_account('Expense', 'IDR', $key); // Jasa / Service
				if($get_coa_persedian_brang == false) {
					$result['status'] = false;
					$result['message'] = 'Settingan Preference untuk Expense Belum Lengkap, Silahkan Setting Ulang untuk Expense Account';
	
					echo json_encode($result);
					die;
				}
			}
			
			$data_credit = array(
				'JCostNumber' => $txt_no,
				'JCostDate' => $txt_date,
				'JCostAccountNumber' => $get_coa_persedian_brang->AccountNumber,
				'JCostSaldoDebet' => 0,
				'JCostSaldoCredit' => $value,
				'JCostSignStatus' => 1,
				'LastUser' => $this->session->userdata("username")
			);
			//$this->m_job_costing->insert_tojournal_credit($data_credit);
			$this->trans_data['insert_journal']['data'][] = $data_credit;
            
        }
        /* ==================================================end======================================================== */

        /* ===================================data debet jobcosting===================================================== */
        $data_debet = array(
            'JCostNumber' => $txt_no,
            'JCostDate' => $txt_date,
            'JCostAccountNumber' => $cmb_jcost,
            'JCostSaldoDebet' => $sub_total_job_cost,
            'JCostSaldoCredit' => 0,
            'JCostSignStatus' => 0,
            'LastUser' => $this->session->userdata("username")
        );
        //$this->m_job_costing->insert_tojournal_debet($data_debet);
        $this->trans_data['insert_journal']['data'][] = $data_debet;
        /* ====================================end======================================================================= */
    }

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

    /* function delete sudah tidak dipakai lagi. nanti harus di delete. TGL 18 September 2015 */

    // Function commented by Prawira //
    public function delete() {
        
    }

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

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

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


        /*
          Update item book
         */

        $get_detail_jobcos = $this->m_job_costing->get_edit_jobcost_detail($id, $this->session->userdata('branch'));

        $this->trans_data['inventori_book']['total'] = count($get_detail_jobcos);
        foreach ($get_detail_jobcos as $row) {
            $this->inventori_book_minus($row->ItemCode, $row->ItemQty);
        }

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

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

    public function approval_mgr() {
        /* ======================================declar variabel===================================== */
        $id = $this->input->post('id');
        $branch_hidden = $this->input->post('branch_hidden');
        $cmb_jcost = $this->input->post('cmb_jcost');
        $txt_no = $this->input->post('txt_no');
        $txt_date = date("Y-m-d", strtotime($this->input->post('txt_date')));
        $txt_no_hidden = $this->input->post('txt_no_hidden');
        $cmb_department = $this->input->post('cmb_departement');
        $txt_item_code = $this->input->post('item_code');
        $txa_desc = $this->input->post('txa_description');
        $detail = $this->input->post('detail');
        $sub_total = $this->input->post('sub_total_koma');
        $cmb_jcost = $this->input->post('cmb_jcost');
        $sess_branch = $this->session->userdata('branch');

        $detail = $this->input->post('detail');
        $detail = json_decode($detail);
        $trans_status = 1;
        $result_approv_mgr = 0;
        /* =======================================end============================================== */

        /* =============================chek jika ada item yang di adjus maka proses dihentikan========================= */
        foreach ($detail as $row_data) {
            $get_inventori_code = $this->m_job_costing->get_inventori_by_item($row_data->ItemCode, $branch_hidden);
			
			if($row_data->ItemType == 0){
				if (!empty($get_inventori_code->ItemCode)) {
					if ($get_inventori_code->LockStatus == 1) {
						$result['status'] = false;
						$result['message'] = "Terdapat Item Yang Sedang Di Adjust, Mohon Kembali Apabila Item Sudah Tidak Dalam Adjustment";
	
						echo json_encode($result);
						die();
					}
				}
			
			
				if($row_data->ItemQty > $get_inventori_code->ItemQty){
					$result['status'] 		= FALSE;
					$result['message']  	= "Transaksi gagal, Item Qty Job Costing melebihi Item Qty Di Inventory untuk Item ". $row_data->JCostDetailDesc ." silahkan lihat kembali Qty Inventory";
					
					echo json_encode($result);
					die();
				}
				if ($get_inventori_code->ItemQty <= 0) {
					$result['status'] = false;
					$result['message'] = "Gagal di approve Item ".$get_inventori_code->ItemCode." Qty di Inventory tidak mencukupi";
	
					echo json_encode($result);
					die();
				}
			}
        }
        /* =====================================end=================================================================== */

        /* ===================================akumulasi inventori dan hpp============================================== */
        $get_detail_jobcos = $this->m_job_costing->get_edit_jobcost_detail($id, $branch_hidden);

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

        foreach ($get_detail_jobcos as $row_detail) {
			if($row_detail->ItemType == 0){
				$get_inventori_item = $this->m_job_costing->get_inventori_by_item($row_detail->ItemCode, $branch_hidden);
				
				$total_book = $get_inventori_item->ItemBooks - $row_detail->ItemQty;
				$total_qty = $get_inventori_item->ItemQty - $row_detail->ItemQty;
				$item_value_new = $get_inventori_item->ItemAverage * $total_qty;
	
				$data_inventori = array(
					'ItemQty' => $total_qty,
					'ItemBooks' => $total_book,
					'ItemValue' => $item_value_new
				);
				//$this->m_job_costing->update_inventori($data_inventori, $row_detail->ItemCode, $branch_hidden);
				$this->trans_data['update_inventori']['data'][] = $data_inventori;
				$this->trans_data['update_inventori']['ItemCode'][] = $row_detail->ItemCode;
				$this->trans_data['update_inventori']['branch'][] = $branch_hidden;
			}
        }
        /* =================================================end=========================================================== */

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

        /* =======================================update app level code dan status, trans status======================== */

        /* ===========================update detail=================================================================== */
        $update_detail = $this->update_detail($detail, $txt_no_hidden, $sess_branch, $txt_no, $cmb_jcost, $txt_date, $sub_total);
        /* =============================end========================================================================== */

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

        //$this->m_job_costing->set_trans_status($id, $trans_status);
        $this->trans_data['trans_status']['TransNumber'] = $id;
        $this->trans_data['trans_status']['data'] = $trans_status;
        /* ============================================end============================================================= */

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

        $this->trans_data = [];


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

        echo json_encode($result);
    }

    public function reversed_data() {
        /* ===================================Deklarasi Variabel untuk proses insert atau update=================================== */
        $no_jobcosting = $this->input->post('id');
        $branch = $this->session->userdata('branch');

        $date_transaction 	= check_end_periode($no_jobcosting);

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

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

        if ($get_end_periode == false) {

            $check_rollover = $this->m_job_costing->check_rollover_transaction($no_jobcosting);

            if ($check_rollover) {
                $no_rollover = $this->m_job_costing->get_no_rollover($no_jobcosting);

                $result['status'] = false;
                $result['message'] = "Transaksi gagal di reverse, karena transaksi job costing ini sudah dibuat roll over dengan no transaksi roll over, ". $no_rollover->ROvrNumber;
                echo json_encode($result);
				
            } else {

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

                $this->trans_data['reverse_data']['data'] = $data;
                $this->trans_data['reverse_data']['TransNumber'] = $no_jobcosting;

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

                $this->trans_data = [];

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

                echo json_encode($result);
            }
        } else {

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

    function reverse_inventori($no_jobcosting, $branch) {

        $detail = $this->m_job_costing->get_edit_jobcost_detail($no_jobcosting, $branch);

        foreach ($detail as $row) {

            $ItemCode = $row->ItemCode;
            $QtyJC = doubleval($row->ItemQty);
            $AmountJC = doubleval($row->ItemAmount);

            /* ================================= check lock unlock inventories ============================ */
            $LockStatus = $this->m_job_costing->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_job_costing->get_data_inventories($ItemCode, $branch);
                $Average = doubleval($get_inventori->ItemAverage);
                $Qtyinv = doubleval($get_inventori->ItemQty);
                $Bookinv = doubleval($get_inventori->ItemBooks);
				
                $TotalQTY = $QtyJC + $Qtyinv;
                $HPP = (($Qtyinv * $Average) + ($AmountJC)) / $TotalQTY;
                $ItemValue = $HPP * $TotalQTY;
                $ItemBooks = $Bookinv + $QtyJC;

                $data_inventori = array(
					'ItemQty' => $TotalQTY, 
					'ItemAverage' => $HPP, 
					'ItemValue' => $ItemValue, 
					'ItemBooks' => $ItemBooks
				);

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

    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_job_costing->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_job_costing->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('job_costing/v_print_job_costing', $data);
        $this->load->view('v_footer');
    }

    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_job_costing->get_detail($id);
        $data['list'] = $this->m_job_costing->get_journal_by_number($id);

        $this->load->view('v_header');
        $this->load->view('job_costing/v_journal_job_cos', $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_job_costing->get_detail_print($id);
            $data['list'] = $this->m_job_costing->get_detail_item_print($data['detail']->JCostNumber);
            // echo $this->db->last_query();   
            $this->load->view('v_header');
            $this->load->view('job_costing/v_print_detail_job_costing', $data);
            $this->load->view('v_footer');
        }
    }

    // mungkin tidak dipakai. harus di audit
    // TGL 18 September 2015 By Prawira. Apabila ingin di delete, mohon berikan comment
    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 persedian_barang_dalam_proses() {
        $data = $this->m_job_costing->get_brg_dlm_proses();
        echo json_encode($data);
    }

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

    function search_job_cos() {
        $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('BranchCode', $this->session->userdata('branch'));
        $this->db->where_in('am_item.TransStatus', array(0, 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');
        $this->db->join('at_inventories', 'at_inventories.ItemCode = am_item.ItemCode', '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_job_costing->search_job_costing();
        /* ======================end================================= */

        for ($i = 0; $i <= ($rows - 1); $i++) {
            if ($result[$i]->IsLock == 1) {
                $Status = "Item Lock";
            } else {
                $Status = "Item UnLock";
            }
            $hasil[] = array(
                'ItemCode' => $result[$i]->ItemCode,
                'ItemDesc' => $result[$i]->ItemDesc,
                'ItemUnit' => $result[$i]->ItemUnit,
                'ItemAverage' => $result[$i]->ItemAverage,
                'ItemValue' => $result[$i]->ItemValue,
                'ItemCategoryID' => $result[$i]->ItemCategoryID,
                'ItemQty' => $result[$i]->ItemQty,
                'IsLock' => $Status,
                'ItemLockId' => $result[$i]->IsLock
            );
        }
        /* ===================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============================================================================== */
}
