<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* Author : Ferry / Tanggal : 12-01-2015 */

class Purchases_requisition extends CI_Controller {

    public $menu_id = 167;
    public $name = "Purchase Requisition";
    public $menu_model = array('m_purchase_requisition', 'm_purchase_order');
    public $app1 = array("MGR", "SPV");
    public $branch = "";
    public $ho;

    public function __construct() {
        parent::__construct();

        $this->load->model('custom/m_custom');
        $this->load->model('setup/m_branchinfo');
        $this->load->model('m_purchase_order');

        //$data_branch  = $this->m_custom->get_branch_detail();
        $this->branch = $this->session->userdata('branch');

        if ($this->session->userdata('branch_status') == 0)
            $this->ho = true;
        else
            $this->ho = false;

        $this->load->model($this->menu_model);
        $this->load->helper('regex');
        $this->load->helper('message');
        $this->load->helper('status');
        $this->load->helper('lables');
        $this->load->helper('convert_date');
        $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_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['lables'] = get_lables_eng(); //tambah dhidhik, 050022016, untuk labelisasi, penamaan biar seperti ini saja biar enak copy-paste

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

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

                    //date_default_timezone_set("Asia/Bangkok");
                    $data['pr_date'] = date('d-m-Y');

                    $data['lables'] = get_lables_eng(); //tambah dhidhik, 050022016, untuk labelisasi, penamaan biar seperti ini saja biar enak copy-paste

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

    public function insert() {
        $branch_code = $this->session->userdata('branch');
        $departement_code = $this->session->userdata('department');

        $preq_date = $this->input->post('txt_preq_date');
        $preq_number = $this->m_purchase_requisition->create_pr_number($preq_date);

        $preq_desc = $this->input->post('txa_preq_desc');

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


        if (count($detail) > 0) {
            $detail_new_array = array();
            /*
              Insert Group
             */
            $data = array(
                'BranchCode' => $branch_code,
                'DepartmentCode' => $departement_code,
                'PReqDate' => date("Y-m-d", strtotime($preq_date)),
                'PReqNumber' => $preq_number,
                'PReqDesc' => $preq_desc,
                'TransStatus' => 4,
                'CreatedBy' => $this->session->userdata("username"),
                'CreatedAt' => date('Y-m-d'),
                'LastUser' => $this->session->userdata("username")
            );
            /* ===================End============================== */

            $result_insert = $this->m_purchase_requisition->insert_new($data, $detail, $preq_number);

            if ($result_insert == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $preq_number);

                $result['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                $result['number'] = $preq_number;
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 1, $preq_number);
            }
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('no_count', 0);
        }
        echo json_encode($result);
    }

    //public function insert() {
//        $branch_code        = $this->session->userdata('branch');
//        $departement_code   = $this->session->userdata('department');
//		
//        $preq_date          = $this->input->post('txt_preq_date');
//		$preq_number        = $this->m_purchase_requisition->create_pr_number($preq_date);
//        
//		$preq_desc          = $this->input->post('txa_preq_desc');
//        
//        $detail_post        = $this->input->post('detail');
//        $detail             = json_decode($detail_post);
////
//        if(count($detail) > 0){
//           $this->db->trans_begin();
////			
////			======================================================================================================
////			
////				insert group
////			
//           	$this->insert_group($branch_code,$departement_code, $preq_date, $preq_number, $preq_desc);
////			========================================end===========================================================
////			
////            ======================================================================================================
////			
////				insert detail
////			
//           	$this->insert_detail($preq_number, $detail);
////			========================================end===========================================================
//			
//			if ($this->db->trans_status() === FALSE) {
//				$this->db->trans_rollback();
//                $result['status']       = FALSE;
//                $result['message']      = get_notification_transaksi($this->name, 'insert', 0, $preq_number);
//
//                $result['menu_link']    = $this->m_menu->get_menulink($this->menu_id);
//                $result['number']       = $preq_number;
//			}
//			else {
//				$this->db->trans_commit();
//				$result['status'] 	= TRUE;
//				$result['message']  = get_notification_transaksi($this->name, 'insert', 1, $preq_number);
//			}
//        }        
//        else{
//            $result['status']   = false;
//            $result['message']  = get_notification('no_count', 0);
//        }	
//
//        echo json_encode($result);
//    }

