<?php
class CT_bc261 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->helper('obj2array');
		
		$this->load->model("exim/mdl_bc27", 'mdl_bc27');
		$this->load->model("exim/mdl_bc23", 'mdl_bc23');
		$this->load->model("exim/mdl_bc261", 'mdl_bc261');
		$this->load->model("exim/mdl_invoice", 'mdl_invoice');
		$this->load->helper('afunction');	
	}
  
	function index(){

	$this->load->view('exim/view_bc261');
	}

	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_bc_out_hdr'; // get index row - i.e. user click to sort
		$sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$q =(isset($_POST['q']) && !empty($_POST['q']))?$_POST['q']:'0';
		$id_bc_out_hdr =(isset($_POST['id_bc_out_hdr']) && !empty($_POST['id_bc_out_hdr']))?$_POST['id_bc_out_hdr']:'';
			
		$where = " 1=1 and typedok='BC261' ";
		
		if (isset($_POST['tglawal']) and isset($_POST['tglakhir'])){
			$tglawal=$_POST['tglawal'];
			$tglakhir=$_POST['tglakhir'];
			$where .= " and TGDAFT between '$tglawal' and '$tglakhir' ";
		}	
		
		if ($q=='66'){
			$where =" id_bc_out_hdr=$id_bc_out_hdr ";
		}
		

		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "CAR" ) {
						$searchString = $k->data;
						$where .= " and CAR like  '%".$searchString."%'"; 
					} else if ( $k->field == "NAMABELI" ) {
						$searchString = $k->data;
						$where .= " and NAMABELI like  '%".$searchString."%'"; 
					} else if ( $k->field == "NEGBELI" ) {
						$searchString = $k->data;
						$where .= " and NEGBELI like  '%".$searchString."%'"; 
					} else if ( $k->field == "NOINV" ) {
						$searchString = $k->data;
						$where .= " and NOINV like  '%".$searchString."%'"; 
					} else if ( $k->field == "NilInv" ) {
						$searchString = $k->data;
						$where .= " and NilInv =  $searchString"; 
					} else if ( $k->field == "TGINV" ) {
						$searchString = $k->data;
						$where .= " and TGINV =  '$searchString'"; 
					} else if ( $k->field == "KDVAL" ) {
						$searchString = $k->data;
						$where .= " and KDVAL like  '%".$searchString."%'"; 
					}  else if ( $k->field == "statusdok" ) {
						$searchString = $k->data;
						$where .= " and statusdok like  '%".$searchString."%'"; 
					} else if ( $k->field == "NODAFT" ) {
						$searchString = $k->data;
						$where .= " and NODAFT like  '%".$searchString."%'"; 
					} 
			
				}
			}
		}	
			
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc27->bc27hdr_All($limit,$start,$sidx,$sord, $where);
		$count = $this->mdl_bc27->bc27hdr_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_bc_out_hdr']=$r->id_bc_out_hdr; 
			$responce->rows[$i]['CAR']=$r->CAR; 
			$responce->rows[$i]['JnEks']=$r->JnEks; 
			$responce->rows[$i]['KatEks']=$r->KatEks; 
			$responce->rows[$i]['JNPEB']=$r->JNPEB; 
			$responce->rows[$i]['JNEKSOld']=$r->JNEKSOld; 
			$responce->rows[$i]['JNLAIN']=$r->JNLAIN; 
			$responce->rows[$i]['JNDAG']=$r->JNDAG; 
			$responce->rows[$i]['JNBYR']=$r->JNBYR; 
			$responce->rows[$i]['IDEKS']=$r->IDEKS; 
			$responce->rows[$i]['NPWPEKS']=$r->NPWPEKS; 
			$responce->rows[$i]['NamaEks']=$r->NamaEks; 
			$responce->rows[$i]['AlmtEks']=$r->AlmtEks; 
			$responce->rows[$i]['NoSiup']=$r->NoSiup; 
			$responce->rows[$i]['TgSiup']=$r->TgSiup; 
			$responce->rows[$i]['JnPerus']=$r->JnPerus; 
			$responce->rows[$i]['NoTdp']=$r->NoTdp; 
			$responce->rows[$i]['TgTdp']=$r->TgTdp; 
			$responce->rows[$i]['Niper']=$r->Niper; 
			$responce->rows[$i]['StatusH']=$r->StatusH; 
			$responce->rows[$i]['IdQq']=$r->IdQq; 
			$responce->rows[$i]['NpwpQq']=$r->NpwpQq; 
			$responce->rows[$i]['NamaQq']=$r->NamaQq; 
			$responce->rows[$i]['AlmtQq']=$r->AlmtQq; 
			$responce->rows[$i]['NiperQq']=$r->NiperQq; 
			$responce->rows[$i]['NAMABELI']=$r->NAMABELI; 
			$responce->rows[$i]['ALMTBELI']=$r->ALMTBELI; 
			$responce->rows[$i]['NEGBELI']=$r->NEGBELI; 
			$responce->rows[$i]['IDPPJK']=$r->IDPPJK; 
			$responce->rows[$i]['NPWPPPJK']=$r->NPWPPPJK; 
			$responce->rows[$i]['NamaPpjk']=$r->NamaPpjk; 
			$responce->rows[$i]['AlmtPpjk']=$r->AlmtPpjk; 
			$responce->rows[$i]['NoPpjk']=$r->NoPpjk; 
			$responce->rows[$i]['TgPpjk']=$r->TgPpjk; 
			$responce->rows[$i]['MODA']=$r->MODA; 
			$responce->rows[$i]['TGEKS']=$r->TGEKS; 
			$responce->rows[$i]['CARRIER']=$r->CARRIER; 
			$responce->rows[$i]['VOY']=$r->VOY; 
			$responce->rows[$i]['NOSHIPORD']=$r->NOSHIPORD; 
			$responce->rows[$i]['TGSHIPORD']=$r->TGSHIPORD; 
			$responce->rows[$i]['PELMUAT']=$r->PELMUAT; 
			$responce->rows[$i]['PELBONGKAR']=$r->PELBONGKAR; 
			$responce->rows[$i]['PELTRANSIT']=$r->PELTRANSIT; 
			$responce->rows[$i]['NOINV']=$r->NOINV; 
			$responce->rows[$i]['TGINV']=$r->TGINV; 
			$responce->rows[$i]['NOLPSE']=$r->NOLPSE; 
			$responce->rows[$i]['TGLPSE']=$r->TGLPSE; 
			$responce->rows[$i]['PROPBRG']=$r->PROPBRG; 
			$responce->rows[$i]['NEGTUJU']=$r->NEGTUJU; 
			$responce->rows[$i]['FLSIE']=$r->FLSIE; 
			$responce->rows[$i]['FLKARANT']=$r->FLKARANT; 
			$responce->rows[$i]['FLSM']=$r->FLSM; 
			$responce->rows[$i]['FLIZLAIN']=$r->FLIZLAIN; 
			$responce->rows[$i]['DELIVERY']=$r->DELIVERY; 
			$responce->rows[$i]['KDVAL']=$r->KDVAL; 
			$responce->rows[$i]['KdHrg']=$r->KdHrg; 
			$responce->rows[$i]['NilInv']=$r->NilInv; 
			$responce->rows[$i]['FREIGHT']=$r->FREIGHT; 
			$responce->rows[$i]['ASURANSI']=$r->ASURANSI; 
			$responce->rows[$i]['KdAss']=$r->KdAss; 
			$responce->rows[$i]['FOB']=$r->FOB; 
			$responce->rows[$i]['MERK']=$r->MERK; 
			$responce->rows[$i]['JMCONT']=$r->JMCONT; 
			$responce->rows[$i]['BRUTO']=$r->BRUTO; 
			$responce->rows[$i]['NETTO']=$r->NETTO; 
			$responce->rows[$i]['JMBRG']=$r->JMBRG; 
			$responce->rows[$i]['JMBRGCTH']=$r->JMBRGCTH; 
			$responce->rows[$i]['JMBRGGAB']=$r->JMBRGGAB; 
			$responce->rows[$i]['JMBRGPJT']=$r->JMBRGPJT; 
			$responce->rows[$i]['NODAFT']=$r->NODAFT; 
			$responce->rows[$i]['TGDAFT']=$r->TGDAFT; 
			$responce->rows[$i]['KDKTR']=$r->KDKTR; 
			$responce->rows[$i]['KTRGATE']=$r->KTRGATE; 
			$responce->rows[$i]['NILPE']=$r->NILPE; 
			$responce->rows[$i]['KDBANK']=$r->KDBANK; 
			$responce->rows[$i]['LOKBANK']=$r->LOKBANK; 
			$responce->rows[$i]['NOSSP']=$r->NOSSP; 
			$responce->rows[$i]['TGSSP']=$r->TGSSP; 
			$responce->rows[$i]['JNTPB']=$r->JNTPB; 
			$responce->rows[$i]['LOKTPB']=$r->LOKTPB; 
			$responce->rows[$i]['KDLOKBRG']=$r->KDLOKBRG; 
			$responce->rows[$i]['KDKTRMUAT']=$r->KDKTRMUAT; 
			$responce->rows[$i]['KDKTRPRIKS']=$r->KDKTRPRIKS; 
			$responce->rows[$i]['TGSIAP']=$r->TGSIAP; 
			$responce->rows[$i]['WKSIAP']=$r->WKSIAP; 
			$responce->rows[$i]['ASALDATA']=$r->ASALDATA; 
			$responce->rows[$i]['TPNAME']=$r->TPNAME; 
			$responce->rows[$i]['PEBOK']=$r->PEBOK; 
			$responce->rows[$i]['LENGKAP']=$r->LENGKAP; 
			$responce->rows[$i]['JNPARTOF']=$r->JNPARTOF; 
			$responce->rows[$i]['BENDERA']=$r->BENDERA;
			$responce->rows[$i]['TTDPEB']=$r->TTDPEB;
			$responce->rows[$i]['STATUS']=$r->STATUS;
			$responce->rows[$i]['SNRF']=$r->SNRF;
			$responce->rows[$i] ['NOBCF'] =$r->NOBCF; 
			$responce->rows[$i] ['TGBCF'] =$r->TGBCF; 
			$responce->rows[$i] ['SERIBCF'] =$r->SERIBCF; 
			$responce->rows[$i] ['NOMOREDI'] =$r->NOMOREDI; 
			$responce->rows[$i] ['KMDT'] =$r->KMDT; 
			$responce->rows[$i] ['VOLUME'] =$r->VOLUME; 
			$responce->rows[$i] ['KDHANGGAR'] =$r->KDHANGGAR; 
			$responce->rows[$i] ['KONS']=$r->KONS; 
			$responce->rows[$i] ['JMLKMSPEB']=$r->JMLKMSPEB; 
			$responce->rows[$i] ['PELMUATEKS'] =$r->PELMUATEKS; 
			$responce->rows[$i] ['NILKURS']=$r->NILKURS; 
			$responce->rows[$i] ['PNBP'] =$r->PNBP; 
			$responce->rows[$i] ['NOBC11'] =$r->NOBC11; 
			$responce->rows[$i] ['TGBC11'] =$r->TGBC11; 
			$responce->rows[$i] ['POSBC11'] =$r->POSBC11; 
			$responce->rows[$i] ['SUBPOSBC11'] =$r->SUBPOSBC11; 
			$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] ['typedok'] =$r->typedok; 
			$responce->rows[$i] ['statusdok']=$r->statusdok; 
			$responce->rows[$i] ['noinv1'] =$r->noinv1; 
			$responce->rows[$i] ['tginv1'] =$r->tginv1; 
			$responce->rows[$i] ['inv_hdr_id'] =$r->inv_hdr_id; 
			$responce->rows[$i] ['bc_in_from_in'] =$r->bc_in_from_in; 
			$responce->rows[$i] ['nopol'] =$r->nopol; 
			
		
			$i++;
		}
		echo json_encode($responce);
			
        
		
		
    }
	function view_bc261_invoice(){
		$this->load->view('exim/view_bc261_invoice');
		
	
	}
	
	function view_bc261_perhitungan_exim(){
		$this->load->view('exim/view_bc261_perhitungan_exim');
		
	
	}
	
	function upload_file_perhitungan_exim(){
		$status = "";
	   $msg = "";
	   $file_element_name = 'userfileperhitungan_exim';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'BC261_perhitungan_exim';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'exim/perhitungan_exim/';
		  $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.'exim/perhitungan_exim/log/'.$data['file_name'];
				$filename=$data['file_name'];
				$dirfile = $apppath.'exim/perhitungan_exim/';

			/* 	echo " exec('[spuload_perhitungan_exim] @filepath=''$dirfile'', @filename=''$filename'', @username=''$username'', @tipe=''$tipe'', @trx=''add'', @id=0 ') ";
				die();	 */	
				$qry = $this->db->query("
					BEGIN TRY
					
					 exec('[spuload_perhitungan_exim] @filepath=''$dirfile'', @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_parths]') ";
				 // $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 data_upload_perhitungan_exim(){
		$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_upload_perhitungan_exim'; // 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],101)  =  '$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_bc261->upload_perhitungan_eximAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc261->upload_perhitungan_eximcountAll($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_upload_perhitungan_exim']=$r->id_upload_perhitungan_exim; 
			$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;
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function data_tblbc261_perhitungan_exim_hdr(){
		$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_bc261_exim_hdr'; // 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 == "NPWPTUJU" ) {
						$searchString = $k->data;
						$where .= " and NPWPTUJU like  '%".$searchString."%'"; 
					} else if ( $k->field == "TGLKONTRAK" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[TGLKONTRAK],101)  =  '$searchString'"; 
					} else if ( $k->field == "NOKONTRAK" ) {
						$searchString = $k->data;
						$where .= " and NOKONTRAK like  '%".$searchString."%'"; 
					}  else if ( $k->field == "ALMTTUJU" ) {
						$searchString = $k->data;
						$where .= " and ALMTTUJU like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc261->tblbc261_perhitungan_exim_hdrAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc261->tblbc261_perhitungan_exim_hdrcountAll($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_bc261_exim_hdr']=$r->id_bc261_exim_hdr; 
			$responce->rows[$i]['NPWPTUJU']=$r->NPWPTUJU; 
			$responce->rows[$i]['NAMATUJU']=$r->NAMATUJU; 
			$responce->rows[$i]['ALMTTUJU']=$r->ALMTTUJU;
			$responce->rows[$i]['NOKONTRAK']=$r->NOKONTRAK;
			$responce->rows[$i]['TGLKONTRAK']=$r->TGLKONTRAK;
			$responce->rows[$i]['custom_bond']=$r->custom_bond;
			$responce->rows[$i]['kurs']=$r->kurs;
			$responce->rows[$i]['kdval']=$r->kdval;
			$responce->rows[$i]['jml_hari_kerja']=$r->jml_hari_kerja;
			$responce->rows[$i]['periode_awal']=$r->periode_awal;
			$responce->rows[$i]['periode_akhir']=$r->periode_akhir;
			$responce->rows[$i]['jenis_pekerjaan']=$r->jenis_pekerjaan;
			$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 data_tblbc261_perhitungan_exim_dtl(){
		$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_bc261_exim_hdr'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		
		$where = " 1=1 ";
		if (isset($_POST['id_bc261_exim_hdr']) && !empty($_POST['id_bc261_exim_hdr'])){
			$id_bc261_exim_hdr = $_POST['id_bc261_exim_hdr'];
			$where = " 1=1 and id_bc261_exim_hdr=$id_bc261_exim_hdr  ";
			
		}
		
		
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "kode_barang" ) {
						$searchString = $k->data;
						$where .= " and kode_barang like  '%".$searchString."%'"; 
					} else if ( $k->field == "ex_tgdaft" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[ex_tgdaft],101)  =  '$searchString'"; 
					} else if ( $k->field == "part_name_customs" ) {
						$searchString = $k->data;
						$where .= " and part_name_customs like  '%".$searchString."%'"; 
					}  else if ( $k->field == "vendor" ) {
						$searchString = $k->data;
						$where .= " and vendor like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc261->tblbc261_perhitungan_exim_dtlAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc261->tblbc261_perhitungan_exim_dtlcountAll($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_bc261_exim_dtl']=$r->id_bc261_exim_dtl;
			$responce->rows[$i]['id_bc261_exim_hdr']=$r->id_bc261_exim_hdr;
			$responce->rows[$i]['assy_code']=$r->assy_code;
			$responce->rows[$i]['assy_name']=$r->assy_name;
			$responce->rows[$i]['part_name_customs']=$r->part_name_customs;
			$responce->rows[$i]['part_number']=$r->part_number;
			$responce->rows[$i]['kode_barang']=$r->kode_barang;
			$responce->rows[$i]['qty']=$r->qty;
			$responce->rows[$i]['unit']=$r->unit;
			$responce->rows[$i]['harga_satuan']=$r->harga_satuan;
			$responce->rows[$i]['total_usd']=$r->total_usd;
			$responce->rows[$i]['nilai_pabean']=$r->nilai_pabean;
			$responce->rows[$i]['ex_aju']=$r->ex_aju;
			$responce->rows[$i]['ex_nodaft']=$r->ex_nodaft;
			$responce->rows[$i]['ex_tgdaft']=$r->ex_tgdaft;
			$responce->rows[$i]['ex_nourut']=$r->ex_nourut;
			$responce->rows[$i]['hs']=$r->hs;
			$responce->rows[$i]['bm']=$r->bm;
			$responce->rows[$i]['ppn']=$r->ppn;
			$responce->rows[$i]['pph']=$r->pph;
			$responce->rows[$i]['vendor']=$r->vendor;
			$responce->rows[$i]['qty_modul']=$r->qty_modul;
			$responce->rows[$i]['qty_dipakai']=$r->qty_dipakai;
			
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	function data_tblbc261_perhitungan_exim_asal_bc(){
		$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_bc261_exim_hdr'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		if(isset($_POST['id_bc261_exim_hdr']) && !empty($_POST['id_bc261_exim_hdr'])){
			$id_bc261_exim_hdr = $_POST['id_bc261_exim_hdr'];
			$where = " 1=1  and id_bc261_exim_hdr=$id_bc261_exim_hdr  ";
		}
		if(isset($_POST['aju']) && !empty($_POST['aju'])){
			if($_POST['aju'] == 'ya'){
				$no_aju = (isset($_POST['no_aju']) && !empty($_POST['no_aju']))?$_POST['no_aju']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
				$tg_aju = (isset($_POST['tg_aju']) && !empty($_POST['tg_aju']))?$_POST['tg_aju']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
				$id_bc261_exim_hdr = (isset($_POST['id_bc261_exim_hdr']) && !empty($_POST['id_bc261_exim_hdr']))?$_POST['id_bc261_exim_hdr']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
				$where = " 1=1  and id_bc261_exim_hdr=$id_bc261_exim_hdr  and no_aju='$no_aju'  and tg_aju='$tg_aju' ";
			
			}
		}
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "ex_aju" ) {
						$searchString = $k->data;
						$where .= " and ex_aju like  '%".$searchString."%'"; 
					} else if ( $k->field == "ex_tgdaft" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[ex_tgdaft],101)  =  '$searchString'"; 
					} else if ( $k->field == "no_aju" ) {
						$searchString = $k->data;
						$where .= " and no_aju like  '%".$searchString."%'"; 
					} else if ( $k->field == "tg_aju" ) {
						$searchString = $k->data;
						$where .= " and CONVERT(VARCHAR(10),[tg_aju],101)  =  '$searchString'"; 
					} else if ( $k->field == "ex_nodaft" ) {
						$searchString = $k->data;
						$where .= " and ex_nodaft like  '%".$searchString."%'"; 
					}  else if ( $k->field == "vendor" ) {
						$searchString = $k->data;
						$where .= " and vendor like  '%".$searchString."%'"; 
					}  else if ( $k->field == "status_data" ) {
						$searchString = $k->data;
						$where .= " and status_data like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc261->tblbc261_perhitungan_exim_asal_bcAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc261->tblbc261_perhitungan_exim_asal_bccountAll($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_bc261_bc_asal']=$r->id_bc261_bc_asal;
			$responce->rows[$i]['id_bc261_exim_dtl']=$r->id_bc261_exim_dtl;
			$responce->rows[$i]['id_bc261_exim_hdr']=$r->id_bc261_exim_hdr;
			$responce->rows[$i]['qty_modul']=$r->qty_modul;
			$responce->rows[$i]['qty_dipakai']=$r->qty_dipakai;
			$responce->rows[$i]['harga_satuan']=$r->harga_satuan;
			$responce->rows[$i]['total_usd']=$r->total_usd;
			$responce->rows[$i]['nilai_pabean']=$r->nilai_pabean;
			$responce->rows[$i]['ex_aju']=$r->ex_aju;
			$responce->rows[$i]['ex_nodaft']=$r->ex_nodaft;
			$responce->rows[$i]['ex_tgdaft']=$r->ex_tgdaft;
			$responce->rows[$i]['ex_nourut']=$r->ex_nourut;
			$responce->rows[$i]['hs']=$r->hs;
			$responce->rows[$i]['bm']=$r->bm;
			$responce->rows[$i]['ppn']=$r->ppn;
			$responce->rows[$i]['pph']=$r->pph;
			$responce->rows[$i]['vendor']=$r->vendor;
			$responce->rows[$i]['assy_code']=$r->assy_code;
			$responce->rows[$i]['assy_name']=$r->assy_name;
			$responce->rows[$i]['part_name_customs']=$r->part_name_customs;
			$responce->rows[$i]['part_number']=$r->part_number;
			$responce->rows[$i]['kode_barang']=$r->kode_barang;
			$responce->rows[$i]['no_aju']=$r->no_aju;
			$responce->rows[$i]['tg_aju']=$r->tg_aju;
			$responce->rows[$i]['status_data']=$r->status_data;
			
			$i++;
		}
		echo json_encode($responce);	
	
	}
	
	
	function proses_perhitungan_exim(){
		$id = (isset($_POST['id_upload_perhitungan_exim']) && !empty($_POST['id_upload_perhitungan_exim']))?$_POST['id_upload_perhitungan_exim']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$filename = (isset($_POST['filename']) && !empty($_POST['filename']))?$_POST['filename']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$txtnokontrak = (isset($_POST['txtnokontrak']) && !empty($_POST['txtnokontrak']))?$_POST['txtnokontrak']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$txttglkontrak = (isset($_POST['txttglkontrak']) && !empty($_POST['txttglkontrak']))?$_POST['txttglkontrak']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$txtnamasubkontrak = (isset($_POST['txtnamasubkontrak']) && !empty($_POST['txtnamasubkontrak']))?$_POST['txtnamasubkontrak']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$txtalmtsubkontrak = (isset($_POST['txtalmtsubkontrak']) && !empty($_POST['txtalmtsubkontrak']))?$_POST['txtalmtsubkontrak']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$txtcustombond = (isset($_POST['txtcustombond']) && !empty($_POST['txtcustombond']))?$_POST['txtcustombond']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$txtharisubkon = (isset($_POST['txtharisubkon']) && !empty($_POST['txtharisubkon']))?$_POST['txtharisubkon']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$txtkurs = (isset($_POST['txtkurs']) && !empty($_POST['txtkurs']))?$_POST['txtkurs']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$txtkdval = (isset($_POST['txtkdval']) && !empty($_POST['txtkdval']))?$_POST['txtkdval']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$txtjenisbarangjadi = (isset($_POST['txtjenisbarangjadi']) && !empty($_POST['txtjenisbarangjadi']))?$_POST['txtjenisbarangjadi']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$txtnpwpsubkontrak = (isset($_POST['txtnpwpsubkontrak']) && !empty($_POST['txtnpwpsubkontrak']))?$_POST['txtnpwpsubkontrak']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		
		$dt_csv = "$txtnokontrak#$txttglkontrak#$txtnamasubkontrak#$txtalmtsubkontrak#$txtcustombond#$txtharisubkon#$txtkurs#$txtkdval#$txtjenisbarangjadi#$txtnpwpsubkontrak|";
		
		$username = $this->session->userdata('DX_username');
		
		$tipe = 'BC261_perhitungan_exim';
/* 		echo   "  exec('[spi_perhitungan_exim] @filename=''$filename'', @id_upload_perhitungan_exim=$id, @tipe=''$tipe'',  @username=''$username'', @datadiff=''$dt_csv'' ') ";
		die();  
 */		
		$qry = $this->db->query("
			BEGIN TRY
			  exec('[spi_perhitungan_exim] @filename=''$filename'', @id_upload_perhitungan_exim=$id, @tipe=''$tipe'',  @username=''$username'', @datadiff=''$dt_csv'' ')
			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 proses_del_perhitungan_exim(){
		$id = (isset($_POST['id_delbc261_perhitungan_exim']) && !empty($_POST['id_delbc261_perhitungan_exim']))?$_POST['id_delbc261_perhitungan_exim']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$qry = $this->db->query("
			if (select count(*) from [dbo].[tblbc261_perhitungan_exim_asal_bc] where [id_bc261_exim_hdr] = $id and [status_data] <> 'NEW') > 0
			begin
				select '06' as status, 'DATA SUDAH DI PROSES BC.. MOHON CANCEL DAHULU' as description
				return
			end
			BEGIN TRY
			  delete from tblbc261_perhitungan_exim_asal_bc where id_bc261_exim_hdr=$id
			  delete from tblbc261_perhitungan_exim_dtl where id_bc261_exim_hdr=$id
			  delete from tblbc261_perhitungan_exim_hdr where id_bc261_exim_hdr=$id
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			select '00' as status, 'DATA DELETED' as description
			
			 ");
		 $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_bc261_perhitungan_exim_dtl(){
		
		$id_bc261_exim_hdr = (isset($_POST['id_bc261_exim_hdr']) && !empty($_POST['id_bc261_exim_hdr']))?$_POST['id_bc261_exim_hdr']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$data['id_bc261_exim_hdr'] = $id_bc261_exim_hdr; 
		$this->load->view('exim/view_bc261_perhitungan_exim_dtl', $data);
	
	}
	
	function bc23_modul_detil(){
		$bc23dir = $this->config->item('APP_modulbc23');
		$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']:'car'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$tglawalbc23car = (isset($_POST['tglawalbc23car']) && !empty($_POST['tglawalbc23car']))?$_POST['tglawalbc23car']:date('Y-m-d');
		$tglakhirbc23car = (isset($_POST['tglakhirbc23car']) && !empty($_POST['tglakhirbc23car']))?$_POST['tglakhirbc23car']:date('Y-m-d');
		$kode_brg = (isset($_POST['kode_brg']) && !empty($_POST['kode_brg']))?$_POST['kode_brg']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		
		$where = " 1=1 ";
		$where = " a.BC23tg between '$tglawalbc23car' and '$tglakhirbc23car' and b.KdBrg = '$kode_brg' ";
		if (isset($_POST['car_kirim'])  && !empty($_POST['car_kirim']) ){
			$car = $_POST['car_kirim'];
			$where = " a.CAR like '%$car%' and b.KdBrg = '$kode_brg' ";
		}
		$this->db->query("
			SET ANSI_NULLS ON
			SET ANSI_WARNINGS ON
		");
		
		$query = $this->db->query("
			
			select COUNT(*) as cnt from
			OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
						'Data Source=$bc23dir;
						Jet OLEDB:Database Password=MumtazFarisHana;Persist Security Info=False;'
						)...tblBC23Hdr a 
			inner join OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
						'Data Source=$bc23dir;
						Jet OLEDB:Database Password=MumtazFarisHana;Persist Security Info=False;'
						)...tblBC23dtl b on a.car = b.car
			where $where 
			
		
		");
		
		$result = $query->result_array();
		
		$cnt = 0;
		foreach ($result as $row){
		
			$cnt = $row['cnt'];
		
		}
				
		$count=$cnt;
		if( $count >0 ) { $total_pages = ceil($count/$limit); } 
			else { $total_pages = 0; } 
		if ($page > $total_pages) $page=$total_pages; 
		$start = $limit*$page - $limit; // do not put $limit*($page - 1) if ($start<0) $start = 0;
		$batas = $count - (($page - 1) * $limit);
		
		 $q = $this->db->query("
			select top $limit car, BC23No, BC23Tgl
				,Serial
				,JnsBarangDtl 
				,TujuanKirimDtl
				,NoHs
				,SeriTrp
				,BrgUrai
				,Merk
				,Tipe
				,SpfLain
				,KdBrg
				,Penggunaan
				,KemasJn
				,KemasJm
				,KdFasDtl
				,BrgAsal
				,DNilInv
				,DCif
				,KdSat
				,JmlSat
				,NettoDtl
				,SatBmJm
				,SatCukJm
				,DtlOk
			from (
				select TOP $batas a.car as CAR, a.BC23No as BC23No, convert(date, a.BC23Tg, 126) as BC23Tgl
				,b.Serial as Serial
				,b.JnsBarangDtl as JnsBarangDtl 
				,b.TujuanKirimDtl as TujuanKirimDtl
				,b.NoHs as NoHs
				,b.SeriTrp as SeriTrp
				,b.BrgUrai as BrgUrai
				,b.Merk as Merk
				,b.Tipe as Tipe
				,b.SpfLain as SpfLain
				,b.KdBrg as KdBrg
				,b.Penggunaan as Penggunaan
				,b.KemasJn as KemasJn
				,b.KemasJm as KemasJm
				,b.KdFasDtl as KdFasDtl
				,b.BrgAsal as BrgAsal
				,b.DNilInv as DNilInv
				,b.DCif as DCif
				,b.KdSat as KdSat
				,b.JmlSat as JmlSat
				,b.NettoDtl as NettoDtl
				,b.SatBmJm as SatBmJm
				,b.SatCukJm as SatCukJm
				,b.DtlOk as DtlOk
				
				from
				OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
							'Data Source=$bc23dir;
							Jet OLEDB:Database Password=MumtazFarisHana;Persist Security Info=False;'
							)...tblBC23Hdr a 
				inner join OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
							'Data Source=$bc23dir;
							Jet OLEDB:Database Password=MumtazFarisHana;Persist Security Info=False;'
							)...tblBC23dtl b on a.car = b.car
				where $where
				order by $sidx desc
			)  t1 Order By car $sord
			
			"); 
		$rs = $q->result_array();
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =(integer) $count;
		$i=0;
		
		foreach ($rs as $r){
			
			$responce->rows[$i]["CAR"]=$r["car"];
			$responce->rows[$i]["BC23No"]=$r["BC23No"];
			$responce->rows[$i]["BC23Tgl"]=$r["BC23Tgl"];
			$responce->rows[$i]["Serial"]=$r["Serial"];
			$responce->rows[$i]["KdBrg"]=$r["KdBrg"];
			$responce->rows[$i]["BrgUrai"]=$r["BrgUrai"];
			$responce->rows[$i]["JmlSat"]=$r["JmlSat"];
			$responce->rows[$i]["DNilInv"]=$r["DNilInv"];
			$responce->rows[$i]["SatBmJm"]=$r["SatBmJm"];
			$responce->rows[$i]["SatCukJm"]=$r["SatCukJm"];
			$responce->rows[$i]["NoHs"]=$r["NoHs"];
			$responce->rows[$i]["NettoDtl"]=$r["NettoDtl"];
			
			
			
			$i++;
			
		}
		
		echo json_encode($responce);
		die();
		
	}
	
	function proses_update_data_dari_modul(){
		$bc23dir = $this->config->item('APP_modulbc23');
		
		$CAR = (isset($_POST['CAR']) && !empty($_POST['CAR']))?$_POST['CAR']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$BC23No = (isset($_POST['BC23No']) && !empty($_POST['BC23No']))?$_POST['BC23No']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$BC23Tgl = (isset($_POST['BC23Tgl']) && !empty($_POST['BC23Tgl']))?$_POST['BC23Tgl']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$JmlSat = (isset($_POST['JmlSat']) && !empty($_POST['JmlSat']))?$_POST['JmlSat']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$id_dtl = (isset($_POST['id_dtl']) && !empty($_POST['id_dtl']))?$_POST['id_dtl']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$id_hdr = (isset($_POST['id_hdr']) && !empty($_POST['id_hdr']))?$_POST['id_hdr']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$Serial = (isset($_POST['Serial']) && !empty($_POST['Serial']))?$_POST['Serial']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$DNilInv = (isset($_POST['DNilInv']) && !empty($_POST['DNilInv']))?$_POST['DNilInv']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$qty_dipake = (isset($_POST['qty_dipake']) && !empty($_POST['qty_dipake']))?$_POST['qty_dipake']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$hskode = (isset($_POST['hskode']) && !empty($_POST['hskode']))?$_POST['hskode']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		
		$harga_satuan  = round($DNilInv/$JmlSat, 4, PHP_ROUND_HALF_UP);
		
		$this->db->query("
			SET ANSI_NULLS ON
			SET ANSI_WARNINGS ON
		");
		
		$qry = $this->db->query("
			declare @kurs float, @qty float
			set @kurs = (select [kurs] from [dbo].[tblbc261_perhitungan_exim_hdr] where [id_bc261_exim_hdr]=$id_hdr)
			set @qty = (select [qty] from [dbo].[tblbc261_perhitungan_exim_dtl] where [id_bc261_exim_dtl]=$id_dtl and [id_bc261_exim_hdr]=$id_hdr)
			
			declare @trpppn  float, @trpbm float 
			select top 1
				@trpppn=trpppn
				,@trpbm=trpbm
			from
				OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
							'Data Source=$bc23dir;
							Jet OLEDB:Database Password=MumtazFarisHana;Persist Security Info=False;'
							)...tblBC23Trf where car='$CAR' and nohs = '$hskode'
			
			BEGIN TRY
				update tblbc261_perhitungan_exim_dtl set 
				[qty_modul]=$JmlSat
				,[ex_aju]='$CAR'
				,[ex_nodaft]='$BC23No'
				,[ex_tgdaft]='$BC23Tgl'
				,[ex_nourut]=$Serial
				,[hs]='$hskode'
				,[harga_satuan]=$harga_satuan
				,[total_usd] = (@qty * $harga_satuan)
				,[nilai_pabean] = (@qty * $harga_satuan * @kurs)
				,[bm]=@trpbm
				,[ppn]=@trpppn
				where  
				 [id_bc261_exim_dtl]=$id_dtl and [id_bc261_exim_hdr]=$id_hdr
			
					
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			select '00' as status, 'DATA UPDATED' as description
			
			 ");
		 $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 add_jml_bc(){
		$id_hdrx = (isset($_POST['id_hdrx']) && !empty($_POST['id_hdrx']))?$_POST['id_hdrx']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$id_dtlx = (isset($_POST['id_dtlx']) && !empty($_POST['id_dtlx']))?$_POST['id_dtlx']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$qtyx = (isset($_POST['qtyx']) && !empty($_POST['qtyx']))?$_POST['qtyx']:die('{"sts":"ERROR","desc":" Param QTY Tidak Ditemukan"}');
		$bc261_no = (isset($_POST['bc261_no']) && !empty($_POST['bc261_no']))?$_POST['bc261_no']:die('{"sts":"ERROR","desc":" Param QTY Tidak Ditemukan"}');
		$bc261_tg = (isset($_POST['bc261_tg']) && !empty($_POST['bc261_tg']))?$_POST['bc261_tg']:die('{"sts":"ERROR","desc":" Param QTY Tidak Ditemukan"}');
		
		
		$qry = $this->db->query("
			if (select count(*) from tblbc261_perhitungan_exim_dtl where id_bc261_exim_hdr=$id_hdrx  and id_bc261_exim_dtl=$id_dtlx) = 0
			begin
				select '06' as status, ' DATA TIDAK DI TEMUKAN' as description
				return
			end
			
			declare @kode_barang varchar(50), @partnamecustoms varchar(50),@hargasatuan float, @hs varchar(50),@bm float, @ppn float, @pph float
			set @kode_barang = (select kode_barang from  tblbc261_perhitungan_exim_dtl where id_bc261_exim_hdr=$id_hdrx  and id_bc261_exim_dtl=$id_dtlx)
			set @partnamecustoms = (select part_name_customs from  tblbc261_perhitungan_exim_dtl where id_bc261_exim_hdr=$id_hdrx  and id_bc261_exim_dtl=$id_dtlx)
			set @hargasatuan = (select harga_satuan from  tblbc261_perhitungan_exim_dtl where id_bc261_exim_hdr=$id_hdrx  and id_bc261_exim_dtl=$id_dtlx)
			set @hs = (select hs from  tblbc261_perhitungan_exim_dtl where id_bc261_exim_hdr=$id_hdrx  and id_bc261_exim_dtl=$id_dtlx)
			set @bm = (select bm from  tblbc261_perhitungan_exim_dtl where id_bc261_exim_hdr=$id_hdrx  and id_bc261_exim_dtl=$id_dtlx)
			set @ppn = (select ppn from  tblbc261_perhitungan_exim_dtl where id_bc261_exim_hdr=$id_hdrx  and id_bc261_exim_dtl=$id_dtlx)
			
			
			BEGIN TRY
				insert into [tblbc261_perhitungan_exim_asal_bc] 
				(
					[id_bc261_exim_dtl]
					,[id_bc261_exim_hdr]
					,kode_barang
					,part_name_customs	
					,qty_dipakai
					,[harga_satuan]
					,[no_aju]
					,[tg_aju]
					,[status_data]
					,[hs]
					,[bm]
					,[ppn]
					,[pph]
				) values (
					$id_dtlx
					,$id_hdrx
					,@kode_barang
					,@partnamecustoms
					,$qtyx 
					,@hargasatuan
					,'$bc261_no'
					,'$bc261_tg'
					,'NEW'
					,@hs
					,@bm
					,@ppn
					,2.5
				)	
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			select '00' as status, 'DATA ADDED' as description
			
			 ");
		 $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 del_jml_bc(){
		$id_hdrx = (isset($_POST['id_hdrx']) && !empty($_POST['id_hdrx']))?$_POST['id_hdrx']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		
		$qry = $this->db->query("
			
			BEGIN TRY
				delete from [tblbc261_perhitungan_exim_asal_bc] where [id_bc261_bc_asal] = $id_hdrx 
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			select '00' as status, 'DATA DELETED' as description
			
			 ");
		 $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 proses_data_bc261(){
		$id_bc261_exim_hdr = (isset($_POST['id_bc261_exim_hdr']) && !empty($_POST['id_bc261_exim_hdr']))?$_POST['id_bc261_exim_hdr']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$no_aju = (isset($_POST['no_aju']) && !empty($_POST['no_aju']))?$_POST['no_aju']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$tg_aju = (isset($_POST['tg_aju']) && !empty($_POST['tg_aju']))?$_POST['tg_aju']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$uid = $this->session->userdata('DX_username');
		$qry = $this->db->query("
			declare @nobc varchar(50), @tgbc date, @NAMABELI varchar(70), @ALMTBELI varchar(100),  @NPWP varchar(50), @kurs float, @kdval varchar(5) 
			declare @NOKONTRAK varchar(50), @TGLKONTRAK date, @custom_bond float, @id_bc_out_hdr bigint, @tgl date, @jml_brg int, @nilinv float 
			set @jml_brg=(select count(*) from tblbc261_perhitungan_exim_asal_bc where no_aju = '$no_aju'  and tg_aju='$tg_aju')
			set @tgl=GETDATE()
			select 
				@nobc='$no_aju'
				,@tgbc='$tg_aju'
				,@NAMABELI=NAMATUJU
				,@ALMTBELI=ALMTTUJU
				,@NPWP=NPWPTUJU
				,@kurs=kurs
				,@kdval=kdval
				,@NOKONTRAK=NOKONTRAK
				,@TGLKONTRAK=TGLKONTRAK
				,@custom_bond=custom_bond
			from 
				[dbo].[tblbc261_perhitungan_exim_hdr]
			where
				id_bc261_exim_hdr=$id_bc261_exim_hdr
			BEGIN TRY
				insert into tbl_bc_out_hdr 
				(
				    CAR
					,[NAMABELI]
					,[ALMTBELI]
					,[NEGBELI]
					,[NamaPpjk]
					,[NOINV]
					,[TGINV]
					,[KDVAL]
					,[NILKURS]
					,[typedok]
					,[statusdok]
					,[inv_hdr_id]
					,[bc_in_from_in]
					,[create_date]
				   ,[create_by]
				   ,[update_date]
				   ,[update_by]
				   ,FREIGHT
				   ,[NODAFT]
				   ,[TGDAFT]
				   ,[STATUS]
				   ,[JMBRG]
				) values (
					@nobc
					,@NAMABELI
					,@ALMTBELI
					,'ID'
					,@NPWP
					,@NOKONTRAK
					,@TGLKONTRAK
					,@kdval
					,@kurs
					,'BC261'
					,'DATA PROCESSED'
					,$id_bc261_exim_hdr
					,CAST($id_bc261_exim_hdr as varchar)
					,@tgl
					,'$uid'
					,@tgl
					,'$uid'
					,@custom_bond
					,@nobc
					,@tgbc
					,'00'
					,@jml_brg
				)	
				set @id_bc_out_hdr=@@IDENTITY
				insert into tbl_bc_out_dtl (
					id_bc_out_hdr
					,CAR
					,[SERIBRG]
					,[HS]
					,[URBRG1]
					,[KDBRG]
					,[JMSATUAN]
					,[JNSATUAN]
					,[DNilInv]
				) select 
					@id_bc_out_hdr
					,@nobc
					,row_number() over(order by (select 0))
					,hs
					,part_name_customs
					,[kode_barang]
					,[qty_dipakai]
					,(select top 1 a.satuan from [dbo].[tbl_kode_barang] a where a.kode_barang=kode_barang)
					,[harga_satuan] * [qty_dipakai]
				 from tblbc261_perhitungan_exim_asal_bc where no_aju = '$no_aju'  and tg_aju='$tg_aju'
				
				set @nilinv = (select sum(DNilInv) from tbl_bc_out_dtl where id_bc_out_hdr=@id_bc_out_hdr )
				update 	tbl_bc_out_hdr set NilInv=@nilinv where id_bc_out_hdr=@id_bc_out_hdr 
				update tblbc261_perhitungan_exim_asal_bc set status_data='DATA PROCESSED', id_bc_out_hdr=@id_bc_out_hdr  where  no_aju = '$no_aju'  and tg_aju='$tg_aju'
				
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			select '00' as status, 'DATA PROCCESSEDD' as description
			
			 ");
		 $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_bc261_dtl(){
		$id_bc_out_hdr = (isset($_POST['id_bc_out_hdr']) && !empty($_POST['id_bc_out_hdr']))?$_POST['id_bc_out_hdr']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$CAR = (isset($_POST['CAR']) && !empty($_POST['CAR']))?$_POST['CAR']:die('{"sts":"ERROR","desc":" Param CAR Tidak Ditemukan"}');
		$NODAFT = (isset($_POST['NODAFT']) && !empty($_POST['NODAFT']))?$_POST['NODAFT']:'';//die('{"sts":"ERROR","desc":" Param NODAFT Tidak Ditemukan"}');
		$TGDAFT = (isset($_POST['TGDAFT']) && !empty($_POST['TGDAFT']))?$_POST['TGDAFT']:'';//die('{"sts":"ERROR","desc":" Param TGDAFT Tidak Ditemukan"}');
		$NILKURS = (isset($_POST['NILKURS']) && !empty($_POST['NILKURS']))?$_POST['NILKURS']:0;
		
		$q = $this->db->query("
			SELECT  id_terkait, doc_out_no, id_data_out_hdr  from [tbl_data_out_hdr] where id_terkait=$id_bc_out_hdr and doc_out_to_id=6
		");
		
		$rs = $q->result_array();
		//var_dump($rs); die();
		$id_data_out_hdr='';
		foreach ($rs as $row){
			$id_data_out_hdr=$row['id_data_out_hdr'];		
		}
		
		
		$q1 = $this->db->query("
			select [id_data_out_hdr]
			  ,[doc_out_no]
			  ,convert(varchar, [doc_out_date], 103) as doc_out_date
			  ,[doc_out_to_id]
			  ,[id_data_out_hdr_h_status]
			  ,[id_terkait]
			  ,convert(varchar, [approve_date], 103) as approve_date
			  FROM[tbl_data_out_hdr]
			  where id_terkait = $id_bc_out_hdr
		");
		
		$rs1 = $q1->result_array();
		//var_dump($rs); die();
		$doc_out_date='';
		$approve_date='';
		foreach ($rs1 as $row1){
			$doc_out_date=$row1['doc_out_date'];		
			$approve_date=$row1['approve_date'];		
		}
		
		$data["doc_out_date"]= $doc_out_date;
		$data["approve_date"]= $approve_date;
		$data["idhdrbc261"]	= $id_data_out_hdr;
		$data['id_bc_out_hdr']=$id_bc_out_hdr;
	    $data['CAR']=$CAR;
		$data['NODAFT']=$NODAFT;
		$data['TGDAFT']=$TGDAFT;
		$data['NILKURS']=$NILKURS;
	    $data['loading_indicator'] =  "<div class='loading_indicator'>loading...<br/><img src='./assets/images/loading.gif' alt='loading' /></div>";
		
		$this->load->view('exim/view_bc261_dtl', $data);
	
	}
	
	
	function loaddatadetil(){
		$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']:'[idpebdtl]'; // get index row - i.e. user click to sort
		$sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		// $gabinvoice = (isset($_POST['gabinvoice']) && !empty($_POST['gabinvoice']))?$_POST['gabinvoice']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		 $idhdrbc261 = (isset($_POST['idhdrbc261']) && !empty($_POST['idhdrbc261']))?$_POST['idhdrbc261']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		 $where = " id_bc_out_hdr=$idhdrbc261 ";
		

		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "[SERIBRG]" ) {
						$searchString = $k->data;
						$where .= " and [SERIBRG] = $searchString "; 
					} else if ( $k->field == "HS" ) {
						$searchString = $k->data;
						$where .= " and HS like  '%".$searchString."%'"; 
					} else if ( $k->field == "URBRG1" ) {
						$searchString = $k->data;
						$where .= " and URBRG1 like  '%".$searchString."%'"; 
					} else if ( $k->field == "URBRG2" ) {
						$searchString = $k->data;
						$where .= " and URBRG2 like  '%".$searchString."%'"; 
					} else if ( $k->field == "URBRG3" ) {
						$searchString = $k->data;
						$where .= " and URBRG3 like  '%".$searchString."%'"; 
					} else if ( $k->field == "URBRG4" ) {
						$searchString = $k->data;
						$where .= " and URBRG4 like  '%".$searchString."%'"; 
					} else if ( $k->field == "DMERK" ) {
						$searchString = $k->data;
						$where .= " and DMERK like  '%".$searchString."%'"; 
					}  else if ( $k->field == "SIZE" ) {
						$searchString = $k->data;
						$where .= " and SIZE like  '%".$searchString."%'"; 
					}  else if ( $k->field == "TYPE" ) {
						$searchString = $k->data;
						$where .= " and TYPE like  '%".$searchString."%'"; 
					}   else if ( $k->field == "KDBRG" ) {
						$searchString = $k->data;
						$where .= " and KDBRG like  '%".$searchString."%'"; 
					}  else if ( $k->field == "JNSATUAN" ) {
						$searchString = $k->data;
						$where .= " and JNSATUAN like  '%".$searchString."%'"; 
					} 
			
				}
			}
		}	
			
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc27->bc27datadtl_All($limit,$start,$sidx,$sord, $where);
		$count = $this->mdl_bc27->bc27datadtl_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_bc_out_dtl']=$r->id_bc_out_dtl;
			  $responce->rows[$i]['id_bc_out_hdr']=$r->id_bc_out_hdr;
			  $responce->rows[$i]['CAR']=$r->CAR;
			  $responce->rows[$i]['SERIBRG']=$r->SERIBRG;
			  $responce->rows[$i]['HS']=$r->HS;
			  $responce->rows[$i]['URBRG1']=$r->URBRG1;
			  $responce->rows[$i]['URBRG2']=$r->URBRG2;
			  $responce->rows[$i]['URBRG3']=$r->URBRG3;
			  $responce->rows[$i]['URBRG4']=$r->URBRG4;
			  $responce->rows[$i]['DMERK']=$r->DMERK;
			  $responce->rows[$i]['SIZE']=$r->SIZE;
			  $responce->rows[$i]['TYPE']=$r->TYPE;
			  $responce->rows[$i]['KDBRG']=$r->KDBRG;
			  $responce->rows[$i]['KDIZIN']=$r->KDIZIN;
			  $responce->rows[$i]['NOIZIN']=$r->NOIZIN;
			  $responce->rows[$i]['TGIZIN']=$r->TGIZIN;
			  $responce->rows[$i]['JMKOLI']=$r->JMKOLI;
			  $responce->rows[$i]['JNKOLI']=$r->JNKOLI;
			  $responce->rows[$i]['DNilInv']=$r->DNilInv;
			  $responce->rows[$i]['FOBPERBRG']=$r->FOBPERBRG;
			  $responce->rows[$i]['FOBPERSAT']=$r->FOBPERSAT;
			  $responce->rows[$i]['KDPE']=$r->KDPE;
			  $responce->rows[$i]['TARIPPE']=$r->TARIPPE;
			  $responce->rows[$i]['HPATOK']=$r->HPATOK;
			  $responce->rows[$i]['JMSATUAN']=$r->JMSATUAN;
			  $responce->rows[$i]['JNSATUAN']=$r->JNSATUAN;
			  $responce->rows[$i]['NETDET']=$r->NETDET;
			  $responce->rows[$i]['JMSATPE']=$r->JMSATPE;
			  $responce->rows[$i]['JNSATPE']=$r->JNSATPE;
			  $responce->rows[$i]['KDVALPE']=$r->KDVALPE;
			  $responce->rows[$i]['NILVALPE']=$r->NILVALPE;
			  $responce->rows[$i]['PEPERBRG']=$r->PEPERBRG;
			  $responce->rows[$i]['DTLOK']=$r->DTLOK;
			  $responce->rows[$i]['NCV']=$r->NCV;
			  $responce->rows[$i]['DVolume']=$r->DVolume;
			  $responce->rows[$i]['NegAsal']=$r->NegAsal;
			 
		
		$i++;
		}
		echo json_encode($responce);
	}
	function loaddatadok(){
		$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']:'[idpebdtl]'; // get index row - i.e. user click to sort
		$sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		// $gabinvoice = (isset($_POST['gabinvoice']) && !empty($_POST['gabinvoice']))?$_POST['gabinvoice']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		 $idhdrbc261 = (isset($_POST['idhdrbc261']) && !empty($_POST['idhdrbc261']))?$_POST['idhdrbc261']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		 $where = " id_bc_out_hdr=$idhdrbc261 ";
		

		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "[SERIBRG]" ) {
						$searchString = $k->data;
						$where .= " and [SERIBRG] = $searchString "; 
					} else if ( $k->field == "HS" ) {
						$searchString = $k->data;
						$where .= " and HS like  '%".$searchString."%'"; 
					} 
			
				}
			}
		}	
			
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc27->bc27datadok_All($limit,$start,$sidx,$sord, $where);
		$count = $this->mdl_bc27->bc27datadok_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_bc_out_dok']=$r->id_bc_out_dok;
			$responce->rows[$i]['id_bc_out_hdr']=$r->id_bc_out_hdr;
			$responce->rows[$i]['CAR']=$r->CAR;
			$responce->rows[$i]['KdDok']=$r->KdDok;
			$responce->rows[$i]['uraian']=$r->uraian;
			$responce->rows[$i]['NoDok']=$r->NoDok;
			$responce->rows[$i]['TgDok']=$r->TgDok;
			$i++;
		}
		echo json_encode($responce);
	
	}
	
	function update_bc261_sa_hdr(){
		$username = $this->session->userdata('DX_username');
		$idbc261hdr = (isset($_POST['id_bc_out_hdr']) && !empty($_POST['id_bc_out_hdr']))?$_POST['id_bc_out_hdr']:die('{"sts":"ERROR","desc":"SA Param Tidak Ditemukan"}');
		$nobc261 = (isset($_POST['nobc261']) && !empty($_POST['nobc261']))?$_POST['nobc261']:die('{"sts":"ERROR","desc":"NO BC Param Tidak Ditemukan"}');
		$tglbc261 = (isset($_POST['tglbc261']) && !empty($_POST['tglbc261']))?$_POST['tglbc261']:die('{"sts":"ERROR","desc":"TGL Param Tidak Ditemukan"}');
		$nilkursbc261 = (isset($_POST['nilkursbc261']) && !empty($_POST['nilkursbc261']))?$_POST['nilkursbc261']:0;
		if ($tglbc261 != ''){
			$tglbc261=explode('/' , $tglbc261);
			$tglbc261 = $tglbc261[2] . '-' . $tglbc261[1] . '-' . $tglbc261[0] ;
		}
		$qry = $this->db->query("
			declare @tgl date
			BEGIN TRY
				update [dbo].[tbl_bc_out_hdr] set [CAR]='$nobc261',[NODAFT]='$nobc261' ,[TGDAFT]='$tglbc261', update_by='$username', update_date=@tgl  where typedok='BC261' and [id_bc_out_hdr]=$idbc261hdr
				update [dbo].[tblbc261_perhitungan_exim_asal_bc] set [no_aju]='$nobc261' ,[tg_aju]='$tglbc261' where [id_bc_out_hdr]=$idbc261hdr  
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			select '00' as status, 'UPDATED' as description
			
			 ");
		 $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 prosesdatatofg_bc261(){
		$id_bc_out = (isset($_POST['id_bc_out']) && !empty($_POST['id_bc_out']))?$_POST['id_bc_out']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$typedok = (isset($_POST['typedok']) && !empty($_POST['typedok']))?$_POST['typedok']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username = $this->session->userdata('DX_username');
		$qry = $this->db->query("
			declare @hasil varchar(50), @doc_out_no varchar(50)
			
			
			
			exec [dbo].[spu_seq] @nomor_untuk = N'inventory_bc_out', @hasil = @hasil OUTPUT
			set @doc_out_no = @hasil 
			
			declare @doc_out_date date, @id_bc_out bigint, @jnsbc int, @username varchar(100), @id_data_out_hdr bigint, @id_data_out_hdr_h_status bigint
			set @id_bc_out=$id_bc_out 
			set @jnsbc=6
			set @username='$username'
			
			if (
			SELECT     COUNT(*) AS cnt
			FROM         tbl_data_out_hdr
			WHERE     (doc_out_to_id = @jnsbc) AND (id_terkait = @id_bc_out))>0
			begin
				select '09' as status, 'Sudah Pernah di transfer' as description
				return
			end
			
			BEGIN TRY
				insert into tbl_data_out_hdr(
					doc_out_no
					,doc_out_date
					,id_terkait
					,doc_out_to_id
					,[create_by]
					,[update_by]
					,[update_date]
					,[create_date]

				) values ( 
				 @doc_out_no	
				,@doc_out_date
				,@id_bc_out
				,@jnsbc  -- keluar sesuai bc
				,@username
				,@username
				,GETDATE()
				,GETDATE() )

				set @id_data_out_hdr=@@IDENTITY
				
				-- insert h status 
				INSERT INTO tbl_data_out_hdr_h_status
									  (id_data_out_hdr, status_date, status, create_by, create_date, update_by, update_date)
				VALUES     (@id_data_out_hdr, GETDATE(), 'DATA PROCESSED INVENTORY', @username, GETDATE(), @username, GETDATE())
				set @id_data_out_hdr_h_status =@@IDENTITY
				
				INSERT INTO tbl_data_out_dtl
				(
				 id_data_out_hdr
				 ,part_name_customs
				 ,part_number
				 ,qty
				 ,qty_supply
				 ,unit_out
				 ,unit_konversi
				 ,pengali
				 ,box
				 ,pack
				 ,assy_code
				 ,type_items
				 )
				select 
				@id_data_out_hdr
				,URBRG1
				,URBRG1
				,JMSATUAN
				,JMSATUAN
				,JNSATUAN
				,JNSATUAN
				,1
				,JMKOLI
				,JMKOLI
				,[KDBRG]
				,'RM'
				from [dbo].tbl_bc_out_dtl where id_bc_out_hdr = @id_bc_out
	
		
				UPDATE    tbl_data_out_hdr
				SET              id_data_out_hdr_h_status = @id_data_out_hdr_h_status
				WHERE     (id_data_out_hdr = @id_data_out_hdr)

				
				update tbl_bc_out_hdr set statusdok='DATA PROCESSED INVENTORY' where id_bc_out_hdr = @id_bc_out	
				
				update [dbo].[tblbc261_perhitungan_exim_asal_bc] set status_data='DATA PROCCESSED INVENTORY' where [id_bc_out_hdr]=@id_bc_out 
				
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			select '00' as status, 'UPDATED dengan ID :' + CAST(@id_data_out_hdr as varchar(255)) as description
			
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		
		$q1 = $this->db->query("
			SELECT  id_terkait, doc_out_no, id_data_out_hdr  from [tbl_data_out_hdr] where id_terkait=$id_bc_out and doc_out_to_id=6
		");
		
		$rs1 = $q1->result_array();
		//var_dump($rs); die();
		$id_data_out_hdr='';
		foreach ($rs1 as $row1){
			$id_data_out_hdr=$row1['id_data_out_hdr'];		
		}
		
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ', 'id_data_out_hdr' => $id_data_out_hdr );
		 }  
		 echo json_encode($responce);
	
	
	
	}
	
	function cancelnocar(){
		$uid = $this->session->userdata('DX_username');
		if ($uid != 'admin') {
			die('{"sts":"ERROR","desc":" Harus Admin"}');
		
		}
		$idhdrbc261 = (isset($_POST['idhdrbc261']) && !empty($_POST['idhdrbc261']))?$_POST['idhdrbc261']:die('{"sts":"ERROR","desc":" idhdrbc27 Param Tidak Ditemukan"}');
		$typedok = (isset($_POST['typedok']) && !empty($_POST['typedok']))?$_POST['typedok']:die('{"sts":"ERROR","desc":" typedok Param Tidak Ditemukan"}');
		
		$qry = $this->db->query("
			declare @bc_in_from_in varchar(50)
			set @bc_in_from_in=(select top 1 bc_in_from_in from tbl_bc_out_hdr where id_bc_out_hdr=$idhdrbc261)
						
			if (select count(*) from tblbc261_perhitungan_exim_asal_bc where id_bc_out_hdr = $idhdrbc261 ) = 0
			begin
				select '06' as status, 'Data Perhitungan Exim tidak ditemukan..' as description
				return
			end
			
			declare @id_bc_out_hdr bigint
			declare @idpebhdr bigint
			
			set @id_bc_out_hdr =$idhdrbc261
			
			declare @id_data_out_hdr bigint
			set @id_data_out_hdr = (select id_data_out_hdr from tbl_data_out_hdr  where id_terkait = @id_bc_out_hdr and doc_out_to_id=6)
			
			BEGIN TRY  
	           	BEGIN TRANSACTION
				delete from tbl_data_out_hdr_h_status where id_data_out_hdr=@id_data_out_hdr
				delete from tbl_data_out_dtl where id_data_out_hdr=@id_data_out_hdr and type_items='RM'
				delete from tbl_data_out_hdr where id_data_out_hdr=@id_data_out_hdr and doc_out_to_id=6
				
				delete from [dbo].[tbl_bc_out_hdr_h_status] where [id_bc_out_hdr] = @id_bc_out_hdr
				delete from [dbo].[tbl_bc_out_kms] where [id_bc_out_hdr] = @id_bc_out_hdr
				delete from [dbo].[tbl_bc_out_con] where [id_bc_out_hdr] = @id_bc_out_hdr
				delete from [dbo].[tbl_bc_out_dok] where [id_bc_out_hdr] = @id_bc_out_hdr
				delete from [dbo].[tbl_bc_out_dtl] where [id_bc_out_hdr] = @id_bc_out_hdr
				delete from [dbo].[tbl_bc_out_hdr] where [id_bc_out_hdr] = @id_bc_out_hdr
				
				update [dbo].[tblbc261_perhitungan_exim_asal_bc] set status_data='NEW' where [id_bc_out_hdr]=@id_bc_out_hdr  
				
				update tbl_bahanpenolong_memo set status_data = 'PROSESEXIM',typedok = NULL, ndpbm =NULL,id_bc_out_hdr=NULL 
				where id_bc_out_hdr = @id_bc_out_hdr  and typedok = 'BC261' 
				update tbl_alatkantor_memo set status_data = 'PROSESEXIM',typedok = NULL, ndpbm =NULL,id_bc_out_hdr=NULL 
				where id_bc_out_hdr = @id_bc_out_hdr  and typedok = 'BC261' 
				
				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, 'DATA CANCELED..Silahkan Upload ulang DATA jika akan diulang' as description
			
			
		 ");
		 $rs = $qry->result_array();
		// $r = $qry->result();		
		//var_dump($rs);die();	
		
		
		
		
		foreach ($rs as $row){
			$status = $row['status'];
			$msg = $row['description'];
		}
		
		echo json_encode(array('sts' => $status, 'desc' => $msg));	
	
	
	}
	
	function excelperhitungan_exim(){
		$id_hdr = (isset($_REQUEST['id_hdr']) && !empty($_REQUEST['id_hdr']))?$_REQUEST['id_hdr']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$datenow = date('Y-m-d');
		
		$qry1 = $this->db->query("
				SELECT [id_bc261_exim_hdr]
				  ,[NPWPTUJU]
				  ,[NAMATUJU]
				  ,[ALMTTUJU]
				  ,[NOKONTRAK]
				  ,[TGLKONTRAK]
				  ,[custom_bond]
				  ,[kurs]
				  ,[kdval]
				  ,[jml_hari_kerja]
				  ,[periode_awal]
				  ,[periode_akhir]
				  ,[jenis_pekerjaan]
				  ,[status_data]
				  ,[create_date]
				  ,[create_by]
				  ,[update_date]
				  ,[update_by]
			  FROM [dbo].[tblbc261_perhitungan_exim_hdr]
			  where id_bc261_exim_hdr=$id_hdr
		");
		$rs1 = $qry1->result_array();
		$NAMATUJU = '';
		$NOKONTRAK='';
		$jenis_pekerjaan = '';
		$kurs = 1;
		foreach ($rs1 as $r1){
			$NAMATUJU = $r1["NAMATUJU"];
			$NOKONTRAK= $r1["NOKONTRAK"];
			$jenis_pekerjaan= $r1["jenis_pekerjaan"];
			$kurs= $r1["kurs"];
		}
		
		
		$qry2 = $this->db->query("
				SELECT [id_bc261_exim_dtl]
				  ,[id_bc261_exim_hdr]
				  ,[assy_code]
				  ,[assy_name]
				  ,[part_name_customs]
				  ,[part_number]
				  ,[kode_barang]
				  ,[qty]
				  ,[unit]
				  ,[harga_satuan]
				  ,[total_usd]
				  ,[nilai_pabean]
				  ,[ex_aju]
				  ,[ex_nodaft]
				  ,[ex_tgdaft]
				  ,[ex_nourut]
				  ,[hs]
				  ,[bm]
				  ,[ppn]
				  ,[pph]
				  ,[vendor]
				  ,[qty_modul]
				  ,[qty_dipakai]
			  FROM [dbo].[tblbc261_perhitungan_exim_dtl]
			  where id_bc261_exim_hdr=$id_hdr
		");
		$rs2 = $qry2->result_array();
		
		 $q_count = $this->db->query("
			select count (*) as cnt
			 FROM [dbo].[tblbc261_perhitungan_exim_dtl]
			  where id_bc261_exim_hdr=$id_hdr


		");
        $rowc = $q_count->result_array();
        foreach ($rowc as $c){
            $cnt = $c["cnt"];
        }
		
		include_once ( APPPATH."libraries/PHPExcel.php");	
		include_once ( APPPATH."libraries/PHPExcel/IOFactory.php");	
		$phpExcel = new PHPExcel();
		$objTpl = PHPExcel_IOFactory::load(APPPATH."libraries/PHPExcel/templates/perhitungan_exim.xls");	
		$objTpl->setActiveSheetIndex(0);  //set first sheet as active
		
		$objTpl->getActiveSheet()->setCellValue('C3', ':'.$NAMATUJU);
		$objTpl->getActiveSheet()->setCellValue('C4', ':'.$NOKONTRAK);
		$objTpl->getActiveSheet()->setCellValue('C5', ':'.'Pembuatan ' . $jenis_pekerjaan);
		$objTpl->getActiveSheet()->setCellValue('D10', 'SET');
		$objTpl->getActiveSheet()->setCellValue('B10', $jenis_pekerjaan);
		
		$part_name_customs = '';
		$qty=0;
		$unit = '';
		$harga_satuan = 0;
		
		$i = 1;
        $j = '';
        $k = 9;
		
		foreach ($rs2 as $r2){
			
			$k = 9 + $i;
            $j = "$k";	
			$objTpl->getActiveSheet()->setCellValue("E".$j, $r2['part_name_customs']);
			$objTpl->getActiveSheet()->setCellValue("F".$j, $r2['qty']);
			$objTpl->getActiveSheet()->setCellValue("G".$j, strtoupper($r2['unit']));
			$objTpl->getActiveSheet()->setCellValue("H".$j, $r2['harga_satuan']);
			$objTpl->getActiveSheet()->setCellValue("I".$j, $r2['harga_satuan'] * $r2['qty'] );
			$objTpl->getActiveSheet()->setCellValue("J".$j, $r2['harga_satuan'] * $r2['qty'] * $kurs );
			$objTpl->getActiveSheet()->setCellValueExplicit("K".$j, $r2['ex_aju']);
			$objTpl->getActiveSheet()->setCellValueExplicit("L".$j, $r2['ex_nodaft']);
			$objTpl->getActiveSheet()->setCellValue("M".$j, $r2['ex_tgdaft']);
			$objTpl->getActiveSheet()->setCellValue("N".$j, $r2['ex_nourut']);
			$objTpl->getActiveSheet()->setCellValueExplicit("O".$j, $r2['hs']);
			$objTpl->getActiveSheet()->setCellValue("P".$j, $r2['bm']);
			$objTpl->getActiveSheet()->setCellValue("Q".$j, ($r2['bm'] * $r2['harga_satuan'] * $r2['qty'] * $kurs)/100);
			$objTpl->getActiveSheet()->setCellValue("R".$j, ($r2['ppn'] * $r2['harga_satuan'] * $r2['qty'] * $kurs)/100);
			
			$i++;
		}
		
		
		if($cnt != 0){
			$objTpl->getActiveSheet()->getStyle("F10:"."F".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			$objTpl->getActiveSheet()->getStyle("H10:"."H".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			$objTpl->getActiveSheet()->getStyle("I10:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			$objTpl->getActiveSheet()->getStyle("J10:"."J".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			$objTpl->getActiveSheet()->getStyle("Q10:"."Q".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			$objTpl->getActiveSheet()->getStyle("R10:"."R".$j)->getNumberFormat()->setFormatCode('#,##0.00');
		
		}
		
		
		$objTpl->setActiveSheetIndex(0);  //set first sheet as active
		$filename =  "perhitungan_exim". "_$datenow";
		
		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 savetoexcelbc261(){
		$id_bc_out_hdr = (isset($_GET['id_bc_out_hdr']) && !empty($_GET['id_bc_out_hdr']))?$_GET['id_bc_out_hdr']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$datenow = date('Y-m-d');
		
		$qry = $this->db->query("

			SELECT [id_bc_out_hdr]
			  ,[CAR]
			  ,[JnEks]
			  ,[KatEks]
			  ,[JNPEB]
			  ,[JNEKSOld]
			  ,[JNLAIN]
			  ,[JNDAG]
			  ,[JNBYR]
			  ,[IDEKS]
			  ,[NPWPEKS]
			  ,[NamaEks]
			  ,[AlmtEks]
			  ,[NoSiup]
			  ,[TgSiup]
			  ,[JnPerus]
			  ,[NoTdp]
			  ,[TgTdp]
			  ,[Niper]
			  ,[StatusH]
			  ,[IdQq]
			  ,[NpwpQq]
			  ,[NamaQq]
			  ,[AlmtQq]
			  ,[NiperQq]
			  ,[NAMABELI]
			  ,[ALMTBELI]
			  ,[NEGBELI]
			  ,[IDPPJK]
			  ,[NPWPPPJK]
			  ,[NamaPpjk]
			  ,[AlmtPpjk]
			  ,[NoPpjk]
			  ,[TgPpjk]
			  ,[MODA]
			  ,[TGEKS]
			  ,[CARRIER]
			  ,[VOY]
			  ,[NOSHIPORD]
			  ,[TGSHIPORD]
			  ,[PELMUAT]
			  ,[PELBONGKAR]
			  ,[PELTRANSIT]
			  ,[NOINV]
			  ,convert(varchar, [TGINV], 106) as TGINV
			  ,[NOLPSE]
			  ,[TGLPSE]
			  ,[PROPBRG]
			  ,[NEGTUJU]
			  ,[FLSIE]
			  ,[FLKARANT]
			  ,[FLSM]
			  ,[FLIZLAIN]
			  ,[DELIVERY]
			  ,[KDVAL]
			  ,[KdHrg]
			  ,[NilInv]
			  ,[FREIGHT]
			  ,[ASURANSI]
			  ,[KdAss]
			  ,[FOB]
			  ,[MERK]
			  ,[JMCONT]
			  ,[BRUTO]
			  ,[NETTO]
			  ,[JMBRG]
			  ,[JMBRGCTH]
			  ,[JMBRGGAB]
			  ,[JMBRGPJT]
			  ,[NODAFT]
			  ,convert(varchar, [TGDAFT], 106) as TGDAFT
			  ,[KDKTR]
			  ,[KTRGATE]
			  ,[NILPE]
			  ,[KDBANK]
			  ,[LOKBANK]
			  ,[NOSSP]
			  ,[TGSSP]
			  ,[JNTPB]
			  ,[LOKTPB]
			  ,[KDLOKBRG]
			  ,[KDKTRMUAT]
			  ,[KDKTRPRIKS]
			  ,[TGSIAP]
			  ,[WKSIAP]
			  ,[ASALDATA]
			  ,[TPNAME]
			  ,[PEBOK]
			  ,[LENGKAP]
			  ,[JNPARTOF]
			  ,[BENDERA]
			  ,[TTDPEB]
			  ,[STATUS]
			  ,[SNRF]
			  ,[NOBCF]
			  ,[TGBCF]
			  ,[SERIBCF]
			  ,[NOMOREDI]
			  ,[KMDT]
			  ,[VOLUME]
			  ,[KDHANGGAR]
			  ,[KONS]
			  ,[JMLKMSPEB]
			  ,[PELMUATEKS]
			  ,[NILKURS]
			  ,[PNBP]
			  ,[NOBC11]
			  ,[TGBC11]
			  ,[POSBC11]
			  ,[SUBPOSBC11]
			  ,[create_date]
			  ,[create_by]
			  ,[update_date]
			  ,[update_by]
			  ,[typedok]
			  ,[statusdok]
			  ,[noinv1]
			  ,[tginv1]
			  ,[inv_hdr_id]
			  ,[bc_in_from_in]
			  ,[nopol]
			  ,(SELECT TOP 1 [tblKpbc].[UrKdKpbc] FROM [tblKpbc] WHERE [tblKpbc].[KdKpbc] = [KDKTR]) AS KantorTujuan 
			  ,(SELECT TOP 1 [Registrasi] FROM [dbo].[tblImportir]) AS Registrasi
			  ,(SELECT SUM ([tbl_bc_out_dtl].DNilInv) FROM [dbo].[tbl_bc_out_dtl] where [tbl_bc_out_dtl].id_bc_out_hdr = [tbl_bc_out_hdr].id_bc_out_hdr) AS NilaiCIF
			  ,((SELECT SUM ([tbl_bc_out_dtl].DNilInv) FROM [dbo].[tbl_bc_out_dtl] where [tbl_bc_out_dtl].id_bc_out_hdr = [tbl_bc_out_hdr].id_bc_out_hdr)*[tbl_bc_out_hdr].NILKURS) as HargaPenyerahan
			  
			  FROM [dbo].[tbl_bc_out_hdr] WHERE 1=1 and typedok='BC261' 
			  and id_bc_out_hdr= $id_bc_out_hdr
		");
		
				
		$rs = $qry->result_array();
		$CAR = '';
		$nodaft = '';
		$TGDAFT = '';
		$NOINV = '';
		$TGINV = '';
		$NILKURS = 0;
		$FREIGHT = 0;
		
		foreach($rs as $row){
			$CAR = $row['CAR'];
			$nodaft = $row['NODAFT'];
			$TGDAFT = $row['TGDAFT'];
			$NOINV = $row['NOINV'];
			$TGINV = $row['TGINV'];
			$NILKURS = $row['NILKURS'];
			$FREIGHT = $row['FREIGHT'];
		}	
		
		$qry_dtl= $this->db->query("
			SELECT [id_bc_out_dtl]
			  ,[id_bc_out_hdr] ,[HS]
			  ,[URBRG1]
			  ,[JMSATUAN]
			  ,[JNSATUAN]
			  ,[DNilInv]
			FROM [dbo].[tbl_bc_out_dtl] where id_bc_out_hdr = $id_bc_out_hdr
		");
		
		$rs_dtl = $qry_dtl->result_array();
		$jmldtl = $qry_dtl->num_rows();
		
		$qry_dtl_nil_inv= $this->db->query("
			SELECT 
				sum([DNilInv]) as NilInv
			FROM [dbo].[tbl_bc_out_dtl] where id_bc_out_hdr = $id_bc_out_hdr
		");	
		$rs_dtl_nil_inv = $qry_dtl_nil_inv->result_array();
		$NilInv = 0;
		foreach($rs_dtl_nil_inv as $row){
			$NilInv = $row['NilInv'];
		}	
		
		$qry_asal_bc= $this->db->query("
			SELECT 
				sum([qty_dipakai] * [harga_satuan] * [bm] * $NILKURS /100 ) as bm
				,sum([qty_dipakai] * [harga_satuan] * [ppn] * $NILKURS /100 ) as ppn
				,sum([qty_dipakai] * [harga_satuan] * [pph] * $NILKURS /100 ) as pph
			FROM [dbo].[tblbc261_perhitungan_exim_asal_bc] where id_bc_out_hdr = $id_bc_out_hdr
		");	
		$rs_asal_bc = $qry_asal_bc->result_array();
		$bm = 0;
		$ppn = 0;
		$pph = 0;
		foreach($rs_asal_bc as $row_asal_bc){
			$bm = $row_asal_bc['bm'];
			$ppn = $row_asal_bc['ppn'];
			$pph = $row_asal_bc['pph'];
		}	
		
		include_once ( APPPATH."libraries/PHPExcel.php");	
		include_once ( APPPATH."libraries/PHPExcel/IOFactory.php");	
		$phpExcel = new PHPExcel();
		$objTpl = PHPExcel_IOFactory::load(APPPATH."libraries/PHPExcel/templates/bc261.xls");	
		
		$objTpl->getActiveSheet()->setCellValueExplicit("E5", $CAR);
		$objTpl->getActiveSheet()->setCellValueExplicit("J6", $nodaft);
		$objTpl->getActiveSheet()->setCellValue("J8", $TGDAFT);
		$objTpl->getActiveSheet()->setCellValue("K55", $TGDAFT);
		$objTpl->getActiveSheet()->setCellValue("E20", $NOINV);
		$objTpl->getActiveSheet()->setCellValue("F20", $TGINV);
		$objTpl->getActiveSheet()->setCellValue("J24", $NilInv);
		$objTpl->getActiveSheet()->setCellValue("E25", $NILKURS);
		$objTpl->getActiveSheet()->setCellValue("J41", $FREIGHT);
		$objTpl->getActiveSheet()->setCellValue("F39", $bm);
		$objTpl->getActiveSheet()->setCellValue("F41", 0);
		$objTpl->getActiveSheet()->setCellValue("F45", 0);
		$objTpl->getActiveSheet()->setCellValue("F43", $ppn);
		$objTpl->getActiveSheet()->setCellValue("F47", $pph);
		$objTpl->getActiveSheet()->setCellValue("C35", " ======= " . $jmldtl . " jenis barang lihat lembar lanjutan=======");
		
		$objTpl->setActiveSheetIndex(1);  //set first sheet as active
		$i = 1;
        $j = '';
        $k = 15;
		
		foreach ($rs_dtl as $r2){
			
			$k = 15 + $i;
            $j = "$k";	
			$objTpl->getActiveSheet()->setCellValue("B".$j, $i);
			$objTpl->getActiveSheet()->setCellValue("C".$j, $r2['URBRG1']);
			$objTpl->getActiveSheet()->setCellValue("H".$j, 'JAPAN');
			$objTpl->getActiveSheet()->setCellValue("J".$j, $r2['JMSATUAN']);
			$objTpl->getActiveSheet()->setCellValue("K".$j, strtoupper($r2['JNSATUAN']));
			$objTpl->getActiveSheet()->setCellValue("L".$j, $r2['DNilInv']);
			
			$i++;
		}
		
		if($jmldtl != 0){
			$objTpl->getActiveSheet()->getStyle("J16:"."J".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			$objTpl->getActiveSheet()->getStyle("L16:"."L".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			
		}
		
		$objTpl->setActiveSheetIndex(0);  //set first sheet as active
		$filename =  "bc261". "_$datenow";
		
		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_bc261_matching_ceisa(){
		$data["param"] = "";
		$this->load->view('exim/view_bc261_matching_ceisa', $data);
		
	}
	
	function datamodul_detil_ceisa(){
		
		$bc23dir = $this->config->item('APP_modulbc23');
		$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']:'car'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$tglawalbc41_ceisacar = (isset($_POST['tglawalbc41_ceisacar']) && !empty($_POST['tglawalbc41_ceisacar']))?$_POST['tglawalbc41_ceisacar']:date('Y-m-d');
		$tglakhirbc41_ceisacar = (isset($_POST['tglakhirbc41_ceisacar']) && !empty($_POST['tglakhirbc41_ceisacar']))?$_POST['tglakhirbc41_ceisacar']:date('Y-m-d');
		
		$car = (isset($_POST['car']) && !empty($_POST['car']))?$_POST['car']:'';
		
		$where = " 1=1 ";
		
		$where = " CAST(SUBSTRING(a.NOMOR_AJU,21,6) as int) < 500000 and c.KODE_DOKUMEN ='261' and  a.KODE_DOKUMEN_PABEAN ='41' and  convert(varchar(10),a.TANGGAL_AJU,126) between '$tglawalbc41_ceisacar' and '$tglakhirbc41_ceisacar' ";
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					if ( $k->field == "CAR" ) {
						$searchString = $k->data;
						$where .= " and a.NOMOR_AJU like  '%".$searchString."%'"; 
					} else if ( $k->field == "carx" ) {
						$searchString = $k->data;
						$where .= " and b.car like  '%".$searchString."%'"; 
					}  
				}
			}
		}
		
		
		if (!empty($car)){
			
			$where = " CAST(SUBSTRING(a.NOMOR_AJU,21,6) as int) < 500000 and c.KODE_DOKUMEN ='261' and a.NOMOR_AJU like '%$car%' and a.KODE_DOKUMEN_PABEAN ='41'  ";
		}
		
		$this->db->query("
			SET ANSI_NULLS ON
			SET ANSI_WARNINGS ON
		");
		
		$query = $this->db->query("
			
			select count(*) as cnt from openquery(TPBDB,'select * from tpb_header') a
			left outer join tbl_bc_out_hdr b on a.NOMOR_AJU = b.CAR
			inner join openquery(TPBDB,'select * from referensi_status')   c on c.KODE_STATUS = a.KODE_STATUS
			where $where 
			
		
		");
	
		
		$result = $query->result_array();
		
		$cnt = 0;
		foreach ($result as $row){
		
			$cnt = $row['cnt'];
		
		}
				
		$count=$cnt;
		if( $count >0 ) { $total_pages = ceil($count/$limit); } 
			else { $total_pages = 0; } 
		if ($page > $total_pages) $page=$total_pages; 
		$start = $limit*$page - $limit; // do not put $limit*($page - 1) if ($start<0) $start = 0;
		$batas = $count - (($page - 1) * $limit);
		
		 $q = $this->db->query("
			select top $limit car, convert(varchar(10), xdate, 126) as xdate,  carx, 
			sts,
			jnsbarang,NOMOR_DAFTAR,TANGGAL_DAFTAR,id_bc_out_hdr, ID,
			URAIAN_STATUS
			 from (
				select TOP $batas a.NOMOR_AJU as CAR, a.TANGGAL_AJU as xdate
				,b.car as carx, 
				a.KODE_STATUS as sts, a.KODE_DOKUMEN_PABEAN as jnsbarang 
				,a.NOMOR_DAFTAR as NOMOR_DAFTAR, CONVERT(varchar(10),a.TANGGAL_DAFTAR, 126) as TANGGAL_DAFTAR
				,b.id_bc_out_hdr ,a.ID as ID, c.URAIAN_STATUS
				from openquery(TPBDB,'select * from tpb_header') a 
				inner join openquery(TPBDB,'select * from referensi_status') c on c.KODE_STATUS = a.KODE_STATUS
				left outer join dbo.tbl_bc_out_hdr b on a.NOMOR_AJU = b.car
				where $where
				order by $sidx desc
			)  t1 Order By car $sord
			
			"); 
		$rs = $q->result_array();
		//echo $this->db->last_query(); die();
		
		// var_dump($rs);
		// die(); 
		
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =(integer) $count;
		$i=0;
		
		foreach ($rs as $r){
			
			$responce->rows[$i]["CAR"]=$r["car"];
			$responce->rows[$i]["carx"]=$r["carx"];
			$responce->rows[$i]["xdate"]=$r["xdate"];
	    	$responce->rows[$i]["NOMOR_DAFTAR"]=$r["NOMOR_DAFTAR"];
			$responce->rows[$i]["TANGGAL_DAFTAR"]=$r["TANGGAL_DAFTAR"]; 
			$responce->rows[$i]["sts"]=$r["sts"];
			$responce->rows[$i]["jnsbarang"]=$r["jnsbarang"];
			$responce->rows[$i]["id_bc_out_hdr"]=$r["id_bc_out_hdr"];
			$responce->rows[$i]["ID"]=$r["ID"];
			$responce->rows[$i]["URAIAN_STATUS"]=$r["URAIAN_STATUS"];
			$i++;
		}
		
		echo json_encode($responce);
		die();
	}
	
	function proses_bahanpenolong_memo(){
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username=$this->session->userdata('DX_username');
		$qry = $this->db->query("
			declare @id_memo bigint = '$id_memo', @id_bc_out_hdr bigint, @now date = GETDATE()
			BEGIN TRY
				
				insert into tbl_bc_out_hdr (
					dbo.tbl_bc_out_hdr.CAR,
					dbo.tbl_bc_out_hdr.JnEks,
					dbo.tbl_bc_out_hdr.KatEks,
					dbo.tbl_bc_out_hdr.JNDAG,
					dbo.tbl_bc_out_hdr.JNBYR,
					dbo.tbl_bc_out_hdr.IDEKS,
					dbo.tbl_bc_out_hdr.NPWPEKS,
					dbo.tbl_bc_out_hdr.NamaEks,
					dbo.tbl_bc_out_hdr.AlmtEks,
					dbo.tbl_bc_out_hdr.NoSiup,
					dbo.tbl_bc_out_hdr.TgSiup,
					dbo.tbl_bc_out_hdr.JnPerus,
					dbo.tbl_bc_out_hdr.NoTdp,
					dbo.tbl_bc_out_hdr.TgTdp,
					dbo.tbl_bc_out_hdr.Niper,
					dbo.tbl_bc_out_hdr.StatusH,
					dbo.tbl_bc_out_hdr.NAMABELI,
					dbo.tbl_bc_out_hdr.ALMTBELI,
					dbo.tbl_bc_out_hdr.NEGBELI,
					dbo.tbl_bc_out_hdr.MODA,
					dbo.tbl_bc_out_hdr.PROPBRG,
					dbo.tbl_bc_out_hdr.NEGTUJU,
					dbo.tbl_bc_out_hdr.DELIVERY,
					dbo.tbl_bc_out_hdr.KDVAL,
					dbo.tbl_bc_out_hdr.KdHrg,
					dbo.tbl_bc_out_hdr.NilInv,
					dbo.tbl_bc_out_hdr.FOB,
					dbo.tbl_bc_out_hdr.JMCONT,
					dbo.tbl_bc_out_hdr.BRUTO,
					dbo.tbl_bc_out_hdr.NETTO,
					dbo.tbl_bc_out_hdr.JMBRG,
					dbo.tbl_bc_out_hdr.KDKTR,
					dbo.tbl_bc_out_hdr.KTRGATE,
					dbo.tbl_bc_out_hdr.JNTPB,
					dbo.tbl_bc_out_hdr.KDLOKBRG,
					dbo.tbl_bc_out_hdr.NpwpQq,
					dbo.tbl_bc_out_hdr.NILKURS,
					dbo.tbl_bc_out_hdr.typedok,
					dbo.tbl_bc_out_hdr.statusdok,
					dbo.tbl_bc_out_hdr.bc_in_from_in,
					dbo.tbl_bc_out_hdr.create_date,
					dbo.tbl_bc_out_hdr.create_by,
					dbo.tbl_bc_out_hdr.update_date,
					dbo.tbl_bc_out_hdr.update_by
				) 
				SELECT 
					'-' as CAR
					,1 as JnEks
					,41 as KatEks
					,3 as JNDAG
					,4 as JNBYR
					,5 as IDEKS
					,(select top 1 NPWPEKS from dbo.tblEksportir) as [NPWPEKS]
					,(select top 1 NamaEks from dbo.tblEksportir) as [NamaEks]
					,(select top 1 AlmtEks from dbo.tblEksportir) as [AlmtEks]
					,(select top 1 NoSiup from dbo.tblEksportir) as [NoSiup]
					,(select top 1 TgSiup  from dbo.tblEksportir) as [TgSiup]
					,(select top 1 JnPerus from dbo.tblEksportir) as [JnPerus]
					,(select top 1 NoTdp from dbo.tblEksportir) as [NoTdp]
					,(select top 1 TgTdp from dbo.tblEksportir) as [TgTdp]
					,(select top 1 Niper from dbo.tblEksportir) as [Niper]
					,(select top 1 StatusH from dbo.tblEksportir) as [StatusH]

					,nama_pembeli as NAMABELI
					,(SELECT top 1 supplier_address from tbl_data_supplier where subcode_as400 = tbl_bahanpenolong_memo.kode_pembeli ) as ALMTBELI
					,'ID' as NEGBELI
					,1 as MODA
					,3671 as PROPBRG
					,'ID' as NEGTUJU
					,'FOB' as DELIVERY
					,kdval as KDVAL
					,1 as KdHrg
					,harga_penyerahan as NilInv
					,harga_penyerahan as FOB
					,1 as JMCONT
					,bruto as BRUTO
					,(select sum(netto) from tbl_bahanpenolong_out where id_memo_bp =  @id_memo and doc_out_to = 3	 ) as NETTO
					,(select count(*) from tbl_bahanpenolong_out where id_memo_bp =  @id_memo and doc_out_to = 3	 ) as JMBRG
					,'150100' as KDKTR
					,'150300' as KTRGATE
					,'KB' as JNTPB
					,'1' as KDLOKBRG
					, SUBSTRING(dbo.axRegexReplace(isnull(npwp_pembeli,''),'[^\d]',''),1,15) as NpwpQq
					,(select dbo.get_rate_valuta(GETDATE(),kdval)) as NILKURS
					,'BC261' as typedok
					,'DATA BARU' as statusdok
					,'MEMOBP' as bc_in_from_in
					,@now
					,'$username'
					,@now
					,'$username'
					from tbl_bahanpenolong_memo 
					where id_memo = @id_memo
					set @id_bc_out_hdr = SCOPE_IDENTITY()
									
					insert into tbl_bc_out_dtl (

						dbo.tbl_bc_out_dtl.id_bc_out_hdr,
						dbo.tbl_bc_out_dtl.SERIBRG,
						dbo.tbl_bc_out_dtl.HS,
						dbo.tbl_bc_out_dtl.URBRG1,
						dbo.tbl_bc_out_dtl.URBRG2,
						dbo.tbl_bc_out_dtl.URBRG3,
						dbo.tbl_bc_out_dtl.URBRG4,
						dbo.tbl_bc_out_dtl.DMERK,
						dbo.tbl_bc_out_dtl.[SIZE],
						dbo.tbl_bc_out_dtl.TYPE,
						dbo.tbl_bc_out_dtl.KDBRG,
						dbo.tbl_bc_out_dtl.JMKOLI,
						dbo.tbl_bc_out_dtl.JNKOLI,
						dbo.tbl_bc_out_dtl.DNilInv,
						dbo.tbl_bc_out_dtl.FOBPERBRG,
						dbo.tbl_bc_out_dtl.JMSATUAN,
						dbo.tbl_bc_out_dtl.JNSATUAN,
						dbo.tbl_bc_out_dtl.NETDET,
						dbo.tbl_bc_out_dtl.NegAsal

				) SELECT

					@id_bc_out_hdr
					,row_number() over(order by (select 0)) as SERIBRG
					,hs_kode as HS
					,SUBSTRING(part_name, 1, 40) as URBRG1
					,SUBSTRING(part_name, 41, 40) as URBRG2
					,SUBSTRING(part_name, 81, 40) as URBRG3
					,SUBSTRING(part_name, 121, 40) as URBRG4
					,'-' as DMERK
					,'-' as [SIZE]
					,'-' as TYPE
					,part_no as KDBRG
					,jmkemas as JMKOLI
					,SUBSTRING(jnkemas, 1, 2) as JNKOLI
					,round((price *  qty), 4) as DNilInv
					,price as FOBPERBRG
					,qty as JMSATUAN
					,uom as JNSATUAN
					,netto as  NETDET
					,'ID' as NegAsal

					from tbl_bahanpenolong_out 
					where id_memo_bp =  @id_memo and doc_out_to = 3

					insert into tbl_bc_out_dok (
					id_bc_out_hdr	
					,kddok
						,nodok
						,tgdok
					) SELECT
					@id_bc_out_hdr
					 ,'380'
					,nomor_memo
					,tgl_memo
					from tbl_bahanpenolong_memo 
					where id_memo = @id_memo

				insert into tbl_bc_out_dok (
					id_bc_out_hdr	
					,kddok
						,nodok
						,tgdok
				) 
				SELECT
					@id_bc_out_hdr
					, '217'
					,nomor_memo
					,tgl_memo
					from tbl_bahanpenolong_memo 
				where id_memo = @id_memo
				
				INSERT INTO tbl_bc_out_hdr_h_status
					  (id_bc_out_hdr, statusdok, status_date
							  ,[create_by]
							  ,[create_date]
							  ,[update_by]
							  ,[update_date])
				VALUES     (@id_bc_out_hdr, (select top 1 statusdok from tbl_bc_out_hdr where id_bc_out_hdr = @id_bc_out_hdr), @now
					,'''+@userid+'''
					,@now
					,'''+@userid+'''
					,@now
				)
				declare @ndpbm float, @kdval varchar(5)
				select
					@kdval=kdval
				from  tbl_bahanpenolong_memo where	 id_memo = @id_memo 
				set @ndpbm = (select dbo.get_rate_valuta(@now,@kdval))
				update tbl_bahanpenolong_memo set status_data = 'PROCESSEDBC', typedok='BC261', ndpbm=@ndpbm,id_bc_out_hdr=@id_bc_out_hdr 	where id_memo = @id_memo 
				
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description
			 ");
		 $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 proses_bahanpenolong_memo_scrap(){
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username=$this->session->userdata('DX_username');
		$qry = $this->db->query("
			declare @id_memo bigint = '$id_memo', @id_bc_out_hdr bigint, @now date = GETDATE()
			BEGIN TRY
				
				insert into tbl_bc_out_hdr (
					dbo.tbl_bc_out_hdr.CAR,
					dbo.tbl_bc_out_hdr.JnEks,
					dbo.tbl_bc_out_hdr.KatEks,
					dbo.tbl_bc_out_hdr.JNDAG,
					dbo.tbl_bc_out_hdr.JNBYR,
					dbo.tbl_bc_out_hdr.IDEKS,
					dbo.tbl_bc_out_hdr.NPWPEKS,
					dbo.tbl_bc_out_hdr.NamaEks,
					dbo.tbl_bc_out_hdr.AlmtEks,
					dbo.tbl_bc_out_hdr.NoSiup,
					dbo.tbl_bc_out_hdr.TgSiup,
					dbo.tbl_bc_out_hdr.JnPerus,
					dbo.tbl_bc_out_hdr.NoTdp,
					dbo.tbl_bc_out_hdr.TgTdp,
					dbo.tbl_bc_out_hdr.Niper,
					dbo.tbl_bc_out_hdr.StatusH,
					dbo.tbl_bc_out_hdr.NAMABELI,
					dbo.tbl_bc_out_hdr.ALMTBELI,
					dbo.tbl_bc_out_hdr.NEGBELI,
					dbo.tbl_bc_out_hdr.MODA,
					dbo.tbl_bc_out_hdr.PROPBRG,
					dbo.tbl_bc_out_hdr.NEGTUJU,
					dbo.tbl_bc_out_hdr.DELIVERY,
					dbo.tbl_bc_out_hdr.KDVAL,
					dbo.tbl_bc_out_hdr.KdHrg,
					dbo.tbl_bc_out_hdr.NilInv,
					dbo.tbl_bc_out_hdr.FOB,
					dbo.tbl_bc_out_hdr.JMCONT,
					dbo.tbl_bc_out_hdr.BRUTO,
					dbo.tbl_bc_out_hdr.NETTO,
					dbo.tbl_bc_out_hdr.JMBRG,
					dbo.tbl_bc_out_hdr.KDKTR,
					dbo.tbl_bc_out_hdr.KTRGATE,
					dbo.tbl_bc_out_hdr.JNTPB,
					dbo.tbl_bc_out_hdr.KDLOKBRG,
					dbo.tbl_bc_out_hdr.NpwpQq,
					dbo.tbl_bc_out_hdr.NILKURS,
					dbo.tbl_bc_out_hdr.typedok,
					dbo.tbl_bc_out_hdr.statusdok,
					dbo.tbl_bc_out_hdr.bc_in_from_in,
					dbo.tbl_bc_out_hdr.create_date,
					dbo.tbl_bc_out_hdr.create_by,
					dbo.tbl_bc_out_hdr.update_date,
					dbo.tbl_bc_out_hdr.update_by
				) 
				SELECT 
					'-' as CAR
					,1 as JnEks
					,41 as KatEks
					,3 as JNDAG
					,4 as JNBYR
					,5 as IDEKS
					,(select top 1 NPWPEKS from dbo.tblEksportir) as [NPWPEKS]
					,(select top 1 NamaEks from dbo.tblEksportir) as [NamaEks]
					,(select top 1 AlmtEks from dbo.tblEksportir) as [AlmtEks]
					,(select top 1 NoSiup from dbo.tblEksportir) as [NoSiup]
					,(select top 1 TgSiup  from dbo.tblEksportir) as [TgSiup]
					,(select top 1 JnPerus from dbo.tblEksportir) as [JnPerus]
					,(select top 1 NoTdp from dbo.tblEksportir) as [NoTdp]
					,(select top 1 TgTdp from dbo.tblEksportir) as [TgTdp]
					,(select top 1 Niper from dbo.tblEksportir) as [Niper]
					,(select top 1 StatusH from dbo.tblEksportir) as [StatusH]

					,nama_pembeli as NAMABELI
					,(SELECT top 1 supplier_address from tbl_data_supplier where subcode_as400 = tbl_bahanpenolong_memo.kode_pembeli ) as ALMTBELI
					,'ID' as NEGBELI
					,1 as MODA
					,3671 as PROPBRG
					,'ID' as NEGTUJU
					,'FOB' as DELIVERY
					,kdval as KDVAL
					,1 as KdHrg
					,round(((select  sum(dbo.tbl_bahanpenolong_memo_scrap.harga_scrap) from tbl_bahanpenolong_memo_scrap where id_memo =  @id_memo ) * (select sum(dbo.tbl_bahanpenolong_memo_scrap.qty_scrap)  from tbl_bahanpenolong_memo_scrap where id_memo =  @id_memo)), 4) as NilInv
					,round(((select  sum(dbo.tbl_bahanpenolong_memo_scrap.harga_scrap) from tbl_bahanpenolong_memo_scrap where id_memo =  @id_memo ) * (select sum(dbo.tbl_bahanpenolong_memo_scrap.qty_scrap)  from tbl_bahanpenolong_memo_scrap where id_memo =  @id_memo)), 4) as FOB
					,1 as JMCONT
					,bruto as BRUTO
					,(select sum(netto_scrap) from tbl_bahanpenolong_memo_scrap where id_memo =  @id_memo ) as NETTO
					,(select count(cnt) from (
						select count(kode_scrap) as cnt from tbl_bahanpenolong_memo_scrap where id_memo =  @id_memo GROUP BY kode_scrap
						) x
					) as JMBRG
					,'150100' as KDKTR
					,'150300' as KTRGATE
					,'KB' as JNTPB
					,'1' as KDLOKBRG
					, SUBSTRING(dbo.axRegexReplace(isnull(npwp_pembeli,''),'[^\d]',''),1,15) as NpwpQq
					,(select dbo.get_rate_valuta(GETDATE(),kdval)) as NILKURS
					,'BC261' as typedok
					,'DATA BARU' as statusdok
					,'MEMOBPSCR' as bc_in_from_in
					,@now
					,'admin'
					,@now
					,'admin'
					from tbl_bahanpenolong_memo 
					where id_memo = @id_memo
					set @id_bc_out_hdr = SCOPE_IDENTITY()
									
					insert into tbl_bc_out_dtl (

						dbo.tbl_bc_out_dtl.id_bc_out_hdr,
						dbo.tbl_bc_out_dtl.SERIBRG,
						dbo.tbl_bc_out_dtl.HS,
						dbo.tbl_bc_out_dtl.URBRG1,
						dbo.tbl_bc_out_dtl.URBRG2,
						dbo.tbl_bc_out_dtl.URBRG3,
						dbo.tbl_bc_out_dtl.URBRG4,
						dbo.tbl_bc_out_dtl.DMERK,
						dbo.tbl_bc_out_dtl.[SIZE],
						dbo.tbl_bc_out_dtl.TYPE,
						dbo.tbl_bc_out_dtl.KDBRG,
						dbo.tbl_bc_out_dtl.JMKOLI,
						dbo.tbl_bc_out_dtl.JNKOLI,
						dbo.tbl_bc_out_dtl.DNilInv,
						dbo.tbl_bc_out_dtl.FOBPERBRG,
						dbo.tbl_bc_out_dtl.JMSATUAN,
						dbo.tbl_bc_out_dtl.JNSATUAN,
						dbo.tbl_bc_out_dtl.NETDET,
						dbo.tbl_bc_out_dtl.NegAsal

				) SELECT

					@id_bc_out_hdr
					,row_number() over(order by (select 0)) as SERIBRG
					,(select hs_code from tbl_scrap_data where part_no = dbo.tbl_bahanpenolong_memo_scrap.kode_scrap ) as HS
					,SUBSTRING(dbo.tbl_bahanpenolong_memo_scrap.nama_scrap, 1, 40) as URBRG1
					,SUBSTRING(dbo.tbl_bahanpenolong_memo_scrap.nama_scrap, 41, 40) as URBRG2
					,SUBSTRING(dbo.tbl_bahanpenolong_memo_scrap.nama_scrap, 81, 40) as URBRG3
					,SUBSTRING(dbo.tbl_bahanpenolong_memo_scrap.nama_scrap, 121, 40) as URBRG4
					,'-' as DMERK
					,'-' as [SIZE]
					,'-' as TYPE
					,dbo.tbl_bahanpenolong_memo_scrap.kode_scrap as KDBRG
					,sum(dbo.tbl_bahanpenolong_memo_scrap.jmkemas_scrap) as JMKOLI
					,SUBSTRING(jnkemas_scrap, 1, 2) as JNKOLI
					,round((sum(dbo.tbl_bahanpenolong_memo_scrap.harga_scrap) *  sum(dbo.tbl_bahanpenolong_memo_scrap.qty_scrap)), 4) as DNilInv
					,sum(dbo.tbl_bahanpenolong_memo_scrap.harga_scrap) as FOBPERBRG
					,sum(dbo.tbl_bahanpenolong_memo_scrap.qty_scrap) as JMSATUAN
					,dbo.tbl_bahanpenolong_memo_scrap.satuan as JNSATUAN
					,sum(dbo.tbl_bahanpenolong_memo_scrap.netto_scrap) as  NETDET
					,'ID' as NegAsal
FROM
					dbo.tbl_bahanpenolong_memo_scrap where id_memo = @id_memo
				GROUP BY
					kode_scrap, nama_scrap, satuan, jnkemas_scrap

					insert into tbl_bc_out_dok (
					id_bc_out_hdr	
					,kddok
						,nodok
						,tgdok
					) SELECT
					@id_bc_out_hdr
					 ,'380'
					,nomor_memo
					,tgl_memo
					from tbl_bahanpenolong_memo 
					where id_memo = @id_memo

				insert into tbl_bc_out_dok (
					id_bc_out_hdr	
					,kddok
						,nodok
						,tgdok
				) 
				SELECT
					@id_bc_out_hdr
					, '217'
					,nomor_memo
					,tgl_memo
					from tbl_bahanpenolong_memo 
				where id_memo = @id_memo
				
				INSERT INTO tbl_bc_out_hdr_h_status
					  (id_bc_out_hdr, statusdok, status_date
							  ,[create_by]
							  ,[create_date]
							  ,[update_by]
							  ,[update_date])
				VALUES     (@id_bc_out_hdr, (select top 1 statusdok from tbl_bc_out_hdr where id_bc_out_hdr = @id_bc_out_hdr), @now
					,'''+@userid+'''
					,@now
					,'''+@userid+'''
					,@now
				)
				declare @ndpbm float, @kdval varchar(5)
				select
					@kdval=kdval
				from  tbl_bahanpenolong_memo where	 id_memo = @id_memo 
				set @ndpbm = (select dbo.get_rate_valuta(@now,@kdval))
				update tbl_bahanpenolong_memo set status_data = 'PROCESSEDBC', typedok='BC261', ndpbm=@ndpbm,id_bc_out_hdr=@id_bc_out_hdr 	where id_memo = @id_memo 
				
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description
			 ");
		 $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 proses_alatkantor_memo(){
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username=$this->session->userdata('DX_username');
		$qry = $this->db->query("
			declare @id_memo bigint = '$id_memo', @id_bc_out_hdr bigint, @now date = GETDATE()
			BEGIN TRY
				
				insert into tbl_bc_out_hdr (
					dbo.tbl_bc_out_hdr.CAR,
					dbo.tbl_bc_out_hdr.JnEks,
					dbo.tbl_bc_out_hdr.KatEks,
					dbo.tbl_bc_out_hdr.JNDAG,
					dbo.tbl_bc_out_hdr.JNBYR,
					dbo.tbl_bc_out_hdr.IDEKS,
					dbo.tbl_bc_out_hdr.NPWPEKS,
					dbo.tbl_bc_out_hdr.NamaEks,
					dbo.tbl_bc_out_hdr.AlmtEks,
					dbo.tbl_bc_out_hdr.NoSiup,
					dbo.tbl_bc_out_hdr.TgSiup,
					dbo.tbl_bc_out_hdr.JnPerus,
					dbo.tbl_bc_out_hdr.NoTdp,
					dbo.tbl_bc_out_hdr.TgTdp,
					dbo.tbl_bc_out_hdr.Niper,
					dbo.tbl_bc_out_hdr.StatusH,
					dbo.tbl_bc_out_hdr.NAMABELI,
					dbo.tbl_bc_out_hdr.ALMTBELI,
					dbo.tbl_bc_out_hdr.NEGBELI,
					dbo.tbl_bc_out_hdr.MODA,
					dbo.tbl_bc_out_hdr.PROPBRG,
					dbo.tbl_bc_out_hdr.NEGTUJU,
					dbo.tbl_bc_out_hdr.DELIVERY,
					dbo.tbl_bc_out_hdr.KDVAL,
					dbo.tbl_bc_out_hdr.KdHrg,
					dbo.tbl_bc_out_hdr.NilInv,
					dbo.tbl_bc_out_hdr.FOB,
					dbo.tbl_bc_out_hdr.JMCONT,
					dbo.tbl_bc_out_hdr.BRUTO,
					dbo.tbl_bc_out_hdr.NETTO,
					dbo.tbl_bc_out_hdr.JMBRG,
					dbo.tbl_bc_out_hdr.KDKTR,
					dbo.tbl_bc_out_hdr.KTRGATE,
					dbo.tbl_bc_out_hdr.JNTPB,
					dbo.tbl_bc_out_hdr.KDLOKBRG,
					dbo.tbl_bc_out_hdr.NpwpQq,
					dbo.tbl_bc_out_hdr.NILKURS,
					dbo.tbl_bc_out_hdr.typedok,
					dbo.tbl_bc_out_hdr.statusdok,
					dbo.tbl_bc_out_hdr.bc_in_from_in,
					dbo.tbl_bc_out_hdr.create_date,
					dbo.tbl_bc_out_hdr.create_by,
					dbo.tbl_bc_out_hdr.update_date,
					dbo.tbl_bc_out_hdr.update_by
				) 
				SELECT 
					'-' as CAR
					,1 as JnEks
					,41 as KatEks
					,3 as JNDAG
					,4 as JNBYR
					,5 as IDEKS
					,(select top 1 NPWPEKS from dbo.tblEksportir) as [NPWPEKS]
					,(select top 1 NamaEks from dbo.tblEksportir) as [NamaEks]
					,(select top 1 AlmtEks from dbo.tblEksportir) as [AlmtEks]
					,(select top 1 NoSiup from dbo.tblEksportir) as [NoSiup]
					,(select top 1 TgSiup  from dbo.tblEksportir) as [TgSiup]
					,(select top 1 JnPerus from dbo.tblEksportir) as [JnPerus]
					,(select top 1 NoTdp from dbo.tblEksportir) as [NoTdp]
					,(select top 1 TgTdp from dbo.tblEksportir) as [TgTdp]
					,(select top 1 Niper from dbo.tblEksportir) as [Niper]
					,(select top 1 StatusH from dbo.tblEksportir) as [StatusH]

					,nama_pembeli as NAMABELI
					,(SELECT top 1 supplier_address from tbl_data_supplier where subcode_as400 = tbl_alatkantor_memo.kode_pembeli ) as ALMTBELI
					,'ID' as NEGBELI
					,1 as MODA
					,3671 as PROPBRG
					,'ID' as NEGTUJU
					,'FOB' as DELIVERY
					,kdval as KDVAL
					,1 as KdHrg
					,harga_penyerahan as NilInv
					,harga_penyerahan as FOB
					,1 as JMCONT
					,bruto as BRUTO
					,(select sum(netto) from tbl_alatkantor_out where id_memo_ak =  @id_memo and doc_out_to = 3	 ) as NETTO
					,(select count(*) from tbl_alatkantor_out where id_memo_ak =  @id_memo and doc_out_to = 3	 ) as JMBRG
					,'150100' as KDKTR
					,'150300' as KTRGATE
					,'KB' as JNTPB
					,'1' as KDLOKBRG
					, SUBSTRING(dbo.axRegexReplace(isnull(npwp_pembeli,''),'[^\d]',''),1,15) as NpwpQq
					,(select dbo.get_rate_valuta(GETDATE(),kdval)) as NILKURS
					,'BC261' as typedok
					,'DATA BARU' as statusdok
					,'MEMOBP' as bc_in_from_in
					,@now
					,'$username'
					,@now
					,'$username'
					from tbl_alatkantor_memo 
					where id_memo = @id_memo
					set @id_bc_out_hdr = SCOPE_IDENTITY()
									
					insert into tbl_bc_out_dtl (

						dbo.tbl_bc_out_dtl.id_bc_out_hdr,
						dbo.tbl_bc_out_dtl.SERIBRG,
						dbo.tbl_bc_out_dtl.HS,
						dbo.tbl_bc_out_dtl.URBRG1,
						dbo.tbl_bc_out_dtl.URBRG2,
						dbo.tbl_bc_out_dtl.URBRG3,
						dbo.tbl_bc_out_dtl.URBRG4,
						dbo.tbl_bc_out_dtl.DMERK,
						dbo.tbl_bc_out_dtl.[SIZE],
						dbo.tbl_bc_out_dtl.TYPE,
						dbo.tbl_bc_out_dtl.KDBRG,
						dbo.tbl_bc_out_dtl.JMKOLI,
						dbo.tbl_bc_out_dtl.JNKOLI,
						dbo.tbl_bc_out_dtl.DNilInv,
						dbo.tbl_bc_out_dtl.FOBPERBRG,
						dbo.tbl_bc_out_dtl.JMSATUAN,
						dbo.tbl_bc_out_dtl.JNSATUAN,
						dbo.tbl_bc_out_dtl.NETDET,
						dbo.tbl_bc_out_dtl.NegAsal

				) SELECT

					@id_bc_out_hdr
					,row_number() over(order by (select 0)) as SERIBRG
					,hs_kode as HS
					,SUBSTRING(part_name, 1, 40) as URBRG1
					,SUBSTRING(part_name, 41, 40) as URBRG2
					,SUBSTRING(part_name, 81, 40) as URBRG3
					,SUBSTRING(part_name, 121, 40) as URBRG4
					,'-' as DMERK
					,'-' as [SIZE]
					,'-' as TYPE
					,part_no as KDBRG
					,jmkemas as JMKOLI
					,SUBSTRING(jnkemas, 1, 2) as JNKOLI
					,round((price *  qty), 4) as DNilInv
					,price as FOBPERBRG
					,qty as JMSATUAN
					,uom as JNSATUAN
					,netto as  NETDET
					,'ID' as NegAsal

					from tbl_alatkantor_out 
					where id_memo_ak =  @id_memo and doc_out_to = 3

					insert into tbl_bc_out_dok (
					id_bc_out_hdr	
					,kddok
						,nodok
						,tgdok
					) SELECT
					@id_bc_out_hdr
					 ,'380'
					,nomor_memo
					,tgl_memo
					from tbl_alatkantor_memo 
					where id_memo = @id_memo

				insert into tbl_bc_out_dok (
					id_bc_out_hdr	
					,kddok
						,nodok
						,tgdok
				) 
				SELECT
					@id_bc_out_hdr
					, '217'
					,nomor_memo
					,tgl_memo
					from tbl_alatkantor_memo 
				where id_memo = @id_memo
				
				INSERT INTO tbl_bc_out_hdr_h_status
					  (id_bc_out_hdr, statusdok, status_date
							  ,[create_by]
							  ,[create_date]
							  ,[update_by]
							  ,[update_date])
				VALUES     (@id_bc_out_hdr, (select top 1 statusdok from tbl_bc_out_hdr where id_bc_out_hdr = @id_bc_out_hdr), @now
					,'''+@userid+'''
					,@now
					,'''+@userid+'''
					,@now
				)
				declare @ndpbm float, @kdval varchar(5)
				select
					@kdval=kdval
				from  tbl_alatkantor_memo where	 id_memo = @id_memo 
				set @ndpbm = (select dbo.get_rate_valuta(@now,@kdval))
				update tbl_alatkantor_memo set status_data = 'PROCESSEDBC', typedok='BC261', ndpbm=@ndpbm,id_bc_out_hdr=@id_bc_out_hdr 	where id_memo = @id_memo 
				
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description
			 ");
		 $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 proses_alatkantor_memo_scrap(){
		$id_memo = (isset($_POST['id_memo']) && !empty($_POST['id_memo']))?$_POST['id_memo']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username=$this->session->userdata('DX_username');
		$qry = $this->db->query("
			declare @id_memo bigint = '$id_memo', @id_bc_out_hdr bigint, @now date = GETDATE()
			BEGIN TRY
				
				insert into tbl_bc_out_hdr (
					dbo.tbl_bc_out_hdr.CAR,
					dbo.tbl_bc_out_hdr.JnEks,
					dbo.tbl_bc_out_hdr.KatEks,
					dbo.tbl_bc_out_hdr.JNDAG,
					dbo.tbl_bc_out_hdr.JNBYR,
					dbo.tbl_bc_out_hdr.IDEKS,
					dbo.tbl_bc_out_hdr.NPWPEKS,
					dbo.tbl_bc_out_hdr.NamaEks,
					dbo.tbl_bc_out_hdr.AlmtEks,
					dbo.tbl_bc_out_hdr.NoSiup,
					dbo.tbl_bc_out_hdr.TgSiup,
					dbo.tbl_bc_out_hdr.JnPerus,
					dbo.tbl_bc_out_hdr.NoTdp,
					dbo.tbl_bc_out_hdr.TgTdp,
					dbo.tbl_bc_out_hdr.Niper,
					dbo.tbl_bc_out_hdr.StatusH,
					dbo.tbl_bc_out_hdr.NAMABELI,
					dbo.tbl_bc_out_hdr.ALMTBELI,
					dbo.tbl_bc_out_hdr.NEGBELI,
					dbo.tbl_bc_out_hdr.MODA,
					dbo.tbl_bc_out_hdr.PROPBRG,
					dbo.tbl_bc_out_hdr.NEGTUJU,
					dbo.tbl_bc_out_hdr.DELIVERY,
					dbo.tbl_bc_out_hdr.KDVAL,
					dbo.tbl_bc_out_hdr.KdHrg,
					dbo.tbl_bc_out_hdr.NilInv,
					dbo.tbl_bc_out_hdr.FOB,
					dbo.tbl_bc_out_hdr.JMCONT,
					dbo.tbl_bc_out_hdr.BRUTO,
					dbo.tbl_bc_out_hdr.NETTO,
					dbo.tbl_bc_out_hdr.JMBRG,
					dbo.tbl_bc_out_hdr.KDKTR,
					dbo.tbl_bc_out_hdr.KTRGATE,
					dbo.tbl_bc_out_hdr.JNTPB,
					dbo.tbl_bc_out_hdr.KDLOKBRG,
					dbo.tbl_bc_out_hdr.NpwpQq,
					dbo.tbl_bc_out_hdr.NILKURS,
					dbo.tbl_bc_out_hdr.typedok,
					dbo.tbl_bc_out_hdr.statusdok,
					dbo.tbl_bc_out_hdr.bc_in_from_in,
					dbo.tbl_bc_out_hdr.create_date,
					dbo.tbl_bc_out_hdr.create_by,
					dbo.tbl_bc_out_hdr.update_date,
					dbo.tbl_bc_out_hdr.update_by
				) 
				SELECT 
					'-' as CAR
					,1 as JnEks
					,41 as KatEks
					,3 as JNDAG
					,4 as JNBYR
					,5 as IDEKS
					,(select top 1 NPWPEKS from dbo.tblEksportir) as [NPWPEKS]
					,(select top 1 NamaEks from dbo.tblEksportir) as [NamaEks]
					,(select top 1 AlmtEks from dbo.tblEksportir) as [AlmtEks]
					,(select top 1 NoSiup from dbo.tblEksportir) as [NoSiup]
					,(select top 1 TgSiup  from dbo.tblEksportir) as [TgSiup]
					,(select top 1 JnPerus from dbo.tblEksportir) as [JnPerus]
					,(select top 1 NoTdp from dbo.tblEksportir) as [NoTdp]
					,(select top 1 TgTdp from dbo.tblEksportir) as [TgTdp]
					,(select top 1 Niper from dbo.tblEksportir) as [Niper]
					,(select top 1 StatusH from dbo.tblEksportir) as [StatusH]

					,nama_pembeli as NAMABELI
					,(SELECT top 1 supplier_address from tbl_data_supplier where subcode_as400 = tbl_alatkantor_memo.kode_pembeli ) as ALMTBELI
					,'ID' as NEGBELI
					,1 as MODA
					,3671 as PROPBRG
					,'ID' as NEGTUJU
					,'FOB' as DELIVERY
					,kdval as KDVAL
					,1 as KdHrg
					,round(((select  sum(dbo.tbl_alatkantor_memo_scrap.harga_scrap) from tbl_alatkantor_memo_scrap where id_memo =  @id_memo ) * (select sum(dbo.tbl_alatkantor_memo_scrap.qty_scrap)  from tbl_alatkantor_memo_scrap where id_memo =  @id_memo)), 4) as NilInv
					,round(((select  sum(dbo.tbl_alatkantor_memo_scrap.harga_scrap) from tbl_alatkantor_memo_scrap where id_memo =  @id_memo ) * (select sum(dbo.tbl_alatkantor_memo_scrap.qty_scrap)  from tbl_alatkantor_memo_scrap where id_memo =  @id_memo)), 4) as FOB
					,1 as JMCONT
					,bruto as BRUTO
					,(select sum(netto_scrap) from tbl_alatkantor_memo_scrap where id_memo =  @id_memo ) as NETTO
					,(select count(cnt) from (
						select count(kode_scrap) as cnt from tbl_alatkantor_memo_scrap where id_memo =  @id_memo GROUP BY kode_scrap
						) x
					) as JMBRG
					,'150100' as KDKTR
					,'150300' as KTRGATE
					,'KB' as JNTPB
					,'1' as KDLOKBRG
					, SUBSTRING(dbo.axRegexReplace(isnull(npwp_pembeli,''),'[^\d]',''),1,15) as NpwpQq
					,(select dbo.get_rate_valuta(GETDATE(),kdval)) as NILKURS
					,'BC261' as typedok
					,'DATA BARU' as statusdok
					,'MEMOBPSCR' as bc_in_from_in
					,@now
					,'admin'
					,@now
					,'admin'
					from tbl_alatkantor_memo 
					where id_memo = @id_memo
					set @id_bc_out_hdr = SCOPE_IDENTITY()
									
					insert into tbl_bc_out_dtl (

						dbo.tbl_bc_out_dtl.id_bc_out_hdr,
						dbo.tbl_bc_out_dtl.SERIBRG,
						dbo.tbl_bc_out_dtl.HS,
						dbo.tbl_bc_out_dtl.URBRG1,
						dbo.tbl_bc_out_dtl.URBRG2,
						dbo.tbl_bc_out_dtl.URBRG3,
						dbo.tbl_bc_out_dtl.URBRG4,
						dbo.tbl_bc_out_dtl.DMERK,
						dbo.tbl_bc_out_dtl.[SIZE],
						dbo.tbl_bc_out_dtl.TYPE,
						dbo.tbl_bc_out_dtl.KDBRG,
						dbo.tbl_bc_out_dtl.JMKOLI,
						dbo.tbl_bc_out_dtl.JNKOLI,
						dbo.tbl_bc_out_dtl.DNilInv,
						dbo.tbl_bc_out_dtl.FOBPERBRG,
						dbo.tbl_bc_out_dtl.JMSATUAN,
						dbo.tbl_bc_out_dtl.JNSATUAN,
						dbo.tbl_bc_out_dtl.NETDET,
						dbo.tbl_bc_out_dtl.NegAsal

				) SELECT

					@id_bc_out_hdr
					,row_number() over(order by (select 0)) as SERIBRG
					,(select hs_code from tbl_scrap_data where part_no = dbo.tbl_alatkantor_memo_scrap.kode_scrap ) as HS
					,SUBSTRING(dbo.tbl_alatkantor_memo_scrap.nama_scrap, 1, 40) as URBRG1
					,SUBSTRING(dbo.tbl_alatkantor_memo_scrap.nama_scrap, 41, 40) as URBRG2
					,SUBSTRING(dbo.tbl_alatkantor_memo_scrap.nama_scrap, 81, 40) as URBRG3
					,SUBSTRING(dbo.tbl_alatkantor_memo_scrap.nama_scrap, 121, 40) as URBRG4
					,'-' as DMERK
					,'-' as [SIZE]
					,'-' as TYPE
					,dbo.tbl_alatkantor_memo_scrap.kode_scrap as KDBRG
					,sum(dbo.tbl_alatkantor_memo_scrap.jmkemas_scrap) as JMKOLI
					,SUBSTRING(jnkemas_scrap, 1, 2) as JNKOLI
					,round((sum(dbo.tbl_alatkantor_memo_scrap.harga_scrap) *  sum(dbo.tbl_alatkantor_memo_scrap.qty_scrap)), 4) as DNilInv
					,sum(dbo.tbl_alatkantor_memo_scrap.harga_scrap) as FOBPERBRG
					,sum(dbo.tbl_alatkantor_memo_scrap.qty_scrap) as JMSATUAN
					,dbo.tbl_alatkantor_memo_scrap.satuan as JNSATUAN
					,sum(dbo.tbl_alatkantor_memo_scrap.netto_scrap) as  NETDET
					,'ID' as NegAsal
FROM
					dbo.tbl_alatkantor_memo_scrap where id_memo = @id_memo
				GROUP BY
					kode_scrap, nama_scrap, satuan, jnkemas_scrap

					insert into tbl_bc_out_dok (
					id_bc_out_hdr	
					,kddok
						,nodok
						,tgdok
					) SELECT
					@id_bc_out_hdr
					 ,'380'
					,nomor_memo
					,tgl_memo
					from tbl_alatkantor_memo 
					where id_memo = @id_memo

				insert into tbl_bc_out_dok (
					id_bc_out_hdr	
					,kddok
						,nodok
						,tgdok
				) 
				SELECT
					@id_bc_out_hdr
					, '217'
					,nomor_memo
					,tgl_memo
					from tbl_alatkantor_memo 
				where id_memo = @id_memo
				
				INSERT INTO tbl_bc_out_hdr_h_status
					  (id_bc_out_hdr, statusdok, status_date
							  ,[create_by]
							  ,[create_date]
							  ,[update_by]
							  ,[update_date])
				VALUES     (@id_bc_out_hdr, (select top 1 statusdok from tbl_bc_out_hdr where id_bc_out_hdr = @id_bc_out_hdr), @now
					,'''+@userid+'''
					,@now
					,'''+@userid+'''
					,@now
				)
				declare @ndpbm float, @kdval varchar(5)
				select
					@kdval=kdval
				from  tbl_alatkantor_memo where	 id_memo = @id_memo 
				set @ndpbm = (select dbo.get_rate_valuta(@now,@kdval))
				update tbl_alatkantor_memo set status_data = 'PROCESSEDBC', typedok='BC261', ndpbm=@ndpbm,id_bc_out_hdr=@id_bc_out_hdr 	where id_memo = @id_memo 
				
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			SELECT 
				'00' AS status
				,' SUKSES' AS description
			 ");
		 $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_bc261_send_ceisa(){
		$this->mysql =$this->load->database('mysql', TRUE);	
		
		$id_bc_out_hdr = (isset($_POST['id_bc_out_hdr']) && !empty($_POST['id_bc_out_hdr']))?$_POST['id_bc_out_hdr']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$q = $this->db->query("select car, nodok as dokno, convert(char(10),tgdok,126) as doktg from tbl_bc_out_dok where id_bc_out_hdr = $id_bc_out_hdr and kddok='380'  ");
		
		$no_inv = "";
		$pre = "";
		
		foreach($q->result() as $r){
			$pre = "<br />";
			$no_inv .= $r->dokno . " # " . $r->doktg . $pre;
		}
		$carr = "";
		$q_car = $this->db->query("
			select car from tbl_bc_out_hdr where id_bc_out_hdr = $id_bc_out_hdr
		");
		foreach ($q_car->result() as $rcar){
			$carr = $rcar->car;
		}
		
		$q_last_car = $this->mysql->query("
			select NOMOR_AJU from tpb_header where KODE_DOKUMEN_PABEAN = '261'  and SUBSTR(NOMOR_AJU, 21, 6) < 5000 order by NOMOR_AJU desc limit 1
		");
		$last_car = "";
		foreach($q_last_car->result() as $r){
			$last_car = $r->NOMOR_AJU;
		}
		
		$this->db->query("
			SET ANSI_NULLS ON
			SET ANSI_WARNINGS ON
		");
		
		$next_car="";
		$q_car = $this->db->query("
			select dbo.FN_CEISA_GET_CAR_AUTO(261,50000) as a
		");
		foreach ($q_car->result() as $rcar){
			$next_car = $rcar->a;
		}
		
		$data['id_bc_out_hdr'] = $id_bc_out_hdr;
		$data['no_inv'] = $no_inv;
		$data['last_car'] = $last_car;
		$data['next_car'] = $next_car;
		$data['car'] = $carr;
		$this->load->view('exim/view_bc261_send_ceisa', $data);
		
	}
	
	function proses_bc261_ceisa(){
		$this->mysql =$this->load->database('mysql', TRUE);	
		$id_bc_out_hdr = (isset($_POST['id_bc_out_hdr']) && !empty($_POST['id_bc_out_hdr']))?$_POST['id_bc_out_hdr']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$this->db->query("
			SET ANSI_NULLS ON
			SET ANSI_WARNINGS ON
		");
		
		$next_car="";
		$q_car = $this->db->query("
			select dbo.FN_CEISA_GET_CAR_AUTO(261,50000) as a
		");
		foreach ($q_car->result() as $rcar){
			$next_car = $rcar->a;
		}
		$ID_MODUL = (int)substr($next_car, 6,6);
		$my_ref_pengusaha = $this->mysql->query("
			SELECT
			referensi_pengusaha.ID,
			referensi_pengusaha.ALAMAT,
			referensi_pengusaha.CONTACT_PERSON,
			referensi_pengusaha.EMAIL,
			referensi_pengusaha.FAX,
			referensi_pengusaha.ID_PENGENAL,
			referensi_pengusaha.JENISTPB,
			referensi_pengusaha.KODE_ID,
			referensi_pengusaha.KODE_KANTOR,
			referensi_pengusaha.NAMA,
			referensi_pengusaha.NOMOR_PENGENAL,
			referensi_pengusaha.NOMOR_SKEP,
			referensi_pengusaha.NPWP,
			referensi_pengusaha.STATUS_IMPORTIR,
			referensi_pengusaha.TANGGAL_SKEP,
			referensi_pengusaha.TELEPON
			FROM
			referensi_pengusaha limit 1
			
		");
		$ALAMAT = "";
		$KODE_ID = "";
		$NAMA = "";
		$NOMOR_SKEP = "";
		$TANGGAL_SKEP = "";
		$NPWP = "";
		$ID = "";
		$ID_PENGENAL = "";
		$NOMOR_PENGENAL = "";
		
		foreach ($my_ref_pengusaha->result() as $r){
			$ALAMAT = $r->ALAMAT;
			$KODE_ID = $r->KODE_ID;
			$NAMA = $r->NAMA;
			$NOMOR_SKEP = $r->NOMOR_SKEP;
			$TANGGAL_SKEP = $r->TANGGAL_SKEP;
			$NPWP = $r->NPWP;
			$ID = $r->ID;
			$ID_PENGENAL = $r->ID_PENGENAL;
			$NOMOR_PENGENAL = $r->NOMOR_PENGENAL;
		}
		
		$q_hdr=$this->db->query("
			select
			  dbo.tbl_bc_out_hdr.CAR,
				dbo.tbl_bc_out_hdr.JnEks,
				dbo.tbl_bc_out_hdr.KatEks,
				dbo.tbl_bc_out_hdr.JNDAG,
				dbo.tbl_bc_out_hdr.JNBYR,
				dbo.tbl_bc_out_hdr.IDEKS,
				dbo.tbl_bc_out_hdr.NPWPEKS,
				dbo.tbl_bc_out_hdr.NamaEks,
				dbo.tbl_bc_out_hdr.AlmtEks,
				dbo.tbl_bc_out_hdr.NoSiup,
				dbo.tbl_bc_out_hdr.TgSiup,
				dbo.tbl_bc_out_hdr.JnPerus,
				dbo.tbl_bc_out_hdr.NoTdp,
				dbo.tbl_bc_out_hdr.TgTdp,
				dbo.tbl_bc_out_hdr.Niper,
				dbo.tbl_bc_out_hdr.StatusH,
				dbo.tbl_bc_out_hdr.NAMABELI,
				dbo.tbl_bc_out_hdr.ALMTBELI,
				dbo.tbl_bc_out_hdr.NEGBELI,
				dbo.tbl_bc_out_hdr.MODA,
				dbo.tbl_bc_out_hdr.PROPBRG,
				dbo.tbl_bc_out_hdr.NEGTUJU,
				dbo.tbl_bc_out_hdr.DELIVERY,
				dbo.tbl_bc_out_hdr.KDVAL,
				dbo.tbl_bc_out_hdr.KdHrg,
				dbo.tbl_bc_out_hdr.NilInv,
				dbo.tbl_bc_out_hdr.FOB,
				dbo.tbl_bc_out_hdr.JMCONT,
				dbo.tbl_bc_out_hdr.BRUTO,
				dbo.tbl_bc_out_hdr.NETTO,
				dbo.tbl_bc_out_hdr.JMBRG,
				dbo.tbl_bc_out_hdr.KDKTR,
				dbo.tbl_bc_out_hdr.KTRGATE,
				dbo.tbl_bc_out_hdr.JNTPB,
				dbo.tbl_bc_out_hdr.KDLOKBRG,
				dbo.tbl_bc_out_hdr.NpwpQq,
				dbo.tbl_bc_out_hdr.NILKURS
			  from 
			  [tbl_bc_out_hdr]
			  where  id_bc_out_hdr = $id_bc_out_hdr
		");
		if($q_hdr->num_rows == 0){
			echo json_encode(array('sts' => '06 ', 'desc' => "DATA TIDAK DITEMUKAN  $next_car ", 'insert_id' => 0 ));
			die();
		} 
		$NPWP_PEMBELI = "";
		foreach($q_hdr->result() as $r){
			$NPWP_PEMBELI = $r->NpwpQq;
		}
		if($NPWP_PEMBELI == ''){
			echo json_encode(array('sts' => '06 ', 'desc' => "DATA NPWP TIDAK DITEMUKAN  $NPWP_PEMBELI ", 'insert_id' => 0 ));
			die();
		}
		
		$my_ref_penerima = $this->mysql->query("
			SELECT
			referensi_pengusaha.ID,
			referensi_pengusaha.ALAMAT,
			referensi_pengusaha.CONTACT_PERSON,
			referensi_pengusaha.EMAIL,
			referensi_pengusaha.FAX,
			referensi_pengusaha.ID_PENGENAL,
			referensi_pengusaha.JENISTPB,
			referensi_pengusaha.KODE_ID,
			referensi_pengusaha.KODE_KANTOR,
			referensi_pengusaha.NAMA,
			referensi_pengusaha.NOMOR_PENGENAL,
			referensi_pengusaha.NOMOR_SKEP,
			referensi_pengusaha.NPWP,
			referensi_pengusaha.STATUS_IMPORTIR,
			referensi_pengusaha.TANGGAL_SKEP,
			referensi_pengusaha.TELEPON
			FROM
			referensi_pengusaha 
			where replace(replace(referensi_pengusaha.NPWP,'.',''),'-','')  = '$NPWP_PEMBELI'
			limit 1
			
		");

		$ALAMAT_PENERIMA = "";
		$KODE_ID_PENERIMA = "";
		$NAMA_PENERIMA = "";
		$NOMOR_SKEP_PENERIMA = "";
		$TANGGAL_SKEP_PENERIMA = "";
		$NPWP_PENERIMA = "";
		$ID_PENERIMA = "";
		$ID_PENGENAL_PENERIMA = "";
		$NOMOR_PENGENAL_PENERIMA = "";
		
		foreach ($my_ref_penerima->result() as $r){
			$ALAMAT_PENERIMA = $r->ALAMAT;
			$KODE_ID_PENERIMA = $r->KODE_ID;
			$NAMA_PENERIMA = $r->NAMA;
			$NOMOR_SKEP_PENERIMA = $r->NOMOR_SKEP;
			$TANGGAL_SKEP_PENERIMA = $r->TANGGAL_SKEP;
			$NPWP_PENERIMA = $r->NPWP;
			$ID_PENERIMA = $r->ID;
			$ID_PENGENAL_PENERIMA = $r->ID_PENGENAL;
			$NOMOR_PENGENAL_PENERIMA = $r->NOMOR_PENGENAL;
		}
		
		
		if($NPWP_PENERIMA == ''){
			echo json_encode(array('sts' => '06 ', 'desc' => "DATA NPWP TIDAK DITEMUKAN  $NPWP_PEMBELI ", 'insert_id' => 0 ));
			die();
		} 
		
		
		$qx = $this->db->query("
			select tipe_out from tbl_bahanpenolong_memo where id_bc_out_hdr = $id_bc_out_hdr
		");
		$KODE_TUJUAN_PENGIRIMAN = "1";
		foreach ($qx->result() as $rx){
			if($rx->tipe_out == 'REPAIR'){
				$KODE_TUJUAN_PENGIRIMAN = "4";
			} 
		} 
		
		$Namattd = "";
		$q_ttd = $this->db->query("
			select top 1 Namattd from tblImportir 
		");
		foreach ($q_ttd->result() as $r_ttd){
			$Namattd = $r_ttd->Namattd;
		}
		$NILKURS = 1;
		$hdr_array = array();
		foreach($q_hdr->result() as $r){
			$NILKURS = $r->NILKURS;
			$hdr_array[] = array(
				"ALAMAT_PENERIMA_BARANG" => $NAMA_PENERIMA,
				"ALAMAT_PENGUSAHA" => $ALAMAT,
				"API_PENGUSAHA" => $NOMOR_PENGENAL,
				"ASAL_DATA" => "I",
				"BRUTO" => $r->BRUTO,
				"CIF" => $r->NilInv,
				"HARGA_PENYERAHAN" => ((float)$r->NilInv * (float)$r->NILKURS),
				"ID_MODUL" => $ID_MODUL,
				"ID_PENERIMA_BARANG" => $NPWP_PENERIMA,
				"ID_PENGUSAHA" => $NPWP,
				"JABATAN_TTD" =>  "KUASA DIREKSI",
				"JUMLAH_BARANG" => $r->JMBRG,
				"JUMLAH_KEMASAN" => "1",
				"KODE_DOKUMEN_PABEAN" => "261",
				"KODE_ID_PENERIMA_BARANG" => "1",
				"KODE_ID_PENGUSAHA" => "1",
				"KODE_JENIS_TPB" => "1",
				"KODE_KANTOR" => "150300", 
				"KODE_KANTOR_TUJUAN" => "150300",
				"KODE_STATUS" => "00",
				"KODE_TUJUAN_PENGIRIMAN" => $KODE_TUJUAN_PENGIRIMAN,
				"KODE_TUJUAN_TPB" => "1",
				"KODE_VALUTA" => $r->KDVAL,
				"KOTA_TTD" => "TANGERANG",
				"NAMA_PENERIMA_BARANG" => $NAMA_PENERIMA,
				"NAMA_PENGANGKUT" => "TRUCK",
				"NAMA_PENGUSAHA" => $NAMA,
				"NAMA_TTD" => $Namattd,
				"NDPBM" => $r->NILKURS,
				"NETTO" => $r->NETTO,
				"NOMOR_AJU" => $next_car,
				"NOMOR_IJIN_TPB" => $NOMOR_SKEP,
				"NOMOR_IJIN_TPB_PENERIMA" => $NOMOR_SKEP_PENERIMA,
				"TANGGAL_AJU" => date("Y-m-d h:i:s"),
				"TANGGAL_TTD" => date("Y-m-d"),
				"VERSI_MODUL" => "3.1.7"
				
				
			);
		}	
		
		
		
		$q_dtl=$this->db->query("
			SELECT
				dbo.tbl_bc_out_dtl.SERIBRG,
				dbo.tbl_bc_out_dtl.HS,
				dbo.tbl_bc_out_dtl.URBRG1 + dbo.tbl_bc_out_dtl.URBRG2 + dbo.tbl_bc_out_dtl.URBRG3 + dbo.tbl_bc_out_dtl.URBRG4 as URAIAN,
				dbo.tbl_bc_out_dtl.DMERK,
				dbo.tbl_bc_out_dtl.[SIZE],
				dbo.tbl_bc_out_dtl.TYPE,
				dbo.tbl_bc_out_dtl.KDBRG,
				dbo.tbl_bc_out_dtl.JMKOLI,
				dbo.tbl_bc_out_dtl.JNKOLI,
				dbo.tbl_bc_out_dtl.DNilInv,
				dbo.tbl_bc_out_dtl.JMSATUAN,
				dbo.tbl_bc_out_dtl.JNSATUAN,
				dbo.tbl_bc_out_dtl.NETDET,
				dbo.tbl_bc_out_dtl.FOBPERBRG

				FROM
				dbo.tbl_bc_out_dtl
				where id_bc_out_hdr = $id_bc_out_hdr
		");
		
		$tpb_barang = array();
		foreach($q_dtl->result() as $r){
			$HARGA_PENYERAHAN = (float) $NILKURS * (float) $r->DNilInv;
			$tpb_barang[] = array(
				"CIF" => $r->DNilInv,
				"HARGA_PENYERAHAN" => $HARGA_PENYERAHAN,
				"JUMLAH_BAHAN_BAKU" => 0,
				"JUMLAH_SATUAN" => $r->JMSATUAN,
				"KODE_BARANG" => $r->KDBRG,
				"KODE_SATUAN" => $r->JNSATUAN,
				"KODE_STATUS" => "00",
				"MERK" => $r->DMERK,
				"NETTO" => $r->NETDET,
				"POS_TARIF" =>  $r->HS,
				"SERI_BARANG" => $r->SERIBRG,
				"TIPE" =>  $r->KDBRG,
				"URAIAN" => $r->URAIAN,
				
			);
		}	
		
		
		$q_dok=$this->db->query("
			select
			 [KdDok]
		 	 ,[NoDok]
		 	 ,CONVERT(varchar, [TgDok], 126) as TgDok
			  from 
			  tbl_bc_out_dok
			  where  id_bc_out_hdr = $id_bc_out_hdr 
		");
		
		
		$tpb_dokumen = array();
		$i = 1;
		foreach($q_dok->result() as $r){
			$tpb_dokumen[] = array(
				"KODE_JENIS_DOKUMEN" => $r->KdDok,
				"NOMOR_DOKUMEN" => $r->NoDok,
				"TANGGAL_DOKUMEN" => $r->TgDok,
				"TIPE_DOKUMEN" => "02",
				"SERI_DOKUMEN" => $i
				
			);
			$i++;
		}	
		
		$this->mysql->trans_start();
		$msg = $this->mysql->insert('tpb_header', $hdr_array[0]);
		$insert_id = $this->mysql->insert_id();
		$this->mysql->trans_complete();
		
		for ($x = 0; $x <= count($tpb_barang) - 1; $x++ ){
			$this->mysql->trans_start();
			$this->mysql->insert("tpb_barang", array_merge($tpb_barang[$x], array("ID_HEADER" => $insert_id)));
			$insert_id_dtl = $this->mysql->insert_id();
			$this->mysql->trans_complete();
			
		}
		
		for ($x = 0; $x <= count($tpb_dokumen) - 1; $x++ ){
			$this->mysql->insert("tpb_dokumen", array_merge($tpb_dokumen[$x], array("ID_HEADER" => $insert_id)));
		}
		
		if( !$msg )
		{
		   $errNo   = $this->mysql->_error_number();
		   $errMess = $this->mysql->_error_message();
		   echo json_encode(array('sts' => $errNo, 'desc' => $errMess));
		   die();		
		}
		$stsa = '00';
		$msga = $msg . ' DATA CREATED..';
		if ($stsa != 1){
			$status = '06';
			$msg = $stsa;
		}
		
		$q=$this->db->query("
			update tbl_bc_out_hdr set CAR='$next_car',  statusdok = 'DATA PROCESSED' where id_bc_out_hdr = $id_bc_out_hdr
		");
		
		echo json_encode(array('sts' => $stsa, 'desc' => $msga, 'insert_id' => $insert_id ));	
	}
	
	function proses_get_replace_bc41_ceisa(){
		$car = (isset($_POST['carproses_matchbc41_ceisa']) && !empty($_POST['carproses_matchbc41_ceisa']))?$_POST['carproses_matchbc41_ceisa']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_ceisa = (isset($_POST['id_ceisa']) && !empty($_POST['id_ceisa']))?$_POST['id_ceisa']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_bc_out_hdr = (isset($_POST['id_bc_out_hdr']) && !empty($_POST['id_bc_out_hdr']))?$_POST['id_bc_out_hdr']:'';
		$username=$this->session->userdata('DX_username');
		
		
		
		$this->db->query("
			SET ANSI_NULLS ON
			SET ANSI_WARNINGS ON
		");
		if ($id_bc_out_hdr != ''){
			$matchcar = $this->db->query("
				declare @car varchar(50)
				declare @NOMOR_DAFTAR varchar(50)
				declare @TANGGAL_DAFTAR date
				
				set @car = (select car from tbl_bc_out_hdr where id_bc_out_hdr = $id_bc_out_hdr) 
				
				BEGIN TRY
				if	(select 
					count(*)	
					from openquery(TPBDB,'select * from tpb_header where KODE_DOKUMEN_PABEAN =''41'' ')
					where NOMOR_AJU = @car and ) <> 1
				begin
					SELECT 
					'06' AS status
					,' CAR TIDAK DITEMUKAN ATAU LEBIH DARI SATU NOMOR AJU SAMA, GUNAKAN TARIK MANUAL' AS description
					return
				end	
				
				select 
					@NOMOR_DAFTAR=NOMOR_DAFTAR,
					@TANGGAL_DAFTAR=TANGGAL_DAFTAR	
				from openquery(TPBDB,'select * from tpb_header where KODE_DOKUMEN_PABEAN ='41' ')
				where NOMOR_AJU = @car
				
				update tbl_bc_out_hdr set NODAFT=@NOMOR_DAFTAR, TGDAFT=@TANGGAL_DAFTAR where id_bc_out_hdr = $id_bc_out_hdr  
				
				SELECT 
					'00' AS status
					,' NO DAFTAR : ' + @NOMOR_DAFTAR AS description;
				END TRY
				BEGIN CATCH 
					SELECT 
					'06' AS status
					,ERROR_MESSAGE() AS description;
					
				END CATCH;
				
			");
		} else {
			
			$q_con = $this->db->query("
				select count(*)  as cnt
				from openquery(TPBDB,'select * from tpb_kontainer where id_header=$id_ceisa ')
				where id_header=$id_ceisa
			");
			
			$JMCON = 0;
			foreach ($q_con->result() as $r_con){
				$JMCON =  $r_con->cnt;
			}
			
				
			$matchcar = $this->db->query("
				declare @car varchar(50)
				declare @carceisa varchar(50)
				declare @NOMOR_DAFTAR varchar(50)
				declare @TANGGAL_DAFTAR date
				declare @id_ceisa bigint
				set @id_ceisa = $id_ceisa
				
				set @carceisa = (select NOMOR_AJU from openquery(TPBDB,'select * from tpb_header where id = $id_ceisa ') where ID = @id_ceisa) 
				
				BEGIN TRY
					insert into [tbl_bc_out_hdr] (
						CAR
						,JnEks
						,KatEks
						,IDEKS
						,NPWPEKS
						,NamaEks
						,AlmtEks
						,NpwpQq
						,NAMABELI
						,ALMTBELI
						,CARRIER
						,MODA
						,KDVAL
						,NilInv
						,FOB
						,BRUTO
						,NETTO
						,JMBRG
						,NODAFT
						,TGDAFT
						,KDKTR
						,KTRGATE
						,JNTPB
						,TTDPEB
						,STATUS
						,NILKURS
						,NEGBELI
						,typedok
						,statusdok
						,bc_in_from_in
						,JMCONT 
						,[create_date]
					      ,[create_by]
					      ,[update_date]
					      ,[update_by]

					) select
					 NOMOR_AJU			
					,KODE_JENIS_TPB
					,'41'
					,KODE_ID_PENGUSAHA
					,ID_PENGUSAHA
					,NAMA_PENGUSAHA
					,SUBSTRING(ALAMAT_PENGUSAHA, 1, 70)
					,ID_PENERIMA_BARANG
					,NAMA_PENERIMA_BARANG
					,SUBSTRING(ALAMAT_PENERIMA_BARANG, 1, 70)
					,NAMA_PENGANGKUT
					,'1'	
					,KODE_VALUTA
					,HARGA_PENYERAHAN
					,HARGA_PENYERAHAN
					,BRUTO
					,NETTO
					,JUMLAH_BARANG
					,NOMOR_DAFTAR
					,TANGGAL_DAFTAR
					,KODE_KANTOR
					,KODE_KANTOR
					,'KB'
					,NAMA_TTD
					,KODE_STATUS
					,NDPBM
					,'ID'
					,'BC41'
					,'DATA PROCESSED'
					,'CEISA_BC41'
					,$JMCON
					,GETDATE()
					,'$username'
					,GETDATE()
					,'$username'
					 from openquery(TPBDB,'select * from tpb_header  where id = $id_ceisa ') where ID = @id_ceisa
				declare @id_hdrx bigint
				set @id_hdrx = @@IDENTITY 
				
				insert into tbl_bc_out_dtl (
					id_bc_out_hdr
					,CAR
					,[SERIBRG]
					,URBRG1
					,URBRG2
					,URBRG3
					,URBRG4
					,DMERK
					,SIZE
					,TYPE
					,KDBRG
					,JMKOLI
					,JNKOLI
					,DNilInv
					,FOBPERBRG
					,JMSATUAN
					,JNSATUAN
					,NETDET
					,DVolume
					,NegAsal
					,HS
				) select
				@id_hdrx
				,@carceisa
				,SERI_BARANG
				,SUBSTRING(URAIAN,1,40)
				,SUBSTRING(URAIAN,41,80)
				,SUBSTRING(URAIAN,81,120)
				,SUBSTRING(URAIAN,121,160)
				,MERK
				,UKURAN
				,TIPE
				,KODE_BARANG
				,JUMLAH_KEMASAN
				,KODE_KEMASAN
				,HARGA_PENYERAHAN
				,HARGA_SATUAN
				,JUMLAH_SATUAN
				,KODE_SATUAN
				,NETTO
				,VOLUME
				,KODE_NEGARA_ASAL
				,POS_TARIF
				 from openquery(TPBDB,'select * from tpb_barang  where ID_HEADER = $id_ceisa ') where ID_HEADER = @id_ceisa
				
				insert into tbl_bc_out_dok (
					id_bc_out_hdr
					,CAR
					,[KdDok]
			      ,[NoDok]
			      ,[TgDok]
					
				) select
				@id_hdrx
				,@carceisa
				,SUBSTRING(KODE_JENIS_DOKUMEN, 1, 3)
				,NOMOR_DOKUMEN
				,CONVERT(varchar(10), TANGGAL_DOKUMEN, 126)
				 from openquery(TPBDB,'select * from tpb_dokumen where ID_HEADER= $id_ceisa ') where ID_HEADER = @id_ceisa
				
				insert into tbl_bc_out_con (
					id_bc_out_hdr
					,CAR
					 ,[NoCont]
				      ,[Size]
				      ,[Type]
				      
					
				) select
				@id_hdrx
				,@carceisa
				,NOMOR_KONTAINER
				,KODE_UKURAN_KONTAINER
				,KODE_TIPE_KONTAINER
				 from openquery(TPBDB,'select * from tpb_kontainer where ID_HEADER= $id_ceisa ') where ID_HEADER = @id_ceisa
				
				insert into tbl_bc_out_kms (
					id_bc_out_hdr
					,CAR
					,[JnKemas]
     				 ,[JmKemas]
					
				) select
				@id_hdrx
				,@carceisa
				,KODE_JENIS_KEMASAN
				,JUMLAH_KEMASAN
				 from openquery(TPBDB,'select * from tpb_kemasan where ID_HEADER= $id_ceisa ') where ID_HEADER = @id_ceisa
					
				
				insert into [tbl_bc_out_bahan_baku] (
					[id_bc_out_hdr]
					,[CAR]
				    ,[ID]
			      ,[CIF]
			      ,[CIF_RUPIAH]
			      ,[HARGA_PENYERAHAN]
			      ,[HARGA_PEROLEHAN]
			      ,[JENIS_SATUAN]
			      ,[JUMLAH_SATUAN]
			      ,[KODE_ASAL_BAHAN_BAKU]
			      ,[KODE_BARANG]
			      ,[KODE_FASILITAS_DOKUMEN]
			      ,[KODE_JENIS_DOK_ASAL]
			      ,[KODE_KANTOR]
			      ,[KODE_SKEMA_TARIF]
			      ,[KODE_STATUS]
			      ,[MERK]
			      ,[NDPBM]
			      ,[NETTO]
			      ,[NOMOR_AJU_DOK_ASAL]
			      ,[NOMOR_DAFTAR_DOK_ASAL]
			      ,[POS_TARIF]
			      ,[SERI_BAHAN_BAKU]
			      ,[SERI_BARANG]
			      ,[SERI_BARANG_DOK_ASAL]
			      ,[SPESIFIKASI_LAIN]
			      ,[TANGGAL_DAFTAR_DOK_ASAL]
			      ,[TIPE]
			      ,[UKURAN]
			      ,[URAIAN]
			      ,[ID_BARANG]
			      ,[ID_HEADER]
				     
				) select
				@id_hdrx
				,@carceisa,
				ID,
				CIF,
				CIF_RUPIAH,
				HARGA_PENYERAHAN,
				HARGA_PEROLEHAN,
				JENIS_SATUAN,
				JUMLAH_SATUAN,
				KODE_ASAL_BAHAN_BAKU,
				KODE_BARANG,
				KODE_FASILITAS_DOKUMEN,
				KODE_JENIS_DOK_ASAL,
				KODE_KANTOR,
				KODE_SKEMA_TARIF,
				KODE_STATUS,
				MERK,
				NDPBM,
				NETTO,
				NOMOR_AJU_DOK_ASAL,
				NOMOR_DAFTAR_DOK_ASAL,
				POS_TARIF,
				SERI_BAHAN_BAKU,
				SERI_BARANG,
				SERI_BARANG_DOK_ASAL,
				SPESIFIKASI_LAIN,
				TANGGAL_DAFTAR_DOK_ASAL,
				TIPE,
				UKURAN,
				URAIAN,
				ID_BARANG,
				ID_HEADER

				 from openquery(TPBDB,'select * from tpb_bahan_baku where  ID_HEADER= $id_ceisa ') where ID_HEADER = @id_ceisa
					
				
				insert into [tbl_bc_out_bahan_baku_tarif] (
					[id_bc_out_hdr]
					,[CAR],
				  ID,
					JENIS_TARIF,
					JUMLAH_SATUAN,
					KODE_ASAL_BAHAN_BAKU,
					KODE_FASILITAS,
					KODE_KOMODITI_CUKAI,
					KODE_SATUAN,
					KODE_TARIF,
					NILAI_BAYAR,
					NILAI_FASILITAS,
					NILAI_SUDAH_DILUNASI,
					SERI_BAHAN_BAKU,
					SERI_BARANG,
					TARIF,
					TARIF_FASILITAS,
					ID_BAHAN_BAKU,
					ID_BARANG,
					ID_HEADER
				     
				) select
				@id_hdrx
				,@carceisa
				,ID,
				JENIS_TARIF,
				JUMLAH_SATUAN,
				KODE_ASAL_BAHAN_BAKU,
				KODE_FASILITAS,
				KODE_KOMODITI_CUKAI,
				KODE_SATUAN,
				KODE_TARIF,
				NILAI_BAYAR,
				NILAI_FASILITAS,
				NILAI_SUDAH_DILUNASI,
				SERI_BAHAN_BAKU,
				SERI_BARANG,
				TARIF,
				TARIF_FASILITAS,
				ID_BAHAN_BAKU,
				ID_BARANG,
				ID_HEADER

				 from openquery(TPBDB,'select * from tpb_bahan_baku_tarif  where  ID_HEADER= $id_ceisa ') where ID_HEADER = @id_ceisa
					
				
					
					
				END TRY
				BEGIN CATCH 
					SELECT 
					'06' AS status
					,ERROR_MESSAGE() AS description;
					
				END CATCH;
				
				SELECT 
					'00' AS status
					,' DATA PROCESSED' AS description;
				
			");
		}	
		$rs = $matchcar->result_array();
        //$r = $matchcar->result();		
		//var_dump($rs);die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
	}
  
 }