<?php
class CT_bc261 extends CI_Controller{
	function __construct()
    {
		parent::__construct();
		if (!$this->dx_auth->is_logged_in()) {
            header('HTTP/1.1 401 Unauthorize');die('expire'); 
        }
        
        $uid = $this->session->userdata('DX_user_id');
        
        if(!permissionAuth(2) && $uid != RID){ 
            header('HTTP/1.1 401 Unauthorize');die('noaccess');
        }
		$this->load->helper('obj2array');
		
		$this->load->model("exim/mdl_bc27", 'mdl_bc27');
		$this->load->model("exim/mdl_bc23", 'mdl_bc23');
		$this->load->model("exim/mdl_bc261", 'mdl_bc261');
		$this->load->model("exim/mdl_invoice", 'mdl_invoice');
		$this->load->helper('afunction');	
	}
  
	function index(){

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

	function loaddata(){
		$search = isset($_POST['_search'])?$_POST['_search']:false;
		$searchField = isset($_POST['searchField'])?$_POST['searchField']:'';
		$searchString = isset($_POST['searchString'])?$_POST['searchString']:'';
		$filters =  isset($_POST['filters'])?$_POST['filters']:'';
		
		$page = isset($_POST['page'])?$_POST['page']:1; // get the requested page
		$limit = isset($_POST['rows'])?$_POST['rows']:20; // get how many rows we want to have into the grid
		$sidx = isset($_POST['sidx'])?$_POST['sidx']:'id_bc_out_hdr'; // get index row - i.e. user click to sort
		$sord = isset($_POST['sord'])?$_POST['sord']:'0'; // get the direction	
		
		$q =(isset($_POST['q']) && !empty($_POST['q']))?$_POST['q']:'0';
		$id_bc_out_hdr =(isset($_POST['id_bc_out_hdr']) && !empty($_POST['id_bc_out_hdr']))?$_POST['id_bc_out_hdr']:'';
			
		$where = " 1=1 and typedok='BC261' ";
		
		if (isset($_POST['tglawal']) and isset($_POST['tglakhir'])){
			$tglawal=$_POST['tglawal'];
			$tglakhir=$_POST['tglakhir'];
			$where .= " and TGDAFT between '$tglawal' and '$tglakhir' ";
		}	
		
		if ($q=='66'){
			$where =" id_bc_out_hdr=$id_bc_out_hdr ";
		}
		

		if ($search == 'true'){
			if (!empty($filters)){
				$array = json_decode($filters);
				foreach($array->rules as $arr=>$k){
					
					if ( $k->field == "CAR" ) {
						$searchString = $k->data;
						$where .= " and CAR like  '%".$searchString."%'"; 
					} else if ( $k->field == "NAMABELI" ) {
						$searchString = $k->data;
						$where .= " and NAMABELI like  '%".$searchString."%'"; 
					} else if ( $k->field == "NEGBELI" ) {
						$searchString = $k->data;
						$where .= " and NEGBELI like  '%".$searchString."%'"; 
					} else if ( $k->field == "NOINV" ) {
						$searchString = $k->data;
						$where .= " and NOINV like  '%".$searchString."%'"; 
					} else if ( $k->field == "NilInv" ) {
						$searchString = $k->data;
						$where .= " and NilInv =  $searchString"; 
					} else if ( $k->field == "TGINV" ) {
						$searchString = $k->data;
						$where .= " and TGINV =  '$searchString'"; 
					} else if ( $k->field == "KDVAL" ) {
						$searchString = $k->data;
						$where .= " and KDVAL like  '%".$searchString."%'"; 
					}  else if ( $k->field == "statusdok" ) {
						$searchString = $k->data;
						$where .= " and statusdok like  '%".$searchString."%'"; 
					} else if ( $k->field == "NODAFT" ) {
						$searchString = $k->data;
						$where .= " and NODAFT like  '%".$searchString."%'"; 
					} 
			
				}
			}
		}	
			
		$start = $limit*$page - $limit;
		if ($start<0) $start=0;
		
		$records = $this->mdl_bc27->bc27hdr_All($limit,$start,$sidx,$sord, $where);
		$count = $this->mdl_bc27->bc27hdr_CountAll($where);
		
		
		if( $count > 0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } 
		if ($page > $total_pages) $page=$total_pages;
		
		$responce->page = $page;
		$responce->total = $total_pages;
		$responce->records =  $count;
		$i=0;
		foreach($records as $r){

			$responce->rows[$i]['id_bc_out_hdr']=$r->id_bc_out_hdr; 
			$responce->rows[$i]['CAR']=$r->CAR; 
			$responce->rows[$i]['JnEks']=$r->JnEks; 
			$responce->rows[$i]['KatEks']=$r->KatEks; 
			$responce->rows[$i]['JNPEB']=$r->JNPEB; 
			$responce->rows[$i]['JNEKSOld']=$r->JNEKSOld; 
			$responce->rows[$i]['JNLAIN']=$r->JNLAIN; 
			$responce->rows[$i]['JNDAG']=$r->JNDAG; 
			$responce->rows[$i]['JNBYR']=$r->JNBYR; 
			$responce->rows[$i]['IDEKS']=$r->IDEKS; 
			$responce->rows[$i]['NPWPEKS']=$r->NPWPEKS; 
			$responce->rows[$i]['NamaEks']=$r->NamaEks; 
			$responce->rows[$i]['AlmtEks']=$r->AlmtEks; 
			$responce->rows[$i]['NoSiup']=$r->NoSiup; 
			$responce->rows[$i]['TgSiup']=$r->TgSiup; 
			$responce->rows[$i]['JnPerus']=$r->JnPerus; 
			$responce->rows[$i]['NoTdp']=$r->NoTdp; 
			$responce->rows[$i]['TgTdp']=$r->TgTdp; 
			$responce->rows[$i]['Niper']=$r->Niper; 
			$responce->rows[$i]['StatusH']=$r->StatusH; 
			$responce->rows[$i]['IdQq']=$r->IdQq; 
			$responce->rows[$i]['NpwpQq']=$r->NpwpQq; 
			$responce->rows[$i]['NamaQq']=$r->NamaQq; 
			$responce->rows[$i]['AlmtQq']=$r->AlmtQq; 
			$responce->rows[$i]['NiperQq']=$r->NiperQq; 
			$responce->rows[$i]['NAMABELI']=$r->NAMABELI; 
			$responce->rows[$i]['ALMTBELI']=$r->ALMTBELI; 
			$responce->rows[$i]['NEGBELI']=$r->NEGBELI; 
			$responce->rows[$i]['IDPPJK']=$r->IDPPJK; 
			$responce->rows[$i]['NPWPPPJK']=$r->NPWPPPJK; 
			$responce->rows[$i]['NamaPpjk']=$r->NamaPpjk; 
			$responce->rows[$i]['AlmtPpjk']=$r->AlmtPpjk; 
			$responce->rows[$i]['NoPpjk']=$r->NoPpjk; 
			$responce->rows[$i]['TgPpjk']=$r->TgPpjk; 
			$responce->rows[$i]['MODA']=$r->MODA; 
			$responce->rows[$i]['TGEKS']=$r->TGEKS; 
			$responce->rows[$i]['CARRIER']=$r->CARRIER; 
			$responce->rows[$i]['VOY']=$r->VOY; 
			$responce->rows[$i]['NOSHIPORD']=$r->NOSHIPORD; 
			$responce->rows[$i]['TGSHIPORD']=$r->TGSHIPORD; 
			$responce->rows[$i]['PELMUAT']=$r->PELMUAT; 
			$responce->rows[$i]['PELBONGKAR']=$r->PELBONGKAR; 
			$responce->rows[$i]['PELTRANSIT']=$r->PELTRANSIT; 
			$responce->rows[$i]['NOINV']=$r->NOINV; 
			$responce->rows[$i]['TGINV']=$r->TGINV; 
			$responce->rows[$i]['NOLPSE']=$r->NOLPSE; 
			$responce->rows[$i]['TGLPSE']=$r->TGLPSE; 
			$responce->rows[$i]['PROPBRG']=$r->PROPBRG; 
			$responce->rows[$i]['NEGTUJU']=$r->NEGTUJU; 
			$responce->rows[$i]['FLSIE']=$r->FLSIE; 
			$responce->rows[$i]['FLKARANT']=$r->FLKARANT; 
			$responce->rows[$i]['FLSM']=$r->FLSM; 
			$responce->rows[$i]['FLIZLAIN']=$r->FLIZLAIN; 
			$responce->rows[$i]['DELIVERY']=$r->DELIVERY; 
			$responce->rows[$i]['KDVAL']=$r->KDVAL; 
			$responce->rows[$i]['KdHrg']=$r->KdHrg; 
			$responce->rows[$i]['NilInv']=$r->NilInv; 
			$responce->rows[$i]['FREIGHT']=$r->FREIGHT; 
			$responce->rows[$i]['ASURANSI']=$r->ASURANSI; 
			$responce->rows[$i]['KdAss']=$r->KdAss; 
			$responce->rows[$i]['FOB']=$r->FOB; 
			$responce->rows[$i]['MERK']=$r->MERK; 
			$responce->rows[$i]['JMCONT']=$r->JMCONT; 
			$responce->rows[$i]['BRUTO']=$r->BRUTO; 
			$responce->rows[$i]['NETTO']=$r->NETTO; 
			$responce->rows[$i]['JMBRG']=$r->JMBRG; 
			$responce->rows[$i]['JMBRGCTH']=$r->JMBRGCTH; 
			$responce->rows[$i]['JMBRGGAB']=$r->JMBRGGAB; 
			$responce->rows[$i]['JMBRGPJT']=$r->JMBRGPJT; 
			$responce->rows[$i]['NODAFT']=$r->NODAFT; 
			$responce->rows[$i]['TGDAFT']=$r->TGDAFT; 
			$responce->rows[$i]['KDKTR']=$r->KDKTR; 
			$responce->rows[$i]['KTRGATE']=$r->KTRGATE; 
			$responce->rows[$i]['NILPE']=$r->NILPE; 
			$responce->rows[$i]['KDBANK']=$r->KDBANK; 
			$responce->rows[$i]['LOKBANK']=$r->LOKBANK; 
			$responce->rows[$i]['NOSSP']=$r->NOSSP; 
			$responce->rows[$i]['TGSSP']=$r->TGSSP; 
			$responce->rows[$i]['JNTPB']=$r->JNTPB; 
			$responce->rows[$i]['LOKTPB']=$r->LOKTPB; 
			$responce->rows[$i]['KDLOKBRG']=$r->KDLOKBRG; 
			$responce->rows[$i]['KDKTRMUAT']=$r->KDKTRMUAT; 
			$responce->rows[$i]['KDKTRPRIKS']=$r->KDKTRPRIKS; 
			$responce->rows[$i]['TGSIAP']=$r->TGSIAP; 
			$responce->rows[$i]['WKSIAP']=$r->WKSIAP; 
			$responce->rows[$i]['ASALDATA']=$r->ASALDATA; 
			$responce->rows[$i]['TPNAME']=$r->TPNAME; 
			$responce->rows[$i]['PEBOK']=$r->PEBOK; 
			$responce->rows[$i]['LENGKAP']=$r->LENGKAP; 
			$responce->rows[$i]['JNPARTOF']=$r->JNPARTOF; 
			$responce->rows[$i]['BENDERA']=$r->BENDERA;
			$responce->rows[$i]['TTDPEB']=$r->TTDPEB;
			$responce->rows[$i]['STATUS']=$r->STATUS;
			$responce->rows[$i]['SNRF']=$r->SNRF;
			$responce->rows[$i] ['NOBCF'] =$r->NOBCF; 
			$responce->rows[$i] ['TGBCF'] =$r->TGBCF; 
			$responce->rows[$i] ['SERIBCF'] =$r->SERIBCF; 
			$responce->rows[$i] ['NOMOREDI'] =$r->NOMOREDI; 
			$responce->rows[$i] ['KMDT'] =$r->KMDT; 
			$responce->rows[$i] ['VOLUME'] =$r->VOLUME; 
			$responce->rows[$i] ['KDHANGGAR'] =$r->KDHANGGAR; 
			$responce->rows[$i] ['KONS']=$r->KONS; 
			$responce->rows[$i] ['JMLKMSPEB']=$r->JMLKMSPEB; 
			$responce->rows[$i] ['PELMUATEKS'] =$r->PELMUATEKS; 
			$responce->rows[$i] ['NILKURS']=$r->NILKURS; 
			$responce->rows[$i] ['PNBP'] =$r->PNBP; 
			$responce->rows[$i] ['NOBC11'] =$r->NOBC11; 
			$responce->rows[$i] ['TGBC11'] =$r->TGBC11; 
			$responce->rows[$i] ['POSBC11'] =$r->POSBC11; 
			$responce->rows[$i] ['SUBPOSBC11'] =$r->SUBPOSBC11; 
			$responce->rows[$i] ['create_date'] =$r->create_date; 
			$responce->rows[$i] ['create_by'] =$r->create_by; 
			$responce->rows[$i] ['update_date']=$r->update_date; 
			$responce->rows[$i] ['update_by']=$r->update_by; 
			$responce->rows[$i] ['typedok'] =$r->typedok; 
			$responce->rows[$i] ['statusdok']=$r->statusdok; 
			$responce->rows[$i] ['noinv1'] =$r->noinv1; 
			$responce->rows[$i] ['tginv1'] =$r->tginv1; 
			$responce->rows[$i] ['inv_hdr_id'] =$r->inv_hdr_id; 
			$responce->rows[$i] ['bc_in_from_in'] =$r->bc_in_from_in; 
			$responce->rows[$i] ['nopol'] =$r->nopol; 
			
		
			$i++;
		}
		echo json_encode($responce);
			
        
		
		
    }
	function view_bc261_invoice(){
		$this->load->view('exim/view_bc261_invoice');
		
	
	}
	
	function view_bc261_perhitungan_exim(){
		$this->load->view('exim/view_bc261_perhitungan_exim');
		
	
	}
	
	function upload_file_perhitungan_exim(){
		$status = "";
	   $msg = "";
	   $file_element_name = 'userfileperhitungan_exim';
	   //$username = $this->session->userdata('DX_user_id');
	   $username = $this->session->userdata('DX_username');
	   $tipe = 'BC261_perhitungan_exim';
	   if ($status != "error")
	   {
		  $apppath = $this->config->item('APP_upload_path');
		  $config['upload_path'] = $apppath.'exim/perhitungan_exim/';
		  $config['allowed_types'] = 'xls';
		  $config['max_size']  = 1024 * 100;
		  $config['encrypt_name'] = false;
		  $config['overwrite']=true;
		  $config['remove_spaces']=true;
		  $this->load->library('upload', $config);
		  if (!$this->upload->do_upload($file_element_name))
		  {
			 $status = 'error';
			 $msg = $this->upload->display_errors('', '');
		  }
		  else
		  {
			 $data = $this->upload->data();
			 
			 // print_r($data);
			 // die();
			 if($data)
			 {
				$myFile = $data['full_path']; 
				$newfile=$apppath.'exim/perhitungan_exim/log/'.$data['file_name'];
				$filename=$data['file_name'];
				$dirfile = $apppath.'exim/perhitungan_exim/';

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

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

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

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

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

				
				update tbl_bc_out_hdr set statusdok='DATA PROCESSED INVENTORY' where id_bc_out_hdr = @id_bc_out	
				
				update [dbo].[tblbc261_perhitungan_exim_asal_bc] set status_data='DATA PROCCESSED INVENTORY' where [id_bc_out_hdr]=@id_bc_out 
				
			END TRY
			BEGIN CATCH 
				SELECT 
				'error' AS status
				,ERROR_MESSAGE() AS description;
				
			END CATCH; 
			select '00' as status, 'UPDATED dengan ID :' + CAST(@id_data_out_hdr as varchar(255)) as description
			
			 ");
		 $rs = $qry->result_array();
         //// $r = $qry->result();		
		//// var_dump($r);die();
		
		$q1 = $this->db->query("
			SELECT  id_terkait, doc_out_no, id_data_out_hdr  from [tbl_data_out_hdr] where id_terkait=$id_bc_out and doc_out_to_id=6
		");
		
		$rs1 = $q1->result_array();
		//var_dump($rs); die();
		$id_data_out_hdr='';
		foreach ($rs1 as $row1){
			$id_data_out_hdr=$row1['id_data_out_hdr'];		
		}
		
		 foreach ($rs as $row){
			 $responce = array("sts" => $row['status'], "desc" => $row['description'].' ', 'id_data_out_hdr' => $id_data_out_hdr );
		 }  
		 echo json_encode($responce);
	
	
	
	}
	
	function cancelnocar(){
		$uid = $this->session->userdata('DX_username');
		if ($uid != 'admin') {
			die('{"sts":"ERROR","desc":" Harus Admin"}');
		
		}
		$idhdrbc261 = (isset($_POST['idhdrbc261']) && !empty($_POST['idhdrbc261']))?$_POST['idhdrbc261']:die('{"sts":"ERROR","desc":" idhdrbc27 Param Tidak Ditemukan"}');
		$typedok = (isset($_POST['typedok']) && !empty($_POST['typedok']))?$_POST['typedok']:die('{"sts":"ERROR","desc":" typedok Param Tidak Ditemukan"}');
		
		$qry = $this->db->query("
			declare @bc_in_from_in varchar(50)
			set @bc_in_from_in=(select top 1 bc_in_from_in from tbl_bc_out_hdr where id_bc_out_hdr=$idhdrbc261)
						
			if (select count(*) from tblbc261_perhitungan_exim_asal_bc where id_bc_out_hdr = $idhdrbc261 ) = 0
			begin
				select '06' as status, 'Data Perhitungan Exim tidak ditemukan..' as description
				return
			end
			
			declare @id_bc_out_hdr bigint
			declare @idpebhdr bigint
			
			set @id_bc_out_hdr =$idhdrbc261
			
			declare @id_data_out_hdr bigint
			set @id_data_out_hdr = (select id_data_out_hdr from tbl_data_out_hdr  where id_terkait = @id_bc_out_hdr and doc_out_to_id=6)
			
			BEGIN TRY  
	           	BEGIN TRANSACTION
				delete from tbl_data_out_hdr_h_status where id_data_out_hdr=@id_data_out_hdr
				delete from tbl_data_out_dtl where id_data_out_hdr=@id_data_out_hdr and type_items='RM'
				delete from tbl_data_out_hdr where id_data_out_hdr=@id_data_out_hdr and doc_out_to_id=6
				
				delete from [dbo].[tbl_bc_out_hdr_h_status] where [id_bc_out_hdr] = @id_bc_out_hdr
				delete from [dbo].[tbl_bc_out_kms] where [id_bc_out_hdr] = @id_bc_out_hdr
				delete from [dbo].[tbl_bc_out_con] where [id_bc_out_hdr] = @id_bc_out_hdr
				delete from [dbo].[tbl_bc_out_dok] where [id_bc_out_hdr] = @id_bc_out_hdr
				delete from [dbo].[tbl_bc_out_dtl] where [id_bc_out_hdr] = @id_bc_out_hdr
				delete from [dbo].[tbl_bc_out_hdr] where [id_bc_out_hdr] = @id_bc_out_hdr
				
				update [dbo].[tblbc261_perhitungan_exim_asal_bc] set status_data='NEW' where [id_bc_out_hdr]=@id_bc_out_hdr  
			
				COMMIT
			END TRY	
			BEGIN CATCH
			-- Whoops, there was an error
			IF @@TRANCOUNT > 0
			 ROLLBACK

			-- Raise an error with the details of the exception
			DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
			Set @ErrMsg = ERROR_MESSAGE()
			set @ErrSeverity = ERROR_SEVERITY()
			select @ErrMsg as status,@ErrSeverity as description
			RAISERROR(@ErrMsg, @ErrSeverity, 1)
			END CATCH 
			
			select '00' as status, 'DATA CANCELED..Silahkan Upload ulang DATA jika akan diulang' as description
			
			
		 ");
		 $rs = $qry->result_array();
		// $r = $qry->result();		
		//var_dump($rs);die();	
		
		
		
		
		foreach ($rs as $row){
			$status = $row['status'];
			$msg = $row['description'];
		}
		
		echo json_encode(array('sts' => $status, 'desc' => $msg));	
	
	
	}
	
	function excelperhitungan_exim(){
		$id_hdr = (isset($_REQUEST['id_hdr']) && !empty($_REQUEST['id_hdr']))?$_REQUEST['id_hdr']:die('{"sts":"ERROR","desc":" Param Tidak Ditemukan"}');
		$datenow = date('Y-m-d');
		
		$qry1 = $this->db->query("
				SELECT [id_bc261_exim_hdr]
				  ,[NPWPTUJU]
				  ,[NAMATUJU]
				  ,[ALMTTUJU]
				  ,[NOKONTRAK]
				  ,[TGLKONTRAK]
				  ,[custom_bond]
				  ,[kurs]
				  ,[kdval]
				  ,[jml_hari_kerja]
				  ,[periode_awal]
				  ,[periode_akhir]
				  ,[jenis_pekerjaan]
				  ,[status_data]
				  ,[create_date]
				  ,[create_by]
				  ,[update_date]
				  ,[update_by]
			  FROM [dbo].[tblbc261_perhitungan_exim_hdr]
			  where id_bc261_exim_hdr=$id_hdr
		");
		$rs1 = $qry1->result_array();
		$NAMATUJU = '';
		$NOKONTRAK='';
		$jenis_pekerjaan = '';
		$kurs = 1;
		foreach ($rs1 as $r1){
			$NAMATUJU = $r1["NAMATUJU"];
			$NOKONTRAK= $r1["NOKONTRAK"];
			$jenis_pekerjaan= $r1["jenis_pekerjaan"];
			$kurs= $r1["kurs"];
		}
		
		
		$qry2 = $this->db->query("
				SELECT [id_bc261_exim_dtl]
				  ,[id_bc261_exim_hdr]
				  ,[assy_code]
				  ,[assy_name]
				  ,[part_name_customs]
				  ,[part_number]
				  ,[kode_barang]
				  ,[qty]
				  ,[unit]
				  ,[harga_satuan]
				  ,[total_usd]
				  ,[nilai_pabean]
				  ,[ex_aju]
				  ,[ex_nodaft]
				  ,[ex_tgdaft]
				  ,[ex_nourut]
				  ,[hs]
				  ,[bm]
				  ,[ppn]
				  ,[pph]
				  ,[vendor]
				  ,[qty_modul]
				  ,[qty_dipakai]
			  FROM [dbo].[tblbc261_perhitungan_exim_dtl]
			  where id_bc261_exim_hdr=$id_hdr
		");
		$rs2 = $qry2->result_array();
		
		 $q_count = $this->db->query("
			select count (*) as cnt
			 FROM [dbo].[tblbc261_perhitungan_exim_dtl]
			  where id_bc261_exim_hdr=$id_hdr


		");
        $rowc = $q_count->result_array();
        foreach ($rowc as $c){
            $cnt = $c["cnt"];
        }
		
		include_once ( APPPATH."libraries/PHPExcel.php");	
		include_once ( APPPATH."libraries/PHPExcel/IOFactory.php");	
		$phpExcel = new PHPExcel();
		$objTpl = PHPExcel_IOFactory::load(APPPATH."libraries/PHPExcel/templates/perhitungan_exim.xls");	
		$objTpl->setActiveSheetIndex(0);  //set first sheet as active
		
		$objTpl->getActiveSheet()->setCellValue('C3', ':'.$NAMATUJU);
		$objTpl->getActiveSheet()->setCellValue('C4', ':'.$NOKONTRAK);
		$objTpl->getActiveSheet()->setCellValue('C5', ':'.'Pembuatan ' . $jenis_pekerjaan);
		$objTpl->getActiveSheet()->setCellValue('D10', 'SET');
		$objTpl->getActiveSheet()->setCellValue('B10', $jenis_pekerjaan);
		
		$part_name_customs = '';
		$qty=0;
		$unit = '';
		$harga_satuan = 0;
		
		$i = 1;
        $j = '';
        $k = 9;
		
		foreach ($rs2 as $r2){
			
			$k = 9 + $i;
            $j = "$k";	
			$objTpl->getActiveSheet()->setCellValue("E".$j, $r2['part_name_customs']);
			$objTpl->getActiveSheet()->setCellValue("F".$j, $r2['qty']);
			$objTpl->getActiveSheet()->setCellValue("G".$j, strtoupper($r2['unit']));
			$objTpl->getActiveSheet()->setCellValue("H".$j, $r2['harga_satuan']);
			$objTpl->getActiveSheet()->setCellValue("I".$j, $r2['harga_satuan'] * $r2['qty'] );
			$objTpl->getActiveSheet()->setCellValue("J".$j, $r2['harga_satuan'] * $r2['qty'] * $kurs );
			$objTpl->getActiveSheet()->setCellValueExplicit("K".$j, $r2['ex_aju']);
			$objTpl->getActiveSheet()->setCellValueExplicit("L".$j, $r2['ex_nodaft']);
			$objTpl->getActiveSheet()->setCellValue("M".$j, $r2['ex_tgdaft']);
			$objTpl->getActiveSheet()->setCellValue("N".$j, $r2['ex_nourut']);
			$objTpl->getActiveSheet()->setCellValueExplicit("O".$j, $r2['hs']);
			$objTpl->getActiveSheet()->setCellValue("P".$j, $r2['bm']);
			$objTpl->getActiveSheet()->setCellValue("Q".$j, ($r2['bm'] * $r2['harga_satuan'] * $r2['qty'] * $kurs)/100);
			$objTpl->getActiveSheet()->setCellValue("R".$j, ($r2['ppn'] * $r2['harga_satuan'] * $r2['qty'] * $kurs)/100);
			
			$i++;
		}
		
		
		if($cnt != 0){
			$objTpl->getActiveSheet()->getStyle("F10:"."F".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			$objTpl->getActiveSheet()->getStyle("H10:"."H".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			$objTpl->getActiveSheet()->getStyle("I10:"."I".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			$objTpl->getActiveSheet()->getStyle("J10:"."J".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			$objTpl->getActiveSheet()->getStyle("Q10:"."Q".$j)->getNumberFormat()->setFormatCode('#,##0.00');
			$objTpl->getActiveSheet()->getStyle("R10:"."R".$j)->getNumberFormat()->setFormatCode('#,##0.00');
		
		}
		
		
		$objTpl->setActiveSheetIndex(0);  //set first sheet as active
		$filename =  "perhitungan_exim". "_$datenow";
		
		header("Content-type:application/vnd.ms-excel");
		header("Content-disposition:attachment; filename=$filename"); 
		header("Pragma:no-cache");
		header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
		header("Expires:0");

		$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5');  //downloadable file is in Excel 2003 format (.xls)
		$objWriter->save('php://output');  //send it to user, of course you can save it to disk also!
		 
		exit; //done.. exiting!	
		
	}
	
	
	
  
 }