    function insert_group($branch_code, $departement_code, $preq_date, $preq_number, $preq_desc) {
        $data = array(
            'BranchCode' => $branch_code,
            'DepartmentCode' => $departement_code,
            'PReqDate' => date("Y-m-d", strtotime($preq_date)),
            'PReqNumber' => $preq_number,
            'PReqDesc' => $preq_desc,
            'TransStatus' => 4,
            'CreatedBy' => $this->session->userdata("username"),
            'CreatedAt' => date('Y-m-d'),
            'LastUser' => $this->session->userdata("username")
        );

        // Insert PReq data.
        $this->m_purchase_requisition->insert($data);
    }

    function insert_detail($preq_number, $detail) {
        foreach ($detail as $row) {
            $detail_data = array(
                'PReqNumber' => $preq_number,
                'ItemCode' => $row->ItemCode,
                'ItemDesc' => $row->ItemDesc,
                'itemUnit' => $row->ItemUnit,
                'itemQty' => $row->ItemQty,
                'RequiredDate' => date("Y-m-d", strtotime($row->RequiredDate)),
                'ItemCategoryID' => $row->ItemCategoryID,
                'ItemCategoryCode' => $row->ItemCategoryCode,
                'ItemType' => $row->ItemType,
                'ItemStatus' => $row->ItemStatus,
                'ItemPPh22Status' => $row->ItemPPh22Status,
                'ItemPPh23Status' => $row->ItemPPh23Status,
                'ItemAdvNetDueIn' => $row->ItemAdvNetDueIn,
                'LastUser' => $this->session->userdata("username")
            );

            //Insert PReq Detail
            $this->m_purchase_requisition->insert_detail($detail_data);
        }
    }

    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);
                    $data['app1'] = $this->app1;

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

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

                    $data['lables'] = get_lables_eng(); //tambah dhidhik, 050022016, untuk labelisasi, penamaan biar seperti ini saja biar enak copy-paste

                    if ($data['detail'] != false) {
                        $this->load->view('v_header');
                        $this->load->view('purchase/purchase_requisition/v_edit_purchase_requsition', $data);
                        $this->load->view('v_footer');
                    }
                    //----------------------end--------------------------------------------------------		
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function update() {
        $preq_number = $this->input->post('txt_preq_no');
        $preq_desc = $this->input->post('txa_preq_desc');

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

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

        if (count($detail) > 0) {
            /*
              Cek Qty, tidak boleh lebih besar dari qty pemesanan
             */
            $check_qty_from_preq_detail = $this->m_purchase_requisition->get_deatil_preq($preq_number);
            foreach ($check_qty_from_preq_detail as $row_detail) {
                $ItemQty = $row_detail->ItemQty;
                $ItemQtyPO = $row_detail->ItemQtyPO;
                $ItemQtySpd = $row_detail->ItemQtySpd;
                $TotalQty = $ItemQtySpd + $ItemQtyPO;

                if ($TotalQty > $ItemQty) {
                    $result['status'] = FALSE;
                    $result['message'] = "Transaksi gagal di update Item Qty Purchase Order melebihi Item Qty Purchase Requisition";
                    echo json_encode($result);
                    die();
                }
            }

            $data = array(
                'PReqDesc' => $preq_desc,
                'TransStatus' => 4,
                'LastUser' => $this->session->userdata("username")
            );

            //1. Edit PurchaseRequisition
            $result_update = $this->m_purchase_requisition->update_all_table_new($data, $detail, $preq_number);

            /* ===============Delete per grid jika tombol delete di klik ===================== */
            if (count($detail_id) > 0) {
                foreach ($detail_id as $PreqDetailID) {
                    $result_update = $this->m_purchase_requisition->delete_detail_new($PreqDetailID);
                }
            }
            /* ====================End========================================================== */
            if ($result_update == 0) {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'update', 0, $preq_number);

                $result['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                $result['number'] = $preq_number;
            } else {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'update', 1, $preq_number);
            }
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('no_count', 0);
        }

        echo json_encode($result);
    }

    //public function update() {
