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

class CT_barangmesin extends CI_Controller {
    function __construct()
    {
       parent::__construct();
    if (!$this->dx_auth->is_logged_in()) {
           header('HTTP/1.1 401 Unauthorize');die('expire'); 
        }
        
        $uid = $this->session->userdata('DX_user_id');
        
        if(!permissionAuth(2) && $uid != RID){ 
            header('HTTP/1.1 401 Unauthorize');die('noaccess');
        } 
		
		$this->load->model("settings/mdl_settings", 'mdl_settings');
    }
    
    
    function index()
    {
        $this->load->view('settings/view_barang_mesin');
    }
	
	function loadData(){
	
		$search = isset($_POST['_search'])?$_POST['_search']:false;
		$searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
		$searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
		$filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
		$limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
		$sidx = isset($_POST['sidx'])?$_POST['sidx']:'id'; // get index row - i.e. user click to sort
		$sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
			
		$where = " 1=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like  '%".$searchString."%'"; 
					} else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$where .= " and part_name like  '%".$searchString."%'"; 
					} else if ( $k->field == "part_name_customs" ) {
						$searchString = $k->data;
						$where .= " and part_name_customs like  '%".$searchString."%'"; 
					} else if ( $k->field == "hs_code" ) {
						$searchString = $k->data;
						$where .= " and hs_code like  '%".$searchString."%'"; 
					} else if ( $k->field == "bm" ) {
						$searchString = $k->data;
						$where .= " and bm like  '%".$searchString."%'"; 
					} else if ( $k->field == "cek_price" ) {
						$searchString = $k->data;
						$where .= " and cek_price like  '%".$searchString."%'"; 
					} else if ( $k->field == "part_no2" ) {
						$searchString = $k->data;
						$where .= " and part_no2 like  '%".$searchString."%'"; 
					}
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_barang_mesindanalatktr_All($limit,$start,$sidx,$sord, $where);
		$count = $this->mdl_settings->data_barang_mesindanalatktr_CountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
		if ($page > $total_pages) $page=$total_pages;
		
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
		foreach($records as $r){
						
			$responce->rows[$i]['id_datampk']=$r->id_datampk; 
			$responce->rows[$i]['kode_brg']=$r->kode_brg; 
			$responce->rows[$i]['nama_barang']=$r->nama_barang;
			$responce->rows[$i]['keterangan']=$r->keterangan;
			$responce->rows[$i]['satuan']=$r->satuan;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
			$i++;
		}
		echo json_encode($responce);		
	
	
	}
	
	
    
    //upload mesin
	
	function view_barang_mesin_upload(){
	
		 $this->load->view('settings/view_barang_mesin_upload');
	
	}
	
	function data_uploaduploadmesin_dan_alat_ktr(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_mesin_upload'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "filename" ) {
						$searchString = $k->data;
						$where .= " and filename like  '%".$searchString."%'"; 
					} else if ( $k->field == "date_upload" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[date_upload],103)  =  '$searchString'"; 
					} else if ( $k->field == "status_upload" ) {
						$searchString = $k->data;
						$where .= " and status_upload like  '%".$searchString."%'"; 
					}  else if ( $k->field == "create_by" ) {
						$searchString = $k->data;
						$where .= " and create_by like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->uploadmesindanalatktrAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->uploadmesindanalatktrCountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_mesin_upload']=$r->id_mesin_upload; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']=$r->filename; 
			$responce->rows[$i]['status_upload']=$r->status_upload;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['tipe']=$r->tipe;
			$responce->rows[$i]['filepath']=$r->filepath;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function upload_file_uploadmesin_dan_alat_ktr(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_uploadmesin_dan_alat_ktr';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'MPK';
	   if ($status != "error")
	   {
		 // echo 'aaaaaaaaaaaaa';
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'invoice/mesin_alat_ktr/';
		  $config['allowed_types'] = 'xls';
		  $config['max_size']  = 1024 * 100;
		  $config['encrypt_name'] = false;
		  $config['overwrite']=true;
		  $config['remove_spaces']=true;
		  $this->load->library('upload', $config);
		  if (!$this->upload->do_upload($file_element_name))
		  {
			 $status = 'error';
			 $msg = $this->upload->display_errors('', '');
		  }
		  else
		  {
			 $data = $this->upload->data();
			 
			  // print_r($data);
			  // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'invoice/mesin_alat_ktr/log/'.$data['file_name'];
				$filename=$data['file_name'];
				//echo $myFile; die();
				/* echo " exec('[spuload_stockawal_fg] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')";
				die(); */
				 
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[spuload_mesindanalatktr] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')
					
					END TRY
					BEGIN CATCH 
						SELECT 
						'error' AS status
						,ERROR_MESSAGE() AS description;
						
					END CATCH;
					
					");
				 
				 $rs = $qry->result_array();
				 // $r = $qry->result();		
				 // var_dump($r);die();
				 foreach ($rs as $row){
					 $status = $row['status'];
					 $msg = $row['description'];
				 }  
				//  echo json_encode($responce);
				 // $stmt = " exec('[spuload_stockawal_fg]') ";
				 // $qry = mssql_query($stmt); 
				 // $row = mssql_fetch_array($qry); 
				 // var_dump($row);die();
						 
				
				
				
				$status = $status;
				$msg = $msg;
			 }
			 else
			 {
				unlink($data['full_path']);
				$status = "error";
				$msg = "Something went wrong when saving the file, please try again.";
			 }
		  }
		  @unlink($_FILES[$file_element_name]);
	   }
	   echo json_encode(array('status' => $status, 'msg' => $msg));
	
	
	}
	
	function deletefile_uploadmesin_dan_alat_ktr(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$tipe = (isset($_POST['tipe']) && !empty($_POST['tipe']))?$_POST['tipe']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_mesin_upload = (isset($_POST['id_mesin_upload']) && !empty($_POST['id_mesin_upload']))?$_POST['id_mesin_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		//$username = $this->session->userdata('DX_user_id');
	    $username = $this->session->userdata('DX_username');
		$apppath = $this->config->item('APP_upload_path');
		
		$path=$apppath.'invoice/mesin_alat_ktr/'.$filename;
		$pathnew=$apppath.'invoice/mesin_alat_ktr/log/'.$filename;
		
		if (!file_exists($path)) {
		   echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
			die();
		}
		
		
		
		$qry = $this->db->query("
			BEGIN TRY
			
			 exec('[spuload_mesindanalatktr] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_mesin_upload ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		 $rs = $qry->result_array();
		 // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $status = $row['status'];
			 $msg = $row['description'];
		 }  
		//  echo json_encode($responce);
		 // $stmt = " exec('[spuload_assylist]') ";
		 // $qry = mssql_query($stmt); 
		 // $row = mssql_fetch_array($qry); 
		 // var_dump($row);die();
		
		$status = $status;
		$msg = $msg;
		
		if ($status=='00'){
			copy($path, $pathnew) or die(array('sts' => '00','desc' => "Unable to copy $path to $pathnew."));
			if (file_exists($path)) {
				unlink($path);
			} else {
				echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
				die();
			}
		}
		echo json_encode(array('sts' => $status, 'desc' => $msg));
	
	
	}
	
	function cek_data_opname_sisa_scrap(){
		error_reporting(E_ALL ^ E_NOTICE);
		//$this->load->file("application/libraries/excel_reader2.php", true);
		
		//require_once 'excel_reader2.php';
		//$this->load->library('Spreadsheet_Excel_Reader');
		include_once ( APPPATH."libraries/excel_reader2.php");
		
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$apppath = $this->config->item('APP_upload_path');
		$path=$apppath.'invoice/mesin_alat_ktr/'.$filename;
		$data = new Spreadsheet_Excel_Reader($path, false);
		
		echo $data->dump(true,true);
			
	
	}
	
	function proses_uploadmesin_dan_alat_ktr(){
	
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $id_mesin_upload = (isset($_POST['id_mesin_upload']) && !empty($_POST['id_mesin_upload']))?$_POST['id_mesin_upload']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$username = $this->session->userdata('DX_username');
		$tipe = 'MPA';
		/*  echo   "  exec('spi_mesindanalatktr @filename=''$filename'', @id_mesin_upload=$id_mesin_upload, @tipe=''$tipe'',  @username=''$username'' ')";
		die();  */
		$tipe='MPK';
		
		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_mesindanalatktr @filename=''$filename'', @id_mesin_upload=$id_mesin_upload, @tipe=''$tipe'',  @username=''$username'' ')
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ');
		 }  
		 echo json_encode($responce);
	}
	
	//---
	
	//upload data in mesin
	function view_barang_mesin_datain(){
	
		 $this->load->view('settings/view_barang_mesin_datain');
	
	}
	
	function data_uploaduploadmesin_in_out(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_data_mesin'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$tipe=(isset($_POST['tipedata']) && !empty($_POST['tipedata']))?$_POST['tipedata']:'';
		
		
		$where = " 1=1 and tipe='$tipe' ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "filename" ) {
						$searchString = $k->data;
						$where .= " and filename like  '%".$searchString."%'"; 
					} else if ( $k->field == "date_upload" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[date_upload],103)  =  '$searchString'"; 
					} else if ( $k->field == "status_upload" ) {
						$searchString = $k->data;
						$where .= " and status_upload like  '%".$searchString."%'"; 
					}  else if ( $k->field == "create_by" ) {
						$searchString = $k->data;
						$where .= " and create_by like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->uploadtbl_upload_data_mesinAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->uploadtbl_upload_data_mesinCountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_data_mesin']=$r->id_data_mesin; 
			$responce->rows[$i]['date_upload']=$r->date_upload; 
			$responce->rows[$i]['filename']=$r->filename; 
			$responce->rows[$i]['status_upload']=$r->status_upload;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['tipe']=$r->tipe;
			$responce->rows[$i]['filepath']=$r->filepath;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
    
	function data_dt_mpk_in(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_mesin_upload'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
			
		$where = " 1=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like  '%".$searchString."%'"; 
					} else if ( $k->field == "date_in" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[date_in],103)  =  '$searchString'"; 
					} else if ( $k->field == "part_name_customs" ) {
						$searchString = $k->data;
						$where .= " and part_name_customs like  '%".$searchString."%'"; 
					}  else if ( $k->field == "no_in" ) {
						$searchString = $k->data;
						$where .= " and no_in like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_mpk_inAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->data_dt_mpk_inCountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_mpk_in']=$r->id_mpk_in; 
			$responce->rows[$i]['date_in']=$r->date_in; 
			$responce->rows[$i]['no_in']=$r->no_in; 
			$responce->rows[$i]['part_name']=$r->part_name;
			$responce->rows[$i]['part_name_customs']=$r->part_name_customs;
			$responce->rows[$i]['part_no']=$r->part_no;
			$responce->rows[$i]['qty_out']=$r->qty_out;
			$responce->rows[$i]['qty_in']=$r->qty_in;
			$responce->rows[$i]['unit_in']=$r->unit_in;
			$responce->rows[$i]['unit_konversi']=$r->unit_konversi;
			$responce->rows[$i]['pengali']=$r->pengali;
			$responce->rows[$i]['box']=$r->box;
			$responce->rows[$i]['pack']=$r->pack;
			$responce->rows[$i]['harga']=$r->harga;
			$responce->rows[$i]['kdval']=$r->kdval;
			
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
    
	function data_dt_mpk_out(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_mpk_out'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		
		$where = " 1=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like  '%".$searchString."%'"; 
					} else if ( $k->field == "date_out" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[date_out],103)  =  '$searchString'"; 
					} else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$where .= " and part_name like  '%".$searchString."%'"; 
					}  else if ( $k->field == "no_out" ) {
						$searchString = $k->data;
						$where .= " and no_out like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_dt_mpk_outAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->data_dt_mpk_outCountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_mpk_out']=$r->id_mpk_out; 
			$responce->rows[$i]['date_out']=$r->date_out; 
			$responce->rows[$i]['no_out']=$r->no_out; 
			$responce->rows[$i]['part_name']=$r->part_name;
			$responce->rows[$i]['part_name_customs']=$r->part_name_customs;
			$responce->rows[$i]['part_no']=$r->part_no;
			$responce->rows[$i]['qty_out']=$r->qty_out;
			$responce->rows[$i]['qty_in']=$r->qty_in;
			$responce->rows[$i]['unit_out']=$r->unit_out;
			$responce->rows[$i]['unit_konversi']=$r->unit_konversi;
			$responce->rows[$i]['pengali']=$r->pengali;
			$responce->rows[$i]['box']=$r->box;
			$responce->rows[$i]['pack']=$r->pack;
			$responce->rows[$i]['harga']=$r->harga;
			$responce->rows[$i]['kdval']=$r->kdval;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	
	function upload_file_data_mesin_in(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_data_in_mpk';
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'MPKIN';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_in/';
		  $config['allowed_types'] = 'xls';
		  $config['max_size']  = 1024 * 100;
		  $config['encrypt_name'] = false;
		  $config['overwrite']=true;
		  $config['remove_spaces']=true;
		  $this->load->library('upload', $config);
		  if (!$this->upload->do_upload($file_element_name))
		  {
			 $status = 'error';
			 $msg = $this->upload->display_errors('', '');
		  }
		  else
		  {
			 $data = $this->upload->data();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_in/log/'.$data['file_name'];
				$filename=$data['file_name'];
				//echo $myFile; die();
				/* echo " exec('[spuload_stockawal_fg] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')";
				die(); */
				 
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[supload_data_mesin_in_out] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')
					
					END TRY
					BEGIN CATCH 
						SELECT 
						'error' AS status
						,ERROR_MESSAGE() AS description;
						
					END CATCH;
					
					");
				 
				 $rs = $qry->result_array();
				 // $r = $qry->result();		
				 // var_dump($r);die();
				 foreach ($rs as $row){
					 $status = $row['status'];
					 $msg = $row['description'];
				 }  
		
				
				$status = $status;
				$msg = $msg;
			 }
			 else
			 {
				unlink($data['full_path']);
				$status = "error";
				$msg = "Something went wrong when saving the file, please try again.";
			 }
		  }
		  @unlink($_FILES[$file_element_name]);
	   }
	   echo json_encode(array('status' => $status, 'msg' => $msg));
	
	
	}
	
	function deletefile_file_data_mesin_in(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$tipe = (isset($_POST['tipe']) && !empty($_POST['tipe']))?$_POST['tipe']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_mesin_upload = (isset($_POST['id_data_mesin']) && !empty($_POST['id_data_mesin']))?$_POST['id_data_mesin']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		//$username = $this->session->userdata('DX_user_id');
	    $username = $this->session->userdata('DX_username');
		$apppath = $this->config->item('APP_upload_path');
		
		$path=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_in/'.$filename;
		$pathnew=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_in/log/'.$filename;
		
		if (!file_exists($path)) {
		   echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
			die();
		}
		
		
		$qry = $this->db->query("
			BEGIN TRY
			
			 exec('[supload_data_mesin_in_out] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_mesin_upload ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		 $rs = $qry->result_array();
		 // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $status = $row['status'];
			 $msg = $row['description'];
		 }  
		//  echo json_encode($responce);
		 // $stmt = " exec('[spuload_assylist]') ";
		 // $qry = mssql_query($stmt); 
		 // $row = mssql_fetch_array($qry); 
		 // var_dump($row);die();
		
		$status = $status;
		$msg = $msg;
		
		if ($status=='00'){
			copy($path, $pathnew) or die(array('sts' => '00','desc' => "Unable to copy $path to $pathnew."));
			if (file_exists($path)) {
				unlink($path);
			} else {
				echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
				die();
			}
		}
		echo json_encode(array('sts' => $status, 'desc' => $msg));
	}
	
	function cek_data_data_in_mpk(){
		error_reporting(E_ALL ^ E_NOTICE);
		//$this->load->file("application/libraries/excel_reader2.php", true);
		
		//require_once 'excel_reader2.php';
		//$this->load->library('Spreadsheet_Excel_Reader');
		include_once ( APPPATH."libraries/excel_reader2.php");
		
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$apppath = $this->config->item('APP_upload_path');
		$path=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_in/'.$filename;
		$data = new Spreadsheet_Excel_Reader($path, false);
		
		echo $data->dump(true,true);
			
	
	}
	
	function proses_mesin_data_in_add(){
	
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $id_mesin_data_in = (isset($_POST['id_mesin_data_in']) && !empty($_POST['id_mesin_data_in']))?$_POST['id_mesin_data_in']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		$tipe = 'MPKIN';
		/*   echo   "   exec('spi_mesin_in_out @filename=''$filename'', @id_mesin_upload=$id_mesin_data_in, @tipe=''$tipe'',  @username=''$username'' ') ";
		die();  */

		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_mesin_in_out @filename=''$filename'', @id_mesin_upload=$id_mesin_data_in, @tipe=''$tipe'',  @username=''$username'' ')
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ');
		 }  
		 echo json_encode($responce);
	}
	
	//--
	//data out
	function view_barang_mesin_dataout(){
	
		$this->load->view('settings/view_barang_mesin_dataout');
	
	}
	
	function upload_file_data_mesin_out(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_data_out_mpk';
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'MPKOUT';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_out/';
		  $config['allowed_types'] = 'xls';
		  $config['max_size']  = 1024 * 100;
		  $config['encrypt_name'] = false;
		  $config['overwrite']=true;
		  $config['remove_spaces']=true;
		  $this->load->library('upload', $config);
		  if (!$this->upload->do_upload($file_element_name))
		  {
			 $status = 'error';
			 $msg = $this->upload->display_errors('', '');
		  }
		  else
		  {
			 $data = $this->upload->data();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_out/log/'.$data['file_name'];
				$filename=$data['file_name'];
				//echo $myFile; die();
				/* echo " exec('[spuload_stockawal_fg] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')";
				die(); */
				 
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[supload_data_mesin_in_out] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')
					
					END TRY
					BEGIN CATCH 
						SELECT 
						'error' AS status
						,ERROR_MESSAGE() AS description;
						
					END CATCH;
					
					");
				 
				 $rs = $qry->result_array();
				 // $r = $qry->result();		
				 // var_dump($r);die();
				 foreach ($rs as $row){
					 $status = $row['status'];
					 $msg = $row['description'];
				 }  
		
				
				$status = $status;
				$msg = $msg;
			 }
			 else
			 {
				unlink($data['full_path']);
				$status = "error";
				$msg = "Something went wrong when saving the file, please try again.";
			 }
		  }
		  @unlink($_FILES[$file_element_name]);
	   }
	   echo json_encode(array('status' => $status, 'msg' => $msg));
	
	
	}
	
	function deletefile_file_data_mesin_out(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$tipe = (isset($_POST['tipe']) && !empty($_POST['tipe']))?$_POST['tipe']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_mesin_upload = (isset($_POST['id_data_mesin']) && !empty($_POST['id_data_mesin']))?$_POST['id_data_mesin']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		//$username = $this->session->userdata('DX_user_id');
	    $username = $this->session->userdata('DX_username');
		$apppath = $this->config->item('APP_upload_path');
		
		$path=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_out/'.$filename;
		$pathnew=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_out/log/'.$filename;
		
		if (!file_exists($path)) {
		   echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
			die();
		}
		
		
		$qry = $this->db->query("
			BEGIN TRY
			
			 exec('[supload_data_mesin_in_out] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_mesin_upload ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		 $rs = $qry->result_array();
		 // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $status = $row['status'];
			 $msg = $row['description'];
		 }  
		//  echo json_encode($responce);
		 // $stmt = " exec('[spuload_assylist]') ";
		 // $qry = mssql_query($stmt); 
		 // $row = mssql_fetch_array($qry); 
		 // var_dump($row);die();
		
		$status = $status;
		$msg = $msg;
		
		if ($status=='00'){
			copy($path, $pathnew) or die(array('sts' => '00','desc' => "Unable to copy $path to $pathnew."));
			if (file_exists($path)) {
				unlink($path);
			} else {
				echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
				die();
			}
		}
		echo json_encode(array('sts' => $status, 'desc' => $msg));
	}
	
	function cek_data_out_mpk(){
		error_reporting(E_ALL ^ E_NOTICE);
		//$this->load->file("application/libraries/excel_reader2.php", true);
		
		//require_once 'excel_reader2.php';
		//$this->load->library('Spreadsheet_Excel_Reader');
		include_once ( APPPATH."libraries/excel_reader2.php");
		
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$apppath = $this->config->item('APP_upload_path');
		$path=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_out/'.$filename;
		$data = new Spreadsheet_Excel_Reader($path, false);
		
		echo $data->dump(true,true);
			
	
	}
	
	function proses_mesin_data_out_add(){
	
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $id_mesin_data_out = (isset($_POST['id_mesin_data_out']) && !empty($_POST['id_mesin_data_out']))?$_POST['id_mesin_data_out']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		$tipe = 'MPKOUT';
		/* echo   "    exec('spi_mesin_in_out @filename=''$filename'', @id_mesin_upload=$id_mesin_data_out, @tipe=''$tipe'',  @username=''$username'' ') ";
		die(); */ 

		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_mesin_in_out @filename=''$filename'', @id_mesin_upload=$id_mesin_data_out, @tipe=''$tipe'',  @username=''$username'' ')
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ');
		 }  
		 echo json_encode($responce);
	}
	
	//---
	//stock awal
	
	function view_barang_mesin_stockawal(){
	
		$this->load->view('settings/view_barang_mesin_stockawal');
	
	}
	
	function data_dt_mpk_stockawal(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_mpk_stockawal'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		
		$where = " 1=1 ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like  '%".$searchString."%'"; 
					} else if ( $k->field == "date_stockawal" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[date_stockawal],103)  =  '$searchString'"; 
					} else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$where .= " and part_name like  '%".$searchString."%'"; 
					}  
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_mpk_stockawalAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->data_mpk_stockawalCountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_mpk_stockawal']=$r->id_mpk_stockawal; 
			$responce->rows[$i]['date_stockawal']=$r->date_stockawal; 
			$responce->rows[$i]['part_name']=$r->part_name;
			$responce->rows[$i]['part_no']=$r->part_no;
			$responce->rows[$i]['qty']=$r->qty;
			$responce->rows[$i]['unit']=$r->unit;
			$responce->rows[$i]['unit_konversi']=$r->unit_konversi;
			$responce->rows[$i]['pengali']=$r->pengali;
			$responce->rows[$i]['box']=$r->box;
			$responce->rows[$i]['pack']=$r->pack;
			$responce->rows[$i]['harga']=$r->harga;
			$responce->rows[$i]['kdval']=$r->kdval;
		
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function upload_file_data_mesin_stockawal(){
	   $status = "";
	   $msg = "";
	   $file_element_name = 'userfile_stockawal_mpk';
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'MPKSTA';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_stockawal/';
		  $config['allowed_types'] = 'xls';
		  $config['max_size']  = 1024 * 100;
		  $config['encrypt_name'] = false;
		  $config['overwrite']=true;
		  $config['remove_spaces']=true;
		  $this->load->library('upload', $config);
		  if (!$this->upload->do_upload($file_element_name))
		  {
			 $status = 'error';
			 $msg = $this->upload->display_errors('', '');
		  }
		  else
		  {
			 $data = $this->upload->data();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_stockawal/log/'.$data['file_name'];
				$filename=$data['file_name'];
				//echo $myFile; die();
				/* echo " exec('[spuload_stockawal_fg] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')";
				die(); */
				 
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[supload_data_mesin_stockawal] @filepath=''$myFile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ')
					
					END TRY
					BEGIN CATCH 
						SELECT 
						'error' AS status
						,ERROR_MESSAGE() AS description;
						
					END CATCH;
					
					");
				 
				 $rs = $qry->result_array();
				 // $r = $qry->result();		
				 // var_dump($r);die();
				 foreach ($rs as $row){
					 $status = $row['status'];
					 $msg = $row['description'];
				 }  
		
				
				$status = $status;
				$msg = $msg;
			 }
			 else
			 {
				unlink($data['full_path']);
				$status = "error";
				$msg = "Something went wrong when saving the file, please try again.";
			 }
		  }
		  @unlink($_FILES[$file_element_name]);
	   }
	   echo json_encode(array('status' => $status, 'msg' => $msg));
	
	
	}
	
	function deletefile_file_data_mesin_stockawal(){
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$tipe = (isset($_POST['tipe']) && !empty($_POST['tipe']))?$_POST['tipe']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_mesin_upload = (isset($_POST['id_data_mesin']) && !empty($_POST['id_data_mesin']))?$_POST['id_data_mesin']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		//$username = $this->session->userdata('DX_user_id');
	    $username = $this->session->userdata('DX_username');
		$apppath = $this->config->item('APP_upload_path');
		
		$path=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_stockawal/'.$filename;
		$pathnew=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_stockawal/log/'.$filename;
		
		if (!file_exists($path)) {
		   echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
			die();
		}
		
		
		$qry = $this->db->query("
			BEGIN TRY
			
			 exec('[supload_data_mesin_stockawal] @filepath=''$path'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''delete'', @id=$id_mesin_upload ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		 $rs = $qry->result_array();
		 // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $status = $row['status'];
			 $msg = $row['description'];
		 }  
		//  echo json_encode($responce);
		 // $stmt = " exec('[spuload_assylist]') ";
		 // $qry = mssql_query($stmt); 
		 // $row = mssql_fetch_array($qry); 
		 // var_dump($row);die();
		
		$status = $status;
		$msg = $msg;
		
		if ($status=='00'){
			copy($path, $pathnew) or die(array('sts' => '00','desc' => "Unable to copy $path to $pathnew."));
			if (file_exists($path)) {
				unlink($path);
			} else {
				echo json_encode(array('sts' => '00', 'desc' => 'file does not exist'));
				die();
			}
		}
		echo json_encode(array('sts' => $status, 'desc' => $msg));
	}
	
	function cek_stockawal_mpk(){
		error_reporting(E_ALL ^ E_NOTICE);
		//$this->load->file("application/libraries/excel_reader2.php", true);
		
		//require_once 'excel_reader2.php';
		//$this->load->library('Spreadsheet_Excel_Reader');
		include_once ( APPPATH."libraries/excel_reader2.php");
		
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$apppath = $this->config->item('APP_upload_path');
		$path=$apppath.'invoice/mesin_alat_ktr/mesin_alat_kantor_stockawal/'.$filename;
		$data = new Spreadsheet_Excel_Reader($path, false);
		
		echo $data->dump(true,true);
			
	
	}
	
	function proses_mesin_stockawal_add(){
	
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
	    $id_mesin_stockawal = (isset($_POST['id_mesin_stockawal']) && !empty($_POST['id_mesin_stockawal']))?$_POST['id_mesin_stockawal']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		$tipe = 'MPKSTA';
		 // echo   "    exec('spi_mesin_stockawal @filename=''$filename'', @id_mesin_upload=$id_mesin_stockawal, @tipe=''$tipe'',  @username=''$username'' ') ";
		// die(); 

		$qry = $this->db->query("
			BEGIN TRY
			  exec('spi_mesin_stockawal @filename=''$filename'', @id_mesin_upload=$id_mesin_stockawal, @tipe=''$tipe'',  @username=''$username'' ')
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ');
		 }  
		 echo json_encode($responce);
	}
	
	function view_barang_mesin_rekapbc23(){
	
		$this->load->view('settings/view_barang_mesin_rekapbc23');
			
	}
	
	function downloadrekapxls(){
		
		$tgawal = (isset($_GET['tgawal']) && !empty($_GET['tgawal']))?$_GET['tgawal']:die('{"sts":"ERROR","desc":" Param  tgawal Tidak Ditemukan"}');
	    $tgakhir = (isset($_GET['tgakhir']) && !empty($_GET['tgakhir']))?$_GET['tgakhir']:die('{"sts":"ERROR","desc":" Param  tglakhir Tidak Ditemukan"}');
	    
	
		include_once ( APPPATH."libraries/PHPExcel.php");	
		include_once ( APPPATH."libraries/PHPExcel/IOFactory.php");	
		$phpExcel = new PHPExcel();
		$objTpl = PHPExcel_IOFactory::load(APPPATH."libraries/PHPExcel/templates/mesin_in.xls");	
		$objTpl->setActiveSheetIndex(1);  //set second sheet as active
	
		$qry_hdr = $this->db->query("
				/****** Script for SelectTopNRows command from SSMS  ******/

		SELECT        tbl_bc_in_hdr.id_bc_in_hdr, tbl_bc_in_hdr.PasokNama, tbl_bc_in_hdr.CAR, tbl_bc_in_dtl.Serial, tbl_bc_in_dtl.KdBrg, tbl_bc_in_dtl.BrgUrai, tbl_bc_in_dtl.JmlSat, tbl_bc_in_dtl.KdSat, tbl_bc_in_hdr.typedok, 
								 tbl_bc_in_hdr.bc_in_from_in, convert(date, BC23Tg, 126) as tgl_aju

						,tbl_bc_in_hdr.BC23No, convert(varchar, tbl_bc_in_hdr.BC23Tg, 103) as BC23Tg 
						,dbo.tbl_bc_in_hdr.typedok				


		FROM            tbl_bc_in_dtl RIGHT OUTER JOIN
								 tbl_bc_in_hdr ON tbl_bc_in_dtl.id_bc_in_hdr = tbl_bc_in_hdr.id_bc_in_hdr

						where (bc_in_from_in = 'INVMS' and BC23No is not null) or JnsBarangDtl = '03' or JnsBarangDtl = '02' 
						and convert(varchar,  tbl_bc_in_hdr.BC23Tg,126) between  '$tgawal' and '$tgakhir'
				");
		
		$rs_hdr = $qry_hdr->result_array();
		
		$CAR = '';
		$Serial = '';
		$KdBrg = '';
		$BrgUrai = '';
		$JmlSat = '';
		$typedok = '';
		$bc_in_from_in = '';
		$tgl_aju = '';
		$BC23Tg = '';
		$BC23No = '';
		$id_bc_in_hdr=0;
		
		$i = 1;
		$j = '';
		$k = '';
		$m = '';
		foreach ($rs_hdr as $r ){
			$k = 1 + $i;
			$j = "$k";
			$CAR = $r['CAR'];
			$BC23No = $r['BC23No'];
			$id_bc_in_hdr = $r['id_bc_in_hdr'];
			
									
			$objTpl->getActiveSheet()->setCellValueExplicit("A".$j, $CAR, PHPExcel_Cell_DataType::TYPE_STRING);
			$objTpl->getActiveSheet()->setCellValueExplicit("B".$j, $BC23No, PHPExcel_Cell_DataType::TYPE_STRING);
			$objTpl->getActiveSheet()->setCellValue("C".$j, $r["BC23Tg"]);
			$objTpl->getActiveSheet()->setCellValue("D".$j, $r["PasokNama"]);
			$objTpl->getActiveSheet()->setCellValueExplicit("E".$j,$r["KdBrg"], PHPExcel_Cell_DataType::TYPE_STRING);
			$objTpl->getActiveSheet()->setCellValueExplicit("F".$j, $r["BrgUrai"], PHPExcel_Cell_DataType::TYPE_STRING);
			$objTpl->getActiveSheet()->setCellValue("G".$j, $r["JmlSat"]);
			$objTpl->getActiveSheet()->setCellValue("H".$j, $r["KdSat"]);
			$objTpl->getActiveSheet()->setCellValue("K".$j, $r["typedok"]);
			$i++;
			
			$qry_cntdok = $this->db->query(" 
				select count(*) as  cnt from [tbl_bc_in_dok] where id_bc_in_hdr=$id_bc_in_hdr and DokKd='380';
			");
			
			$rs_cntdok = $qry_cntdok->result_array();
			foreach ($rs_cntdok as $rs_cntdokk){
				$cntdok = 	$rs_cntdokk["cnt"];		
			}
			if ($cntdok == $r['Serial']){
			
				$qry_cdok = $this->db->query(" 
					select DokNo,  convert(varchar,[DokTg], 103)  as DokTg from [tbl_bc_in_dok] where id_bc_in_hdr=$id_bc_in_hdr and DokKd='380';
				");
				$rs_cdok= $qry_cdok->result_array();
				
				$z = 1;
				$w = 0;
				foreach ($rs_cdok as $rrs_cdok){
					$x = $z - $cntdok; 
					$w = $j + $x;
					$objTpl->getActiveSheet()->setCellValueExplicit("I".$w, $rrs_cdok["DokNo"], PHPExcel_Cell_DataType::TYPE_STRING);	
					$objTpl->getActiveSheet()->setCellValueExplicit("J".$j, $rrs_cdok["DokTg"], PHPExcel_Cell_DataType::TYPE_STRING);	
					
					$z++;
				}
					
				
			}
		}
			
		
		
		$filename = 'BC23_rekapdatamesin_'.$tgawal. '_SD_'.$tgakhir . '.xls';
		header("Content-type:application/vnd.ms-excel");
		header("Content-disposition:attachment; filename=$filename"); 
		header("Pragma:no-cache");
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		header("Expires:0");

		$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5');  //downloadable file is in Excel 2003 format (.xls)
		$objWriter->save('php://output');  //send it to user, of course you can save it to disk also!
		 
		exit; //done.. exiting!
	
	}
	
	function view_alatkantor_memo(){
		
		$this->load->view('settings/view_alatkantor_memo');
		
	}
	
	function data_alatkantor_memo_Allx(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_memo'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		$fill = isset($_POST['fill'])?$_POST['fill']:'0';
		if($fill == 'EXIM' ){
			$status_data = isset($_POST['status_data'])?$_POST['status_data']:'0';
			$TIPEOUT = isset($_POST['TIPEOUT'])?$_POST['TIPEOUT']:'0';
			$where = " status_data = '$status_data' "; 
			if ($TIPEOUT == 'NONSCRAP'){
					$where .= " AND tipe_out <> 'SCRAP' "; 
			} else if ($TIPEOUT == 'SCRAP'){
				$where .= " AND tipe_out = 'SCRAP' "; 
			} 
		} else if ($fill == 'SCRAP' ){
			$status_data = isset($_POST['status_data'])?$_POST['status_data']:'NEW';
			$where = " tipe_out = 'SCRAP' and status_data='$status_data' ";			
		}	
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "nomor_memo" ) {
						$searchString = $k->data;
						$where .= " and nomor_memo like '%".$searchString."%'"; 
					}  else if ( $k->field == "car" ) {
						$searchString = $k->data;
						$where .= " and car like  '%".$searchString."%'"; 
					}  else if ( $k->field == "kode_pembeli" ) {
						$searchString = $k->data;
						$where .= " and kode_pembeli like  '%".$searchString."%'"; 
					} else if ( $k->field == "nama_pembeli" ) {
						$searchString = $k->data;
						$where .= " and nama_pembeli like  '%".$searchString."%'"; 
					} else if ( $k->field == "tipe_out" ) {
						$searchString = $k->data;
						$where .= " and tipe_out like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_alatkantor_memo_All($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->data_alatkantor_memo_CountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
		foreach($records as $r){
			$responce->rows[$i]['id_memo']=$r->id_memo;
			$responce->rows[$i]['nomor_memo']=$r->nomor_memo;
			$responce->rows[$i]['tgl_memo']=$r->tgl_memo;
			$responce->rows[$i]['npwp_pembeli']=$r->npwp_pembeli;
			$responce->rows[$i]['kode_pembeli']=$r->kode_pembeli;
			$responce->rows[$i]['harga_penyerahan']=$r->harga_penyerahan;
			$responce->rows[$i]['id_ceisa_hdr']=$r->id_ceisa_hdr;
			$responce->rows[$i]['bc_no']=$r->bc_no;
			$responce->rows[$i]['tgl_bc']=$r->tgl_bc;;
			$responce->rows[$i]['car']=$r->car;
			$responce->rows[$i]['nama_pembeli']=$r->nama_pembeli;
			$responce->rows[$i]['typedok']=$r->typedok;
			$responce->rows[$i]['tipe_out']=$r->tipe_out;
			$responce->rows[$i]['kdval']=$r->kdval;
			$responce->rows[$i]['ndpbm']=$r->ndpbm;
			$responce->rows[$i]['bruto']=$r->bruto;
			$responce->rows[$i]['status_data']=$r->status_data;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
			$i++;
		}
		echo json_encode($responce);
		
	
	}
	
	function view_alatkantor_memo_update(){
		$command = (isset($_POST['command']) && !empty($_POST['command']))?$_POST['command']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		$id_memo='';
		$nomor_memo = '';
		$tanggal_memo = '';
		$tipe_out = '';
		$harga_penyerahan = '';
		$bruto = '';
		$kode_pembeli = '';
		$kdval = '';
		$npwp_pembeli = '';
		$nama_pembeli = '';
		if ($command == 'UPDATE'){
			$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
			$qry = $this->db->query("
				select * from tbl_alatkantor_memo 
				where id_memo = $id_memo
			
			");	
			
			foreach ($qry->result() as $r ){
				$id_memo=$r->id_memo;
				$nomor_memo=$r->nomor_memo;
				$tanggal_memo=$r->tgl_memo;
				$tipe_out=$r->tipe_out;
				$harga_penyerahan=$r->harga_penyerahan;
				$kode_pembeli=$r->kode_pembeli;
				$kdval=$r->kdval;
				$npwp_pembeli=$r->npwp_pembeli;
				$nama_pembeli=$r->nama_pembeli;
				$bruto=$r->bruto;
			}
			
		}
		$data['command'] = $command;
		$data['id_memo'] = $id_memo;
		$data['nomor_memo'] = $nomor_memo;
		$data['tanggal_memo'] = $tanggal_memo;
		$data['tipe_out'] = $tipe_out;
		$data['harga_penyerahan'] = $harga_penyerahan;
		$data['kode_pembeli'] = $kode_pembeli;
		$data['kdval'] = $kdval;
		$data['npwp_pembeli'] = $npwp_pembeli;
		$data['nama_pembeli'] = $nama_pembeli;
		$data['bruto'] = $bruto;
		$this->load->view('settings/view_alatkantor_memo_update', $data);
		
	}
	
	
	function view_alatkantor_memo_update_view(){
		$command = (isset($_POST['command']) && !empty($_POST['command']))?$_POST['command']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		$id_memo='';
		$nomor_memo = '';
		$tanggal_memo = '';
		$tipe_out = '';
		$harga_penyerahan = '';
		$bruto = '';
		$kode_pembeli = '';
		$kdval = '';
		$npwp_pembeli = '';
		$nama_pembeli = '';
		if ($command == 'UPDATE'){
			$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
			$qry = $this->db->query("
				select * from tbl_alatkantor_memo 
				where id_memo = $id_memo
			
			");	
			
			foreach ($qry->result() as $r ){
				$id_memo=$r->id_memo;
				$nomor_memo=$r->nomor_memo;
				$tanggal_memo=$r->tgl_memo;
				$tipe_out=$r->tipe_out;
				$harga_penyerahan=$r->harga_penyerahan;
				$kode_pembeli=$r->kode_pembeli;
				$kdval=$r->kdval;
				$npwp_pembeli=$r->npwp_pembeli;
				$nama_pembeli=$r->nama_pembeli;
				$bruto=$r->bruto;
			}
			
		}
		$data['command'] = $command;
		$data['id_memo'] = $id_memo;
		$data['nomor_memo'] = $nomor_memo;
		$data['tanggal_memo'] = $tanggal_memo;
		$data['tipe_out'] = $tipe_out;
		$data['harga_penyerahan'] = $harga_penyerahan;
		$data['kode_pembeli'] = $kode_pembeli;
		$data['kdval'] = $kdval;
		$data['npwp_pembeli'] = $npwp_pembeli;
		$data['nama_pembeli'] = $nama_pembeli;
		$data['bruto'] = $bruto;
		$this->load->view('settings/view_alatkantor_memo_update_view', $data);
		
	}
	
	function update_memo_alatkantor(){
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:'0';
		$nomor_memo = (isset($_POST['nomor_memo']) && !empty($_POST['nomor_memo']))?$_POST['nomor_memo']:die('{"sts":"ERROR","desc":" Param  NOMOR MEMO Tidak Ditemukan"}');
		$tanggal_memo = (isset($_POST['tanggal_memo']) && !empty($_POST['tanggal_memo']))?$_POST['tanggal_memo']:die('{"sts":"ERROR","desc":" Param  TGL MEMO Tidak Ditemukan"}');
		$tipe_out = (isset($_POST['tipe_out']) && !empty($_POST['tipe_out']))?$_POST['tipe_out']:die('{"sts":"ERROR","desc":" Param  TIPE OUT Tidak Ditemukan"}');
		$harga_penyerahan = (isset($_POST['harga_penyerahan']) && !empty($_POST['harga_penyerahan']))?$_POST['harga_penyerahan']:die('{"sts":"ERROR","desc":" Param  HARGA PENYERAHAN Tidak Ditemukan"}');
		$bruto = (isset($_POST['bruto']) && !empty($_POST['bruto']))?$_POST['bruto']:die('{"sts":"ERROR","desc":" Param  BRUTO Tidak Ditemukan"}');
		$kode_pembeli = (isset($_POST['kode_pembeli']) && !empty($_POST['kode_pembeli']))?$_POST['kode_pembeli']:die('{"sts":"ERROR","desc":" Param  KD PEMBELI Tidak Ditemukan"}');
		$kdval = (isset($_POST['kdval']) && !empty($_POST['kdval']))?$_POST['kdval']:die('{"sts":"ERROR","desc":" Param   KDVAL Tidak Ditemukan"}');
		
		
		$command = (isset($_POST['command']) && !empty($_POST['command']))?$_POST['command']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		
		
		$qry = $this->db->query("
			declare @command varchar(19) = '$command'
			if (select count(*) from tbl_data_supplier where subcode_as400 = '$kode_pembeli' )	= 0
			begin	
				SELECT 
					'06' AS status
					,' DATA SUPPLIER TIDAK DITEMUKAN ' AS description
					,'' as id_memo
				 return
			end
			declare @supplier_name varchar(100), @NPWP varchar(100), @id_memo bigint
			select 
			top 1
				@supplier_name=supplier_name
				,@NPWP=NPWP
			from tbl_data_supplier
			where subcode_as400 = '$kode_pembeli' 
			BEGIN TRY
				
				if @command = 'CREATE'
				begin
					insert into tbl_alatkantor_memo (
						dbo.tbl_alatkantor_memo.nomor_memo,
			dbo.tbl_alatkantor_memo.tgl_memo,
			dbo.tbl_alatkantor_memo.npwp_pembeli,
			dbo.tbl_alatkantor_memo.kode_pembeli,
			dbo.tbl_alatkantor_memo.harga_penyerahan,
			dbo.tbl_alatkantor_memo.create_date,
			dbo.tbl_alatkantor_memo.create_by,
			dbo.tbl_alatkantor_memo.update_date,
			dbo.tbl_alatkantor_memo.update_by,
			dbo.tbl_alatkantor_memo.tipe_out,
			dbo.tbl_alatkantor_memo.status_data,
			dbo.tbl_alatkantor_memo.nama_pembeli,
			dbo.tbl_alatkantor_memo.kdval,
			dbo.tbl_alatkantor_memo.bruto	
					
					
					) VALUES (
					'$nomor_memo'
					,'$tanggal_memo'
					,@NPWP
					,'$kode_pembeli'
					,$harga_penyerahan
					,GETDATE()
					,'$username'
					,GETDATE()
					,'$username'
					,'$tipe_out'
					,'NEW'
					,@supplier_name
					,'$kdval'
					,$bruto
					
					)
				set @id_memo = SCOPE_IDENTITY() 	
				end
				
				if @command = 'UPDATE'
				begin
					if (select status_data from tbl_alatkantor_memo where id_memo=$id_memo) <> 'NEW'
					begin
						set @id_memo = $id_memo
						SELECT 
						'00' AS status
						,' DATA SUDAH PROSES EXIM, BATALKAN DAHULU' AS description
						,CONVERT(varchar, @id_memo) as id_memo
						
						return
					
					end
					
					update tbl_alatkantor_memo set  
					dbo.tbl_alatkantor_memo.nomor_memo = '$nomor_memo',
					dbo.tbl_alatkantor_memo.tgl_memo = '$tanggal_memo',
					dbo.tbl_alatkantor_memo.npwp_pembeli = @NPWP,
					dbo.tbl_alatkantor_memo.kode_pembeli = '$kode_pembeli',
					dbo.tbl_alatkantor_memo.harga_penyerahan = $harga_penyerahan,
					dbo.tbl_alatkantor_memo.update_date = GETDATE(),
					dbo.tbl_alatkantor_memo.update_by = '$username',
					dbo.tbl_alatkantor_memo.nama_pembeli = @supplier_name,
					dbo.tbl_alatkantor_memo.kdval = '$kdval',
					dbo.tbl_alatkantor_memo.bruto = '$bruto'	
					where id_memo = $id_memo
					
					set @id_memo = $id_memo
				
				end
				if @command = 'DELETE'
				begin
					if (select status_data from tbl_alatkantor_memo where id_memo=$id_memo) <> 'NEW'
					begin
						set @id_memo = $id_memo
						SELECT 
						'00' AS status
						,' DATA SUDAH PROSES EXIM, BATALKAN DAHULU' AS description
						,CONVERT(varchar, $id_memo) as id_memo
						
						return
					
					end
					delete from tbl_alatkantor_memo where id_memo = 	$id_memo
					delete from tbl_alatkantor_out  where id_memo_bp =  $id_memo and doc_out_to = 3	
				end
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description
				,CONVERT(varchar, @id_memo) as id_memo
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ', 'id_memo' => $row['id_memo']);
		 }  
		 echo json_encode($responce);
		
		
	}
	
	function update_memo_alatkantor_dtl(){
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param  id_memoTidak Ditemukan"}');
		$part_no = (isset($_POST['part_no']) && !empty($_POST['part_no']))?$_POST['part_no']:die('{"sts":"ERROR","desc":" Param  part_no Tidak Ditemukan"}');
		$part_name = (isset($_POST['part_name']) && !empty($_POST['part_name']))?$_POST['part_name']:die('{"sts":"ERROR","desc":" Param  part_name Tidak Ditemukan"}');
		$hs_code = (isset($_POST['hs_code']) && !empty($_POST['hs_code']))?$_POST['hs_code']:die('{"sts":"ERROR","desc":" Param  hs_code Tidak Ditemukan"}');
		$uom = (isset($_POST['uom']) && !empty($_POST['uom']))?$_POST['uom']:die('{"sts":"ERROR","desc":" Param  HARGA uom Tidak Ditemukan"}');
		$qty = (isset($_POST['qty']) && !empty($_POST['qty']))?$_POST['qty']:die('{"sts":"ERROR","desc":" Param  qty Tidak Ditemukan"}');
		$price = (isset($_POST['price']) && !empty($_POST['price']))?$_POST['price']:die('{"sts":"ERROR","desc":" Param  price Tidak Ditemukan"}');
		$jmkemas = (isset($_POST['jmkemas']) && !empty($_POST['jmkemas']))?$_POST['jmkemas']:'0';
		$jnkemas = (isset($_POST['jnkemas']) && !empty($_POST['jnkemas']))?$_POST['jnkemas']:'';
		$netto = (isset($_POST['netto']) && !empty($_POST['netto']))?$_POST['netto']:die('{"sts":"ERROR","desc":" Param   netto Tidak Ditemukan"}');
		$id_bp_out_dtl = (isset($_POST['id_bp_out_dtl']) && !empty($_POST['id_bp_out_dtl']))?$_POST['id_bp_out_dtl']:'0';
		$command = (isset($_POST['command']) && !empty($_POST['command']))?$_POST['command']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		
		
		$qry = $this->db->query("
			declare @command varchar(19) = '$command'
			declare @id_memo bigint = $id_memo
			if (select count(*) from tbl_data_bahan_penolong where part_no = '$part_no' )	= 0
			begin	
				SELECT 
					'06' AS status
					,' DATA BARANG TIDAK DITEMUKAN ' AS description
					,'' as id_bp_out_dtl
					,'' as nilinv
				 return
			end
			declare @id_bp_out_dtl bigint, @nomor_memo varchar(100), @tgl_memo date
			select 
				@nomor_memo = nomor_memo
				,@tgl_memo = tgl_memo
			from tbl_alatkantor_memo where id_memo = $id_memo
			
			if (select status_data from tbl_alatkantor_memo where id_memo=$id_memo) <> 'NEW'
			begin
				set @id_memo = $id_memo
				SELECT 
				'00' AS status
				,' DATA SUDAH PROSES EXIM, BATALKAN DAHULU' AS description
				,CONVERT(varchar, $id_bp_out_dtl) as id_bp_out_dtl
				,'' as nilinv
				
				return
			
			end
			

			BEGIN TRY
				
				if @command = 'CREATE'
				begin
					insert into tbl_alatkantor_out (
						
						dbo.tbl_alatkantor_out.part_no,
						dbo.tbl_alatkantor_out.part_name,
						dbo.tbl_alatkantor_out.qty,
						dbo.tbl_alatkantor_out.qty_out,
						dbo.tbl_alatkantor_out.uom,
						dbo.tbl_alatkantor_out.doc_no,
						dbo.tbl_alatkantor_out.doc_date,
						dbo.tbl_alatkantor_out.doc_out_to,
						dbo.tbl_alatkantor_out.price,
						dbo.tbl_alatkantor_out.status_data,
						dbo.tbl_alatkantor_out.id_memo_bp,
						dbo.tbl_alatkantor_out.hs_kode,
						dbo.tbl_alatkantor_out.jmkemas,
						dbo.tbl_alatkantor_out.jnkemas,
						dbo.tbl_alatkantor_out.netto
					
					
					) VALUES (
						'$part_no'
						,'$part_name'
						,$qty
						,$qty
						,'$uom'
						,@nomor_memo
						,@tgl_memo
						,3
						,$price
						,'NEW'
						,$id_memo
						,'$hs_code'
						,$jmkemas
						,'$jnkemas'
						,$netto
					)
				set @id_bp_out_dtl = SCOPE_IDENTITY() 	
				end
				
				if @command = 'UPDATE'
				begin
					update tbl_alatkantor_out set 
						dbo.tbl_alatkantor_out.part_no='$part_no'
						,dbo.tbl_alatkantor_out.part_name='$part_name'
						,dbo.tbl_alatkantor_out.qty=$qty
						,dbo.tbl_alatkantor_out.qty_out=$qty
						,dbo.tbl_alatkantor_out.uom='$uom'
						,dbo.tbl_alatkantor_out.price=$price
						,dbo.tbl_alatkantor_out.hs_kode='$hs_code'
						,dbo.tbl_alatkantor_out.jmkemas=$jmkemas
						,dbo.tbl_alatkantor_out.jnkemas='$jnkemas'
						,dbo.tbl_alatkantor_out.netto=$netto
					where id_memo_bp =  $id_memo and id_bp_out_dtl = $id_bp_out_dtl and doc_out_to = 3
				end
				
				if @command = 'DELETE'
				begin
					delete from tbl_alatkantor_out where id_memo_bp =  $id_memo and id_bp_out_dtl = $id_bp_out_dtl and doc_out_to = 3
				end
				declare @nilinv decimal(38,4)
				set @nilinv = (select round(sum(qty * price), 2) from dbo.tbl_alatkantor_out where id_memo_bp =  $id_memo and doc_out_to = 3)
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description
				,CONVERT(varchar, @id_bp_out_dtl) as id_bp_out_dtl
				,CONVERT(varchar, @nilinv) as nilinv
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ', 'id_bp_out_dtl' => $row['id_bp_out_dtl'], 'nilinv' => $row['nilinv']);
		 }  
		 echo json_encode($responce);
		
		
	}
	
	
	function update_memo_exim(){
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param  id_memoTidak Ditemukan"}');
		$command = (isset($_POST['command']) && !empty($_POST['command']))?$_POST['command']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		$status_data = (isset($_POST['status_data']) && !empty($_POST['status_data']))?$_POST['status_data']:die('{"sts":"ERROR","desc":" Param  filename Tidak Ditemukan"}');
		
		
		$qry = $this->db->query("
			
			
			BEGIN TRY
				update tbl_alatkantor_memo set
				status_data = '$status_data'
				where id_memo = $id_memo
				
				if '$status_data' =  'PROSESEXIM'
				begin
					update tbl_alatkantor_out set
					status_data = 'APPROVED'
					where id_memo_bp = $id_memo and doc_out_to = 3
				end	 
				if '$status_data' =  'NEW'
				begin
					update tbl_alatkantor_out set
					status_data = 'NEW'
					where id_memo_bp = $id_memo and doc_out_to = 3
				end	 
				
				
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description
				,CONVERT(varchar, $id_memo) as id_memo
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ', 'id_memo' => $row['id_memo']);
		 }  
		 echo json_encode($responce);
		
		
	}
	
	function data_alatkantor_out_memo(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_bp_out_dtl'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		
		$doc_out_to = isset($_POST['doc_out_to'])?$_POST['doc_out_to']:die();
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:'0';
		$where = " doc_out_to=3 and  id_memo_bp=$id_memo ";
		
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "no_invoice" ) {
						$searchString = $k->data;
						$where .= " and no_invoice like  '%".$searchString."%'"; 
					} else if ( $k->field == "tgl_invoice" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[tgl_invoice],126)  =  '$searchString'"; 
					} else if ( $k->field == "part_no" ) {
						$searchString = $k->data;
						$where .= " and part_no like  '%".$searchString."%'"; 
					}  else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$where .= " and part_name like  '%".$searchString."%'"; 
					}  else if ( $k->field == "doc_no" ) {
						$searchString = $k->data;
						$where .= " and doc_no like  '%".$searchString."%'"; 
					}  else if ( $k->field == "filename" ) {
						$searchString = $k->data;
						$where .= " and filename like  '%".$searchString."%'"; 
					}  else if ( $k->field == "car" ) {
						$searchString = $k->data;
						$where .= " and car like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_settings->data_alatkantor_outAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_settings->data_alatkantor_outcountAll($where);
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
        if ($page > $total_pages) $page=$total_pages;
        
        $responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
        foreach($records as $r){
						
			$responce->rows[$i]['id_bp_out_dtl']=$r->id_bp_out_dtl;
			$responce->rows[$i]['container_number']=$r->container_number;
			$responce->rows[$i]['no_invoice']=$r->no_invoice;
			$responce->rows[$i]['tgl_invoice']=$r->tgl_invoice;
			$responce->rows[$i]['part_no']=$r->part_no;
			$responce->rows[$i]['part_name']=$r->part_name;
			$responce->rows[$i]['qty']=$r->qty;
			$responce->rows[$i]['qty_out']=$r->qty_out;
			$responce->rows[$i]['uom']=$r->uom;
			$responce->rows[$i]['doc_no']=$r->doc_no;
			$responce->rows[$i]['doc_date']=$r->doc_date;
			$responce->rows[$i]['doc_out_to']=$r->doc_out_to;
			$responce->rows[$i]['filename']=$r->filename;
			$responce->rows[$i]['car']=$r->car;
			$responce->rows[$i]['create_date']=$r->create_date;
			$responce->rows[$i]['create_by']=$r->create_by;
			$responce->rows[$i]['update_date']=$r->update_date;
			$responce->rows[$i]['update_by']=$r->update_by;
			$responce->rows[$i]['approved_date']=$r->approved_date;
			$responce->rows[$i]['price']=$r->price;
			$responce->rows[$i]['status_data']=$r->status_data;
			$responce->rows[$i]['kode_buyer']=$r->kode_buyer;
			$responce->rows[$i]['nama_buyer']=$r->nama_buyer;
			$responce->rows[$i]['id_memo_bp']=$r->id_memo_bp;
			$responce->rows[$i]['bruto']=$r->bruto;
			$responce->rows[$i]['hs_kode']=$r->hs_kode;
			$responce->rows[$i]['jmkemas']=$r->jmkemas;
			$responce->rows[$i]['jnkemas']=$r->jnkemas;
			$responce->rows[$i]['netto']=$r->netto;
			$responce->rows[$i]['hargaxqty']=(float)$r->qty * (float)$r->price;	
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function view_alatkantor_memo_exim_bc27(){
		$data['bruto'] = '';
		$this->load->view('settings/view_alatkantor_memo_exim_bc27', $data);
		
	}
	function view_alatkantor_memo_exim_bc25(){
		$data['bruto'] = '';
		$this->load->view('settings/view_alatkantor_memo_exim_bc25', $data);
		
	}
	
	function view_alatkantor_memo_scrap(){
		$data['bruto'] = '';
		$this->load->view('settings/view_alatkantor_memo_scrap', $data);
		
	}
	
	function update_memo_scrap_alatkantor(){
		$id_memo_bp = (isset($_POST['id_memo_bp']) && !empty($_POST['id_memo_bp']))?$_POST['id_memo_bp']:die('{"sts":"ERROR","desc":" Param  id_memo Tidak Ditemukan"}');
		$id_bp_out_dtl = (isset($_POST['id_bp_out_dtl']) && !empty($_POST['id_bp_out_dtl']))?$_POST['id_bp_out_dtl']:die('{"sts":"ERROR","desc":" Param  id_bp_out_dtl Tidak Ditemukan"}');
		$part_no = (isset($_POST['part_no']) && !empty($_POST['part_no']))?$_POST['part_no']:die('{"sts":"ERROR","desc":" Param  part_no Tidak Ditemukan"}');
		$part_name = (isset($_POST['part_name']) && !empty($_POST['part_name']))?$_POST['part_name']:die('{"sts":"ERROR","desc":" Param  part_name Tidak Ditemukan"}');
		$qty = (isset($_POST['qty_scrap']) && !empty($_POST['qty_scrap']))?$_POST['qty_scrap']:die('{"sts":"ERROR","desc":" Param  qty Tidak Ditemukan"}');
		$jmkemas = (isset($_POST['jmkemas_scrap']) && !empty($_POST['jmkemas_scrap']))?$_POST['jmkemas_scrap']:die('{"sts":"ERROR","desc":" Param  jmkemas Tidak Ditemukan"}');
		$jnkemas = (isset($_POST['jnkemas_scrap']) && !empty($_POST['jnkemas_scrap']))?$_POST['jnkemas_scrap']:die('{"sts":"ERROR","desc":" Param  jnkemas Tidak Ditemukan"}');
		$netto_scrap = (isset($_POST['netto_scrap']) && !empty($_POST['netto_scrap']))?$_POST['netto_scrap']:die('{"sts":"ERROR","desc":" Param  netto_scrap Tidak Ditemukan"}');
		$bruto_scrap = (isset($_POST['bruto_scrap']) && !empty($_POST['bruto_scrap']))?$_POST['bruto_scrap']:die('{"sts":"ERROR","desc":" Param  bruto_scrap Tidak Ditemukan"}');
		$harga_scrap = (isset($_POST['harga_scrap']) && !empty($_POST['harga_scrap']))?$_POST['harga_scrap']:die('{"sts":"ERROR","desc":" Param  harga_scrap Tidak Ditemukan"}');
		
	
		$username = $this->session->userdata('DX_username');
		
		$q = $this->db->query("
			BEGIN TRY
				BEGIN TRANSACTION
			if (select count(*) from tbl_alatkantor_memo_scrap where id_memo = $id_memo_bp and id_bp_out_dtl= $id_bp_out_dtl) = 0
			begin
				
				insert into tbl_alatkantor_memo_scrap (
						
						dbo.tbl_alatkantor_memo_scrap.id_memo,
						dbo.tbl_alatkantor_memo_scrap.id_bp_out_dtl,
						dbo.tbl_alatkantor_memo_scrap.kode_scrap,
						dbo.tbl_alatkantor_memo_scrap.nama_scrap,
						dbo.tbl_alatkantor_memo_scrap.qty_scrap,
						dbo.tbl_alatkantor_memo_scrap.satuan,
						dbo.tbl_alatkantor_memo_scrap.bruto_scrap,
						dbo.tbl_alatkantor_memo_scrap.harga_scrap,
						dbo.tbl_alatkantor_memo_scrap.jmkemas_scrap,
						dbo.tbl_alatkantor_memo_scrap.jnkemas_scrap,
						dbo.tbl_alatkantor_memo_scrap.netto_scrap
											
					
					) VALUES (
						$id_memo_bp
						,$id_bp_out_dtl
						,'$part_no'
						,'$part_name'
						,$qty
						,'KGM'
						,$bruto_scrap
						,$harga_scrap 
						,$jmkemas
						,'$jnkemas'
						,$netto_scrap
						
					)
			end	else 
			begin
				update tbl_alatkantor_memo_scrap set 
				dbo.tbl_alatkantor_memo_scrap.id_memo = $id_memo_bp	
				,dbo.tbl_alatkantor_memo_scrap.id_bp_out_dtl = $id_bp_out_dtl	
				,dbo.tbl_alatkantor_memo_scrap.kode_scrap = '$part_no'	
				,dbo.tbl_alatkantor_memo_scrap.nama_scrap = '$part_name'	
				,dbo.tbl_alatkantor_memo_scrap.qty_scrap = $qty	
				,dbo.tbl_alatkantor_memo_scrap.satuan = 'KGM'	
				,dbo.tbl_alatkantor_memo_scrap.bruto_scrap = $bruto_scrap	
				,dbo.tbl_alatkantor_memo_scrap.harga_scrap = $harga_scrap 	
				,dbo.tbl_alatkantor_memo_scrap.jmkemas_scrap = $jmkemas	
				,dbo.tbl_alatkantor_memo_scrap.jnkemas_scrap = '$jnkemas'	
				,dbo.tbl_alatkantor_memo_scrap.netto_scrap = $netto_scrap	
				where id_memo = $id_memo_bp and id_bp_out_dtl= $id_bp_out_dtl

			end
			COMMIT
			END TRY
			BEGIN CATCH
				-- Whoops, there was an error
				IF @@TRANCOUNT > 0
				 ROLLBACK
		-- Raise an error with the details of the exception
			DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
			Set @ErrMsg = ERROR_MESSAGE()
			set @ErrSeverity = ERROR_SEVERITY()
			select @ErrMsg as status,@ErrSeverity as description
			RAISERROR(@ErrMsg, @ErrSeverity, 1)
			END CATCH 	
			
			SELECT 
				'00' AS status
				,' SUKSES' AS description
				
					
		
		");
		
		
		$rs = $q->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description']);
		 }  
		 echo json_encode($responce);
		
		
	}
	
	function autocomplete_barang(){
		$namasupplier = isset($_GET['name_startsWith'])?$_GET['name_startsWith']:'';
		$where = " (part_no like '%$namasupplier%' or part_name like '%$namasupplier%' ) " ;
		$q = $this->db->query("
			select
			
		dbo.tbl_data_alat_kantor.part_no,
dbo.tbl_data_alat_kantor.part_name,
dbo.tbl_data_alat_kantor.part_name_customs,
dbo.tbl_data_alat_kantor.hs_code,
dbo.tbl_data_alat_kantor.kode_barang,
dbo.tbl_data_alat_kantor.uom
			from
			tbl_data_alat_kantor where $where
		
		");
        $i=0;
		$responce = '';
        foreach($q->result() as $r){
			$responce[$i]['part_no']=$r->part_no; 
			$responce[$i]['part_name']=$r->part_name; 
			$responce[$i]['part_name_customs']=$r->part_name_customs; 
$responce[$i]['hs_code']=$r->hs_code;  
$responce[$i]['kode_barang']=$r->kode_barang;  		
$responce[$i]['uom']=$r->uom;  			
			$i++;
		}
		echo json_encode($responce);
		
		
	}
	
	
	
	
        
}
    



?>