<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*	
 *	Author 	: Agus / Tanggal : 08-08-2014	
 *	Revisi 	: Ferry / Tanggal : 17-02-2014
 	Revisi 	: Fachri /
 */
 
class Sales_quotation extends CI_Controller {
    // inisialisasi manual
    public $menu_id			= 159;
    public $code 			= "Sales Quotation Number";
    public $name 			= "Sales Quotation";
	public $transaction 	= [];
	
    public function __construct(){
        parent::__construct();
        $this->load->helper('message');
		$this->load->helper('status');
		$this->load->helper('convert_date');
		$this->load->helper('approval');
		$this->load->helper('lables');
		$this->load->helper('custom_string_helper');

		$this->load->model('m_sales_quotation');
		$this->load->model('m_sales_order');
		$this->load->model('m_items');
		$this->load->model('m_inventories');
		$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();
            }
        }
	}
	
    //Function Index
    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{
					$group_menu 		= $this->session->userdata('group_menu');
					// set data
					$data['menu_id'] 	=  $this->menu_id;

					// get link from tbl_menu 
					$data['menu_label']	= $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link']	= $this->m_menu->get_menulink($this->menu_id);
					$data['list_cust'] 	= $this->m_sales_quotation->get_all_customer(); 
					
					//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('sales/sales_quotation/v_salesquotation', $data);	
					$this->load->view('v_footer');	
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
    //Function Form Edit
    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)
					*/
					$group_menu 		= $this->session->userdata('group_menu');
					// set data
					$data['menu_id']    =  $this->menu_id;

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

					$data['sq_date']    = date('d-m-Y');
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					// set for view
					$this->load->view('v_header');
					$this->load->view('sales/sales_quotation/v_new_salesquotation', $data);
					$this->load->view('v_footer');	
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
    
    //Function Form Insert
    public function insert() {
		
		/*==========================deklar variabel====================================*/
		$cmb_customer       = $this->input->post('cmb_customer');
		$txa_address        = $this->input->post('txa_address');
		$txa_ship_to        = $this->input->post('txa_ship_to');
		$txt_sq_date        = $this->input->post('txt_sq_date');
		
		/*=====================================jcos number==========================================*/
		$sq_no  			= $this->m_sales_quotation->create_sq_number($txt_sq_date);
		/*==========================================================================================*/
		
		$txt_po_no          = $this->input->post('txt_po_no');
		$txt_po_date        = $this->input->post('txt_po_date');
		$cmb_salesman       = $this->input->post('cmb_salesman');
		$txa_description    = $this->input->post('txa_description');
		/*=========================end=================================================*/
			
        $detail_post        = $this->input->post('detail');
        $detail             = json_decode($detail_post);
        
        if(count($detail) > 0) {
			/*=======================insert group============================*/
			$this->insert_group($cmb_customer, $sq_no, $txt_sq_date, $txt_po_no, $txt_po_date, $cmb_salesman, $txa_address, $txa_description, $txa_ship_to);
			/*=====================end========================================*/
            
            /*============================insert detail=======================*/
			$this->insert_detail($detail, $sq_no);
            /*===============================end===============================*/
			$result_insert 		= $this->m_sales_quotation->insert_all_new($this->transaction);
			
			$this->transaction 	= [];
            /*=============================trans roll back dan trans commit============================/*/
			if ($result_insert == 0) {
				$result['status'] 	= FALSE;
				$result['message']  = get_notification_transaksi($this->name, 'insert', 0, $sq_no);
			}
			else {
				$result['status'] 	= TRUE;
				$result['message']  = get_notification_transaksi($this->name, 'insert', 1, $sq_no);
			}
			/*==================================end======================================================*/		
        }
        else {
            $result['status'] = false;
            $result['message'] = 'Data gagal disimpan, karena tidak ada "Item" yang dipilih';
        }

        echo json_encode($result);
    }
	
	function insert_group($cmb_customer, $sq_no, $txt_sq_date, $txt_po_no, $txt_po_date, $cmb_salesman, $txa_address, $txa_description, $txa_ship_to){
		$data = array (
			'BranchCode'		=> $this->session->userdata('branch'),
			'CustomerCode'		=> $cmb_customer,
			'SQuoNumber'		=> $sq_no,
			'SQuoDate'			=> date("Y-m-d", strtotime($txt_sq_date)),		
			'CustPONumber'		=> $txt_po_no,
			'CustPODate'		=> date("Y-m-d", strtotime($txt_po_date)),			
			'SalesmanCode'		=> $cmb_salesman,
			'BillingAddress'	=> $txa_address,
			'ShippingAddress'	=> $txa_ship_to,
			'SQuoDesc'			=> $txa_description,
			'TransStatus'		=> 1,
			'CreatedBy' 		=> $this->session->userdata("username"),
			'CreatedAt' 		=> date('Y-m-d'),
			'LastUser'			=> $this->session->userdata("username")
		);
            
		//1. Insert into Sales Quotation
		$this->transaction['insert_group']['data'] = $data;
	}
	
	function insert_detail($detail, $sq_no){
		foreach($detail as $row) {
			$detail_data = array(
				'SQuoNumber'	 => $sq_no,
				'ItemCode'		 => $row->ItemCode,
				'ItemDesc'		 => $row->ItemDesc,
				'ItemUnit'		 => $row->ItemUnit,
				'ItemQty'		 => $row->ItemQty,
				'ItemCategoryID' => $row->Item_CategoryID,
				'ItemCategoryCode' => $row->ItemCategoryCode,
				'ItemType' 		 => $row->ItemStatus,
				'RequiredDate'	 => date("Y-m-d", strtotime($row->RequiredDate)),
				'LastUser'		 => $this->session->userdata("username")				
			);             
	
			//2. Insert into SQuoDetail
			$this->transaction['insert_detail']['data'][] = $detail_data;
		}
	}
    
	//Function Form Edit
    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)
					*/
					$group_menu 		= $this->session->userdata('group_menu');
					// set data
					$data['menu_id'] =  $this->menu_id;
					
					// get link from tbl_menu 
					$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
					
					// inisialisasi additional parameter
					$id = str_replace($data['menu_link'].'/edit/',"",$this->uri->uri_string());
					$data['detail'] = $this->m_sales_quotation->get_detail($id);
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					if($data['detail'] != false){
						// set for view
						$this->load->view('v_header');
						$this->load->view('sales/sales_quotation/v_edit_salesquotation',$data);
						$this->load->view('v_footer');
					}
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
    // Function Update
    public function update() {
		
		/*=========================deklar variabel=======================================*/
		$CustPODate 	= date("Y-m-d", strtotime($this->input->post('txt_po_date')));
        $SQuoNumber 	= $this->input->post('txt_sq_no');
        $CustPONumber 	= $this->input->post('txt_po_no');            
        $SalesmanCode 	= $this->input->post('cbg_salesman');
        $SQuoDesc 		= $this->input->post('txa_description');
		/*=====================end=======================================================*/
			
        $detail_post 	= $this->input->post('hdn_detail');
        $detail 		= json_decode($detail_post);
		
		$detail_id 		= $this->input->post('detail_id');
        $detail_id 		= json_decode($detail_id);
        
        if(count($detail) > 0){
			/*
				Cek Qty, tidak boleh lebih besar dari qty pemesanan
			*/
			$check_qty_from_squo_detail = $this->m_sales_quotation->get_deatil_squo($SQuoNumber);
			foreach($check_qty_from_squo_detail as $row_detail){
				$ItemQty 	= $row_detail->ItemQty;
				$ItemQtySO 	= $row_detail->ItemQtySO;
				$ItemQtySpd = $row_detail->ItemQtySpd;
				$TotalQty 	= $ItemQtySpd + $ItemQtySO;
				
				if($TotalQty > $ItemQty){
					$result['status']       = FALSE;
                	$result['message']      = "Transaksi gagal di update Item Qty Sales Order melebihi Item Qty Sales Quotation";
					echo json_encode($result);
					die();
				}
			}
			
			/*===========update group======================================*/
			$this->update_group($CustPODate, $CustPONumber, $SalesmanCode, $SQuoDesc, $SQuoNumber);
			/*==================end==========================================*/
			
			/*===========================delete detail=================================================================*/
			$this->transaction['delete_detail']['total'] = count($detail_id);
			if(count($detail_id) > 0){
				foreach ($detail_id as $SQuoDetailID) {
					$this->transaction['delete_detail']['SQuoDetailID'][] = $SQuoDetailID;
				}
			}
			/*=============================end==========================================================================*/
			
			/*==================update detail==================================*/
			$this->update_detail($detail);
			/*==================end============================================*/
			
			$result_update = $this->m_sales_quotation->update_all_new($this->transaction);
			
			$this->transaction 	= [];
            /*=============================trans roll back dan trans commit============================/*/
			if ($result_update == 0) {
				$result['status'] 	= FALSE;
				$result['message']  = get_notification_transaksi($this->name, 'update', 0, $SQuoNumber);
			}
			else {
				$result['status'] 	= TRUE;
				$result['message']  = get_notification_transaksi($this->name, 'update', 1, $SQuoNumber);
			}
			/*==================================end======================================================*/	
        }
        else{
            $result['status'] = false;
            $result['message'] = 'Data gagal disimpan, karena tidak ada "Item" yang dipilih';	
        }
		
        echo json_encode($result);
    }
    
	function update_group($CustPODate, $CustPONumber, $SalesmanCode, $SQuoDesc, $SQuoNumber){
		$data = array(
			'CustPODate'        => $CustPODate,
			'CustPONumber'      => $CustPONumber,
			'SalesmanCode'      => $SalesmanCode,
			'SQuoDesc'          => $SQuoDesc,
			'TransStatus'       => 1
		);
		
		//1. Edit Sales Quotation
		$this->transaction['update_group']['data'] 			= $data;
		$this->transaction['update_group']['TransNumber'] 	= trim($SQuoNumber);
		
		//$this->m_sales_quotation->update($data, $SQuoNumber);
	}

	function update_detail($detail){
		foreach($detail as $row){
			$data_detail = array(
				'ItemCode'			=> $row->ItemCode,
				'itemUnit'			=> $row->ItemUnit,
				'itemQty'			=> $row->ItemQty,
				'ItemCategoryID'	=> $row->ItemCategoryID,
				'ItemCategoryCode'	=> $row->ItemCategoryCode,
				//'itemDesc'		=> $row->ItemDesc,
				'ItemType' 		 	=> $row->ItemStatus,
				'RequiredDate'		=> date("Y-m-d", strtotime($row->RequiredDate)),
				'LastUser'			=> $this->session->userdata("username")				
			);
			
			//2. Update SQuoDetail
			$this->transaction['update_detail']['data'][] 			= $data_detail;
			$this->transaction['update_detail']['SQuoDetailID'][] 	= $row->SQuoDetailID;
			
			//$this->m_sales_quotation->update_detail($data_detail, $row->SQuoDetailID);
		}
	}
	

    public function suspend_data(){
        $squo_number    = $this->input->post('id');        
        $check_pr       = $this->m_sales_quotation->check_item_suspend($squo_number);
        
		
        if($check_pr == false) {
            $this->db->trans_begin();
            $result_edit    = 0;
            $total_qty      = 0;

            //1. Update SalesQuotation for Status
            $data_sq = array (			
                            'TransStatus'   => 3,
                            'LastUser'      => $this->session->userdata("username")
                            );

            $this->m_sales_quotation->update($data_sq, $squo_number);
            //----------------------------------------------------------------------------------------------------------//

           /* $data_detail = $this->m_sales_quotation->get_detail_data($squo_number);
            
            foreach($data_detail as $row){
                //2. Update SQuoDetail for ItemQtySO
                $detail_sq = array (
                                'ItemQtySO'     => 0,
                                'LastUser'      => $this->session->userdata("username")
                                );
                
                $this->m_sales_quotation->update_detail($detail_sq, $row->SQuoDetailID);
                //------------------------------------------------------------------------------------------------------//
            }*/
                        
            /*=============================trans roll back dan trans commit============================/*/
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$result['status'] 	= FALSE;
				$result['message']  = get_notification('cancel', 0);
			}
			else {
				$this->db->trans_commit();
				$result['status'] 	= TRUE;
				$result['message']  = get_notification('cancel', 1);
			}
			/*==================================end======================================================*/
        }
        else {
            $result['status']   = false;
            $result['message']  = 'Suspend Transaksi gagal disimpan, karena Item Suspend telah digunakan atau item sudah diproses pada Sales Order';
        }
        
        echo json_encode($result);
    }

    public function suspend_item(){ 
        $suspend_all    	= 1;
		$finish				= 1;
        
        $squo_number    	= $this->input->post('squo_number');        
        $detail_post    	= $this->input->post('detail');
        $detail         	= json_decode($detail_post);	
		$arr_qty_spd 		= array();
		$arr_transstatus 	= array();
		
		$check_approved  = $this->m_sales_order->check_item_so_approved_by_squonumber($squo_number);
		if($check_approved == false){
			foreach($detail as $row){
				if($row->RowStatus == 1){
					
					/*
						Check data PO apakah sudah di buat
					*/
					$get_item_qty_on_sq = $this->m_sales_quotation->get_detail_sum_squo($squo_number, $row->ItemCode);
					if($get_item_qty_on_sq->ItemQtySO > $get_item_qty_on_sq->ItemQtySQ){
						 $result['status']   = false;
						 $result['message']  = 'Item tidak berhasil di Suspend, karena item ini sudah di proses di PO keseluruhan';
						 echo json_encode($result);
						 die();
					}
						
					//1. Update SQuoDetail for suspend data
					$squo_data      = array (
						'ItemQty'		=> $row->Status == 'Yes' ? $row->ItemQtyOld : $row->ItemQtyOld,
						'ItemQtySpd'	=> $row->Status == 'Yes' ? $row->ItemQtySpd : 0,
						'ItemSpdStatus'	=> $row->Status == 'Yes' ? 1 : 0,
						'LastUser'		=> $this->session->userdata("username"),
						'SQuoDetailID' 	=> $row->SQuoDetailID
					);
					
					//$this->m_sales_quotation->update_detail($squo_data, $row->SQuoDetailID);
					$arr_qty_spd[] = $squo_data;
				}
				
				if (($row->Status == 'No') or ($row->ItemQtySO>0)) {
					$suspend_all = 0;
				}
				
				if (($row->ItemQty-$row->ItemQtySO-$row->ItemQtySpd)!=0) {
					$finish = 0;
				}
			}
       
			//3. Edit SalesQuatation for TransStatus is equalto 8 as Item Suspend
			if(($suspend_all == 1) or ($finish == 1)) {
				if($suspend_all==1){
					$TransStatus = 8;
				}
				elseif($finish==1){
					$SOrdAppStatus = $this->m_sales_order->check_sord_app_status($squo_number);
					if($SOrdAppStatus==1){
						$TransStatus = 2;
					}
					else{
						$TransStatus = 1;
					}
				}
				
				$data = array (
					'TransStatus'       => $TransStatus,
					'LastUser'          => $this->session->userdata("username")
				);
				$arr_transstatus[] = $data;
			}
			//--------------------------------------------------------------------------------------------------------------//
			$result_app_item = $this->m_sales_quotation->update_suspend_item($arr_qty_spd, $arr_transstatus, $squo_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'] = 'Data telah berhasil disimpan';
			}
			/*==================================end======================================================*/
		}
        else{            
            $result['status']   = false;
            $result['message']  = 'Item Suspend tidak berhasil disimpan, karena item belum di Approval pada Sales Order';
        }
		
        echo json_encode($result);
        die();
    }    
    
    //Function preview data
    public function to_preview($obj_string = null){
        // set data
		
        $data['menu_id'] 	=  $this->menu_id;
        $data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link']  = $this->m_menu->get_menulink($this->menu_id);
		$data['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_sales_quotation->get_all_to_print($data_filter);

        $this->load->view('v_header');
        $this->load->view('sales/sales_quotation/v_preview_salesquotation', $data);	
        $this->load->view('v_footer');	
    }
	
    //Function To Print
    public function to_print(){	
        // set data
        $data['menu_id'] =  $this->menu_id;
        $data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);

        $data['list'] = $this->m_sales_quotation->get_all();

        $this->load->view('v_header');
        $this->load->view('sales/sales_quotation/v_print_salesquotation', $data);	
        $this->load->view('v_footer');	
    }
	
    // Function Print
    function to_print_detail(){
        // get link from tbl_menu 
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		
        // get label from tbl_menu 
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
        // set data
        $id = str_replace($data['menu_link'].'/to_print_detail/',"",$this->uri->uri_string());
	
        if($id!=""){		
            $data['detail'] = $this->m_sales_quotation->get_detail_print($id);
            $data['list'] = $this->m_sales_quotation->get_detail_item_print($data['detail']->SQuoNumber);		

            $this->load->view('v_header');
            $this->load->view('sales/sales_quotation/v_print_detail_salesquotation', $data);	
            $this->load->view('v_footer');	
        }
    }
	
    //Function preview data
    function to_preview_detail(){
        // get link from tbl_menu 
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		
        // get label from tbl_menu 
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
		
        // set data
        $id = str_replace($data['menu_link'].'/to_preview_detail/',"",$this->uri->uri_string());
	
        if($id!=""){
            $data['detail'] = $this->m_sales_quotation->get_detail($id);
            $data['list'] = $this->m_sales_quotation->get_detail_item($data['detail']->SQuoNumber);		

            $this->load->view('v_header');
            $this->load->view('sales/sales_quotation/v_preview_detail_salesquotation', $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'] : '';
		
		$cmb_CustomerCode	= isset($param['cmb_CustomerCode']) ? $param['cmb_CustomerCode'] : '';
		/*============================================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('SQuoNumber', $Number);} 
		if($Desc != ""){$this->db->like('SQuoDesc', $Desc);} 
		if($cmb_CustomerCode != ""){$this->db->where('CustomerCode', $cmb_CustomerCode);} 
		
		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_salesquotation.SQuoDate >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where('at_salesquotation.SQuoDate <=', date("Y-m-d", strtotime($DateTo))); 
			}
        }
		/*==========================end=================================================================*/
		
		$count_data = $this->db->count_all_results('at_salesquotation');
		
		/*========================end=======================================*/
		$result = $this->m_sales_quotation->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,
				'CustomerName' 		=>	$result[$i]->CustomerName,
				'TransNumber' 		=>	$result[$i]->SQuoNumber,
				'SQuoDate' 			=>	$result[$i]->SQuoDate, 
				'CustPONumber' 		=>	$result[$i]->CustPONumber,
				'SQuoDesc' 			=>	$result[$i]->SQuoDesc,
				'TransStatus' 		=>	$TransStatus,
				'CreatedBy' 		=>	$result[$i]->CreatedBy
			);
		}
		
		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 ajax_item(){		
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $id = str_replace($data['menu_link'].'/ajax_item/',"",$this->uri->uri_string());
	
        $result = $this->m_sales_quotation->get_detail_item($id);
		//echo $this->db->last_query();
        echo json_encode($result);
    }	
	
    public function ajax_filter(){
        $cust = $this->input->post('cust_code');
		
        if(!empty($cust)){
           echo json_encode($this->m_sales_quotation->get_by_cust2($cust));
        }
        else{
            echo '[]';
        }
    }
	
	public function reverse_data_detail(){
		$squo_number    = $this->input->post('squo_number');        
        $detail_post    = $this->input->post('hdn_detail');
        $detail         = json_decode($detail_post);	
		
		$this->db->trans_begin();
		
		foreach($detail as $row){
			/*================cek qty do=============================*/
			if($row->ItemQtyDO != 0){
				$result['status'] 	= FALSE;
				$result['message'] = msg_reverse_sq('msg_do','Delivery Order');
				echo json_encode($result);
				die();
			}
			/*==================end=============================*/
			
			/*========================cek qty so=====================*/
			if($row->ItemQtySO != 0){
				$result['status'] 	= FALSE;
				$result['message'] = msg_reverse_sq('msg_so','Sales Order');
				echo json_encode($result);
				die();
			}
			/*==end============================*/
			
			/*========================cek qty so=====================*/
			if($row->ItemQtySpd != 0){
				$data_detail = array(
					'ItemQtySpd' 	=> 0,
					'ItemSpdStatus' => 0
				);
				
				$this->m_sales_quotation->update_detail($data_detail, $row->SQuoDetailID);
			}
			/*=======================end============================*/
			
			$data = array (
				'TransStatus'    => 1
			);
			
			$this->m_sales_quotation->update($data, $squo_number);
		}
		
		/*=============================trans roll back dan trans commit============================/*/
		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			$result['status'] 	= FALSE;
			$result['message']  = get_notification('cancel', 0);
		}
		else {
			$this->db->trans_commit();
			$result['status'] 	= TRUE;
			$result['message']  = get_notification('cancel', 1);
		}
		/*==================================end======================================================*/
		echo json_encode($result);
	}
}
	