//        $preq_number        = $this->input->post('txt_preq_no');
//        $preq_desc          = $this->input->post('txa_preq_desc');
//		
//        $detail_post        = $this->input->post('detail');
//        $detail             = json_decode($detail_post);	
//		
//		$detail_id			= $this->input->post('detail_id');
//        $detail_id			= json_decode($detail_id);
//		
//        if(count($detail) > 0){ 
//            $this->db->trans_begin();	
//			/*
//				Cek Qty, tidak boleh lebih besar dari qty pemesanan
//			*/
//			$check_qty_from_preq_detail = $this->m_purchase_requisition->get_deatil_preq($preq_number);
//			foreach($check_qty_from_preq_detail as $row_detail){
//				$ItemQty 	= $row_detail->ItemQty;
//				$ItemQtyPO 	= $row_detail->ItemQtyPO;
//				$ItemQtySpd = $row_detail->ItemQtySpd;
//				$TotalQty 	= $ItemQtySpd + $ItemQtyPO;
//				
//				if($TotalQty > $ItemQty){
//					$result['status']       = FALSE;
//                	$result['message']      = "Transaksi gagal di update Item Qty Purchase Order melebihi Item Qty Purchase Requisition";
//					echo json_encode($result);
//					die();
//				}
//			}
//			
//            $data = array (
//                        'PReqDesc'          => $preq_desc,		
//                        'TransStatus'       => 4,
//                        'LastUser'          => $this->session->userdata("username")
//                    );
//
//            //1. Edit PurchaseRequisition
//            $this->m_purchase_requisition->update($data, $preq_number);
//
//            foreach($detail as $row){	
//                $detail_data = array(
//									  'RequiredDate' 		=> date("Y-m-d", strtotime($row->RequiredDate)),
//                                    'ItemQty'           => $row->ItemQty,
//                                    'LastUser'          => $this->session->userdata("username")				
//                                );                    
//
//                //2. Update PReqDetail
//                $this->m_purchase_requisition->update_detail($detail_data, $row->PreqDetailID);	
//            }
//			
//			/*===============Delete per grid jika tombol delete di klik =====================*/
//			if(count($detail_id)>0){
//				foreach ($detail_id as $PreqDetailID) {
//					$this->m_purchase_requisition->delete_detail_by_id($PreqDetailID);
//				}
//			}
//			/*====================End==========================================================*/
//			
//            if ($this->db->trans_status() === FALSE) {
//				$this->db->trans_rollback();
//                $result['status']       = FALSE;
//                $result['message']      = get_notification_transaksi($this->name, 'update', 0, $preq_number);
//
//                $result['menu_link']    = $this->m_menu->get_menulink($this->menu_id);
//                $result['number']       = $preq_number;
//			}
//			else {
//				$this->db->trans_commit();
//				$result['status'] 	= TRUE;
//				$result['message']  = get_notification_transaksi($this->name, 'update', 1, $preq_number);
//			}
//	}
//        else{
//            $result['status']   = false;
//            $result['message'] = get_notification('no_count', 0);
//        }
//
//        echo json_encode($result);
//    }

    function delete() {
        $preq_detail_id = $this->input->post('preq_detail_id');

        if (!empty($preq_detail_id)) {
            $this->db->trans_begin();
            $this->m_purchase_requisition->delete_detail_by_id($preq_detail_id);

            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = get_notification('delete', 0);
            } else {
                $this->db->trans_commit();
                $result['status'] = TRUE;
                $result['message'] = get_notification('delete', 1);
            }

            echo json_encode($result);
        }
    }

    public function suspend_data() {
        $result_suspend = 0;
        $id = str_replace(".", "/", $this->input->post('id'));
        $PReqDetail = $this->m_purchase_requisition->get_detail($id);

        $this->db->trans_begin();
        if (($PReqDetail->TransStatus == 0) || ($PReqDetail->TransStatus == 4)) {
            $data = array(
                'TransStatus' => 3,
                'LastUser' => $this->session->userdata("username")
            );
            $this->m_purchase_requisition->update_group_single($data, $id);

            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = get_notification('suspend', 0);
            } else {
                $this->db->trans_commit();
                $result['status'] = TRUE;
                $result['message'] = get_notification('suspend', 1);
            }
        } else {
            $result['status'] = false;
            $result['message'] = get_notification('suspend', 0);
            $this->db->trans_rollback();
        }

        echo json_encode($result);
    }

    public function suspend_item() {
        $suspend_all = 1;
        $trans_status = 1;

        $preq_number = $this->input->post('PReqNumber');
        $detail_post = $this->input->post('detail');
        $status = $this->input->post('status'); //saat klik tombol suspend item

        $detail = json_decode($detail_post);
		$arr_qty_spd 		= array();
		$arr_transstatus 	= array();
		
        $check_approved = $this->m_purchase_order->check_item_po_approved_by_preqnumber($preq_number);
        if ($check_approved == false) {
            foreach ($detail as $row) {
                $PReqDetailID = $row->PreqDetailID;
                if ($row->Modus_Type == 2) {
                    $get_item_qty_on_pr = $this->m_purchase_requisition->get_detail_sum_preq($preq_number, $row->ItemCode);
                    $item_qty_suspend = $get_item_qty_on_pr->TotalItemQtyPR - $get_item_qty_on_pr->TotalItemQtyPO;

                    /*
                      Check data PO apakah sudah di buat
                     */
                    if ($status == 1) {
                        if ($get_item_qty_on_pr->TotalItemQtyPO >= $get_item_qty_on_pr->TotalItemQtyPR) {
                            $result['status'] = false;
                            $result['message'] = 'Item tidak berhasil di Suspend, karena item ini sudah di proses di PO keseluruhan';
							
                            echo json_encode($result);
                            die();
                        }
                    }

                    $data_preq = array(
                        'ItemQtySpd' => $item_qty_suspend,
                        'ItemSpdStatus' => $row->Status == 'Yes' ? 1 : 0,
						'PreqDetailID' 	=> $row->PreqDetailID,
                        'LastUser' => $this->session->userdata("username")
                    );

                    //Edit PRegDetail for Suspend Data
					$arr_qty_spd[] = $data_preq;
                   // $result_suspend = $this->m_purchase_requisition->update_detail_single($data, $PReqDetailID);
                    //-----------------------------------------------------------------------------------------------------//
                }

                if (($row->Status == 'No') or ( $row->ItemQtyPO > 0)) {
                    $suspend_all = 0;
                }

                //$total_qty_curr = $item_qty - $item_qty_ri - $item_qty_suspend;
                if (($row->ItemQty - $row->ItemQtyPO - $row->ItemQtySpd) != 0) {
                    $trans_status = 0;
                }
            }

            //3. Edit SalesQuatation for TransStatus is equalto 8 as Item Suspend
            if (($suspend_all == 1) or ( $trans_status == 1)) {
                if ($suspend_all == 1) {
                    $TransStatus = 8;
                } elseif ($trans_status == 1) {

                    $POordAppStatus = $this->m_purchase_order->check_pord_app_status($preq_number);
                    if ($POordAppStatus == 1) {
                        $TransStatus = 2;
                    } else {
                        $TransStatus = 1;
                    }
                }

                $data = array(
                    'TransStatus' => $TransStatus,
                    'LastUser' => $this->session->userdata("username")
                );
				
				$arr_transstatus[] = $data;
                //$result_suspend = $this->m_purchase_requisition->update_group_single($data, $preq_number);
            }
            //--------------------------------------------------------------------------------------------------------------//
			
			//--------------------------------------------------------------------------------------------------------------//
			$result_app_item = $this->m_purchase_requisition->update_suspend_item($arr_qty_spd, $arr_transstatus, $preq_number);
			/*=============================trans roll back dan trans commit============================/*/
			
            if ($result_app_item == 0) {
				$result['status'] 	= FALSE;
				$result['message'] = 'Data suspend / unsuspend gagal disimpan';
			}
			else {
				$result['status'] 	= TRUE;
				$result['message']  = 'Item Suspend / UnSuspend berhasil disimpan';
			}
        } else {
            $result['status'] = false;
            $result['message'] = 'Item Suspend tidak berhasil disimpan, karena item belum di Approval pada Purchase Order';
        }

        echo json_encode($result);
    }

    public function approval() {
        $this->db->trans_begin();
        $preq_number = $this->input->post('txt_preq_no');
        $result_app = 0;
        $data = array(
            'TransStatus' => 1,
            'AppLevel1Status' => 1,
            'AppLevel1Code' =>  $this->session->userdata("username"),
            'AppLevel1Date' => date('Y-m-d'),
            'LastUser' => $this->session->userdata("username")
        );

        $this->m_purchase_requisition->update_group_single($data, $preq_number);
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
            $result['message'] = get_notification('approval', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification('approval', 1);
        }

        echo json_encode($result);
    }

    public function reversed_data() {
        $preq_number = $this->input->post('id');
        $this->db->trans_begin();
		$get_no_transaction = $this->m_purchase_requisition->get_old_no_transaaction($preq_number);
		 
		if($get_no_transaction->OldPReqNumber != ""){
			$result['status'] = FALSE;
            $result['message'] = "Transaksi gagal di reverse, karena item ini adalah transaksi dari import file";
            echo json_encode($result);
            $this->db->trans_rollback();
            die();
		}
        /*
          Check om PO Transstatus 1,2,4,5,6,8,0
         */
        $get_detail_preq = $this->m_purchase_requisition->check_item_pod_reverse($preq_number);

        if ($get_detail_preq) {
            $result['status'] = FALSE;
            $result['message'] = msg_check_po_reverse('Purchase Order');
            echo json_encode($result);
            $this->db->trans_rollback();
            die();
        }
        /* =============================END=================================== */
        $data = array(
            'TransStatus' => 4,
            'AppLevel1Status' => 0,
            'AppLevel1Code' => NULL,
            'AppLevel1Date' => NULL,
            'LastUser' => $this->session->userdata("username")
        );

        $this->m_purchase_requisition->update_group_single($data, $preq_number);

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
            $result['message'] = get_notification('approval', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification('approval', 1);
        }

        echo json_encode($result);
    }

    function to_preview($obj_string = null) {
        $data['menu_id']        = $this->menu_id;
        $data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
//        $data['list'] = $this->m_purchase_requisition->get_all($this->ho);
        $data['lables']         = get_lables_eng(); //tambah dhidhik, 050022016, untuk labelisasi, penamaan biar seperti ini saja biar enak copy-paste

        $data_filter            = arrayParamInUrlToStr($obj_string);
		$data['branch_code'] = $data_filter['cmb_branch'];
		$data['company_code'] = $data_filter['cmb_company'];
        $data['list']           = $this->m_purchase_requisition->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('purchase/purchase_requisition/v_preview_purchase_requisition', $data);
        $this->load->view('v_footer');
    }
    function to_preview_LAMA() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
        $data['list'] = $this->m_purchase_requisition->get_all($this->ho);
        $data['lables'] = get_lables_eng(); //tambah dhidhik, 050022016, untuk labelisasi, penamaan biar seperti ini saja biar enak copy-paste

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_requisition/v_preview_purchase_requisition', $data);
        $this->load->view('v_footer');
    }

    function to_print() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
        $data['list'] = $this->m_purchase_requisition->get_all($this->ho);
        $data['lables'] = get_lables_eng(); //tambah dhidhik, 050022016, untuk labelisasi, penamaan biar seperti ini saja biar enak copy-paste

        $this->load->view('v_header');
        $this->load->view('purchase/purchase_requisition/v_print_purchase_requisition', $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);
        $data['lables'] = get_lables_eng(); //tambah dhidhik, 050022016, untuk labelisasi, penamaan biar seperti ini saja biar enak copy-paste

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

        if ($id != "") {
            $data['detail'] = $this->m_purchase_requisition->get_detail_print($id);

            $data['list'] = $this->m_purchase_requisition->get_detail_item_print($data['detail']->PReqNumber);
            $this->load->view('v_header');
            $this->load->view('purchase/purchase_requisition/v_print_detail_purchase_requisition', $data);
            $this->load->view('v_footer');
        }
    }

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

        $hasil = array();
        $result = 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('PReqNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('PReqDesc', $Desc);
        }
        if ($TransStatus != '') {
            $this->db->where_in('TransStatus', $TransStatus);
        } else {
            /*
              default adalah 2,6. Finished dan Need Approval
             */
            $this->db->where_in('TransStatus', array(0, 1, 4, 5, 6, 7));
        }


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

        $count_data = $this->db->count_all_results('at_purchaserequisition');
        /* ========================end======================================= */
        $result = $this->m_purchase_requisition->get_all();

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

            $hasil[] = array(
                'BranchName' => $result[$i]->BranchName,
                'DepartmentName' => $result[$i]->DepartmentName,
                'TransNumber' => $result[$i]->PReqNumber,
                'PReqDate' => $result[$i]->PReqDate,
                'PReqDesc' => $result[$i]->PReqDesc,
                'CreatedBy' => $result[$i]->CreatedBy,
                'TransStatus' => $TransStatus
            );
        }

        $result['total'] = $count_data;
        $result['rows'] = $hasil;
        echo json_encode($result);
    }

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

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

        echo json_encode($this->m_purchase_requisition->get_detail_item_for_edit($preq_number));
    }

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

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

    public function get_preq_number() {
        $date = $this->input->post('date') == '' ? date('d-m-Y') : $this->input->post('date');
        $preq_number = $this->m_purchase_requisition->create_pr_number($date);

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

        echo json_encode($result);
    }

}
