<?php
class CT_bc40 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_bc40", 'mdl_bc40');
		$this->load->model("exim/mdl_invoice", 'mdl_invoice');
		$this->load->helper('afunction');
	}

	function index(){

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

	
	function loaddata(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 and typedok='bc40' ";
		if (isset($_POST['tglawal']) and isset($_POST['tglakhir'])){
			$tglawal=$_POST['tglawal'];
			$tglakhir=$_POST['tglakhir'];
			$where .= " and BC23Tg between '$tglawal' and '$tglakhir' ";
		}				
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "nobl" ) {
						$searchString = $k->data;
						$where .= " and nobl like  '%".$searchString."%'"; 
					} else if ( $k->field == "tglbl" ) {
						$searchString = $k->data;
						$where .= " and tglbl =  '$searchString'"; 
					} else if ( $k->field == "CAR" ) {
						$searchString = $k->data;
						$where .= " and CAR like  '%".$searchString."%'"; 
					} else if ( $k->field == "KdKpbc" ) {
						$searchString = $k->data;
						$where .= " and KdKpbc like  '%".$searchString."%'"; 
					} else if ( $k->field == "PasokNama" ) {
						$searchString = $k->data;
						$where .= " and PasokNama like  '%".$searchString."%'"; 
					} else if ( $k->field == "BC23No" ) {
						$searchString = $k->data;
						$where .= " and BC23No like  '%".$searchString."%'"; 
					} else if ( $k->field == "BC23Tg" ) {
						$searchString = $k->data;
						$where .= " and BC23Tg like  '%".$searchString."%'"; 
					} else if ( $k->field == "JmBrg" ) {
						$searchString = $k->data;
						$where .= " and JmBrg = $searchString"; 
					} else if ( $k->field == "Status" ) {
						$searchString = $k->data;
						$where .= " and Status like  '%".$searchString."%'"; 
					}  else if ( $k->field == "statusdok" ) {
						$searchString = $k->data;
						$where .= " and statusdok like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc23->bc23hdrdataAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc23->bc23hdrdataCountAll($where);
	//	var_dump($records); die();
		
		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){
			if($r->Status == null){
				$status = '-';
				
			} else { $status=$r->Status;  }
			
			$responce->rows[$i]['id_bc_in_hdr']=$r->id_bc_in_hdr; 
			$responce->rows[$i]['CAR']=$r->CAR; 
			$responce->rows[$i]['KdKpbc']=$r->KdKpbc; 
			$responce->rows[$i]['Tujuan']=$r->Tujuan; 
			$responce->rows[$i]['JnsBarang']=$r->JnsBarang; 
			$responce->rows[$i]['TujuanKirim']=$r->TujuanKirim; 
			$responce->rows[$i]['PasokNama']=$r->PasokNama; 
			$responce->rows[$i]['PasokAlmt']=$r->PasokAlmt; 
			$responce->rows[$i]['PasokNeg']=$r->PasokNeg; 
			$responce->rows[$i]['UsahaId']=$r->UsahaId; 
			$responce->rows[$i]['UsahaNpwp']=$r->UsahaNpwp; 
			$responce->rows[$i]['KdTPB']=$r->KdTPB; 
			$responce->rows[$i]['Registrasi']=$r->Registrasi; 
			$responce->rows[$i]['UsahaNama']=$r->UsahaNama; 
			$responce->rows[$i]['UsahaAlmt']=$r->UsahaAlmt; 
			$responce->rows[$i]['UsahaStatus']=$r->UsahaStatus; 
			$responce->rows[$i]['ApiKd']=$r->ApiKd; 
			$responce->rows[$i]['ApiNo']=$r->ApiNo; 
			$responce->rows[$i]['PpjkId']=$r->PpjkId; 
			$responce->rows[$i]['PpjkNpwp']=$r->PpjkNpwp; 
			$responce->rows[$i]['PpjkNama']=$r->PpjkNama; 
			$responce->rows[$i]['PpjkAlmt']=$r->PpjkAlmt; 
			$responce->rows[$i]['PpjkNo']=$r->PpjkNo; 
			$responce->rows[$i]['PpjkTg']=$r->PpjkTg; 
			$responce->rows[$i]['IndId']=$r->IndId; 
			$responce->rows[$i]['IndNpwp']=$r->IndNpwp; 
			$responce->rows[$i]['IndNama']=$r->IndNama; 
			$responce->rows[$i]['IndAlmt']=$r->IndAlmt; 
			$responce->rows[$i]['Moda']=$r->Moda; 
			$responce->rows[$i]['AngkutNama']=$r->AngkutNama; 
			$responce->rows[$i]['AngkutNo']=$r->AngkutNo; 
			$responce->rows[$i]['AngkutFl']=$r->AngkutFl; 
			$responce->rows[$i]['PelBkr']=$r->PelBkr; 
			$responce->rows[$i]['PelMuat']=$r->PelMuat; 
			$responce->rows[$i]['PelTransit']=$r->PelTransit; 
			$responce->rows[$i]['BC23No']=$r->BC23No; 
			$responce->rows[$i]['BC23Tg']=$r->BC23Tg; 
			$responce->rows[$i]['KdKpbcBongkar']=$r->KdKpbcBongkar; 
			$responce->rows[$i]['KdKpbcAwas']=$r->KdKpbcAwas; 
			$responce->rows[$i]['DokTupKd']=$r->DokTupKd; 
			$responce->rows[$i]['DokTupNo']=$r->DokTupNo; 
			$responce->rows[$i]['DokTupTg']=$r->DokTupTg; 
			$responce->rows[$i]['PosNo']=$r->PosNo; 
			$responce->rows[$i]['PosSub']=$r->PosSub; 
			$responce->rows[$i]['TmpTbn']=$r->TmpTbn; 
			$responce->rows[$i]['KdVal']=$r->KdVal; 
			$responce->rows[$i]['Ndpbm']=$r->Ndpbm; 
			$responce->rows[$i]['NilInv']=$r->NilInv; 
			$responce->rows[$i]['Freight']=$r->Freight; 
			$responce->rows[$i]['BTambahan']=$r->BTambahan; 
			$responce->rows[$i]['Diskon']=$r->Diskon; 
			$responce->rows[$i]['KdAss']=$r->KdAss; 
			$responce->rows[$i]['Asuransi']=$r->Asuransi; 
			$responce->rows[$i]['KdHrg']=$r->KdHrg; 
			$responce->rows[$i]['Fob']=$r->Fob; 
			$responce->rows[$i]['Cif']=$r->Cif; 
			$responce->rows[$i]['Bruto']=$r->Bruto; 
			$responce->rows[$i]['Netto']=$r->Netto; 
			$responce->rows[$i]['JmCont']=$r->JmCont; 
			$responce->rows[$i]['JmBrg']=$r->JmBrg; 
			$responce->rows[$i]['TglTtd']=$r->TglTtd; 
			$responce->rows[$i]['KotaTtd']=$r->KotaTtd; 
			$responce->rows[$i]['Namattd']=$r->Namattd; 
			$responce->rows[$i]['ContakPerson']=$r->ContakPerson; 
			$responce->rows[$i]['NoPhone']=$r->NoPhone; 
			$responce->rows[$i]['NoFax']=$r->NoFax; 
			$responce->rows[$i]['Email']=$r->Email; 
			$responce->rows[$i]['Status']=$status;//$r->Status; 
			$responce->rows[$i]['Snrf']=$r->Snrf; 
			$responce->rows[$i]['Lengkap']=$r->Lengkap; 
			$responce->rows[$i]['PosSubSub']=$r->PosSubSub; 
			$responce->rows[$i]['NoKontrak']=$r->NoKontrak; 
			$responce->rows[$i]['TgKontrak']=$r->TgKontrak; 
			$responce->rows[$i]['HargaRp']=$r->HargaRp; 
			$responce->rows[$i]['TmpPeriksaFisik']=$r->TmpPeriksaFisik; 
			$responce->rows[$i]['AlmtPeriksaFisik']=$r->AlmtPeriksaFisik; 
			$responce->rows[$i]['TgPeriksaFisik']=$r->TgPeriksaFisik; 
			$responce->rows[$i]['WkPeriksaFisik']=$r->WkPeriksaFisik; 
			$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]['noinv']=$r->noinv; 
			$responce->rows[$i]['tglinv']=$r->tglinv;
			$responce->rows[$i]['inv_hdr_id']=$r->inv_hdr_id;
			$responce->rows[$i]['nobl']=$r->nobl;
			$responce->rows[$i]['tglbl']=$r->tglbl;
			$i++;
		}
		echo json_encode($responce);
		
	}
	
	function view_bc40_nonhib(){
		$this->load->view('exim/view_bc40_nonhib');
	}
	
	function loaddata_bc40_nonhib(){
		$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_nonhib_hdr'; // get index row - i.e. user click to sort
		$sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " status='new' and tbl_data_supplier.supplier_country='ID' ";
		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "gabinvoice" ) {
						$searchString = $k->data;
						$where .= " and gabinvoice like  '%".$searchString."%'"; 
					} else if ( $k->field == "laodeddate" ) {
						$searchString = $k->data;
						$where .= " and laodeddate =  '$searchString'"; 
					} else if ( $k->field == "NAMABELI" ) {
						$searchString = $k->data;
						$where .= " and NAMABELI like  '%".$searchString."%'"; 
					} else if ( $k->field == "vendor" ) {
						$searchString = $k->data;
						$where .= " and vendor 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."%'"; 
					} 
			
				}
			}
		}	
		
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc27->bc271datanonhibhdrAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc27->bc271datanonhibhdrcountAll($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){
			if ($r->status == 0){ $stat = "New"; } else { $stat = "Not New"; };
			if ($r->tgbl == '1900-10-23'){ $tgbl = ""; } else { $tgbl = $r->tgbl; };	
				
			$responce->rows[$i]['id_nonhib_hdr']=$r->id_nonhib_hdr; 
			$responce->rows[$i]['from_file_name']=$r->from_file_name; 
			$responce->rows[$i]['totalitemfile']=$r->totalitemfile; 
			$responce->rows[$i]['exec_date']=$r->exec_date;
			$responce->rows[$i]['status']= $r->status;
			$responce->rows[$i]['itemcount']=$r->itemcount;
			$responce->rows[$i]['noinv']=$r->noinv;
			$responce->rows[$i]['tglinv']=$r->tglinv;
			$responce->rows[$i]['tglinv2']=$r->tglinv2;
			$responce->rows[$i]['nobl']=trim($r->nobl);
			$responce->rows[$i]['tgbl']=$tgbl;
			$responce->rows[$i]['vendor']=$r->vendor;
			$i++;
		}
		echo json_encode($responce);
	}
	
	function view_bc40_nonhibaddnoajudata(){
		
		$this->load->view('exim/view_bc40_nonhibaddnoajudata');
		
	}
	function loaddata_groupinv_nonhib(){
		$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_nonhib_hdr'; // get index row - i.e. user click to sort
		$sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		//$where = " status='new' ";
		$nobl = (isset($_POST['nobl']) && !empty($_POST['nobl']))?$_POST['nobl']:'';
		$tgbl = (isset($_POST['tgbl']) && !empty($_POST['tgbl']))?$_POST['tgbl']:'';
		
		
		//$where = " a.status_inv=0 ";
		$where = " 1=1 ";
		$where .= " and nobl =  '".$nobl."'";
		$where .= " and tgbl =  '".$tgbl."'";
		
			
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
	    $records = $this->mdl_bc27->bc271datanonhibhdrAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc27->bc271datanonhibhdrcountAll($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){
			if ($r->status == 0){ $stat = "New"; } else { $stat = "Not New"; };
			if ($r->tgbl =='1900-10-23'){ $tgbl = ""; } else { $tgbl = $r->tgbl; };	

			 if ($r->status == 'new'){
					  $status = 'INVOICE NEW ADDED';
			} else if ($r->status == 'DATA PROCESSED'){
				 $status = 'DATA ALREADY PROCESSED';
			}	
			
			if ($r->status == 'new'){
					  $statusx = 0;
			} else {
				 $statusx = 1;
			}	
			
			$responce->rows[$i]['id_nonhib_hdr']=$r->id_nonhib_hdr; 
			$responce->rows[$i]['from_file_name']=$r->from_file_name; 
			$responce->rows[$i]['totalitemfile']=$r->totalitemfile; 
			$responce->rows[$i]['exec_date']=$r->exec_date;
			$responce->rows[$i]['status']= $status;//$r->status;
			$responce->rows[$i]['itemcount']=$r->itemcount;
			$responce->rows[$i]['noinv']=$r->noinv;
			$responce->rows[$i]['tglinv']=$r->tglinv;
			$responce->rows[$i]['tglinv2']=$r->tglinv2;
			$responce->rows[$i]['nobl']=$r->nobl;
			$responce->rows[$i]['tgbl']=$r->tgbl;
			$responce->rows[$i]['statusx']=$statusx;
			$i++;
		}
		echo json_encode($responce);
	
	}
	
	function prosesgroupinv_nonhib(){
		
		$datadiff = (isset($_POST['datadiff']) && !empty($_POST['datadiff']))?$_POST['datadiff']:die('{"sts":"ERROR","desc":" Data  Tidak Ditemukan"}'); 
		$datadiff=json_decode($datadiff);
		$datacsv = '';
		$databl = '';
		foreach ($datadiff as $data ){
		    $inv_hdr_id = (isset($data->id_nonhib_hdr) && !empty($data->id_nonhib_hdr ))?$data->id_nonhib_hdr :die('{"sts":"ERROR","desc":" Param inv_hdr_id Tidak Ditemukan"}');
			$invno = (isset($data->noinv) && !empty($data->noinv ))?$data->noinv :die('{"sts":"ERROR","desc":" Param invno Tidak Ditemukan"}');
			$tglinv = (isset($data->tglinv) && !empty($data->tglinv ))?$data->tglinv :die('{"sts":"ERROR","desc":" Param invno Tidak Ditemukan"}');
			$nobl= (isset($data->nobl) && !empty($data->nobl ))?$data->nobl :'';
			$tgbl= (isset($data->tgbl) && !empty($data->tgbl ))?$data->tgbl :'';
			$datacsv .= $inv_hdr_id . ',' . $invno . ',' .$tglinv; 
			$datacsv .= "|";
			$databl .=  $nobl;
		}
		
		if ($databl != ''){
			$responce = array("sts" => '00', "desc" => 'Data Dok Group sudah ada, Mohon periksa kembali datanya atau lakukan cancel utk Group Ulang');
			echo json_encode($responce);
			die();
		}
		//echo $datacsv;	die();
	    //var_dump($datadiff); die();
		$datacsv=substr($datacsv, 0, strlen($datacsv) - 1); 
		//echo $datacsv; die();
		
		$qry = $this->db->query("
		
			 EXEC ('sp_groupinv_bc40 @datadiff=''$datacsv'', @cmd=''proses''   ') 
			
		 ");
		 $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 cancelgroupinv_nonhib(){
		$datadiff = (isset($_POST['datadiff']) && !empty($_POST['datadiff']))?$_POST['datadiff']:die('{"sts":"ERROR","desc":" Data  Tidak Ditemukan"}'); 
		
		$datadiff=json_decode($datadiff);
		$datacsv = '';
		foreach ($datadiff as $data ){
			$datacsv .= $data->id_nonhib_hdr . ',' . $data->noinv . ',' . '-' . ',' . '1900-10-23'; 
			$datacsv .= "|";
		}
		$datacsv=substr($datacsv, 0, strlen($datacsv) - 1); 
		 // echo $datacsv;	
		//var_dump($datadiff); die();
		// echo "
		
			 // EXEC ('spu_nonhib_bl @datadiff=''$datacsv'', @nobl=''$nobl'', @tgbl=''$tgbl'' ') 
			
		 // ";
		 // die();
		 
		$qry = $this->db->query("
			BEGIN TRY
			 EXEC ('sp_groupinv_bc40 @datadiff=''$datacsv'',@cmd=''cancel'' ') 
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
		 ");
		$rs = $qry->result_array();
        // $r = $qry->result();		
		// var_dump($r);die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
	}
	
	function view_bc40_nonhibprosesinsertinv(){
		$nobl = (isset($_POST['nobl']) or !empty($_POST['nobl']))?$_POST['nobl']:die('{"sts":"ERROR","desc":" Param nobl Tidak Ditemukan"}');
		$tgbl = (isset($_POST['tgbl']) or !empty($_POST['tgbl']))?$_POST['tgbl']:die('{"sts":"ERROR","desc":" Param tgbl Tidak Ditemukan"}');
		$data["tgbl"] = $tgbl;
		$data["nobl"] = $nobl;
		
		$this->load->view('exim/view_bc40_nonhibprosesinsertinv', $data);
	
	}
	
	function listinvbl_nonhib_proses(){
	
	
	
	
	}
	
	function updatestatusproses_nonhib(){
		$datanoinv = (isset($_POST['noinv']) or !empty($_POST['noinv']))?$_POST['noinv']:die('{"sts":"ERROR","desc":" Param INV Tidak Ditemukan"}');
		$nobl = (isset($_POST['nobl']) or !empty($_POST['nobl']))?$_POST['nobl']:die('{"sts":"ERROR","desc":" Param nobl Tidak Ditemukan"}');
		$tgbl= (isset($_POST['tgbl']) or !empty($_POST['tgbl']))?$_POST['tgbl']:die('{"sts":"ERROR","desc":" Param tg bl Tidak Ditemukan"}');
		$typebc = 'BC40';
		$datanoinv=json_decode($datanoinv);
		$datacsv = '';
		foreach ($datanoinv as $data ){
			$datacsv .= $data->id_nonhib_hdr . ',' . trim($data->noinv); 
			$datacsv .= "|";
		}
		// echo $datacsv;	
		// var_dump($datanoinv); die();
		$datacsv = substr($datacsv, 0,  strlen($datacsv) -1); 
		// echo "EXEC [sp_nonhib_insert] @datanoinv ='$datacsv', @typebc='$typebc', @tgbl='$tgbl', @nobl='$nobl' "; die();
		$qry = $this->db->query("
			
			EXEC [sp_nonhib_insert] @datanoinv ='$datacsv', @typebc='$typebc', @tgbl='$tgbl', @nobl='$nobl' 
		
		");
		$rs = $qry->result_array();	
		// var_dump($rs);
		// die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
	}
	
	function recalculate_new_inv_bl_nonhib(){
		$typebc = 'BC40';
		$noinv = (isset($_POST['noinv']) && !empty($_POST['noinv']))?$_POST['noinv']:die('{"sts":"ERROR","desc":" Param INV Tidak Ditemukan"}');
		$nobl = (isset($_POST['nobl']) && !empty($_POST['nobl']))?$_POST['nobl']:die('{"sts":"ERROR","desc":" Param nobl Tidak Ditemukan"}');
		$tgbl= (isset($_POST['tgbl']) && !empty($_POST['tgbl']))?$_POST['tgbl']:die('{"sts":"ERROR","desc":" Param tg bl Tidak Ditemukan"}');
		
		$noinv=json_decode($noinv);
		
		$noinvcsv = '';
		foreach ($noinv as $data ){
			if ($data->statusx == 0){
				$id_nonhib_hdr = (isset($data->id_nonhib_hdr) && !empty($data->id_nonhib_hdr ))?$data->id_nonhib_hdr :die('{"sts":"ERROR","desc":" Param id_nonhib_hdr Tidak Ditemukan"}');
				$invno = (isset($data->noinv) && !empty($data->noinv ))?$data->noinv :die('{"sts":"ERROR","desc":" Param noinv Tidak Ditemukan"}');
				$noinvcsv .= $id_nonhib_hdr. ',' . $invno; 
				$noinvcsv .= "|";
			}
		}
		$listinv = substr($noinvcsv, 0,  strlen($noinvcsv) -1); 
		// echo "
			// EXEC [sp_nonhib_insertcb23_recalculate_new_inv_bl] @nobl = N'$nobl', @tgbl = '$tgbl', @typebc = N'$typebc',@noinv = '$listinv'
		// ";
		// var_dump($noinv); die();
		 // die();
		$qry = $this->db->query("
			
			EXEC [sp_nonhib_insertcb23_recalculate_new_inv_bl] @nobl = N'$nobl', @tgbl = '$tgbl', @typebc = N'$typebc',@noinv = '$listinv'
			
		");
		$rs = $qry->result_array();	
		// var_dump($rs);
		// die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
		
	}
	
	function view_bc40_dtl(){
		$idhdrbc40 = (isset($_POST['idhdrbc40']) && !empty($_POST['idhdrbc40']))?$_POST['idhdrbc40']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$inv_hdr_idbc40 = (isset($_POST['inv_hdr_idbc40']) && !empty($_POST['inv_hdr_idbc40']))?$_POST['inv_hdr_idbc40']:'lihat doc';
		$noinv  = (isset($_POST['noinv']) && !empty($_POST['noinv']))?$_POST['noinv']:'lihat doc';
		$car= (isset($_POST['car']) && !empty($_POST['car']))?$_POST['car']:'-';
		$gabinv  = (isset($_POST['gabinv']) && !empty($_POST['gabinv']))?$_POST['gabinv']:'lihat doc';
		$tglgabinv  = (isset($_POST['tglgabinv']) && !empty($_POST['tglgabinv']))?$_POST['tglgabinv']:'lihat doc';
		$DokTupTg  = (isset($_POST['DokTupTg']) && !empty($_POST['DokTupTg']))?$_POST['DokTupTg']:'';
		$BC23No  = (isset($_POST['BC23No']) && !empty($_POST['BC23No']))?$_POST['BC23No']:'';
		$BC23Tg  = (isset($_POST['BC23Tg']) && !empty($_POST['BC23Tg']))?$_POST['BC23Tg']:'';
		$PasokNama  = (isset($_POST['PasokNama']) && !empty($_POST['PasokNama']))?$_POST['PasokNama']:'';
		
		
		$data["idhdrbc40"] = $idhdrbc40; 
		$data["inv_hdr_idbc40"] = $inv_hdr_idbc40; 
		$data["noinv"] = $noinv;
		$data["car"] = $car;
		$data["gabinv"] = $gabinv;
		$data["tglgabinv"] = $tglgabinv;
		$data["DokTupTg"] = $DokTupTg;
		$data["BC23No"] = $BC23No;
		$data["BC23Tg"] = $BC23Tg;
		$data["PasokNama"] = $PasokNama;
		
		$this->load->view('exim/view_bc40_dtl', $data);
	
	}
	
	function loaddataheader(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		$idy = (isset($_POST['idhdrbc40']) or !empty($_POST['idhdrbc40']))?$_POST['idhdrbc40']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$where = " id_bc_in_hdr=$idy ";
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc23->bc23hdrdataAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc23->bc23hdrdataCountAll($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){
			if($r->Status == null){
				$status = 'New';
				
			} else { $status=$r->Status;  }
			
			$responce->rows[$i]['id_bc_in_hdr']=$r->id_bc_in_hdr; 
			$responce->rows[$i]['CAR']=$r->CAR; 
			$responce->rows[$i]['KdKpbc']=$r->KdKpbc; 
			$responce->rows[$i]['Tujuan']=$r->Tujuan; 
			$responce->rows[$i]['JnsBarang']=$r->JnsBarang; 
			$responce->rows[$i]['TujuanKirim']=$r->TujuanKirim; 
			$responce->rows[$i]['PasokNama']=$r->PasokNama; 
			$responce->rows[$i]['PasokAlmt']=$r->PasokAlmt; 
			$responce->rows[$i]['PasokNeg']=$r->PasokNeg; 
			$responce->rows[$i]['UsahaId']=$r->UsahaId; 
			$responce->rows[$i]['UsahaNpwp']=$r->UsahaNpwp; 
			$responce->rows[$i]['KdTPB']=$r->KdTPB; 
			$responce->rows[$i]['Registrasi']=$r->Registrasi; 
			$responce->rows[$i]['UsahaNama']=$r->UsahaNama; 
			$responce->rows[$i]['UsahaAlmt']=$r->UsahaAlmt; 
			$responce->rows[$i]['UsahaStatus']=$r->UsahaStatus; 
			$responce->rows[$i]['ApiKd']=$r->ApiKd; 
			$responce->rows[$i]['ApiNo']=$r->ApiNo; 
			$responce->rows[$i]['PpjkId']=$r->PpjkId; 
			$responce->rows[$i]['PpjkNpwp']=$r->PpjkNpwp; 
			$responce->rows[$i]['PpjkNama']=$r->PpjkNama; 
			$responce->rows[$i]['PpjkAlmt']=$r->PpjkAlmt; 
			$responce->rows[$i]['PpjkNo']=$r->PpjkNo; 
			$responce->rows[$i]['PpjkTg']=$r->PpjkTg; 
			$responce->rows[$i]['IndId']=$r->IndId; 
			$responce->rows[$i]['IndNpwp']=$r->IndNpwp; 
			$responce->rows[$i]['IndNama']=$r->IndNama; 
			$responce->rows[$i]['IndAlmt']=$r->IndAlmt; 
			$responce->rows[$i]['Moda']=$r->Moda; 
			$responce->rows[$i]['AngkutNama']=$r->AngkutNama; 
			$responce->rows[$i]['AngkutNo']=$r->AngkutNo; 
			$responce->rows[$i]['AngkutFl']=$r->AngkutFl; 
			$responce->rows[$i]['PelBkr']=$r->PelBkr; 
			$responce->rows[$i]['PelMuat']=$r->PelMuat; 
			$responce->rows[$i]['PelTransit']=$r->PelTransit; 
			$responce->rows[$i]['BC23No']=$r->BC23No; 
			$responce->rows[$i]['BC23Tg']=$r->BC23Tg; 
			$responce->rows[$i]['KdKpbcBongkar']=$r->KdKpbcBongkar; 
			$responce->rows[$i]['KdKpbcAwas']=$r->KdKpbcAwas; 
			$responce->rows[$i]['DokTupKd']=$r->DokTupKd; 
			$responce->rows[$i]['DokTupNo']=$r->DokTupNo; 
			$responce->rows[$i]['DokTupTg']=$r->DokTupTg; 
			$responce->rows[$i]['PosNo']=$r->PosNo; 
			$responce->rows[$i]['PosSub']=$r->PosSub; 
			$responce->rows[$i]['TmpTbn']=$r->TmpTbn; 
			$responce->rows[$i]['KdVal']=$r->KdVal; 
			$responce->rows[$i]['Ndpbm']=$r->Ndpbm; 
			$responce->rows[$i]['NilInv']=$r->NilInv; 
			$responce->rows[$i]['Freight']=$r->Freight; 
			$responce->rows[$i]['BTambahan']=$r->BTambahan; 
			$responce->rows[$i]['Diskon']=$r->Diskon; 
			$responce->rows[$i]['KdAss']=$r->KdAss; 
			$responce->rows[$i]['Asuransi']=$r->Asuransi; 
			$responce->rows[$i]['KdHrg']=$r->KdHrg; 
			$responce->rows[$i]['Fob']=$r->Fob; 
			$responce->rows[$i]['Cif']=$r->Cif; 
			$responce->rows[$i]['Bruto']=$r->Bruto; 
			$responce->rows[$i]['Netto']=$r->Netto; 
			$responce->rows[$i]['JmCont']=$r->JmCont; 
			$responce->rows[$i]['JmBrg']=$r->JmBrg; 
			$responce->rows[$i]['TglTtd']=$r->TglTtd; 
			$responce->rows[$i]['KotaTtd']=$r->KotaTtd; 
			$responce->rows[$i]['Namattd']=$r->Namattd; 
			$responce->rows[$i]['ContakPerson']=$r->ContakPerson; 
			$responce->rows[$i]['NoPhone']=$r->NoPhone; 
			$responce->rows[$i]['NoFax']=$r->NoFax; 
			$responce->rows[$i]['Email']=$r->Email; 
			$responce->rows[$i]['Status']=$status;//$r->Status; 
			$responce->rows[$i]['Snrf']=$r->Snrf; 
			$responce->rows[$i]['Lengkap']=$r->Lengkap; 
			$responce->rows[$i]['PosSubSub']=$r->PosSubSub; 
			$responce->rows[$i]['NoKontrak']=$r->NoKontrak; 
			$responce->rows[$i]['TgKontrak']=$r->TgKontrak; 
			$responce->rows[$i]['HargaRp']=$r->HargaRp; 
			$responce->rows[$i]['TmpPeriksaFisik']=$r->TmpPeriksaFisik; 
			$responce->rows[$i]['AlmtPeriksaFisik']=$r->AlmtPeriksaFisik; 
			$responce->rows[$i]['TgPeriksaFisik']=$r->TgPeriksaFisik; 
			$responce->rows[$i]['WkPeriksaFisik']=$r->WkPeriksaFisik; 
			$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]['noinv']=$r->noinv; 
			$responce->rows[$i]['tglinv']=$r->tglinv;
			$responce->rows[$i]['inv_hdr_id']=$r->inv_hdr_id;
			$responce->rows[$i]['bc_in_from_in']=$r->bc_in_from_in;
			
			$i++;
		}
		echo json_encode($responce);
		
	}
	
	
	function loaddata_bc40_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'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$idhdr = (isset($_POST['idhdrbc40']) && !empty($_POST['idhdrbc40']))?$_POST['idhdrbc40']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$where = " id_bc_in_hdr=$idhdr ";
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc23->bc23detildataAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc23->bc23detildataCountAll($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_in_dtl']=$r->id_bc_in_dtl; 
			$responce->rows[$i]['id_bc_in_hdr']=$r->id_bc_in_hdr; 
			$responce->rows[$i]['CAR']=$r->CAR; 
			$responce->rows[$i]['Serial']=$r->Serial; 
			$responce->rows[$i]['JnsBarangDtl']=$r->JnsBarangDtl; 
			$responce->rows[$i]['TujuanKirimDtl']=$r->TujuanKirimDtl; 
			$responce->rows[$i]['NoHs']=$r->NoHs; 
			$responce->rows[$i]['SeriTrp']=$r->SeriTrp; 
			$responce->rows[$i]['BrgUrai']=$r->BrgUrai; 
			$responce->rows[$i]['Merk']=$r->Merk; 
			$responce->rows[$i]['Tipe']=$r->Tipe; 
			$responce->rows[$i]['SpfLain']=$r->SpfLain; 
			$responce->rows[$i]['KdBrg']=$r->KdBrg; 
			$responce->rows[$i]['Penggunaan']=$r->Penggunaan; 
			$responce->rows[$i]['KemasJn']=$r->KemasJn;
			$responce->rows[$i]['KemasJm']=$r->KemasJm;
			$responce->rows[$i]['KdFasDtl']=$r->KdFasDtl;
			$responce->rows[$i]['BrgAsal']=$r->BrgAsal;
			$responce->rows[$i]['DNilInv']=$r->DNilInv;
			$responce->rows[$i]['KdSat']=$r->KdSat;
			$responce->rows[$i]['JmlSat']=$r->JmlSat;
			$responce->rows[$i]['NettoDtl']=$r->NettoDtl;
			$responce->rows[$i]['SatBmJm']=$r->SatBmJm;
			$responce->rows[$i]['SatCukJm']=$r->SatCukJm;
			$responce->rows[$i]['DtlOk']=$r->DtlOk;
			$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 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']:'id'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$idhdr = (isset($_POST['idhdrbc40']) && !empty($_POST['idhdrbc40']))?$_POST['idhdrbc40']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$where = " id_bc_in_hdr=$idhdr ";
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc23->bc23dokdataAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc23->bc23dokdataCountAll($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_in_dok']=$r->id_bc_in_dok; 
			$responce->rows[$i]['id_bc_in_hdr']=$r->id_bc_in_hdr; 
			$responce->rows[$i]['CAR']=$r->CAR; 
			$responce->rows[$i]['DokKd']=$r->DokKd; 
			$responce->rows[$i]['uraian']=$r->uraian; 
			$responce->rows[$i]['DokNo']=$r->DokNo; 
			$responce->rows[$i]['DokTg']=$r->DokTg; 
			
			$i++;
		}
		echo json_encode($responce);
		
	}
	function loaddatacon(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
        $searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
        $searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
        $filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
        $limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
        $sidx = isset($_POST['sidx'])?$_POST['sidx']:'id'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$idhdr = (isset($_POST['idhdrbc40']) && !empty($_POST['idhdrbc40']))?$_POST['idhdrbc40']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		$where = " id_bc_in_hdr=$idhdr ";
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc23->bc23condataAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc23->bc23condataCountAll($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_in_con']=$r->id_bc_in_con; 
			$responce->rows[$i]['id_bc_in_hdr']=$r->id_bc_in_hdr; 
			$responce->rows[$i]['CAR']=$r->CAR; 
			$responce->rows[$i]['ContNo']=$r->ContNo; 
			$responce->rows[$i]['ContUkur']=$r->ContUkur; 
			$responce->rows[$i]['ContTipe']=$r->ContTipe; 
			
			$i++;
		}
		echo json_encode($responce);
		
	}
	
	function updatenoaju_bc40(){
		$idhdrbc40 = (isset($_POST['idhdrbc40']) && !empty($_POST['idhdrbc40']))?$_POST['idhdrbc40']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$bc40noaju = (isset($_POST['bc40noaju']) && !empty($_POST['bc40noaju']))?$_POST['bc40noaju']:'';
		$bc40tglaju  = (isset($_POST['bc40tglaju']) && !empty($_POST['bc40tglaju']))?$_POST['bc40tglaju']:'';
		$bc40nobc40= (isset($_POST['bc40nobc40']) && !empty($_POST['bc40nobc40']))?$_POST['bc40nobc40']:'';
		$bc40tglbc40= (isset($_POST['bc40tglbc40']) && !empty($_POST['bc40tglbc40']))?$_POST['bc40tglbc40']:'';
		$PasokNama= (isset($_POST['PasokNama']) && !empty($_POST['PasokNama']))?$_POST['PasokNama']:'';
		
		$username = $this->session->userdata('DX_username');
		
		// if ($bc40tglaju != ''){
			// $bc40tglajux = explode('/', $bc40tglaju);
			// $bc40tglaju = 	$bc40tglajux[1]. '/' . $bc40tglajux[0]. '/' . $bc40tglajux[2];
		// }
		
		// if ($bc40tglbc40 != ''){
			// $bc40tglbc40x = explode('/', $bc40tglbc40);
			// $bc40tglbc40 = 	$bc40tglbc40x[1]. '/' . $bc40tglbc40x[0]. '/' . $bc40tglbc40x[2];
		// }
		
		//echo $bc40tglaju; die();
		/* echo " exec(' spu_updatenobc40 @idbc40hdr=$idhdrbc40,@userid=''$username'', @noajubc40=''$bc40noaju'', @tgajubc40=''$bc40tglaju'', @nobc40=''$bc40nobc40'', @tglbc40=''$bc40tglbc40'' ')
			";die(); */
		
		$qry = $this->db->query("
			BEGIN TRY
			
			 exec(' spu_updatenobc40 @idbc40hdr=$idhdrbc40,@userid=''$username'', @noajubc40=''$bc40noaju'', @tgajubc40=''$bc40tglaju'', @nobc40=''$bc40nobc40'', @tglbc40=''$bc40tglbc40'', @supplier=''$PasokNama'' ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		 $rs = $qry->result_array();
		 // $r = $qry->result();		
		 // var_dump($r);die();
		 foreach ($rs as $row){
			 $status = $row['status'];
			 $msg = $row['description'];
		 }  
		 
		 echo json_encode(array('sts' => $status, 'desc' => $msg));
		
		
	
	}
	
	function view_bc40_move(){
		$id_inv_hdr = (isset($_POST['inv_hdr_idbc23']) && !empty($_POST['inv_hdr_idbc23']))?$_POST['inv_hdr_idbc23']:die('{"sts":"ERROR","desc":" Param id_inv_hdr Tidak Ditemukan"}');
		$noinv = (isset($_POST['noinv']) && !empty($_POST['noinv']))?$_POST['noinv']:die('{"sts":"ERROR","desc":" Param noinv Tidak Ditemukan"}');
		$idhdrbc23 = (isset($_POST['idhdrbc23']) && !empty($_POST['idhdrbc23']))?$_POST['idhdrbc23']:die('{"sts":"ERROR","desc":" Param idhdrbc23 Tidak Ditemukan"}');
		$nobc23 = (isset($_POST['nobc23']) && !empty($_POST['nobc23']))?$_POST['nobc23']:'KOSONG';
		
		// if ($nobc23 == ""){
			// $nobc23 = 'KOSONG';
		// }
		
		$data["noinv"] = $noinv;
		$data["id_inv_hdr"] = $id_inv_hdr;
		$data["idhdrbc23"] = $idhdrbc23;
		$data["nobc23"] = $nobc23;
		
		
		
		$this->load->view('exim/view_bc40_move', $data);
	
	}
	
	function view_bc40_hdr_form_old(){
		$id_inv_hdr = (isset($_POST['id_inv_hdr']) && !empty($_POST['id_inv_hdr']))?$_POST['id_inv_hdr']:die('{"sts":"ERROR","desc":" Param id_inv_hdr Tidak Ditemukan"}');
		$BC23No = (isset($_POST['BC23No']) && !empty($_POST['BC23No']))?$_POST['BC23No']:die('{"sts":"ERROR","desc":" Param BC23No Tidak Ditemukan"}');
		$data["BC23No"]=$BC23No;
		$this->load->view('exim/view_bc40_hdr_form_old', $data);
		//$this->load->view('exim/view_bc40_hdr_form', $data);
	
	}
	
	function view_bc40_hdr_form_print(){
	
		$data["BC23No"]="BC23No";
		$this->load->view('exim/view_bc40_hdr_form_print', $data);	
	
	}
	
	function view_bc40_hdr_print(){
	
		/* $id_inv_hdr = 'zzzz';
		$BC23No = 'xxxxxxxxxx';
		$data["BC23No"]='cccccccc';
		$this->load->view('exim/view_bc40_hdr_form', $data);
		// Get output html
		$html = $this->output->get_output();
		$this->load->library('dompdf_gen');
		$this->dompdf->load_html($html);
		$this->dompdf->render();
		$this->dompdf->stream("welcome.pdf"); */
		 
         $this->load->helper(array('dompdf', 'file'));
		 $id_inv_hdr = 'zzzz';
		 $BC23No = 'xxxxxxxxxx';
		 $data["BC23No"]='cccccccc'; 
		 //$html = $this->load->view('exim/view_bc40_hdr_form', $data);
		  $html = $this->load->view('exim/view_bc40_hdr_form', $data, true);   
		 //echo $html;
		  pdf_create($html,'bc40',true);  
		  
		  
		 //$html = $this->load->view('controller/viewfile', $data, true);
		 //pdf_create($html, 'filename');
		  //$data = pdf_create($html, '', false);
          //write_file('name', $data);
		  
		
	/* 	$this->load->helper(array('html2pdf', 'file'));
		 $id_inv_hdr = 'zzzz';
		 $BC23No = 'xxxxxxxxxx';
		 $data['id_inv_hdr'] = $id_inv_hdr;
		 $data['BC23No'] = $BC23No;
		 $html = $this->load->view('exim/view_bc40_hdr_form', $data, true);  
		 html2pdf_create($html,"test"); */
		 die();
		 
		  
	}
	
	function savetoexcelbc40(){
		$id_bc_in_hdr = (isset($_REQUEST['id_bc_in_hdr']) && !empty($_REQUEST['id_bc_in_hdr']))?$_REQUEST['id_bc_in_hdr']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$Ndpbm1 = 0;
		$BC23Tg1 = '';
		$kdval1 = '';
		$rshdr1= $this->db->query("
			SELECT [id_bc_in_hdr]
			,[Ndpbm]
			,convert(date, BC23Tg) as BC23Tg
			,kdval 
			FROM [dbo].[tbl_bc_in_hdr]
		    where [typedok] = 'bc40' and  id_bc_in_hdr=$id_bc_in_hdr 
		");
		$qryhdr1 = $rshdr1->result_array();
		foreach($qryhdr1 as $rowhdr1){
			$Ndpbm1 = $rowhdr1['Ndpbm'];
			$BC23Tg1 = $rowhdr1['BC23Tg'];
			$kdval1 =  $rowhdr1['kdval']; 
		}
		
		if ($kdval1 != 'IDR'){ $kdval1 = 'USD'; }
		$nilaikurs = 1;
		if ($BC23Tg1 != ''){
			$qrykurs= $this->db->query("
				SELECT [id_kurs]
				  ,[KdKurs]
				  ,[TgAwal]
				  ,[TgAkhir]
				  ,[Nilai]
				  ,[Ket]
			  FROM [dbo].[tblKurs]
			  where [KdKurs] = '$kdval1' and [TgAwal] <= '$BC23Tg1' and [TgAkhir] >= '$BC23Tg1'
			");
			
			$rs = $qrykurs->result_array();	
			foreach ($rs as $row){
				$nilaikurs = $row["Nilai"];
			 }  
		
		} else {
		    $BC23Tg1 = date('Y-m-d');
			$qrykurs= $this->db->query("
				SELECT [id_kurs]
				  ,[KdKurs]
				  ,[TgAwal]
				  ,[TgAkhir]
				  ,[Nilai]
				  ,[Ket]
			  FROM [dbo].[tblKurs]
			  where [KdKurs] = '$kdval1' and [TgAwal] <= '$BC23Tg1' and [TgAkhir] >= '$BC23Tg1'
			");
			
			$rs = $qrykurs->result_array();	
			
			foreach ($rs as $row){
				$nilaikurs = $row["Nilai"];
			 }  
			
		}

		
		$rshdr= $this->db->query("
			SELECT [id_bc_in_hdr]
			  ,[CAR]
			  ,[KdKpbc]
			  ,[Tujuan]
			  ,[JnsBarang]
			  ,[TujuanKirim]
			  ,[PasokNama]
			  ,[PasokAlmt]
			  ,[PasokNeg]
			  ,[UsahaId]
			  ,[UsahaNpwp]
			  ,[KdTPB]
			  ,[Registrasi]
			  ,[UsahaNama]
			  ,[UsahaAlmt]
			  ,[UsahaStatus]
			  ,[ApiKd]
			  ,[ApiNo]
			  ,[PpjkId]
			  ,[PpjkNpwp]
			  ,[PpjkNama]
			  ,[PpjkAlmt]
			  ,[PpjkNo]
			  ,[PpjkTg]
			  ,[IndId]
			  ,[IndNpwp]
			  ,[IndNama]
			  ,[IndAlmt]
			  ,[Moda]
			  ,[AngkutNama]
			  ,[AngkutNo]
			  ,[AngkutFl]
			  ,[PelBkr]
			  ,[PelMuat]
			  ,[PelTransit]
			  ,[BC23No]
			  ,convert(varchar,[BC23Tg], 106) as BC23Tg
			  ,[KdKpbcBongkar]
			  ,[KdKpbcAwas]
			  ,[DokTupKd]
			  ,[DokTupNo]
			  ,convert(varchar,[DokTupTg], 106) as DokTupTg
			  ,[PosNo]
			  ,[PosSub]
			  ,[TmpTbn]
			  ,[KdVal]
			  ,[Ndpbm]
			  ,[NilInv]
			  ,[Freight]
			  ,[BTambahan]
			  ,[Diskon]
			  ,[KdAss]
			  ,[Asuransi]
			  ,[KdHrg]
			  ,[Fob]
			  ,[Cif]
			  ,[Bruto]
			  ,[Netto]
			  ,[JmCont]
			  ,[JmBrg]
			  ,[TglTtd]
			  ,[KotaTtd]
			  ,[Namattd]
			  ,[ContakPerson]
			  ,[NoPhone]
			  ,[NoFax]
			  ,[Email]
			  ,[Status]
			  ,[Snrf]
			  ,[Lengkap]
			  ,[PosSubSub]
			  ,[NoKontrak]
			  ,[TgKontrak]
			  ,[HargaRp]
			  ,[TmpPeriksaFisik]
			  ,[AlmtPeriksaFisik]
			  ,[TgPeriksaFisik]
			  ,[WkPeriksaFisik]
			  ,[create_date]
			  ,[create_by]
			  ,[update_date]
			  ,[update_by]
			  ,[typedok]
			  ,[statusdok]
			  ,[noinv]
			  ,[tginv]
			  ,[inv_hdr_id]
			  ,[bc_in_from_in]
			  ,[nopol]
			  ,[nobl]
			  ,[tglbl]
			  ,[tgaju]
		  FROM [dbo].[tbl_bc_in_hdr]
		  where [typedok] = 'bc40' and  id_bc_in_hdr=$id_bc_in_hdr 
			");
		
		$qryhdr = $rshdr->result_array();
		
		$BC23No = '';
		$BC23Tg = '';
		$DokTupTg = '';
		$PasokNama = '';
		$NilInv= 0;
		$car = '';
		foreach($qryhdr as $rowhdr){
			$BC23No = $rowhdr['BC23No'];
			$BC23Tg = $rowhdr['BC23Tg'];
			$PasokNama = $rowhdr['PasokNama'];
			$NilInv=$rowhdr['NilInv'];
			$car = $rowhdr['CAR'];
			$DokTupTg = $rowhdr['DokTupTg'];
		}
		
		
		
		$rssup= $this->db->query("
			SELECT [id]
			  ,[supplier_code]
			  ,[supplier_name]
			  ,[supplier_address]
			  ,[supplier_country]
			  ,[base_price]
			  ,[copper_base_reff]
			  ,[subgct]
			  ,[subcode_as400]
			  ,[NPWP]
			  ,[NOIJIN]
			  ,[NOKONTRAK]
			  ,[TGLIJIN]
			  ,[TGLKONTRAK]
			  ,[supplier_address1]
		  FROM [dbo].[tbl_data_supplier]
		  where [supplier_name] like '%$PasokNama%'
		
		
		");
		
		$qrysup = $rssup->result_array();
		
		$supplier_address = '';
		$supplier_address1 = '';
		$supplier_NPWP = '';
		foreach($qrysup as $rowsup){
			$supplier_address = $rowsup['supplier_address'];
			$supplier_address1 = $rowsup['supplier_address1'];
			$supplier_NPWP = $rowsup['NPWP'];
		}
		
		$rsdtl_count= $this->db->query("
			select count(*) as cnt  
			 FROM [dbo].[tbl_bc_in_dtl_partnumber]
			where id_bc_in_hdr=$id_bc_in_hdr 
		");
		
		$qryrsdtl_count = $rsdtl_count->result_array();
		
		$jmldt = 0;
		foreach($qryrsdtl_count as $rowdtl_count){
			$jmldt = $rowdtl_count["cnt"];
		}
		
		$rsdtl= $this->db->query("
			SELECT [id_bc_in_dtl_partnumber]
			  ,[inv_dtl]
			  ,[inv_hdr_id]
			  ,[id_partnumber]
			  ,[id_bc_in_hdr]
			  ,[noinv]
			  ,[car]
			  ,[nobc]
			  ,[tglbc]
			  ,[seri_detil]
			  ,[part_no2]
			  ,[part_number]
			  ,[part_name]
			  ,[part_name_customs]
			  ,[hscode]
			  ,[bm]
			  ,[qty]
			  ,[unit]
			  ,[harga]
			  ,[kdval]
			  ,[box]
			  ,[pack]
		  FROM [dbo].[tbl_bc_in_dtl_partnumber]
		  where id_bc_in_hdr=$id_bc_in_hdr 
		
		
		");
		
		$qryrsdtl = $rsdtl->result_array();
		$cntrsdtl = $rsdtl->num_rows();
		
		
		$rsdok= $this->db->query("
			SELECT [id_bc_in_dok]
				  ,[id_bc_in_hdr]
				  ,[CAR]
				  ,[DokKd]
				  ,[DokNo]
				  ,convert(varchar, [DokTg], 106) as DokTg
			  FROM [dbo].[tbl_bc_in_dok]
			   where id_bc_in_hdr=$id_bc_in_hdr  
		
		
		");
		
		$qryrsdok = $rsdok->result_array();
		$jml_inv = $rsdok->num_rows;
		
		$rssumbox= $this->db->query("
			SELECT sum(kemasjm) as sumbox
				
			   FROM [dbo].[tbl_bc_in_dtl]
		       where id_bc_in_hdr=$id_bc_in_hdr 
		
		
		");
		$qrysumbox = $rssumbox->result_array();
		
		$sumbox = 1;
		foreach($qrysumbox as $rsumbox){
			
			$sumbox = $rsumbox["sumbox"];
		}
		$invoice = '';
		$tgl_invoice = '';
		if($jml_inv > 3){
			$invoice = "Silahkan Lihat Dok Lampiran";
		} else 	{
			foreach($qryrsdok as $rowdok){
				if ( $rowdok["DokKd"] == '380'  ){
					$invoice .= $rowdok["DokNo"] . ' ' ;
				}
				$tgl_invoice = ' Tgl ' . $rowdok["DokTg"];
			}
		}
		
		
		
		$datenow = date('Y-m-d');
		$filename =  "BC40_". $BC23No ."_$datenow";
		
		$jmlhal = 1;
		if($jmldt > 5){
			$jmlhal = ceil($jmldt/27) + 1 + 1;
			if($jml_inv <= 3){
				$jmlhal = ceil($jmldt/27) + 1;
			}
		}
		
		include_once ( APPPATH."libraries/PHPExcel/IOFactory.php");	
		$objTpl = PHPExcel_IOFactory::load(APPPATH."libraries/PHPExcel/templates/BC_40.xls");	
		
		$objTpl->setActiveSheetIndex(0);  //set first sheet as active
		$objTpl->getActiveSheet()->setCellValue('F15', '');
		$objTpl->getActiveSheet()->setCellValue('C4', ':'. $car);
		$objTpl->getActiveSheet()->setCellValue('G5', ':'. $BC23No);
		$objTpl->getActiveSheet()->setCellValue('G6', ':'. $BC23Tg);	
		$objTpl->getActiveSheet()->setCellValue('G12', ':'.$supplier_NPWP);
		$objTpl->getActiveSheet()->setCellValue('G13', ':'.$PasokNama);
		$objTpl->getActiveSheet()->setCellValue('G14', ':'.$supplier_address);
		$objTpl->getActiveSheet()->setCellValue('G15', ':'.$supplier_address1);
		$objTpl->getActiveSheet()->setCellValue('C18', ':'.$invoice . $tgl_invoice);
		$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '        ');
		$objTpl->getActiveSheet()->setCellValue('G27', ':'.$sumbox);	
		$objTpl->getActiveSheet()->setCellValue('D25', $NilInv);
		$objTpl->getActiveSheet()->getStyle("D25:D25")->getNumberFormat()->setFormatCode('#,##0.00');	
		if($jml_inv > 3){
			$objTpl->setActiveSheetIndex(3);
			$i = 1;
			$j = '';
			$k = 13;
			foreach($qryrsdok as $rowdok){
				if ( $rowdok["DokKd"] == '380'  ){
					$k = 13 + $i;
					$j = "$k";
					$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
					$objTpl->getActiveSheet()->setCellValue("C".$j, "INVOICE");
					$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdok["DokNo"]);
					$objTpl->getActiveSheet()->setCellValue("I".$j, $rowdok["DokTg"]);
					$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						
				}
				$i++;
			}
			$objTpl->getActiveSheet()->setCellValue('F52', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
			$objTpl->getActiveSheet()->setCellValue("E6", "Halaman 2  dari  " . $jmlhal);
		}
		
		$objTpl->setActiveSheetIndex(0);  //set first sheet as active
		
		if ($cntrsdtl != 0){
		//show detil
			if($jmldt > 5){
				$objTpl->getActiveSheet()->setCellValue('B39', ' ==== Terdapat ' . $jmldt . ' barang' . ' Silahkan lihat Pada Lembar Lampiran ===');
				$objTpl->getActiveSheet()->setCellValue('B40', '');
				$objTpl->getActiveSheet()->setCellValue('A38', '');
				$objTpl->getActiveSheet()->setCellValue('A39', '');
				$objTpl->getActiveSheet()->setCellValue('A40', '');
				$objTpl->getActiveSheet()->setCellValue('A41', '');
				$objTpl->getActiveSheet()->setCellValue('A42', '');
				
				$i = 1;
				$j = '';
				$k = 15;
				$i1 = 1;
				$i2 = 1;
				$i3 = 1;
				$i4 = 1;
				$i5 = 1;
				$i6 = 1;
				$i7 = 1;
				$i8 = 1;
				$i9 = 1;
				$i10 = 1;
				foreach($qryrsdtl as $rowdtl){
					if ($i < 28){
						$objTpl->setActiveSheetIndex(1); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$harga =  $rowdtl["harga"]  * $rowdtl["qty"];
						$k = 15 + $i1;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["part_no2"] . "," . $rowdtl["part_name"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["qty"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["unit"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i1++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 2  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 3  dari  " . $jmlhal);
						}
						
					
					 }	else if($i>=28 && $i<55 ) {
						
						$objTpl->setActiveSheetIndex(2); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$harga =  $rowdtl["harga"]  * $rowdtl["qty"];
						$k = 15 + $i2;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["part_no2"] . "," . $rowdtl["part_name"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["qty"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["unit"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i2++;
						
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 3  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 4  dari  " . $jmlhal);
						}
						
					 } 	else if($i>=55 && $i<82 ) {
						
						$objTpl->setActiveSheetIndex(4); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$harga =  $rowdtl["harga"]  * $rowdtl["qty"];
						$k = 15 + $i3;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["part_no2"] . "," . $rowdtl["part_name"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["qty"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["unit"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i3++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 4  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 5  dari  " . $jmlhal);
						}
					 }  else if($i>=82 && $i<109 ) {
						
						$objTpl->setActiveSheetIndex(5); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$harga =  $rowdtl["harga"]  * $rowdtl["qty"];
						$k = 15 + $i4;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["part_no2"] . "," . $rowdtl["part_name"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["qty"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["unit"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i4++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 5  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 6  dari  " . $jmlhal);
						}
					 }  else if($i>=109 && $i<136 ) {
						
						$objTpl->setActiveSheetIndex(6); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$harga =  $rowdtl["harga"]  * $rowdtl["qty"];
						$k = 15 + $i5;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["part_no2"] . "," . $rowdtl["part_name"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["qty"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["unit"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i5++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 6  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 7  dari  " . $jmlhal);
						}
					 }   else if($i>=136 && $i<163 ) {
						
						$objTpl->setActiveSheetIndex(7); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$harga =  $rowdtl["harga"]  * $rowdtl["qty"];
						$k = 15 + $i6;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["part_no2"] . "," . $rowdtl["part_name"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["qty"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["unit"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i6++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 7  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 8  dari  " . $jmlhal);
						}
					 } else if($i>=163 && $i<190 ) {
						
						$objTpl->setActiveSheetIndex(8); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$harga =  $rowdtl["harga"]  * $rowdtl["qty"];
						$k = 15 + $i7;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["part_no2"] . "," . $rowdtl["part_name"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["qty"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["unit"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i7++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 8  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 9  dari  " . $jmlhal);
						}
					 } else if($i>=190 && $i<217 ) {
						
						$objTpl->setActiveSheetIndex(9); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$harga =  $rowdtl["harga"]  * $rowdtl["qty"];
						$k = 15 + $i8;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["part_no2"] . "," . $rowdtl["part_name"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["qty"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["unit"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i8++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 9  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 10  dari  " . $jmlhal);
						}
					 } else if($i>=217 && $i<244 ) {
						
						$objTpl->setActiveSheetIndex(10); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$harga =  $rowdtl["harga"]  * $rowdtl["qty"];
						$k = 15 + $i9;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["part_no2"] . "," . $rowdtl["part_name"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["qty"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["unit"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i9++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 10  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 11  dari  " . $jmlhal);
						}
					 } else {
						$objTpl->setActiveSheetIndex(11); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$harga =  $rowdtl["harga"]  * $rowdtl["qty"];
						$k = 15 + $i10;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["part_no2"] . "," . $rowdtl["part_name"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["qty"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["unit"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i10++;
					 
					 }
					 
					 
					$i++;
				}
				
			
			} else {
				$i = 1;
				$j = '';
				$k = 37;
				foreach($qryrsdtl as $rowdtl){
					
					//$harga =  $rowdtl["harga"]   * $nilaikurs * $rowdtl["qty"];
					$harga =  $rowdtl["harga"]   * $rowdtl["qty"];
					$k = 37 + $i;
					$j = "$k";
					$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
					$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["part_no2"] . "," . $rowdtl["part_name"]);
					$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["qty"] );
					$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["unit"] );
					$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
					
					
					$i++;
				}
				
				$objTpl->getActiveSheet()->getStyle("I37:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			
			}
		
		
		} else {
			$rsdtl= $this->db->query("
				SELECT TOP 1000 [id_bc_in_dtl]
				  ,[id_bc_in_hdr]
				  ,[CAR]
				  ,[Serial]
				  ,[JnsBarangDtl]
				  ,[TujuanKirimDtl]
				  ,[NoHs]
				  ,[SeriTrp]
				  ,[BrgUrai]
				  ,[Merk]
				  ,[Tipe]
				  ,[SpfLain]
				  ,[KdBrg]
				  ,[Penggunaan]
				  ,[KemasJn]
				  ,[KemasJm]
				  ,[KdFasDtl]
				  ,[BrgAsal]
				  ,[DNilInv]
				  ,[DCif]
				  ,[KdSat]
				  ,[JmlSat]
				  ,[NettoDtl]
				  ,[SatBmJm]
				  ,[SatCukJm]
				  ,[DtlOk]
				  ,[create_date]
				  ,[create_by]
				  ,[update_date]
				  ,[update_by]
			  FROM [dbo].[tbl_bc_in_dtl]
			  where id_bc_in_hdr=$id_bc_in_hdr 
			");
		
			$qryrsdtl = $rsdtl->result_array();
			$jmldt = $rsdtl->num_rows();
			
			$jmlhal = 1;
			if($jmldt > 5){
				$jmlhal = ceil($jmldt/27) + 1 + 1;
				if($jml_inv <= 3){
					$jmlhal = ceil($jmldt/27) + 1;
				}
			}
			
			if($jmldt > 5){
				
				$objTpl->getActiveSheet()->setCellValue('B39', ' ==== Terdapat ' . $jmldt . ' barang' . ' Silahkan lihat Pada Lembar Lampiran ===');
				$objTpl->getActiveSheet()->setCellValue('B40', '');
				$objTpl->getActiveSheet()->setCellValue('A38', '');
				$objTpl->getActiveSheet()->setCellValue('A39', '');
				$objTpl->getActiveSheet()->setCellValue('A40', '');
				$objTpl->getActiveSheet()->setCellValue('A41', '');
				$objTpl->getActiveSheet()->setCellValue('A42', '');
				$i = 1;
				$j = '';
				$k = 15;
				$i1 = 1;
				$i2 = 1;
				$i3 = 1;
				$i4 = 1;
				$i5 = 1;
				$i6 = 1;
				$i7 = 1;
				$i8 = 1;
				$i9 = 1;
				$i10 = 1;
				foreach($qryrsdtl as $rowdtl){
					if ($i < 28){
						$harga = $rowdtl["DNilInv"];
						$objTpl->setActiveSheetIndex(1); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$k = 15 + $i1;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["KdBrg"] . "," . $rowdtl["BrgUrai"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["JmlSat"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["KdSat"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i1++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 2  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 3  dari  " . $jmlhal);
						}
					 }	else if($i>=28 && $i<55 ) {
						$harga = $rowdtl["DNilInv"];
						$objTpl->setActiveSheetIndex(2); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$k = 15 + $i2;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["KdBrg"] . "," . $rowdtl["BrgUrai"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["JmlSat"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["KdSat"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i2++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 3  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 4  dari  " . $jmlhal);
						}
					 } 	else if($i>=55 && $i<82 ) {
						$harga = $rowdtl["DNilInv"];
						$objTpl->setActiveSheetIndex(4); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$k = 15 + $i3;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["KdBrg"] . "," . $rowdtl["BrgUrai"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["JmlSat"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["KdSat"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i3++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 4  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 5  dari  " . $jmlhal);
						}
					 }  else if($i>=82 && $i<109 ) {
						$harga = $rowdtl["DNilInv"];
						$objTpl->setActiveSheetIndex(5); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$k = 15 + $i4;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["KdBrg"] . "," . $rowdtl["BrgUrai"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["JmlSat"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["KdSat"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i4++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 5  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 6  dari  " . $jmlhal);
						}
					 }  else if($i>=109 && $i<136 ) {
						$harga = $rowdtl["DNilInv"];
						$objTpl->setActiveSheetIndex(6); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$k = 15 + $i5;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["KdBrg"] . "," . $rowdtl["BrgUrai"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["JmlSat"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["KdSat"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i5++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 6  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 7 dari  " . $jmlhal);
						}
					 }   else if($i>=136 && $i<163 ) {
						$harga = $rowdtl["DNilInv"];
						$objTpl->setActiveSheetIndex(7); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$k = 15 + $i6;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["KdBrg"] . "," . $rowdtl["BrgUrai"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["JmlSat"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["KdSat"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i6++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 7  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 8 dari  " . $jmlhal);
						}
					 } else if($i>=163 && $i<190 ) {
						$harga = $rowdtl["DNilInv"];
						$objTpl->setActiveSheetIndex(8); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$k = 15 + $i7;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["KdBrg"] . "," . $rowdtl["BrgUrai"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["JmlSat"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["KdSat"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i7++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 8  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 9 dari  " . $jmlhal);
						}
					 } else if($i>=190 && $i<217 ) {
						$harga = $rowdtl["DNilInv"];
						$objTpl->setActiveSheetIndex(9); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$k = 15 + $i8;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["KdBrg"] . "," . $rowdtl["BrgUrai"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["JmlSat"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["KdSat"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i8++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 9  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 10 dari  " . $jmlhal);
						}
					 } else if($i>=217 && $i<244 ) {
						$harga = $rowdtl["DNilInv"];
						$objTpl->setActiveSheetIndex(10); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$k = 15 + $i9;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["KdBrg"] . "," . $rowdtl["BrgUrai"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["JmlSat"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["KdSat"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i9++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 10  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 11 dari  " . $jmlhal);
						}
					 } else {
						$harga = $rowdtl["DNilInv"];
						$objTpl->setActiveSheetIndex(11); 
						$objTpl->getActiveSheet()->setCellValue('A7', 'NOMOR PENGAJUAN : ' . $car);
						$objTpl->getActiveSheet()->setCellValue('G8', ': ' . $BC23No);
						$objTpl->getActiveSheet()->setCellValue('G9', ': ' . $BC23Tg);
						$k = 15 + $i10;
						$j = "$k";
						
						$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
						$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["KdBrg"] . "," . $rowdtl["BrgUrai"]);
						$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["JmlSat"] );
						$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["KdSat"] );
						$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
						$objTpl->getActiveSheet()->getStyle("I15:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
						$i10++;
						$objTpl->getActiveSheet()->setCellValue('F54', '                       Balaraja,   Tgl  ' . $DokTupTg . '         ..');
						if($jml_inv <= 3){
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 11  dari  " . $jmlhal);
						} else {
							$objTpl->getActiveSheet()->setCellValue("H6", "Halaman 12 dari  " . $jmlhal);
						}
					 }
				
					$i++;
				}
							
				
				
			} else {
				
				$i = 1;
				$j = '';
				$k = 37;
				foreach($qryrsdtl as $rowdtl){
					
					//$harga =  $rowdtl["harga"]   * $nilaikurs * $rowdtl["qty"];
					//$harga =  $rowdtl["harga"]   * $rowdtl["qty"];
					$harga = $rowdtl["DNilInv"];
					$k = 37 + $i;
					$j = "$k";
					$objTpl->getActiveSheet()->setCellValue("A".$j, $i);
					$objTpl->getActiveSheet()->setCellValue("B".$j, $rowdtl["KdBrg"] . "," . $rowdtl["BrgUrai"]);
					$objTpl->getActiveSheet()->setCellValue("F".$j, $rowdtl["JmlSat"] );
					$objTpl->getActiveSheet()->setCellValue("G".$j, $rowdtl["KdSat"] );
					$objTpl->getActiveSheet()->setCellValue("I".$j, $harga );
					
					
					$i++;
				}
				
				$objTpl->getActiveSheet()->getStyle("I37:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
				
			
			}
			
		
		}	  
		
		$objTpl->setActiveSheetIndex(0); 
		if($jmldt < 5){
			$objTpl->getActiveSheet()->setCellValue("E3", "Halaman 1  dari " . $jmlhal);
		} else if ($jmldt > 5 and $jmldt < 27) {
			$objTpl->getActiveSheet()->setCellValue("E3", "Halaman 1  dari " . $jmlhal);
		
		} else if ($jmldt > 27) {
			$objTpl->getActiveSheet()->setCellValue("E3", "Halaman 1  dari " . $jmlhal);
		
		}
		
		
		
		
		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!	
	
	}
	
	
	
	//--------------bc40 HIIB
	
	function loaddatahib_bc40(){
		
		
		$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']:'inv_hdr_id'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		//$where = " a.status_inv=0 ";
		$where = " b.supplier_country = 'ID' ";
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "r3" ) {
						$searchString = $k->data;
						$where .= " and r3 like  '%".$searchString."%'"; 
					}  else if ( $k->field == "supplier_name" ) {
						$searchString = $k->data;
						$where .= " and b.supplier_name like  '%".$searchString."%'"; 
					}  else if ( $k->field == "r4" ) {
						$searchString = $k->data;
						$where .= " and r4 like  '%".$searchString."%'"; 
					}  else if ( $k->field == "r20" ) {
						$searchString = $k->data;
						$where .= " and r20 like  '%".$searchString."%'"; 
					}  else if ( $k->field == "nobl" ) {
						$searchString = $k->data;
						$where .= " and nobl like  '%".$searchString."%'"; 
					}  else if ( $k->field == "tgbl" ) {
						$searchString = $k->data;
						$where .= " and tgbl =  '$searchString'"; 
					} else if ( $k->field == "r2" ) {
						$searchString = $k->data;
						$where .= " and r2 like  '%".$searchString."%'"; 
					} else if ( $k->field == "status_inv" ) {
						$searchString = $k->data;
							if ($searchString==1){ 
								$where = " a.status_inv=$searchString  "; 
							} else if ($searchString==2){ 
								$where .= " "; 
								//$where .= " or a.status_inv=1  "; 
							} else if ($searchString=='-'){ 
								$where .= " and a.status_inv=0  "; 
							} else {
								$where .= " and (a.status_inv=0  or a.status_inv='$searchString') "; 
							}
					} else if ( $k->field == "status_inv" && $k->field == "r2" )  {
						$searchString = $k->data;
						$where = " r3 like  '%".$searchString."%'"; 
					
					}
				
				}
			}
		} else {
		
			$where .= "  and a.status_inv=0 ";
		}
		
	//	echo $where;
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc40->inv_all($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc40->inv_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){
			if ($r->status_inv == 0){ $stat = "New"; } else { $stat = "Not New"; };
			if ($r->tgbl =='1900-10-23'){ $tgbl = ""; } else { $tgbl = $r->tgbl; };	
			$responce->rows[$i]['inv_hdr_id']=$r->inv_hdr_id; 
			$responce->rows[$i]['r3']=$r->r3; 
			$responce->rows[$i]['r2']=$r->r2; 
			$responce->rows[$i]['r4']=$r->r4;
			$responce->rows[$i]['r5']= inv_parsedate($r->r5); //$r->r5;
			$responce->rows[$i]['r20']=$r->r20;
			$responce->rows[$i]['supplier_name']=$r->supplier_name; 
			$responce->rows[$i]['date_create']=$r->date_create; 
			$responce->rows[$i]['status_inv']=$stat;
			$responce->rows[$i]['nobl']=$r->nobl;
			$responce->rows[$i]['tgbl']=$tgbl;
			
			$i++;
		}
		echo json_encode($responce);
		
	}
	
	function view_bc40_hib(){
		$q = $this->db->query("
			SELECT     v_noinv_dtl.noinv
			FROM         v_noinv_dtl LEFT OUTER JOIN
								  tbl_data_part_hs ON replace(v_noinv_dtl.partnumber,' ','') = tbl_data_part_hs.part_no2
			where tbl_data_part_hs.part_no is null
			group by v_noinv_dtl.noinv
		");
		$rs = $q->result_array();
		$datanull='';
		foreach ($rs as $row){
			$datanull.=$row['noinv'].'|';		
		}
		if ($datanull != ''){
			$data["test"] = 'Part Number di Data Part HS Not Match Di Invoice Berikut, Silahkan Cek Di View Data : ' . $datanull;
		} else {
			$data["test"]=$datanull;
		}
		$this->load->view('exim/view_bc40_hib', $data);
		

	
	
	}
	function view_bc40_group_invoice(){
	
		$data["test"] = "";
		$this->load->view('exim/view_bc40_group_invoice', $data);
	
	}
	
	function prosesdatabl(){
		
		$datadiff = (isset($_POST['datadiff']) && !empty($_POST['datadiff']))?$_POST['datadiff']:'0'; 
		$datadiff=json_decode($datadiff);
		$datacsv = '';
		foreach ($datadiff as $data ){
			$inv_hdr_id = (isset($data->inv_hdr_id) && !empty($data->inv_hdr_id ))?$data->inv_hdr_id :die('{"sts":"ERROR","desc":" Param inv_hdr_id Tidak Ditemukan"}');
			$invno = (isset($data->invno) && !empty($data->invno ))?$data->invno :die('{"sts":"ERROR","desc":" Param invno Tidak Ditemukan"}');
			
			$datacsv .= $inv_hdr_id . ',' . $invno; 
			$datacsv .= "|";
		}
		// echo $datacsv;	
		// var_dump($datadiff); die();
		
		
		$qry = $this->db->query("
		
			BEGIN TRY
			
				EXEC ('[spi_invoiceupdatebl_bc40_27] @datadiff=''$datacsv'', @cmd=''proses'', @typebc=''BC40''  ') 
			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 canceldatabl(){
		
		$datadiff = (isset($_POST['datadiff']) or !empty($_POST['datadiff']))?$_POST['datadiff']:'0'; 
		$datadiff=json_decode($datadiff);
		$datacsv = '';
		foreach ($datadiff as $data ){
			$datacsv .= $data->inv_hdr_id . ',' . $data->invno . ',' . $data->blawbno . ',' . '1900-10-23'; 
			$datacsv .= "|";
		}
		 // echo $datacsv;	
		// var_dump($datadiff); die();
		
		// echo "
		
			 // EXEC ('spi_invoiceupdatebl @datadiff=''$datacsv'', @nobl=''$nobl'', @tgbl=''$tgbl'', @cmd=''cancel'' ') 
			
		 // "; die();
		
		$qry = $this->db->query("
			BEGIN TRY	
			 EXEC ('spi_invoiceupdatebl_bc40_27 @datadiff=''$datacsv'', @cmd=''cancel'', @typebc=''BC40'' ') 
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
		 ");
		$rs = $qry->result_array();
        // $r = $qry->result();		
		// var_dump($r);die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
	
	}
	
	function view_bc40_prosesinsertinv(){
		$nobl = (isset($_POST['nobl']) or !empty($_POST['nobl']))?$_POST['nobl']:die('{"sts":"ERROR","desc":" Param nobl Tidak Ditemukan"}');
		$tgbl = (isset($_POST['tgbl']) or !empty($_POST['tgbl']))?$_POST['tgbl']:die('{"sts":"ERROR","desc":" Param tgbl Tidak Ditemukan"}');
		$data["tgbl"] = $tgbl;
		$data["nobl"] = $nobl;
		$this->load->view('exim/view_bc40_prosesinsertinv',$data);
	
	}
	
	function loaddatanonobl(){
		$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']:'inv_hdr_id'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$nobl = (isset($_POST['nobl']) && !empty($_POST['nobl']))?$_POST['nobl']:'';
		$tgbl = (isset($_POST['tgbl']) && !empty($_POST['tgbl']))?$_POST['tgbl']:'';
		
		
		//$where = " a.status_inv=0 ";
		$where = " 1=1 ";
		$where .= " and nobl =  '".$nobl."'";
		$where .= " and tgbl =  '".$tgbl."'";
		
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_invoice->inv_all($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_invoice->inv_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){
		    if ($r->status_inv == 0){
					  $status_inv = 'INVOICE NEW ADDED';
			} else if ($r->status_inv == 1){
				 $status_inv = 'DATA ALREADY PROCESSED';
			}
			$responce->rows[$i]['inv_hdr_id']=$r->inv_hdr_id; 
			$responce->rows[$i]['invno']=$r->r3; 
			$responce->rows[$i]['blawbno']=$r->nobl; 
			$responce->rows[$i]['tglblawb']=$r->tgbl;
			$responce->rows[$i]['status_inv']=$status_inv;
			$responce->rows[$i]['status_invx']=$r->status_inv;
			
			
			$i++;
		}
		echo json_encode($responce);
		
	}
	
	function updatestatusproses(){
		$typebc = 'BC40';
		$noinv = (isset($_POST['noinv']) && !empty($_POST['noinv']))?$_POST['noinv']:die('{"sts":"ERROR","desc":" Param INV Tidak Ditemukan"}');
		$nobl = (isset($_POST['nobl']) && !empty($_POST['nobl']))?$_POST['nobl']:die('{"sts":"ERROR","desc":" Param nobl Tidak Ditemukan"}');
		$tgbl= (isset($_POST['tgbl']) && !empty($_POST['tgbl']))?$_POST['tgbl']:die('{"sts":"ERROR","desc":" Param tg bl Tidak Ditemukan"}');
		
		$noinv=json_decode($noinv);
		$noinvcsv = '';
		foreach ($noinv as $data ){
			$inv_hdr_id = (isset($data->inv_hdr_id) && !empty($data->inv_hdr_id ))?$data->inv_hdr_id :die('{"sts":"ERROR","desc":" Param inv_hdr_id Tidak Ditemukan"}');
			$invno = (isset($data->invno) && !empty($data->invno ))?$data->invno :die('{"sts":"ERROR","desc":" Param invno Tidak Ditemukan"}');
			$noinvcsv .= $inv_hdr_id. ',' . $invno; 
			$noinvcsv .= "|";
		}
		$listinv = substr($noinvcsv, 0,  strlen($noinvcsv) -1); 
		 // echo "EXEC  [sp_insertbc23] @nobl = N'$nobl', @tgbl = '$tgbl', @typebc = N'$typebc',@noinv = '$listinv'";
		 // var_dump($noinv); die();
		$typebc = 'BC40';
		$qry = $this->db->query("
			BEGIN TRY
				EXEC  [sp_insertbc23] @nobl = N'$nobl', @tgbl = '$tgbl', @typebc = N'$typebc',@noinv = '$listinv'
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
		");
		$rs = $qry->result_array();	
		// var_dump($rs);
		// die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
		
		
		
	}
	
	function recalculate_new_inv_bl(){
		$typebc = 'BC40';
		$noinv = (isset($_POST['noinv']) && !empty($_POST['noinv']))?$_POST['noinv']:die('{"sts":"ERROR","desc":" Param INV Tidak Ditemukan"}');
		$nobl = (isset($_POST['nobl']) && !empty($_POST['nobl']))?$_POST['nobl']:die('{"sts":"ERROR","desc":" Param nobl Tidak Ditemukan"}');
		$tgbl= (isset($_POST['tgbl']) && !empty($_POST['tgbl']))?$_POST['tgbl']:die('{"sts":"ERROR","desc":" Param tg bl Tidak Ditemukan"}');
		
		$noinv=json_decode($noinv);
		$noinvcsv = '';
		foreach ($noinv as $data ){
			$inv_hdr_id = (isset($data->inv_hdr_id) && !empty($data->inv_hdr_id ))?$data->inv_hdr_id :die('{"sts":"ERROR","desc":" Param inv_hdr_id Tidak Ditemukan"}');
			$invno = (isset($data->invno) && !empty($data->invno ))?$data->invno :die('{"sts":"ERROR","desc":" invno Param invno Tidak Ditemukan"}');
			$noinvcsv .= $inv_hdr_id. ',' . $invno; 
			$noinvcsv .= "|";
		}
		$listinv = substr($noinvcsv, 0,  strlen($noinvcsv) -1); 
		 //echo "EXEC  [sp_insertcb23_recalculate_new_inv_bl] @nobl = N'$nobl', @tgbl = '$tgbl', @typebc = N'$typebc',@noinv = '$listinv'";
		 // var_dump($noinv); die();
		$typebc = 'BC40';
		$qry = $this->db->query("
			EXEC [sp_insertcb23_recalculate_new_inv_bl] @nobl = N'$nobl', @tgbl = '$tgbl', @typebc = N'$typebc',@noinv = '$listinv'
		");
		$rs = $qry->result_array();	
		//var_dump($rs);
		//die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
		
	}
	function recalculatedatabl(){
	
		$nobl = (isset($_POST['nobl']) && !empty($_POST['nobl']))?$_POST['nobl']:die('{"sts":"ERROR","desc":" Param  Tidak Ditemukan"}'); 
		$tgbl = (isset($_POST['tgbl']) && !empty($_POST['tgbl']))?$_POST['tgbl']:die('{"sts":"ERROR","desc":" Param  Tidak Ditemukan"}');
		
		$datadiff = (isset($_POST['datadiff']) && !empty($_POST['datadiff']))?$_POST['datadiff']:'0'; 
		$datadiff=json_decode($datadiff);
		$datacsv = '';
		foreach ($datadiff as $data ){
			$inv_hdr_id = (isset($data->inv_hdr_id) && !empty($data->inv_hdr_id ))?$data->inv_hdr_id :die('{"sts":"ERROR","desc":" Param inv_hdr_id Tidak Ditemukan"}');
			$invno = (isset($data->invno) && !empty($data->invno ))?$data->invno :die('{"sts":"ERROR","desc":" Param invno Tidak Ditemukan"}');
			$blawbno = (isset($data->blawbno) && !empty($data->blawbno ))?$data->blawbno :die('{"sts":"ERROR","desc":" Param blawbno Tidak Ditemukan"}');
			$tglblawb = (isset($data->tglblawb) && !empty($data->tglblawb ))?$data->tglblawb :die('{"sts":"ERROR","desc":" Param tglblawb Tidak Ditemukan"}');
			
			$datacsv .= $inv_hdr_id . ',' . $invno . ',' . $blawbno . ',' . $tglblawb; 
			$datacsv .= "|";
		}
		// echo $datacsv;	
		// var_dump($datadiff); die();
		
		
		$qry = $this->db->query("
			BEGIN TRY
			 EXEC ('spu_insertbc23_bl @datadiff=''$datacsv'', @nobl=''$nobl'', @tgbl=''$tgbl''  ') 
			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 cancelbcinvoicebc(){
	
		$nobl = (isset($_POST['nobl']) && !empty($_POST['nobl']))?$_POST['nobl']:die('{"sts":"ERROR","desc":" Param  Tidak Ditemukan"}'); 
		$tgbl = (isset($_POST['tgbl']) && !empty($_POST['tgbl']))?$_POST['tgbl']:die('{"sts":"ERROR","desc":" Param  Tidak Ditemukan"}');
		
		/* echo " EXEC ('spu_invoicenonhib_del_bc40_27 @nobl=''$nobl'', @tgbl=''$tgbl'', @typebc=''BC40''  ')  ";
		die();
		 */
		$qry = $this->db->query("
			BEGIN TRY
			 EXEC ('spu_invoicenonhib_del_bc40_27 @nobl=''$nobl'', @tgbl=''$tgbl'', @typebc=''BC40''  ') 
			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);
	
	}
	
	
	
	//---------------proses invoice_bc40 bahan penolong
	function proses_inv_bc40(){
		$id_inv_bc40 = (isset($_POST['id_inv_bc40']) && !empty($_POST['id_inv_bc40']))?$_POST['id_inv_bc40']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$uid = $this->session->userdata('DX_username');
		
		// echo " exec('[spi_invoice_bc40sparepart]  @id_inv_bc40 = $id_inv_bc40, @tipe=''INVMPK'', @username=''$uid'' ') ";
		// die();
		$qry_inv_bc40 = $this->db->query("
			
			BEGIN TRY
			
			 exec('[spi_invoice_bc40]  @id_inv_bc40 = $id_inv_bc40, @tipe=''INVBC40'', @username=''$uid'' ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		$rs = $qry_inv_bc40->result_array();
        //$r = $qry_inv_bc40->result();		
		//var_dump($rs);die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
	
	
	}
	
	function view_bc40_getdatapo(){
		
		$this->load->view('exim/view_bc40_getdatapo');
	}
	
	function loaddata_proses_inv_bc40_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']:'order_date'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$where = " 1=1 ";
		$field = '';
		$nobl = '';		
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "invoice_no" ) {
						$searchString = $k->data;
						$nobl = $searchString;
						$field = "invoice_no";
						$where .= " and invoice_no like  '%".$searchString."%'"; 
					} else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$nobl = $searchString;
						$field = "part_name";
						$where .= " and part_name like  '%".$searchString."%'"; 
					}  else if ( $k->field == "nobl" ) {
						$searchString = $k->data;
						$nobl = $searchString;
						$field = "nobl";
						$where .= " and nobl like  '%".$searchString."%'"; 
					} else if ( $k->field == "status_data" ) {
						$searchString = $k->data;
						$where .= " and status_data like  '%".$searchString."%'"; 
						if ($searchString == 'all'){
							$where = " 1=1 ";
						} else if ($searchString == '-'){
							if ($field != ''){ 
								$where = $field . " like '%" . $nobl . "%'";
							} else if ($field == '') {
								$where = " 1=1 ";
							}
							//echo $where; die();
						}
					}
				}
			}
		} else {
		
			$where = " 1=1 and status_data='new' ";
		
		}
		
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc40->bc40_invbc40_hdrAll($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc40->bc40_invbc40_hdrCountAll($where);
	//	var_dump($records); die();
		
		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]['kode_supplier']=$r->kode_supplier;
			$responce->rows[$i]['order_no']=$r->order_no;
			$responce->rows[$i]['order_date']=$r->order_date;
			$responce->rows[$i]['invoice_no']=$r->invoice_no;
			$responce->rows[$i]['invoice_date']=$r->invoice_date;
			$responce->rows[$i]['status_data']=$r->status_data;
			$responce->rows[$i]['nobl']=$r->nobl;
			$responce->rows[$i]['tglbl']=$r->tglbl;
			
			$i++;
		}
		echo json_encode($responce);
	}
	
	function view_bc40_detil_invbc40(){
	
		$postData = (isset($_POST['postData']) && !empty($_POST['postData']))?$_POST['postData']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan or not selected"}');
		
		$data['dataarray'] =  $postData;
		$this->load->view('exim/view_bc40_detil_invbc40', $data);		

	
	
	
	}
	function loaddata_proses_inv_bc40(){
		$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_invoice_bc40'; // get index row - i.e. user click to sort
        $sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		$dimana = (isset($_POST['where']) && !empty($_POST['where']))?$_POST['where']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$dimana = str_replace("<font color='red'>", "", $dimana);
		$rep = array('<font color="red">', '<font color="blue">','</font>');
		$dimana = str_replace($rep, "", $dimana);
		$dataarray = json_decode($dimana);
		/*
		print_r($dataarray);
		die();
		 */
		$wherestatus_data = 'new';
		$whereinvoice_no = '';
		$whereorder_no = '';
		foreach ($dataarray as $r ){
			$whereinvoice_no .= "'" . $r->invoice_no . "'" .',';
			$whereorder_no .= "'" . $r->order_no . "'"  . ',';
			$wherestatus_data = $r->status_data ;
		}
		
				
		$whereinvoice_no = substr($whereinvoice_no, 0, strlen($whereinvoice_no) - 1);
		$whereorder_no = substr($whereorder_no, 0, strlen($whereorder_no) - 1);
		
		$whereinvoice_no = '('.$whereinvoice_no.')';
		$whereorder_no = '('.$whereorder_no.')';
		
				
		$where = " 1=1 and status_data='$wherestatus_data' and [invoice_no] in $whereinvoice_no and order_no in $whereorder_no  ";
			
		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "invoice_no" ) {
						$searchString = $k->data;
						$where .= " and invoice_no like  '%".$searchString."%'"; 
					} else if ( $k->field == "part_name" ) {
						$searchString = $k->data;
						$where .= " and part_name like  '%".$searchString."%'"; 
					} 
				}
			}
		}
		
		
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc40->bc40_invbc40_All($limit,$start,$sidx,$sord, $where);
        $count = $this->mdl_bc40->bc40_invbc40_CountAll($where);
	//	var_dump($records); die();
		
		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_invoice_bc40']=$r->id_invoice_bc40;
			$responce->rows[$i]['part_name']=$r->part_name;
			$responce->rows[$i]['part_no']=$r->part_no;
			$responce->rows[$i]['kode_barang']=$r->kode_barang;
			$responce->rows[$i]['kode_supplier']=$r->kode_supplier;
			$responce->rows[$i]['maker']=$r->maker;
			$responce->rows[$i]['order_qty']=$r->order_qty;
			$responce->rows[$i]['order_no']=$r->order_no;
			$responce->rows[$i]['order_date']=$r->order_date;
			$responce->rows[$i]['req_eta_date']=$r->req_eta_date;
			$responce->rows[$i]['shipping_by']=$r->shipping_by;
			$responce->rows[$i]['invoice_no']=$r->invoice_no;
			$responce->rows[$i]['invoice_date']=$r->invoice_date;
			$responce->rows[$i]['inv_qty']=$r->inv_qty;
			$responce->rows[$i]['inv_unit']=$r->inv_unit;
			$responce->rows[$i]['status_inv']=$r->status_inv;
			$responce->rows[$i]['rec_qty']=$r->rec_qty;
			$responce->rows[$i]['rec_date']=$r->rec_date;
			$responce->rows[$i]['amount']=$r->amount;
			$responce->rows[$i]['remark']=$r->remark;
			$responce->rows[$i]['nobl']=$r->nobl;
			$responce->rows[$i]['tglbl']=$r->tglbl;
			$responce->rows[$i]['nocar']=$r->nocar;
			$responce->rows[$i]['tglaju']=$r->tglaju;
			$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 proses_update_bl_bc40(){
		
		$this->load->library('arraytoxml');
		$uid = $this->session->userdata('DX_username');
		$postData = (isset($_POST['postData']) && !empty($_POST['postData']))?$_POST['postData']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan or not selected"}');
		$no_bl_bc40 = (isset($_POST['no_bl_bc40']) && !empty($_POST['no_bl_bc40']))?$_POST['no_bl_bc40']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan or not selected"}');
		$date_bl_bc40 = (isset($_POST['date_bl_bc40']) && !empty($_POST['date_bl_bc40']))?$_POST['date_bl_bc40']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan or not selected"}');
		
		$rep = array('<font color="red">', '<font color="blue">','</font>');
		$postData = str_replace($rep, "", $postData);
		
		$array = json_decode($postData);
		$array = objectToArray($array);
		
		$postdata = $this->arraytoxml->toXml($array);
		//$xxx = str_replace("&Acirc;&nbsp;", "", $postdata);		
		$search = array('&acirc;��','&acirc;��','&acirc;��','&acirc;��','&Acirc;&pound;','&Acirc;&not;','&acirc;�&cent;','&Acirc;','&nbsp;','&Acirc;&nbsp;');
		$xxx = str_replace($search, "", $postdata);
			
		
		//echo $xxx1;
			
 	 /* 	echo " exec('[spu_bl_mesinsparepart]  @username=''$uid'', @xmldata=''$xxx'',@no_bl_bc40=''$no_bl_bc40'',@date_bl_bc40=''$date_bl_bc40'' ')";
		die(); */ 
		
		$uid = $this->session->userdata('DX_username');
		$qry_inv_mesin = $this->db->query("
			
			BEGIN TRY
			
			 exec('[spu_bl_invbc40]  @username=''$uid'', @xmldata=''$xxx'',@no_bl_invbc40=''$no_bl_bc40'',@date_bl_invbc40=''$date_bl_bc40'' ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		$rs = $qry_inv_mesin->result_array();
        //$r = $qry_inv_mesin->result();		
		//var_dump($rs);die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
		
	
	
	
	}
	
	function proses_update_inv_bc40(){
	
		$this->load->library('arraytoxml');
		$uid = $this->session->userdata('DX_username');
		$postData = (isset($_POST['postData']) && !empty($_POST['postData']))?$_POST['postData']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan or not selected"}');
		
		$rep = array('<font color="red">', '<font color="blue">','</font>', '<font color=\"red\">');
		$postData = str_replace($rep, "", $postData);
		
				
		$array = json_decode($postData);
		$array = objectToArray($array);
		
				
		$postdata = $this->arraytoxml->toXml($array);
		//$xxx = str_replace("&Acirc;&nbsp;", "", $postdata);		
		$search = array('&acirc;��','&acirc;��','&acirc;��','&acirc;��','&Acirc;&pound;','&Acirc;&not;','&acirc;�&cent;','&Acirc;','&nbsp;','&Acirc;&nbsp;','&lt;font color="red"&gt;new');
		$xxx = str_replace($search, "", $postdata);
			
		/* echo $xxx;
		die(); */	
 		/* echo " exec('[spu_invoice_bc40]  @username=''$uid'', @xmldata=''$xxx'' ')";
		die();  */
		
		$uid = $this->session->userdata('DX_username');
		$qry_inv_mesin = $this->db->query("
			
			BEGIN TRY
			
			 exec('[spu_invoice_bc40]  @username=''$uid'', @xmldata=''$xxx'' ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		$rs = $qry_inv_mesin->result_array();
        //$r = $qry_inv_mesin->result();		
		//var_dump($rs);die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
		
	
	
	
	
	}
	
	function proses_bc40_invbc40(){
	
		$this->load->library('arraytoxml');
		$uid = $this->session->userdata('DX_username');
		$postData = (isset($_POST['postData']) && !empty($_POST['postData']))?$_POST['postData']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan or not selected"}');
		
		$array = json_decode($postData);
		$array = objectToArray($array);
		
		$postdata = $this->arraytoxml->toXml($array);
		//$xxx = str_replace("&Acirc;&nbsp;", "", $postdata);		
		$search = array('&acirc;��','&acirc;��','&acirc;��','&acirc;��','&Acirc;&pound;','&Acirc;&not;','&acirc;�&cent;','&Acirc;','&nbsp;'
		,'&Acirc;&nbsp;','&lt;font color="red"&gt;new&lt;/font&gt;');
		$xxx = str_replace($search, "", $postdata);
		$typebc = 'BC40';	
		//echo $xxx1;
		/* $typebc = 'BC40';	
 	 	 echo "  exec('[spi_proses_inv_bc40]  @username=''$uid'', @xmldata=''$xxx'', @typebc=''$typebc'' ')
			 ";
		 die(); 
		 */
		$uid = $this->session->userdata('DX_username');
		$qry_inv_mesin = $this->db->query("
			
			BEGIN TRY
			
			 exec('[spi_proses_inv_bc40]  @username=''$uid'', @xmldata=''$xxx'', @typebc=''$typebc'' ')
			
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			
			");
		$rs = $qry_inv_mesin->result_array();
        //$r = $qry_inv_mesin->result();		
		//var_dump($rs);die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
	
	
	}
	function cancelnocar(){
	
		$idhdrbc40 = (isset($_POST['idhdrbc40']) && !empty($_POST['idhdrbc40']))?$_POST['idhdrbc40']:die('{"sts":"ERROR","desc":" idhdrbc40 Param Tidak Ditemukan"}');
		$typedok = (isset($_POST['typedok']) && !empty($_POST['typedok']))?$_POST['typedok']:die('{"sts":"ERROR","desc":" typedok Param Tidak Ditemukan"}');
		$bc_in_from_in = (isset($_POST['bc_in_from_in']) && !empty($_POST['bc_in_from_in']))?$_POST['bc_in_from_in']:die('{"sts":"ERROR","desc":" bc_in_from_in Param Tidak Ditemukan"}');
		
		if ($bc_in_from_in != 'INVMS'){
			die('{"sts":"ERROR","desc":" Bukan Data PO"}');
		
		}
		
		$qry = $this->db->query("
			declare @nobl varchar(100)
			declare @tglbl date
			
			set @nobl = (select nobl from tbl_bc_in_hdr where id_bc_in_hdr=$idhdrbc40 and typedok='BC40')
			set @tglbl = (select tglbl from tbl_bc_in_hdr where id_bc_in_hdr=$idhdrbc40 and typedok='BC40')
			
			if @nobl is null
			begin
				select '06' as status, 'BL/Surat Jalan tidak ditemukan' as description
				return
			end
			
			if @tglbl is null
			begin
				select '06' as status, 'Tanggal BL/Surat Jalan tidak ditemukan' as description
				return
			end
			
			--if (select top 1 statusdok from tbl_bc_in_hdr where id_bc_in_hdr=$idhdrbc40 and typedok='BC40' ) <> 'DATA BARU'
			--begin
			--	select '06' as status, 'DATA TIDAK DAPAT DI CANCEL, LIHAT STATUS' as description
			--	return
			--end
			
			BEGIN TRY  
	           BEGIN TRANSACTION
				delete from [tbl_invoice_bc40] where [nobl]=@nobl and [tglbl]=@tglbl 
				
				delete from [tbl_bc_in_hdr_h_status]  where id_bc_in_hdr=$idhdrbc40	
				delete from tbl_bc_in_con where id_bc_in_hdr=$idhdrbc40	
				delete from tbl_bc_in_dok  where id_bc_in_hdr=$idhdrbc40	
				delete from tbl_bc_in_dtl  where id_bc_in_hdr=$idhdrbc40	
				delete from tbl_bc_in_dtl_partnumber  where id_bc_in_hdr=$idhdrbc40	
				delete from tbl_bc_in_fas  where id_bc_in_hdr=$idhdrbc40	
				delete from tbl_bc_in_kms  where id_bc_in_hdr=$idhdrbc40	
				delete from tbl_bc_in_trf  where id_bc_in_hdr=$idhdrbc40	
				delete from tbl_bc_in_hdr  where id_bc_in_hdr=$idhdrbc40	
				
				
				
				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 INVOICENYA 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 cancel_car(){
		$id_bc_in_hdr = (isset($_POST['id_bc_in_hdr']) && !empty($_POST['id_bc_in_hdr']))?$_POST['id_bc_in_hdr']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		//$doc_in_from_id = (isset($_POST['doc_in_from_id']) && !empty($_POST['doc_in_from_id']))?$_POST['doc_in_from_id']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		
		$in_inv = $this->db->query("
			declare @nobl varchar(50), @tglbl date, @jnsinv varchar(50)
			declare @id_data_in_hdr bigint
			
			--if (select count(*) from [tbl_data_in_hdr] where id_terkait=$id_bc_in_hdr and doc_in_from_id=5) > 0 
			--begin
			--	select '06' as status, ' DATA SUDAH DIPROSES.. CANCEL DAHULU, KALO DAH APPROVE KAGAK BISA' as description
			--	return
			--end
			
			set @nobl = (select nobl from [tbl_bc_in_hdr] where id_bc_in_hdr = $id_bc_in_hdr)
			set @tglbl = (select tglbl from [tbl_bc_in_hdr] where id_bc_in_hdr = $id_bc_in_hdr)
			
						
			if (select count(*) from [dbo].[tbl_inv_hdr] where [nobl] = @nobl and [tgbl]=@tglbl) > 0
			begin
				
			    set @jnsinv='HIB'
				
			end
			if  @jnsinv = 'HIB'
			begin
				set @id_data_in_hdr = (select id_data_in_hdr from [tbl_data_in_hdr] where id_terkait=$id_bc_in_hdr and doc_in_from_id=5)
				delete from [tbl_data_in_hdr_h_status] where id_data_in_hdr = @id_data_in_hdr
				delete from [tbl_data_in_dtl] where id_data_in_hdr = @id_data_in_hdr
				delete from [tbl_data_in_hdr] where id_data_in_hdr = @id_data_in_hdr
				if (select count(*) from tbl_bc_in_hdr where JnsBarang = '01' and id_bc_in_hdr = $id_bc_in_hdr and bc_in_from_in='INV HIB' and nobl=@nobl and [tglbl]=@tglbl ) > 0 
				begin
					update  [dbo].[tbl_inv_hdr]  set nobl = '-', tgbl = NULL, status_inv = 0, nobc=0, car=0  where [nobl] = @nobl and [tgbl]=@tglbl

					delete from [dbo].[tbl_bc_in_hdr_h_status] where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_dtl where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_dtl_partnumber where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_dok where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_con where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_kms where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_fas where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_hdr where id_bc_in_hdr = $id_bc_in_hdr
					
				end
				
			end
			
			
			select '00' as status, ' SUKSES UPDATED ' + @jnsinv + '  ' + @nobl +'  '+ cast(@tglbl as varchar)  as description
				
			");
		$rs = $in_inv->result_array();
        //$r = $in_inv->result();		
		//var_dump($r);die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
	
	
	
	}
	*/
	
	function cancel_car(){
		$id_bc_in_hdr = (isset($_POST['id_bc_in_hdr']) && !empty($_POST['id_bc_in_hdr']))?$_POST['id_bc_in_hdr']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		//$doc_in_from_id = (isset($_POST['doc_in_from_id']) && !empty($_POST['doc_in_from_id']))?$_POST['doc_in_from_id']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		
		
		$in_inv = $this->db->query("
			declare @nobl varchar(50), @tglbl date, @jnsinv varchar(50)
			declare @id_data_in_hdr bigint
			declare @bc_in_from_in varchar(20)
			
			
			--if (select count(*) from [tbl_data_in_hdr] where id_terkait=$id_bc_in_hdr and doc_in_from_id=5   and [status] = 'APPROVED') > 0 
			--begin
			--	select '06' as status, ' DATA SUDAH DIPROSES.. CANCEL DAHULU, KALO DAH APPROVE KAGAK BISA' as description
			--	return
			--end
			
			set @nobl = (select nobl from [tbl_bc_in_hdr] where id_bc_in_hdr = $id_bc_in_hdr)
			set @tglbl = (select tglbl from [tbl_bc_in_hdr] where id_bc_in_hdr = $id_bc_in_hdr)
			
			set @bc_in_from_in = (select bc_in_from_in from  tbl_bc_in_hdr where id_bc_in_hdr = $id_bc_in_hdr )
			if 	@bc_in_from_in = 'COO'
			begin
				set @id_data_in_hdr = (select id_data_in_hdr from [tbl_data_in_hdr] where id_terkait=$id_bc_in_hdr and doc_in_from_id=5)
				delete from [tbl_data_in_hdr_h_status] where id_data_in_hdr = @id_data_in_hdr
				delete from [tbl_data_in_dtl] where id_data_in_hdr = @id_data_in_hdr
				delete from [tbl_data_in_hdr] where id_data_in_hdr = @id_data_in_hdr
				
				delete from [dbo].[tbl_bc_in_hdr_h_status] where id_bc_in_hdr = $id_bc_in_hdr
				delete from [dbo].tbl_bc_in_dtl where id_bc_in_hdr = $id_bc_in_hdr
				delete from [dbo].tbl_bc_in_dtl_partnumber where id_bc_in_hdr = $id_bc_in_hdr
				delete from [dbo].tbl_bc_in_dok where id_bc_in_hdr = $id_bc_in_hdr
				delete from [dbo].tbl_bc_in_con where id_bc_in_hdr = $id_bc_in_hdr
				delete from [dbo].tbl_bc_in_kms where id_bc_in_hdr = $id_bc_in_hdr
				delete from [dbo].tbl_bc_in_fas where id_bc_in_hdr = $id_bc_in_hdr
				delete from [dbo].tbl_bc_in_hdr where id_bc_in_hdr = $id_bc_in_hdr
				
				
				update  [dbo].[tbl_coo_data]  set [nobl] = NULL, [tgbl] = NULL, [id_bc_in_hdr] = NULL, [nobc]=NULL, [tglbc]=NULL, [car]=NULL, [type_bc] = NULL, [status_inv] = 'NEW'
 				where nobl = @nobl and tgbl = @tglbl and id_bc_in_hdr = $id_bc_in_hdr
				select '00' as status, ' SUKSES UPDATED ' + @bc_in_from_in + ' NO GROUP/BL/SRT JLN: ' + @nobl +'  '+ cast(@tglbl as varchar)  as description
				return
			end
			
						
			if (select count(*) from [dbo].[tbl_inv_hdr] where [nobl] = @nobl and [tgbl]=@tglbl) > 0
			begin
				
			    set @jnsinv='HIB'
				
			end
			if  @jnsinv = 'HIB'
			begin
				set @id_data_in_hdr = (select id_data_in_hdr from [tbl_data_in_hdr] where id_terkait=$id_bc_in_hdr and doc_in_from_id=5)
				delete from [tbl_data_in_hdr_h_status] where id_data_in_hdr = @id_data_in_hdr
				delete from [tbl_data_in_dtl] where id_data_in_hdr = @id_data_in_hdr
				delete from [tbl_data_in_hdr] where id_data_in_hdr = @id_data_in_hdr
				if (select count(*) from tbl_bc_in_hdr where JnsBarang = '01' and id_bc_in_hdr = $id_bc_in_hdr and bc_in_from_in='INV HIB' and nobl=@nobl and [tglbl]=@tglbl ) > 0 
				begin
					update  [dbo].[tbl_inv_hdr]  set nobl = '-', tgbl = NULL, status_inv = 0, nobc=0, car=0  where [nobl] = @nobl and [tgbl]=@tglbl

					delete from [dbo].[tbl_bc_in_hdr_h_status] where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_dtl where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_dtl_partnumber where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_dok where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_con where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_kms where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_fas where id_bc_in_hdr = $id_bc_in_hdr
					delete from [dbo].tbl_bc_in_hdr where id_bc_in_hdr = $id_bc_in_hdr
					
				end
				
			end
			
			
			select '00' as status, ' SUKSES UPDATED ' + @jnsinv + '  ' + @nobl +'  '+ cast(@tglbl as varchar)  as description
				
			");
		$rs = $in_inv->result_array();
        //$r = $in_inv->result();		
		//var_dump($r);die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
	
	
	
	}
	
	function view_bc40_search(){
	
		$this->load->view('exim/view_bc40_search');
	
	}
	
	function view_bc40_update_invoice(){
		$no_invoice_bc40_update = (isset($_POST['no_invoice_bc40_update']) && !empty($_POST['no_invoice_bc40_update']))?$_POST['no_invoice_bc40_update']:die('{"sts":"ERROR","desc":" idhdrbc40 Param Tidak Ditemukan"}');
		$tgl_invoice_bc40_update = (isset($_POST['tgl_invoice_bc40_update']) && !empty($_POST['tgl_invoice_bc40_update']))?$_POST['tgl_invoice_bc40_update']:die('{"sts":"ERROR","desc":" typedok Param Tidak Ditemukan"}');
		$idhdrbc40 = (isset($_POST['idhdrbc40']) && !empty($_POST['idhdrbc40']))?$_POST['idhdrbc40']:die('{"sts":"ERROR","desc":" idhdrbc40 Param Tidak Ditemukan"}');
		$iddokbc40 = (isset($_POST['iddokbc40']) && !empty($_POST['iddokbc40']))?$_POST['iddokbc40']:die('{"sts":"ERROR","desc":" typedok Param Tidak Ditemukan"}');
		
		$data['no_invoice_bc40_update'] = $no_invoice_bc40_update;
		$data['tgl_invoice_bc40_update'] = $tgl_invoice_bc40_update;
		$data['idhdrbc40'] = $idhdrbc40;
		$data['iddokbc40'] = $iddokbc40;
		
		
		$this->load->view('exim/view_bc40_update_invoice', $data);
	
	}
	
	function update_no_invoicebc40(){
		$idhdrbc40 = (isset($_POST['idhdrbc40']) && !empty($_POST['idhdrbc40']))?$_POST['idhdrbc40']:die('{"sts":"ERROR","desc":" idhdrbc40 Param Tidak Ditemukan"}');
		$id_bc_in_dok = (isset($_POST['id_bc_in_dok']) && !empty($_POST['id_bc_in_dok']))?$_POST['id_bc_in_dok']:die('{"sts":"ERROR","desc":" typedok Param Tidak Ditemukan"}');
		$nomor_invoice_bc40 = (isset($_POST['nomor_invoice_bc40']) && !empty($_POST['nomor_invoice_bc40']))?$_POST['nomor_invoice_bc40']:die('{"sts":"ERROR","desc":" idhdrbc40 Param Tidak Ditemukan"}');
		$tgl_invoice_bc40 = (isset($_POST['tgl_invoice_bc40']) && !empty($_POST['tgl_invoice_bc40']))?$_POST['tgl_invoice_bc40']:die('{"sts":"ERROR","desc":" typedok Param Tidak Ditemukan"}');
		$hdn_nomor_invoice_bc40 = (isset($_POST['hdn_nomor_invoice_bc40']) && !empty($_POST['hdn_nomor_invoice_bc40']))?$_POST['hdn_nomor_invoice_bc40']:die('{"sts":"ERROR","desc":" idhdrbc40 Param Tidak Ditemukan"}');
		$hdn_tgl_invoice_bc40 = (isset($_POST['hdn_tgl_invoice_bc40']) && !empty($_POST['hdn_tgl_invoice_bc40']))?$_POST['hdn_tgl_invoice_bc40']:die('{"sts":"ERROR","desc":" typedok Param Tidak Ditemukan"}');
		
		$qry_inv_mesin = $this->db->query("
			declare @tgl_invoice_old date, @tgl_invoice_new date
			set @tgl_invoice_old = '$hdn_tgl_invoice_bc40'
			set @tgl_invoice_new = '$tgl_invoice_bc40'
			BEGIN TRY
				update tbl_bc_in_dok set DokNo='$nomor_invoice_bc40',  DokTg = '$tgl_invoice_bc40'	
			 	where id_bc_in_dok=$id_bc_in_dok and  id_bc_in_hdr=$idhdrbc40
			 	update tbl_inv_hdr set r3 = '$nomor_invoice_bc40', r5=CONVERT(VARCHAR(8), @tgl_invoice_new, 11)
			 	where r3='$hdn_nomor_invoice_bc40'  and r5=CONVERT(VARCHAR(8), @tgl_invoice_old, 11) 
			END TRY
			BEGIN CATCH 
				SELECT 
				'06' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH;
			SELECT 
				'00' AS status
				,'SUKSES UPDATE' AS description;
			");
		$rs = $qry_inv_mesin->result_array();
        //$r = $qry_inv_mesin->result();		
		//var_dump($rs);die();
		foreach ($rs as $row){
			$responce = array("sts" => $row['status'], "desc" => $row['description']);
		}  
		echo json_encode($responce);
		
		
	}
	
	function view_coo_bc40_ceisa(){
		$this->mysql =$this->load->database('mysql', TRUE);	
		
		$id_bc_in_hdr = (isset($_POST['id_bc40_hdr_ceisa']) && !empty($_POST['id_bc40_hdr_ceisa']))?$_POST['id_bc40_hdr_ceisa']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		$q = $this->db->query("select dokno, convert(char(10),doktg,126) as doktg from tbl_bc_in_dok where id_bc_in_hdr = $id_bc_in_hdr and dokkd='380'  ");
		
		$q_last_car = $this->mysql->query("
			select NOMOR_AJU from tpb_header where KODE_DOKUMEN_PABEAN = '40'  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;
		}
		$no_inv = "";
		$pre = "";
		foreach($q->result() as $r){
			$pre = "<br />";
			$no_inv .= $r->dokno . " # " . $r->doktg . $pre;
			
		}
		
		$q_car = $this->db->query("
			select car from tbl_bc_in_hdr where id_bc_in_hdr = $id_bc_in_hdr
		");
		foreach ($q_car->result() as $rcar){
			$carr = $rcar->car;
		}
		
		$no_reg = substr($last_car,0,12);
		$aju_last = substr($last_car,-6);
		$aju_next = sprintf('%06d', ((int) $aju_last + 1));
		$next_car = $no_reg . date("Ymd") . $aju_next; 
		$data['id_bc_in_hdr'] = $id_bc_in_hdr;
		$data['no_inv'] = $no_inv;
		$data['last_car'] = $last_car;
		$data['next_car'] = $next_car;
		$data['car'] = $carr;
		$this->load->view('exim/view_coo_bc40_ceisa', $data);
	
	}
	
	function proses_bc40_ceisa(){
		$this->mysql =$this->load->database('mysql', TRUE);	
		$id_bc_in_hdr = (isset($_POST['id_bc_in_hdr']) && !empty($_POST['id_bc_in_hdr']))?$_POST['id_bc_in_hdr']:die('{"sts":"ERROR","desc":" Param ID Tidak Ditemukan"}');
		
		$q = $this->db->query("select dokno, convert(char(8),doktg,103) as doktg from tbl_bc_in_dok where id_bc_in_hdr = $id_bc_in_hdr and dokkd='380'  ");
		
		$q_last_car = $this->mysql->query("
			select NOMOR_AJU from tpb_header  where KODE_DOKUMEN_PABEAN = '40'  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;
		}
		
		$ID_MODUL = (int)substr($last_car, 6,6);
		
		$no_inv = "";
		$pre = "";
		foreach($q->result() as $r){
			$pre = "<br />";
			$no_inv .= $r->dokno . " # " . $r->doktg . $pre;
			
		}
		$no_reg = substr($last_car,0,12);
		$aju_last = substr($last_car,-6);
		$aju_next = sprintf('%06d', ((int) $aju_last + 1));
		$next_car = $no_reg . date("Ymd") . $aju_next; 
		
		$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 = "";
		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;
		}
		
		
		$q_bc23_hdr=$this->db->query("
			select
			  id_bc_in_hdr
			  ,[CAR]
			  ,[KdKpbc]
			  ,[Tujuan]
			  ,[JnsBarang]
			  ,[TujuanKirim]
			  ,[PasokNama]
			  ,[PasokAlmt]
			  ,[PasokNeg]
			  ,[UsahaId]
			  ,[UsahaNpwp]
			  ,[KdTPB]
			  ,[Registrasi]
			  ,[UsahaNama]
			  ,[UsahaAlmt]
			  ,[UsahaStatus]
			  ,[ApiKd]
			  ,[ApiNo]
			  ,[PpjkId]
			  ,[PpjkNpwp]
			  ,[PpjkNama]
			  ,[PpjkAlmt]
			  ,[PpjkNo]
			  ,[PpjkTg]
			  ,[IndId]
			  ,[IndNpwp]
			  ,[IndNama]
			  ,[IndAlmt]
			  ,[Moda]
			  ,[AngkutNama]
			  ,[AngkutNo]
			  ,[AngkutFl]
			  ,[PelBkr]
			  ,[PelMuat]
			  ,[PelTransit]
			  ,[BC23No]
			  ,CONVERT(varchar, [BC23Tg], 126) as BC23Tg
			  ,[KdKpbcBongkar]
			  ,[KdKpbcAwas]
			  ,[DokTupKd]
			  ,[DokTupNo]
			  ,CONVERT(varchar, [DokTupTg], 126) as DokTupTg 
			  ,[PosNo]
			  ,[PosSub]
			  ,[TmpTbn]
			  ,[KdVal]
			  ,[Ndpbm]
			  ,[NilInv]
			  ,[Freight]
			  ,[BTambahan]
			  ,[Diskon]
			  ,[KdAss]
			  ,[Asuransi]
			  ,[KdHrg]
			  ,[Fob]
			  ,[Cif]
			  ,[Bruto]
			  ,[Netto]
			  ,[JmCont]
			  ,[JmBrg]
			  ,[TglTtd]
			  ,[KotaTtd]
			  ,[Namattd]
			  ,[ContakPerson]
			  ,[NoPhone]
			  ,[NoFax]
			  ,[Email]
			  ,[Status]
			  ,[Snrf]
			  ,[Lengkap]
			  ,[PosSubSub]
			  ,[NoKontrak]
			  ,[TgKontrak]
			  ,[HargaRp]
			  ,[TmpPeriksaFisik]
			  ,[AlmtPeriksaFisik]
			  ,[TgPeriksaFisik]
			  ,[WkPeriksaFisik]
			  ,(case when (isnull(isnull(create_by, update_by), (select top 1 [createby] FROM [dbo].[v_bc_in_hdr_h_status] where id_bc_in_hdr=[tbl_bc_in_hdr].id_bc_in_hdr))) = 'admin' then 'nurhadi' else (isnull(isnull(create_by, update_by), (select top 1 [createby] FROM [dbo].[v_bc_in_hdr_h_status] where id_bc_in_hdr=[tbl_bc_in_hdr].id_bc_in_hdr))) end) as create_by
			  ,(case when (isnull(isnull(create_by, update_by), (select top 1 [createby] FROM [dbo].[v_bc_in_hdr_h_status] where id_bc_in_hdr=[tbl_bc_in_hdr].id_bc_in_hdr))) = 'admin' then 'nurhadi' else (isnull(isnull(create_by, update_by),  (select top 1 [createby] FROM [dbo].[v_bc_in_hdr_h_status] where id_bc_in_hdr=[tbl_bc_in_hdr].id_bc_in_hdr))) end) as update_by
			   ,convert(varchar, isnull(isnull(create_date, update_date),  (select top 1 create_date  FROM [dbo].[v_bc_in_hdr_h_status]  where id_bc_in_hdr=[tbl_bc_in_hdr].id_bc_in_hdr)), 103) as create_date
	           ,convert(varchar, isnull(isnull(create_date, update_date),  (select top 1 create_date  FROM [dbo].[v_bc_in_hdr_h_status]  where id_bc_in_hdr=[tbl_bc_in_hdr].id_bc_in_hdr)), 103) as update_date
			  ,[typedok]
			  ,[statusdok]
			  ,[noinv]
			  ,CONVERT(varchar, [tginv], 126) as tglinv
			  ,inv_hdr_id
			  ,nobl
			  ,CONVERT(varchar, [tglbl], 126) as tglbl
			  ,bc_in_from_in
			  ,CONVERT(varchar, tgaju, 126) as tgaju
			  ,(select top 1 dbo.fnRemoveNonNumericCharacters([NPWP]) from [tbl_data_supplier] where supplier_name = tbl_bc_in_hdr.PasokNama  ) as NPWP  
			  from 
			  tbl_bc_in_hdr
			  where  id_bc_in_hdr = $id_bc_in_hdr
		");
		
		
		$hdr_array = array();
		foreach($q_bc23_hdr->result() as $r){
			$kode_harga = 'FOB';
			if ($r->KdHrg == '1'){
				$kode_harga = 'CIF';
			}  else if ($r->KdHrg == '2'){
				$kode_harga = 'CNF';
			}
			$KODE_KANTOR_BONGKAR = '050300';
			if($r->Moda == '4'){
				$KODE_KANTOR_BONGKAR = '050100';
			} else if ($r->Moda == '1'){
				$KODE_KANTOR_BONGKAR = '040300';
			}
			
			$hdr_array[] = array(
				
				//"KODE_KANTOR" => "050100",
				//"KODE_TUJUAN_TPB" => "1",
				//"NAMA_PEMASOK" => $r->PasokNama,
				//"ALAMAT_PEMASOK" => $r->PasokAlmt,
				//"KODE_NEGARA_PEMASOK" => $r->PasokNeg,
				//"KODE_ID_PENGUSAHA" => "1",
				//"KODE_JENIS_API_PENGUSAHA" => $r->ApiKd,
				//"ID_PENGUSAHA" => $r->UsahaNpwp,
				//"ID_PEMILIK" => $r->UsahaNpwp,
				//"NOMOR_IJIN_TPB" => $r->Registrasi,
				//"PERUSAHAAN" => $r->UsahaNama,
				//"ALAMAT_PEMILIK" => $r->UsahaAlmt,
				//"API_PENGUSAHA" => $r->ApiNo,
				//"KODE_CARA_ANGKUT" => $r->Moda,
				//"NAMA_PENGANGKUT" => $r->AngkutNama,
				//"NOMOR_VOY_FLIGHT" => $r->AngkutNo,
				//"KODE_BENDERA" => $r->AngkutFl,
				//"KODE_KANTOR_BONGKAR" => $KODE_KANTOR_BONGKAR,
				//"KODE_PEL_MUAT" => $r->PelMuat,
				//"KODE_PEL_TRANSIT" => $r->PelTransit,
				//"NOMOR_DAFTAR" => $r->BC23No,
				//"TANGGAL_DAFTAR" => $r->BC23Tg,
				//"KODE_PEL_BONGKAR" => $r->PelBkr,
				//"KODE_KANTOR" => $r->KdKpbcAwas,
				//"NOMOR_BC11" => $r->DokTupNo,
				//"TANGGAL_BC11" => $r->DokTupTg,
				//"POS_BC11" => $r->PosNo,
				//"SUBPOS_BC11" => $r->PosSub,
				//"KODE_TPS" => $r->TmpTbn,
				//"KODE_VALUTA" => $r->KdVal,
				//"NDPBM" => $r->Ndpbm,
				//"HARGA_INVOICE" => $r->NilInv,
				//"FREIGHT" => $r->Freight,
				//"BIAYA_TAMBAHAN" => $r->BTambahan,
				//"DISKON" => $r->Diskon,
				//"KODE_ASURANSI" => $r->KdAss,
				//"ASURANSI" => $r->Asuransi,
				//"KODE_HARGA" => $kode_harga, //$r->KdHrg,
				//"FOB" => $r->Fob,
				//"CIF" => $r->Cif,
				//"BRUTO" => $r->Bruto,
				//"NETTO" => $r->Netto,
				//"JUMLAH_KONTAINER" => $r->JmCont,
				//"JUMLAH_BARANG" => $r->JmBrg,
				//"TANGGAL_TTD" => Date("Y-m-d"),
				//"API_PEMILIK" => $r->ApiNo,
				//"API_PENGUSAHA" => $r->ApiNo,
				//"KODE_STATUS" => "00",
				"ALAMAT_PENGUSAHA" => $ALAMAT,
				"KODE_ID_PENGUSAHA" => $ID,
				"ID_PENGUSAHA" => $NPWP,
				"NAMA_PENGUSAHA" => $NAMA,
				"NOMOR_IJIN_TPB" => $NOMOR_SKEP,
				"BRUTO" => $r->Bruto,
				"NETTO" => $r->Netto,
				"NOMOR_AJU" => $next_car,
				"KODE_STATUS" => "00",
				"KOTA_TTD" => $r->KotaTtd,
				"NAMA_TTD" => $r->Namattd,
				"TANGGAL_TTD" => date("Y-m-d"),
				"KODE_DOKUMEN_PABEAN" => "40", 
				"JABATAN_TTD" =>"KUASA DIREKSI",
				"VERSI_MODUL" => "3.1.5",
				"ALAMAT_PENGIRIM" => $r->PasokAlmt,
				"NAMA_PENGIRIM" => $r->PasokNama,
				"JUMLAH_BARANG" => $r->JmBrg,
				"KODE_JENIS_TPB" => "1",
				"KODE_KANTOR" => "150300",
				"KODE_TUJUAN_PENGIRIMAN" => "5",
				"NAMA_PENGANGKUT" => "TRUCK",
				"HARGA_PENYERAHAN" => $r->NilInv,
				"JUMLAH_KEMASAN" => "1",
				"KODE_ID_PENGIRIM" => "1",
				"ID_PENGIRIM" => $r->NPWP
			);
		}
		
		//var_dump($hdr_array);
		//die();
		
		$q_bc23_dtl=$this->db->query("
			select
			 [id_bc_in_dtl]
			  ,[id_bc_in_hdr]
			  ,[CAR]
			  ,[Serial]
			  ,[JnsBarangDtl]
			  ,[TujuanKirimDtl]
			  ,[NoHs]
			  ,[SeriTrp]
			  ,[BrgUrai]
			  ,[Merk]
			  ,[Tipe]
			  ,[SpfLain]
			  ,[KdBrg]
			  ,[Penggunaan]
			  ,[KemasJn]
			  ,[KemasJm]
			  ,[KdFasDtl]
			  ,[BrgAsal]
			  ,[DNilInv]
			  ,[DCif]
			  ,[KdSat]
			  ,[JmlSat]
			  ,[NettoDtl]
			  ,[SatBmJm]
			  ,[SatCukJm]
			  ,[DtlOk]
			  ,[create_date]
			  ,[create_by]
			  ,[update_date]
			  ,[update_by]
			  from 
			  tbl_bc_in_dtl
			  where  id_bc_in_hdr = $id_bc_in_hdr
		");
		
		
		$tpb_barang = array();
		foreach($q_bc23_dtl->result() as $r){
			$HARGA_SATUAN = (float)$r->DNilInv / (float)$r->JmlSat;
			$tpb_barang[] = array(
				//"KODE_BARANG" => $r->KdBrg,
				//"TIPE" => $r->Tipe,
				//"URAIAN" => $r->BrgUrai,
				//"NETTO" => $r->NettoDtl,
				//"KODE_SATUAN" => $r->KdSat,
				//"JUMLAH_SATUAN" => $r->JmlSat,
				//"JUMLAH_KEMASAN" => $r->KemasJm,
				//"SERI_BARANG" => $r->Serial,
				//"HARGA_INVOICE" => $r->DNilInv,
				//"HARGA_PENYERAHAN" => $r->DNilInv,
				//"CIF" => $r->DNilInv,
				//"FOB" => $r->DNilInv,
				//"HARGA_SATUAN" => $HARGA_SATUAN,
				//"KODE_NEGARA_ASAL" => $r->BrgAsal,
				//"POS_TARIF" => $r->NoHs,
				//"KATEGORI_BARANG" => "11",
				//"KODE_KEMASAN" => $r->KemasJn,
				//"ASURANSI" => "0.00",
				//"KODE_STATUS" => "02"
				"SERI_BARANG" => $r->Serial,
				"KODE_BARANG" => $r->KdBrg,
				"TIPE" => $r->KdBrg,
				"URAIAN" => $r->BrgUrai,
				"NETTO" => $r->NettoDtl,
				"KODE_SATUAN" => $r->KdSat,
				"JUMLAH_SATUAN" => $r->JmlSat,
				"JUMLAH_KEMASAN" => $r->KemasJm,
				"HARGA_PENYERAHAN" => $r->DNilInv,
				"KODE_STATUS" => "03"
			);
		}	
		
		//var_dump($tpb_barang);
		//die();
		
		$q_bc23_dok=$this->db->query("
			select
			 [id_bc_in_dok]
		 	 ,[id_bc_in_hdr]
			  ,[CAR]
		 	 ,[DokKd]
		 	 ,[DokNo]
		 	 ,CONVERT(varchar, [DokTg], 126) as DokTg
			  from 
			  tbl_bc_in_dok
			  where  id_bc_in_hdr = $id_bc_in_hdr 
		");
		
		
		$tpb_dokumen = array();
		$i = 1;
		foreach($q_bc23_dok->result() as $r){
			$tpb_dokumen[] = array(
				"KODE_JENIS_DOKUMEN" => $r->DokKd,
				"NOMOR_DOKUMEN" => $r->DokNo,
				"TANGGAL_DOKUMEN" => $r->DokTg,
				"TIPE_DOKUMEN" => "02",
				"SERI_DOKUMEN" => $i
				
			);
			$i++;
		}	
		
		$q_bc23_kms=$this->db->query("
			select [id_bc_in_kms]
		      ,[id_bc_in_hdr]
		      ,[CAR]
		      ,[JnKemas]
		      ,[JmKemas]
		      ,[merkkemas]
		     from [tbl_bc_in_kms] 
			  where  id_bc_in_hdr = $id_bc_in_hdr 
		");
		
		
		$tpb_kms = array();
		$i = 1;
		foreach($q_bc23_kms->result() as $r){
			$tpb_kms[] = array(
				"JUMLAH_KEMASAN" => $r->JmKemas,
				"KODE_JENIS_KEMASAN" => $r->JnKemas,
				"MERK_KEMASAN" => $r->merkkemas
				
			);
			$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)));
		}
		for ($x = 0; $x <= count($tpb_kms) - 1; $x++ ){
			$this->mysql->insert("tpb_kemasan", array_merge($tpb_kms[$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_in_hdr set CAR='$next_car',  statusdok = 'DATA PROCESSED' where id_bc_in_hdr = $id_bc_in_hdr
		");
		
		echo json_encode(array('sts' => $stsa, 'desc' => $msga, 'insert_id' => $insert_id . " CAR: -> " . $next_car ));	
	}
	
	function view_bc40_matching_ceisa(){
		$data["param"] = "";
		$this->load->view('exim/view_bc40_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	
		
		$tglawalbc40_ceisacar = (isset($_POST['tglawalbc40_ceisacar']) && !empty($_POST['tglawalbc40_ceisacar']))?$_POST['tglawalbc40_ceisacar']:date('Y-m-d');
		$tglakhirbc40_ceisacar = (isset($_POST['tglakhirbc40_ceisacar']) && !empty($_POST['tglakhirbc40_ceisacar']))?$_POST['tglakhirbc40_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 = '40' and  a.KODE_DOKUMEN_PABEAN ='40' and  convert(varchar(10),a.TANGGAL_AJU,126) between '$tglawalbc40_ceisacar' and '$tglakhirbc40_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.SA_NO like  '%".$searchString."%'"; 
					}  
				}
			}
		}
		
		
		if (!empty($car)){
			
			$where = "  CAST(SUBSTRING(a.NOMOR_AJU,21,6) as int) < 500000 and c.KODE_DOKUMEN = '40' and a.NOMOR_AJU like '%$car%' and a.KODE_DOKUMEN_PABEAN ='40'  ";
		}
		
		$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_in_hdr on a.NOMOR_AJU = tbl_bc_in_hdr.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_in_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_in_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_in_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_in_hdr"]=$r["id_bc_in_hdr"];
			$responce->rows[$i]["ID"]=$r["ID"];
			$responce->rows[$i]["URAIAN_STATUS"]=$r["URAIAN_STATUS"];
			$i++;
			
		}
		
		echo json_encode($responce);
		die();
	}
	
	
	function proses_get_bc40_ceisa(){
		$id_bc_in_hdr = (isset($_POST['id_bc_in_hdr']) && !empty($_POST['id_bc_in_hdr']))?$_POST['id_bc_in_hdr']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$username=$this->session->userdata('DX_username');
		
		
		
		$this->db->query("
			SET ANSI_NULLS ON
			SET ANSI_WARNINGS ON
		");
		$matchcar = $this->db->query("
			declare @car varchar(50)
			declare @NOMOR_DAFTAR varchar(50)
			declare @TANGGAL_DAFTAR date
			declare @tglaju date 
			declare @NDPBM float 
			declare @BRUTO float 
			set @car = (select car from tbl_bc_in_hdr where id_bc_in_hdr = $id_bc_in_hdr) 
			if ISDATE(substring(@car,13,8))=1
			begin
				set @tglaju= CONVERT(DATE,SUBSTRING(@car,13,4)+SUBSTRING(@car,17,2)+SUBSTRING(@car,19,2))
			end
			
			BEGIN TRY
			if	(select 
				count(*)	
				from openquery(TPBDB,'select * from tpb_header where KODE_DOKUMEN_PABEAN =''40'' ')
				where NOMOR_AJU = @car ) <> 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,
				@NDPBM=NDPBM,
				@BRUTO=BRUTO
			from openquery(TPBDB,'select * from tpb_header where KODE_DOKUMEN_PABEAN = ''40'' ' )
			where NOMOR_AJU = @car  	
			
			update tbl_bc_in_hdr set BC23No=@NOMOR_DAFTAR, BC23Tg=@TANGGAL_DAFTAR, DokTupTg=@tglaju, BRUTO=@BRUTO where id_bc_in_hdr = $id_bc_in_hdr  
			update tbl_coo_data set [car]=@car, [nobc]=@NOMOR_DAFTAR, [tglbc]=@TANGGAL_DAFTAR where  id_bc_in_hdr = $id_bc_in_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;
			
			");
			
		$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);
	}	
	
	function proses_get_replace_bc40_ceisa(){
		$car = (isset($_POST['carproses_matchbc40_ceisa']) && !empty($_POST['carproses_matchbc40_ceisa']))?$_POST['carproses_matchbc40_ceisa']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_hdr_ceisa = (isset($_POST['id_hdr_ceisa']) && !empty($_POST['id_hdr_ceisa']))?$_POST['id_hdr_ceisa']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$id_bc_in_hdr = (isset($_POST['id_bc_in_hdr']) && !empty($_POST['id_bc_in_hdr']))?$_POST['id_bc_in_hdr']:'';
		
		$username=$this->session->userdata('DX_username');
		
		
		
		$this->db->query("
			SET ANSI_NULLS ON
			SET ANSI_WARNINGS ON
		");
		if ($id_bc_in_hdr != ''){
			$matchcar = $this->db->query("
				declare @car varchar(50)
				declare @NOMOR_DAFTAR varchar(50)
				declare @TANGGAL_DAFTAR date
				declare @NDPBM float
				declare @BRUTO float
				set @car = (select car from tbl_bc_in_hdr where id_bc_in_hdr = $id_bc_in_hdr) 
				
				BEGIN TRY
				if	(select 
					count(*)	
					from openquery(TPBDB,'select * from tpb_header')
					where NOMOR_AJU = @car and KODE_DOKUMEN_PABEAN ='40' and ID = $id_hdr_ceisa) <> 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,
				@NDPBM=NDPBM,
				@BRUTO=BRUTO	
				from openquery(TPBDB,'select * from tpb_header where  KODE_DOKUMEN_PABEAN =''40'' ')
				where NOMOR_AJU = @car	
				
				update tbl_bc_in_hdr set BC23No=@NOMOR_DAFTAR, BC23Tg=@TANGGAL_DAFTAR, NDPBM=@NDPBM, BRUTO=@BRUTO where id_bc_in_hdr = $id_bc_in_hdr  
				update tbl_coo_data set [car]=@car, [nobc]=@NOMOR_DAFTAR, [tglbc]=@TANGGAL_DAFTAR where  id_bc_in_hdr = $id_bc_in_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 {
			$matchcar = $this->db->query("
				declare @car varchar(50)
				declare @NOMOR_DAFTAR varchar(50)
				declare @TANGGAL_DAFTAR date
				set @car = '$car'				
				BEGIN TRY
				if	(select 
					count(*)	
					from openquery(TPBDB,'select * from tpb_header where ID = $id_hdr_ceisa ')
					where NOMOR_AJU = @car and KODE_DOKUMEN_PABEAN ='40') <> 1
				begin
					SELECT 
					'06' AS status
					,' CAR TIDAK DITEMUKAN ATAU LEBIH DARI SATU NOMOR AJU SAMA, GUNAKAN TARIK MANUAL' AS description
					return
				end	
				declare @tbl_id_coo table(id_coo bigint not null)
				
				declare @TBLKATEGORI_BARANG Table (KATEGORI_BARANG varchar(50) null) 
				insert into @TBLKATEGORI_BARANG (
					KATEGORI_BARANG
				)
				select 
					KATEGORI_BARANG
				from openquery(TPBDB,'select * from tpb_barang where ID_HEADER = $id_hdr_ceisa  ')
				group by KATEGORI_BARANG
				
				declare @tbl_kode_brg table(kode_brg varchar(50))
				insert into @tbl_kode_brg (
					kode_brg
				)
				select 
					KODE_BARANG
				from openquery(TPBDB,'select * from tpb_barang where ID_HEADER = $id_hdr_ceisa ')
				group by KODE_BARANG
				
				DECLARE @tblno_inv table(nomor varchar(50) null, tgl date)
				insert into  @tblno_inv(
					nomor
					,tgl
				) select
				NOMOR_DOKUMEN
				,TANGGAL_DOKUMEN
				from openquery(TPBDB,'select * from tpb_dokumen where ID_HEADER = $id_hdr_ceisa and KODE_JENIS_DOKUMEN = ''380'' ')
				

				------CEK DATA -----
				declare @jnsbrg varchar(30)
				if (select count(*) from @TBLKATEGORI_BARANG where KATEGORI_BARANG is not null) = 1
				begin
					declare @katbrg varchar(50) 
					DECLARE db_cursor_kat CURSOR FOR 
					select KATEGORI_BARANG from @TBLKATEGORI_BARANG where KATEGORI_BARANG is not null					
					OPEN db_cursor_kat 
					FETCH NEXT FROM db_cursor_kat INTO @katbrg
					WHILE @@FETCH_STATUS = 0  
					BEGIN 
						if @katbrg = '11' 
						begin
							if (select count(*) from [tbl_kode_barang] b inner join @tbl_kode_brg a on a.kode_brg = b.kode_barang) > 0
							begin
								declare @x_inv_no varchar(50), @x_inv_tgl date, @null_inv_no varchar(max), @xno_invoice varchar(50)
								set @null_inv_no = ''
								DECLARE db_cursor CURSOR FOR 
								select a.nomor, a.tgl, [no_invoice] from @tblno_inv a
								left outer join [tbl_coo_data] on a.nomor=[tbl_coo_data].no_invoice   where nomor is not null and [no_invoice] is null
								OPEN db_cursor  
								FETCH NEXT FROM db_cursor INTO @x_inv_no,  @x_inv_tgl, @xno_invoice
								WHILE @@FETCH_STATUS = 0  
								BEGIN  
									set @null_inv_no = @null_inv_no + @x_inv_no + '  '
									FETCH NEXT FROM db_cursor INTO @x_inv_no,  @x_inv_tgl, @xno_invoice  
								END  

								CLOSE db_cursor  
								DEALLOCATE db_cursor
					
								if dbo.trim(@null_inv_no) <> ''
								begin
									select '06' as status, @null_inv_no + ' INVOICE COO TIDAK DITEMUKAN'  as description
									RETURN
								end
								declare @id_coo bigint
								DECLARE db_cursor CURSOR FOR 
								select id_coo_data from @tblno_inv a
								left outer join [tbl_coo_data] on a.nomor=[tbl_coo_data].no_invoice   where nomor is not null and [no_invoice] is not null
								OPEN db_cursor  
								FETCH NEXT FROM db_cursor INTO @id_coo
								WHILE @@FETCH_STATUS = 0  
								BEGIN  
									insert into @tbl_id_coo (id_coo) values (@id_coo)
									FETCH NEXT FROM db_cursor INTO @id_coo 
								END  

								CLOSE db_cursor  
								DEALLOCATE db_cursor
								set @jnsbrg = 'PART'
							end
							else 
							begin
								set @jnsbrg = 'NONCOO'
							end
						end
						if @katbrg = '12' 
						begin
							set @jnsbrg = 'KEMAS'
						end
						if @katbrg = '13' 
						begin
							set @jnsbrg = 'ALATBANGUNAN'
						end
						if @katbrg = '14' 
						begin
							set @jnsbrg = 'BARANGMODAL'
						end
						if @katbrg = '15' 
						begin
							set @jnsbrg = 'BARANGCONTOH'
						end
						if @katbrg = '16' 
						begin
							set @jnsbrg = 'BARANGJADI'
						end
						if @katbrg = '17' 
						begin
							set @jnsbrg = 'INVREIM'
						end
						if @katbrg = '18' 
						begin
							set @jnsbrg = 'ALATKANTOR'
						end
					FETCH NEXT FROM db_cursor_kat INTO @katbrg  
					END  

					CLOSE db_cursor_kat  
					DEALLOCATE db_cursor_kat
					
				end				
				
				if (select count(*) from @TBLKATEGORI_BARANG where KATEGORI_BARANG is not null) =0
				begin
					select '06' as status, ' KATEGORY TIDAK DITEMUKAN'  as description
					RETURN
				end


				if (select count(*) from @TBLKATEGORI_BARANG where KATEGORI_BARANG is not null) > 1
				begin
					set @jnsbrg = 'GABUNGAN'
				end

				declare @id_bc_in_hdr bigint
				select top 1
					@id_bc_in_hdr=id_bc_in_hdr
				from tbl_bc_in_hdr
				where car=@car and typedok = 'BC40'

				if(select count(*) from tbl_data_in_hdr where id_terkait = @id_bc_in_hdr) > 0
				begin
					SELECT 
					'06 ' AS status
					,' NO CAR SUDAH ADA : ' + @car + ' PERIKSA DULU.. BATALKAN DULU JIKA AKAN DITARIK ' AS description;
				end
				------END CEK DATA -----
				-------PART (KATEGRI 11)
				
				declare @nobl varchar(30), @tglbl date 
				select top 1
					@nobl=NOMOR_DOKUMEN
				,@tglbl=TANGGAL_DOKUMEN
				from openquery(TPBDB,'select * from tpb_dokumen where ID_HEADER = $id_hdr_ceisa ')
				where ID_HEADER = $id_hdr_ceisa and (KODE_JENIS_DOKUMEN = '705' or KODE_JENIS_DOKUMEN = '740' or KODE_JENIS_DOKUMEN = '640')

				if @nobl is null and @tglbl is null
				begin
					SELECT 
					'06 ' AS status
					,' BL atau AWB tidak ditemukan ' AS description;
					return

				end

				
				--- part
				if @jnsbrg = 'PART'
				begin	
					if (select COUNT(*) as cnt  from dbo.tbl_bc_in_hdr where dbo.tbl_bc_in_hdr.nobl = @nobl and dbo.tbl_bc_in_hdr.tglbl = @tglbl ) > 0
					begin
						select '04' as status, 'Data Sudah Ada di data BC'  as [description]
						return	
					end	
					
					declare @jmldetil int
					set @jmldetil = (
						select count(*)  from (
						select count(*) as cnt from [v_coo_data] where id_coo_data in (select id_coo from @tbl_id_coo)
						group by 
							ITEM_NUMBER, 
							kd_neg, 
							UOM
							,[DESCRIPTION]
							,HS_CODE
							,hskode 
							) x
					)

					
					if (  select count(*)
					FROM
					  dbo.[v_coo_data]
					WHERE
					  id_coo_data in (select id_coo from @tbl_id_coo) and [part_no] is null 
					) > 0
					begin
						select '01' as status, 'Part Number tidak ditemukan. Isikan dahulu di Data Part HS'  as [description]
						return	
					end

					if (  select count(*) from  (
						 select
							[supplier_country]
										FROM
										  dbo.[v_coo_data]
						 where id_coo_data in (select id_coo from @tbl_id_coo)  and ([supplier_country] <> 'ID')
						 group by  [supplier_country] 
						 ) x
					) <> 1
					begin
						select '01' as status, ' SUPPLIER BC23 TIDAK BOLEH DARI INDONESIA (ID) atau NULL PERBAIKI DATA SUPPLIER DAHULU'  as [description]
						return	
					end

					if( select count(kd_neg) from [v_coo_data] where id_coo_data in (select id_coo from @tbl_id_coo) and ISNUMERIC(kd_neg) = 1 ) > 0
					begin
						select '01' as status, 'ADA DATA NEGARA YANG SALAH..MOHON DILENGKAPI'  as [description]
						return	
					end
					
					
					insert into tbl_bc_in_hdr (
					CAR
					,KdKpbc
					,Tujuan
					,PasokNama
					,PasokAlmt
					,PasokNeg
					,UsahaNpwp
					,Registrasi
					,UsahaNama
					,ApiKd
					,ApiNo
					,Moda
					,AngkutNama
					,AngkutNo
					,AngkutFl
					,PelBkr
					,PelMuat
					,PelTransit
					,BC23No
					,BC23Tg
					--,DokTupKd
					,DokTupTg
					,PosNo
					,PosSub
					,TmpTbn
					,KdVal
					,Ndpbm
					,NilInv
					,Freight
					,BTambahan
					,Diskon
					,KdAss
					,Asuransi
					--,KdHrg
					,Fob
					,Cif
					,Bruto
					,Netto
					,JmCont
					,JmBrg
					,TglTtd
					,KotaTtd
					,Namattd
					,[Status]
					--,PosSubSub
					,nobl
					,tglbl
					,[typedok]	
					,[bc_in_from_in]
					,statusdok
					,[create_date]
					,[create_by]
					,[update_date]
					,[update_by]
    
				)
					select
						NOMOR_AJU
						,KODE_KANTOR
						,KODE_TUJUAN_TPB
						,NAMA_PEMASOK
						,SUBSTRING(ALAMAT_PEMASOK, 70, 1)
						,KODE_NEGARA_PEMASOK
						,ID_PENGUSAHA
						,NOMOR_IJIN_TPB
						,NAMA_PENGUSAHA
						,KODE_JENIS_API_PENGUSAHA
						,API_PENGUSAHA
						,KODE_CARA_ANGKUT
						,NAMA_PENGANGKUT
						,NOMOR_VOY_FLIGHT
						,KODE_BENDERA
						,KODE_PEL_BONGKAR
						,KODE_PEL_MUAT
						,KODE_PEL_TRANSIT
						,NOMOR_DAFTAR
						,convert(varchar(10), TANGGAL_DAFTAR, 126)
						--,NOMOR_BC11
						,convert(varchar(10), TANGGAL_BC11, 126)
						,POS_BC11
						,SUBPOS_BC11
						,KODE_TPS
						,KODE_VALUTA
						,NDPBM
						,HARGA_INVOICE
						,FREIGHT
						,BIAYA_TAMBAHAN
						,DISKON
						,KODE_ASURANSI
						,ASURANSI
						--,KODE_HARGA
						,FOB
						,CIF
						,BRUTO
						,NETTO
						,JUMLAH_KONTAINER
						,JUMLAH_BARANG
						,convert(varchar(10), TANGGAL_TTD, 126)
						,KOTA_TTD
						,NAMA_TTD
						,KODE_STATUS
						--,SUBSUBPOS_BC11
						,@nobl
						,@tglbl
						,'BC40'
						,'COO'
						,'DATA PROCESSED'
						,GETDATE()
						,'$username'
						,GETDATE()
						,'$username'
					from openquery(TPBDB,'select * from tpb_header where ID=$id_hdr_ceisa')
					where ID = $id_hdr_ceisa
					set @id_bc_in_hdr = SCOPE_IDENTITY() 
					
					update tbl_coo_data set 
					[car]=@car, 
					[nobc]=@NOMOR_DAFTAR, 
					[tglbc]=@TANGGAL_DAFTAR,
					id_bc_in_hdr = @id_bc_in_hdr,
					nobl=@nobl,
					tgbl=@tglbl,
					type_bc='BC40',
					status_inv = 'BCPROSES'
					where id_coo_data in (select id_coo from @tbl_id_coo)
					
					insert into tbl_bc_in_dtl_partnumber (
   					   [inv_dtl]
					  ,[inv_hdr_id]
					  ,[id_bc_in_hdr]
					  ,[noinv]
					  ,[car]
					  ,[nobc]
					  ,[tglbc]
					  ,part_no2
					  ,[part_number]
					  ,[part_name]
					  ,[part_name_customs]
					  ,[bm]
					  ,[qty]
					  ,[unit]
					  ,[harga]
					  ,[kdval]
					  ,[box]
					  ,[pack]
					  ,hscode
					  ,id_partnumber
					  ,seri_detil
   	
   					) select
   					  id_coo
   					  ,id_coo_data
   					  ,@id_bc_in_hdr
					  ,INVOICE_NO
					  ,NULL
					  ,nobc
					  ,tglbc
					  ,REPLACE(ITEM_NUMBER, char(32),'')
					  ,ITEM_NUMBER
					  ,part_name
					  ,part_name_customs
					  ,null as bm
					  ,ARRIV_PLAN_NUMBER
					  ,UOM
					  ,PRICE
					  ,CURRENT_MONEY
					  ,CTN_QUANTITY
					  ,PACKING_QTY
					  ,hskode
					  ,NULL
					  ,(select top 1 Serial from tbl_bc_in_dtl where id_bc_in_hdr = @id_bc_in_hdr and KdBrg=ITEM_NUMBER)
   					FROM
					  [dbo].[v_coo_data]
					where nobl = @nobl and tgbl = @tglbl

					insert into tbl_bc_in_dtl (
						id_bc_in_hdr
						,CAR
						,Serial
						,JnsBarangDtl
						--,TujuanKirimDtl
						,NoHs
						,SeriTrp
						,BrgUrai
						,Merk
						,Tipe
						,SpfLain
						,KdBrg
						,Penggunaan
						,KemasJn
						,KemasJm
						--,KdFasDtl
						,BrgAsal
						,DNilInv
						,DCif
						,KdSat
						,JmlSat
						,NettoDtl
					) select
						@id_bc_in_hdr
						,@car
						,SERI_BARANG
						,KATEGORI_BARANG
						--,KODE_GUNA
						,POS_TARIF
						,SERI_POS_TARIF
						,URAIAN
						,MERK
						,SUBSTRING(TIPE, 1, 15)
						,SPESIFIKASI_LAIN
						,KODE_BARANG
						,KODE_GUNA
						,KODE_KEMASAN
						,JUMLAH_KEMASAN
						--,KODE_SKEMA_TARIF
						,KODE_ASAL_BARANG
						,HARGA_INVOICE
						,CIF
						,KODE_SATUAN
						,JUMLAH_SATUAN
						,NETTO
					from openquery(TPBDB,'select * from tpb_barang where ID_HEADER=$id_hdr_ceisa')
					where ID_HEADER = $id_hdr_ceisa
					
					insert into tbl_bc_in_dok (
						id_bc_in_hdr
						,CAR
						,DokKd
						,DokNo
						,DokTg

					) select 
						@id_bc_in_hdr
						,@car
						,KODE_JENIS_DOKUMEN
						,SUBSTRING(NOMOR_DOKUMEN,1,25) 
						,convert(varchar(10), TANGGAL_DOKUMEN, 126)
					from openquery(TPBDB,'select * from tpb_dokumen where ID_HEADER=$id_hdr_ceisa')
					where ID_HEADER = $id_hdr_ceisa

					insert into tbl_bc_in_con (
						id_bc_in_hdr
						,CAR
						,ContNo
						,ContUkur
						,ContTipe

					) select 
						@id_bc_in_hdr
						,@car
						,NOMOR_KONTAINER
						,KODE_UKURAN_KONTAINER
						,KODE_TIPE_KONTAINER

					from openquery(TPBDB,'select * from tpb_kontainer where ID_HEADER=$id_hdr_ceisa')
					where ID_HEADER = $id_hdr_ceisa

					SELECT 
					'00' AS status
					,' NOMOR : ' + @car AS description;
				end
				-- end part
				--- non part ---
				if @jnsbrg <> 'PART'
				begin	
					if (select COUNT(*) as cnt  from dbo.tbl_bc_in_hdr where dbo.tbl_bc_in_hdr.nobl = @nobl and dbo.tbl_bc_in_hdr.tglbl = @tglbl ) > 0
					begin
						select '04' as status, 'Data Sudah Ada di data BC'  as [description]
						return	
					end	
					insert into tbl_bc_in_hdr (
					CAR
					,KdKpbc
					,Tujuan
					,PasokNama
					,PasokAlmt
					,PasokNeg
					,UsahaNpwp
					,Registrasi
					,UsahaNama
					,ApiKd
					,ApiNo
					,Moda
					,AngkutNama
					,AngkutNo
					,AngkutFl
					,PelBkr
					,PelMuat
					,PelTransit
					,BC23No
					,BC23Tg
					--,DokTupKd
					,DokTupTg
					,PosNo
					,PosSub
					,TmpTbn
					,KdVal
					,Ndpbm
					,NilInv
					,Freight
					,BTambahan
					,Diskon
					,KdAss
					,Asuransi
					--,KdHrg
					,Fob
					,Cif
					,Bruto
					,Netto
					,JmCont
					,JmBrg
					,TglTtd
					,KotaTtd
					,Namattd
					,[Status]
					--,PosSubSub
					,nobl
					,tglbl
					,[typedok]	
					,[bc_in_from_in]
					,statusdok
					,[create_date]
					,[create_by]
					,[update_date]
					,[update_by]
    
				)
					select
						NOMOR_AJU
						,KODE_KANTOR
						,KODE_TUJUAN_TPB
						,NAMA_PEMASOK
						,SUBSTRING(ALAMAT_PEMASOK, 70, 1)
						,KODE_NEGARA_PEMASOK
						,ID_PENGUSAHA
						,NOMOR_IJIN_TPB
						,NAMA_PENGUSAHA
						,KODE_JENIS_API_PENGUSAHA
						,API_PENGUSAHA
						,KODE_CARA_ANGKUT
						,NAMA_PENGANGKUT
						,NOMOR_VOY_FLIGHT
						,KODE_BENDERA
						,KODE_PEL_BONGKAR
						,KODE_PEL_MUAT
						,KODE_PEL_TRANSIT
						,NOMOR_DAFTAR
						,convert(varchar(10), TANGGAL_DAFTAR, 126)
						--,NOMOR_BC11
						,convert(varchar(10), TANGGAL_BC11, 126)
						,POS_BC11
						,SUBPOS_BC11
						,KODE_TPS
						,KODE_VALUTA
						,NDPBM
						,HARGA_INVOICE
						,FREIGHT
						,BIAYA_TAMBAHAN
						,DISKON
						,KODE_ASURANSI
						,ASURANSI
						--,KODE_HARGA
						,FOB
						,CIF
						,BRUTO
						,NETTO
						,JUMLAH_KONTAINER
						,JUMLAH_BARANG
						,convert(varchar(10), TANGGAL_TTD, 126)
						,KOTA_TTD
						,NAMA_TTD
						,KODE_STATUS
						--,SUBSUBPOS_BC11
						,@nobl
						,@tglbl
						,'BC40'
						,'CEISANONCOO'
						,'DATA PROCESSED'
						,GETDATE()
						,'$username'
						,GETDATE()
						,'$username'
					from openquery(TPBDB,'select * from tpb_header where ID=$id_hdr_ceisa')
					where ID = $id_hdr_ceisa
					set @id_bc_in_hdr = SCOPE_IDENTITY() 
					
					insert into tbl_bc_in_dtl (
						id_bc_in_hdr
						,CAR
						,Serial
						,JnsBarangDtl
						--,TujuanKirimDtl
						,NoHs
						,SeriTrp
						,BrgUrai
						,Merk
						,Tipe
						,SpfLain
						,KdBrg
						,Penggunaan
						,KemasJn
						,KemasJm
						--,KdFasDtl
						,BrgAsal
						,DNilInv
						,DCif
						,KdSat
						,JmlSat
						,NettoDtl
					) select
						@id_bc_in_hdr
						,@car
						,SERI_BARANG
						,KATEGORI_BARANG
						--,KODE_GUNA
						,POS_TARIF
						,SERI_POS_TARIF
						,URAIAN
						,MERK
						,SUBSTRING(TIPE, 1, 15)
						,SPESIFIKASI_LAIN
						,KODE_BARANG
						,KODE_GUNA
						,KODE_KEMASAN
						,JUMLAH_KEMASAN
						--,KODE_SKEMA_TARIF
						,KODE_ASAL_BARANG
						,HARGA_INVOICE
						,CIF
						,KODE_SATUAN
						,JUMLAH_SATUAN
						,NETTO
					from openquery(TPBDB,'select * from tpb_barang where ID_HEADER=$id_hdr_ceisa')
					where ID_HEADER = $id_hdr_ceisa
					
					insert into tbl_bc_in_dok (
						id_bc_in_hdr
						,CAR
						,DokKd
						,DokNo
						,DokTg

					) select 
						@id_bc_in_hdr
						,@car
						,KODE_JENIS_DOKUMEN
						,SUBSTRING(NOMOR_DOKUMEN,1,25) 
						,convert(varchar(10), TANGGAL_DOKUMEN, 126)
					from openquery(TPBDB,'select * from tpb_dokumen where ID_HEADER=$id_hdr_ceisa')
					where ID_HEADER = $id_hdr_ceisa

					insert into tbl_bc_in_con (
						id_bc_in_hdr
						,CAR
						,ContNo
						,ContUkur
						,ContTipe

					) select 
						@id_bc_in_hdr
						,@car
						,NOMOR_KONTAINER
						,KODE_UKURAN_KONTAINER
						,KODE_TIPE_KONTAINER

					from openquery(TPBDB,'select * from tpb_kontainer where ID_HEADER=$id_hdr_ceisa')
					where ID_HEADER = $id_hdr_ceisa



					SELECT 
					'00' AS status
					,' NOMOR : ' + @car +  ' INVOICE : CEISANONCOO '  AS description;

				end


				--- end non part ---
 
				
				END TRY
				BEGIN CATCH 
					SELECT 
					'06' AS status
					,ERROR_MESSAGE() AS description;
					
				END CATCH;
				
			");
		}	
		$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);
	}
	
	function cekdokmacthing_ceisa(){
		$car = (isset($_POST['car']) && !empty($_POST['car']))?$_POST['car']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$bc23dir = $this->config->item('APP_modulbc23');
		
		
		$this->db->query("
			SET ANSI_NULLS ON
			SET ANSI_WARNINGS ON
		");
         $q = $this->db->query("
			select a.NOMOR_DOKUMEN as dokno, convert(varchar(10), a.TANGGAL_DOKUMEN, 126) as doktg, a.KODE_JENIS_DOKUMEN as dokkd
			 from
				openquery(TPBDB,'select * from tpb_dokumen') a inner join openquery(TPBDB,'select * from tpb_header') b
				on a.ID_HEADER = b.ID
				
				
				where NOMOR_AJU='$car'
			"); 
		$rs = $q->result_array();
		$i=0;	
		foreach ($rs as $r){
			
		 	$responce[$i]["dokno"]=$r["dokno"];
			$responce[$i]["doktg"]=$r["doktg"]; 
			$responce[$i]["dokkd"]=$r["dokkd"]; 
			$i++;
			
		}
		
		echo json_encode($responce);
		
	
	
	}
	
	function cekdetilmacthing_ceisa(){
		$car = (isset($_POST['car']) && !empty($_POST['car']))?$_POST['car']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$bc23dir = $this->config->item('APP_modulbc23');
		
		
		$this->db->query("
			SET ANSI_NULLS ON
			SET ANSI_WARNINGS ON
		");
         $q = $this->db->query("
			select *
			 from
				openquery(TPBDB,'select 
				a.KATEGORI_BARANG as KATEGORI_BARANG,
			 a.KODE_BARANG as KODE_BARANG, a.TIPE, a.URAIAN as URAIAN, 
			a.JUMLAH_SATUAN, a.HARGA_SATUAN, a.POS_TARIF 
				from tpb_barang a inner join tpb_header b on a.ID_HEADER = b.ID where NOMOR_AJU = ''$car'' ') 
			"); 
		$rs = $q->result_array();
		$i=0;	
		$k = 1;
		foreach ($rs as $r){
			$responce[$i]["nomor"]=$k;
		 	$responce[$i]["KATEGORI_BARANG"]=$r["KATEGORI_BARANG"];
			$responce[$i]["KODE_BARANG"]=$r["KODE_BARANG"]; 
			$responce[$i]["TIPE"]=$r["TIPE"]; 
			$responce[$i]["URAIAN"]=$r["URAIAN"]; 
			$responce[$i]["JUMLAH_SATUAN"]=$r["JUMLAH_SATUAN"]; 
			$responce[$i]["HARGA_SATUAN"]=$r["HARGA_SATUAN"]; 
			$responce[$i]["POS_TARIF"]=$r["POS_TARIF"]; 
			$i++;
			$k++;
			
		}
		echo json_encode($responce);
	}
	
 }