<?php

use PhpOffice\PhpSpreadsheet\Worksheet\Row;

 if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Trxin extends MY_Controller {
	
	function __construct()
	{
		parent::__construct();
		
		// LOCAL
		$this->tbl = 'mat_inchdr_sub';		
		$this->tbl2 = 'mat_incdet_sub';
		$this->tbl3 = 'mst_in_type';
		$this->tbl4 = 'mst_perusahaan';
		$this->tbl5 = 'mst_barang';
		$this->tbl6 = 'jenis_dok';
		$this->pk = 'matin_id';
		$this->pk2 = 'child_no';
		$this->pk3 = 'matin_type';
		$this->pk4 = 'KdPrshn';
		$this->pk5 = 'KdBarang';
		$this->pk6 = 'KdJnsDok';
		$this->pkh = 'matin_no';
		// TPB
		$this->tpbdb						= 'tpbdb';
		$this->tpb_header				= 'tpb_header';		
		$this->tpb_pemasok			= 'referensi_pemasok';		
		$this->tpb_pengusaha		= 'referensi_pengusaha';		
		$this->tpb_pk_id				= 'ID';
		$this->tpb_fk_id				= 'ID_TPB';
		$this->tpb_fk_header		= 'ID_HEADER';
		$this->url = 'https://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
	}
	
	public function index()
	{	
		$content	=	$this->pmodul.'/index';
		$cjs			=	$this->pmodul.'/_cjs';
		$mjs			=	$this->pmodul.'/_mjs';
		$data = array(
			'content' 	=> 	$content,
			't'			=>	$this->session->userdata('t'),
			'u'			=>	$this->session->userdata('u'),
			'h'			=>	$this->session->userdata('h')
			);
		$data['ri'] = $this->mdl->buat_kodeIn();		
		$this->load('tpl',$data['content'], $data);
		$this->load->view($cjs);
		$this->load->view($mjs);
	}
	
	function dataHdr(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 100;	
		$KdJnsDok = isset($_POST["KdJnsDok"]) ? $_POST["KdJnsDok"] : '';	
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getHdr($page,$rows,$key,$KdJnsDok);
		
		echo json_encode($rs);
	}

	// finished goods plating --dim
	function dataHdrFGP(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 100;	
		$KdJnsDok = isset($_POST["KdJnsDok"]) ? $_POST["KdJnsDok"] : '';	
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getHdrFGP($page,$rows,$key,$KdJnsDok);
		
		echo json_encode($rs);
	}

	// finished goods non plating --dim
	function dataHdrFGNP(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 100;	
		$KdJnsDok = isset($_POST["KdJnsDok"]) ? $_POST["KdJnsDok"] : '';	
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getHdrFGNP($page,$rows,$key,$KdJnsDok);
		
		echo json_encode($rs);
	}

	// finished goods subkon --dim
	function dataHdrFGS(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 100;	
		$KdJnsDok = isset($_POST["KdJnsDok"]) ? $_POST["KdJnsDok"] : '';	
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getHdrFGS($page,$rows,$key,$KdJnsDok);
		
		echo json_encode($rs);
	}
	
	function dataDet(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 100;	
		$matin_id = $_REQUEST["matin_id"];
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getDet($page,$rows,$matin_id,$key);
		echo json_encode($rs);
	}

	function dataDetDok(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 100;	
		$matin_id = $_REQUEST["matin_id"];
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getDetDok($page,$rows,$matin_id,$key);
		echo json_encode($rs);
	}

	function dataDetKon(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 100;	
		$matin_id = $_REQUEST["matin_id"];
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getDetKon($page,$rows,$matin_id,$key);
		echo json_encode($rs);
	}

		function dataDetJaminan(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 100;	
		$matin_id = $_REQUEST["matin_id"];
		$key = $_REQUEST["q"];
		$rs = $this->mdl->getDetJaminan($page,$rows,$matin_id,$key);
		echo json_encode($rs);
	}
	
	function dataHdrDet(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 999999;	
		$key = $_REQUEST["q"];

			$rs = $this->mdl->getHdrDet($page,$rows,$key);
		
		echo json_encode($rs);
	}

	function dataHdrDetFGP(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 999999;	
		$key = $_REQUEST["q"];

			$rs = $this->mdl->getHdrDetFGP($page,$rows,$key);
		
		echo json_encode($rs);
	}

	function dataHdrDetFGNP(){
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 999999;	
		$key = $_REQUEST["q"];

			$rs = $this->mdl->getHdrDetFGNP($page,$rows,$key);
		
		echo json_encode($rs);
	}
	
	function getform($cmd){
		$form_data = $this->input->post();
	
		$form_data['mat_type']=$this->mat_type;
		$form_data['matin_date']=$this->dmys2ymd($this->input->post('matin_date'));
		$form_data['TgAju']=$this->dmys2ymd($this->input->post('TgAju'));
		$form_data['TgDaf']=$this->dmys2ymd($this->input->post('TgDaf'));
		$form_data['TgTTD']=$this->dmys2ymd($this->input->post('TgTTD'));
		$form_data['tglInv']=$this->dmys2ymd($this->input->post('tglInv'));
		$form_data['mat_type']=$this->mat_type;
		$form_data['kd_cmpy']=$this->session->userdata('kd_cmpy');
		$form_data['notes']="JI".substr($this->input->post('matin_no'),2,-1);
		// $form_data['tot_amount']=0;
		   // Check if 'po_no' is an array or a single value
		   if (is_array($_POST['po_no'])) {
			// If 'po_no' is an array, directly implode it to a string
			$form_data['po_no'] = implode(',', $_POST['po_no']);
		} else {
			// If 'po_no' is a string, convert it to an array by exploding the string
			$poNumbers = array_map('trim', explode(',', $_POST['po_no']));
			$form_data['po_no'] = implode(',', $poNumbers);
		}
		


		$pk[$this->pk]=$form_data[$this->pk];
		if ($cmd=="add"){	
			// $this->add($form_data);
			$this->edit($form_data,$pk);
			// INSERT & UPDATE TO MATIN DET --ir
			$po_id = $form_data['po_id'];
			$key = $form_data['matin_no'];
			$key2 = $form_data['po_no'];
			if($po_id != ""){
				$getCountPO = $this->mdl->getCountPO($po_id);
				foreach ($getCountPO as $getCountPO) {
					$countPO = $getCountPO->po_id;
				}			
			}else{
				$getCountPO1 = $this->mdl->getCountPO1($key);
				foreach ($getCountPO1 as $getCountPO1) {
					$countPO = $getCountPO1->matin_no;
				}			
			}		
			$getPartial = $this->mdl->getPartial2($key2);
			foreach ($getPartial as $getPartial) {
				$getPart = $getPartial->partial;
			}			
			if($countPO <= 1){
				$getPodet = $this->mdl->getPodet($key);
				
				// ARRAY DETAIL INCOMING -ir
				$child_no = 1;
				foreach ($getPodet as $getPodet) {
					$dataDet = array(
						'matin_id'	=> $getPodet->matin_id,
						'child_no'	=> $child_no,
						'mat_id'		=> $getPodet->mat_id,
						'weight'		=> $getPodet->netto,
						'poqty'			=> $getPodet->qty,
						'balance'		=> $getPodet->qty,
						'qty'				=> 0,
						'price'			=> $getPodet->price
					);
					$child_no++;
					
					// INSERT DETAIL INCOMING -ir
					$this->mdl->addDet($dataDet);
				}
			} else if($countPO > 1) {
				$child_no = 1;
				
				// ARRAY DETAIL INCOMING -ir
				$getMatin = $this->mdl->getMatin($key);
				foreach ($getMatin as $getMatin) {
					$matin_id = $getMatin->matin_id;
				}
				
				$getPodet = $this->mdl->getPodet2($key2,$getPart);
				foreach ($getPodet as $getPodet) {
					if($getPodet->balance == 0 && $getPodet->all_in == "yes") {
						$has_edited="yes";
						$all_in="yes";
						$status="0";
					} else {
						$has_edited="no";
						$all_in="no";
						$status="1";
					} 
					$dataDet = array(
						'matin_id' 	=> $matin_id,
						'child_no'	=> $child_no,
						'mat_id'		=> $getPodet->mat_id,
						'weight'		=> $getPart,
						'poqty'			=> $getPodet->poqty,
						'qty'			=> 0,
						'Dqty'			=> $getPodet->Dqty,
						'balance'		=> $getPodet->balance,
						'price'			=> $getPodet->price,
						'has_edited'=> $has_edited,
						'all_in'		=> $all_in,
						'status'		=> $status
					);
					$child_no++;
					
					// INSERT DETAIL INCOMING -ir
					$success = $this->mdl->addDet($dataDet);
				}
				if ($success){				
					$id					= $matin_id;	
					$partial		= $getPodet->partial;

					// UPDATE +1 PARTIAL ON NEW HEADER --IR
					$updatePartial = array(
						'partial'			=> $getPodet->partial + 1
					);
					$this->mdl->editPartial($updatePartial, $id);

					// LOCK PREVIOUS PARTIAL WHEN AFTER ADDING HEADER --IR
					$updateLocked = array(
						'locked'			=> 'yes'
					);
					$this->mdl->editLocked($updateLocked, $po_id, $partial);
				} else {
					$bol=false;
					$msg="Item di Incoming ini sudah masuk semua!.";
				}
			}
		} else {
			$this->edit($form_data,$pk);
		}
	}
	
	function getformDet($cmd){
		$form_data = $this->input->post();
		
		$pk=array(
			'matin_id' => $form_data[$this->pk],
			'child_no' => $form_data[$this->pk2],
			'mat_id' 		=> $form_data['mat_id']
			);
		if ($cmd=="add"){	
			$this->addDet($form_data);	

			$key = $form_data['matin_id'];
			$getCountDet = $this->mdl->getCountDet($key);
			foreach ($getCountDet as $getCountDet) {
				$child_no = $getCountDet->matin_id;
			}	
			
			$updateChildNo = array(
				'child_no'			=> $child_no,
				'has_edited'		=> 'yes',
				'all_in'				=> 'yes'
			);
			$this->mdl->editChildNo($updateChildNo, $pk);

			// CALCULATE TOTAL AMOUNT #ir
			$key = $form_data[$this->pk];
			$getTotAmount = $this->mdl->getTotAmount2($key);
			foreach ($getTotAmount as $getTotAmount) {
				 $tot_amount = $getTotAmount->tot_amount;
				 $tot_qty	 = $getTotAmount->tot_qty;
				 $tot_volume	 = $getTotAmount->tot_volume;
			 	break;
			}


			// GET ITEM COUNT #ir
			$getCountDetailIn = $this->mdl->getCountDetailIn($key);
			foreach ($getCountDetailIn as $x) {
				$countItem = $x->matin_id;
			}			

			// UPDATE HEADER TRANSACTION #ir
			$updateHeader = array(
				'tot_volume'			=> $tot_volume,
				'tot_amount'			=> $tot_amount,
				'tot_qty'				=> $tot_qty,
				'HargaSerah'			=> $tot_amount,
				'JmlBarang'				=> $countItem,
			);
			$pk = $form_data[$this->pk];
			$this->mdl->editHdr($updateHeader, $pk);
		} else {
			$matin_id=$_REQUEST['matin_id'];
			$child_no=$_REQUEST['child_no'];
			$mat_id=$_REQUEST['mat_id'];
			$pk=array(
				'matin_id' => $matin_id,
				'child_no' => $child_no,
				'mat_id' 		=> $mat_id
			);

			$this->editDet($form_data,$pk);
			// IF BALANCE=0 THEN ALL IN #ir
			$balance= $form_data['balance'];
			$qty 		= $form_data['qty'];
			if($balance == 0) $all_in = 'yes'; else $all_in = 'no';
			if($qty > 0) $has_edited = 'yes'; else $has_edited = 'no';
			// UPDATE DETAIL TRANSACTIONS #ir
			$updateDetail = array(
				'has_edited'			=> $has_edited,
				'all_in'					=> $all_in
			);
			$this->mdl->editDetail($updateDetail, $pk);
			
			// CALCULATE TOTAL AMOUNT #ir
			$key = $form_data[$this->pk];
			$getTotAmount = $this->mdl->getTotAmount2($key);
			foreach ($getTotAmount as $getTotAmount) {
				$tot_amount 	= $getTotAmount->tot_amount;
				$tot_qty 		= $getTotAmount->tot_qty;
				$tot_volume	 = $getTotAmount->tot_volume;
				
			 	// GET PO_ID, PARTIAL AND LOCK for parameter to recalculate next partial
			 	$po_id			= $getTotAmount->po_id;
			 	$partial		= $getTotAmount->partial;
			 	$locked			= $getTotAmount->locked;
			 	break;
			}
			
			// GET ITEM COUNT #ir
			$getCountDetailIn = $this->mdl->getCountDetailIn($key);
			foreach ($getCountDetailIn as $x) {
				$countItem = $x->matin_id;
			}			
			// UPDATE HEADER TRANSACTION #ir
			$updateHeader = array(
				'tot_amount'			=> $tot_amount,
				'tot_volume'			=> $tot_volume,
				'tot_qty'				=> $tot_qty,
				'HargaSerah'			=> $tot_amount,
				'JmlBarang'				=> $countItem
			);
			$pk = $form_data[$this->pk];
			$this->mdl->editHdr($updateHeader, $pk);

			// RECALCULATE OTHER ITEM ON THE NEXT PARTIAL --ir
			if($locked == "yes"){
				$getDetRowAllPartial = $this->mdl->getDetRowAllPartial($po_id, $mat_id, $partial, $child_no);
				foreach ($getDetRowAllPartial as $getDetRowAllPartial) {
					$oldQty			 	= $getDetRowAllPartial->qty;
					$oldBalance 	= $getDetRowAllPartial->balance;
					$newDqty 			= ($getDetRowAllPartial->Dqty) + ($qty);
					$newbalance 	= ($getDetRowAllPartial->balance) - ($qty);
					$amount 			= ($getDetRowAllPartial->price) - ($oldQty);

					// $oldQty			 	= $getDetRowAllPartial->qty;
					// $oldBalance 	= $getDetRowAllPartial->balance;
					// $newDqty 			= ($getDetRowAll	Partial->Dqty) + ($qty);
					// $newbalance 	= $balance;
					// $amount 			= ($getDetRowAllPartial->price) - ($oldQty);
				
					// IF BALANCE = 0 AND QTY >= 0 THEN STATUS IS 0= --ir
					if($oldBalance > 0 && $newbalance == 0 && $getDetRowAllPartial->qty > 0 ) {
						$status = "1";
						$all_in = "yes";
						$has_edited = "yes";
					}else if($newbalance == 0 && $getDetRowAllPartial->qty >= 0 ) {
						$status = "0";
						$all_in = "yes";
						$has_edited = "yes";
					}else if($newbalance > 0 && $getDetRowAllPartial->qty == 0 ) {
						$status = "1";
						$all_in = "no";
						$has_edited = "no";
					}else if($newbalance > 0 && $getDetRowAllPartial->qty > 0) {
						$status = "1";
						$all_in = "no";
						$has_edited = "yes";
					}else if($newbalance == 0) {
						$status="0"; 
						$all_in = "yes";
						$has_edited = "yes";
					// IF THE EDITED ITEM ON CURRENT PARTAL HAS 0 QTY, THEN.. -ir
					}else if($balance == 0 || ($newbalance == 0 && $oldQty == 0)){
						$status			= "0"; 
						$all_in 		= "yes";
						$has_edited = "no";
						$oldQty			= "0"; 
						$newbalance	= "0"; 
						$newDqty 		= $getDetRowAllPartial->poqty;
					}else if($newbalance < 0){
						$status			= "1"; 
						$all_in 		= "yes";
						$has_edited = "yes";
						$oldQty			= $oldQty + $newbalance; 
						$newDqty 		= $newDqty + $newbalance;
						$newbalance	= $newbalance - $newbalance; 
					}
					
					// OVERWRITE BALANCE VALUE WITH NEW BALANCE ON CURRENT PARTIAL --ir
					$balance = $newbalance;

					$amount			= $oldQty * $getDetRowAllPartial->price;
					$dataDet = array(
						'qty'				=> $oldQty,
						'Dqty'			=> $newDqty,
						'balance'		=> $newbalance,
						'status'		=> $status,
						'all_in'		=> $all_in,
						'has_edited'=> $has_edited,
						'amount'		=> $amount
					);
					$pk2=array(
						$this->pk 	=> $getDetRowAllPartial->matin_id,
						$this->pk2 	=> $getDetRowAllPartial->child_no,
						'mat_id' 		=> $mat_id
					);
					$success = $this->mdl->editDet($dataDet,$pk2);
					$matin_id2 = $getDetRowAllPartial->matin_id;

					// CALCULATE TOTAL AMOUNT #ir
					$getTotAmount = $this->mdl->getTotAmount2($matin_id2);
					foreach ($getTotAmount as $getTotAmount) {
					 	$tot_amount 	= $getTotAmount->tot_amount;
					 	$tot_qty	 	= $getTotAmount->tot_qty;
					 	break;
					}
				
					// GET ITEM COUNT #ir
					$getCountDetailIn2 = $this->mdl->getCountDetailIn($matin_id2);
					foreach ($getCountDetailIn2 as $z) {
						$countItem = $z->matin_id;
					}		

					// UPDATE HEADER TRANSACRION #ir
					$updateHeader = array(
						'tot_amount'			=> $tot_amount,
						'tot_qty'				=> $tot_qty,
						'HargaSerah'			=> $tot_amount,
						'JmlBarang'				=> $countItem - 1
					);

					$success2 = $this->mdl->editHdr($updateHeader, $matin_id2);
				}	
			}

			// GET PO_ID, Partial and Locked for Recalculate Next Partial
			$rhdr = $this->mdl->getRow($matin_id);

			// foreach ($rhdr as $rhdr2) {
			// 	$po_id = $rhdr2->po_id;
			// 	$partial = $rhdr2->partial;
			// 	$locked = $rhdr2->locked;
			// }
		}
	}

	public function delDetKon() {
		$id = $this->input->post('id'); // Retrieve the ID sent via POST
	
		if ($id) {
			$result = $this->mdl->delKon($id); // Call the model function delKon
	
			if ($result) {
				// If the deletion is successful
				echo json_encode(['success' => true, 'msg' => 'Data berhasil dihapus.']);
			} else {
				// If deletion fails
				echo json_encode(['success' => false, 'msg' => 'Gagal menghapus data.']);
			}
		} else {
			// If no ID is provided
			echo json_encode(['success' => false, 'msg' => 'ID tidak valid.']);
		}
	}
	public function delDetDok() {
		$id = $this->input->post('id'); // Retrieve the ID sent via POST
	
		if ($id) {
			$result = $this->mdl->delDok($id); // Call the model function delKon
	
			if ($result) {
				// If the deletion is successful
				echo json_encode(['success' => true, 'msg' => 'Data berhasil dihapus.']);
			} else {
				// If deletion fails
				echo json_encode(['success' => false, 'msg' => 'Gagal menghapus data.']);
			}
		} else {
			// If no ID is provided
			echo json_encode(['success' => false, 'msg' => 'ID tidak valid.']);
		}
	}


	public function delDetJaminan() {
		$id = $this->input->post('id'); // Retrieve the ID sent via POST
	
		if ($id) {
			$result = $this->mdl->delJaminan($id); // Call the model function delJaminan

			if ($result) {
				// If the deletion is successful
				echo json_encode(['success' => true, 'msg' => 'Data berhasil dihapus.']);
			} else {
				// If deletion fails
				echo json_encode(['success' => false, 'msg' => 'Gagal menghapus data.']);
			}
		} else {
			// If no ID is provideds
			echo json_encode(['success' => false, 'msg' => 'ID tidak valid.']);
		}
	}

	function getformDetKon($cmd){
		$form_data = $this->input->post();
		
		$pk=array(
			'matin_id' 		=> $form_data['matin_id'],
			'NOMOR_KONTAINER' 		=> $form_data['NOMOR_KONTAINER']
			);
		if ($cmd=="add"){	
			$success =	$this->mdl->addDetKon($form_data);	
	
			if ($success){				
				$bol=true;
				$msg="Add data Kontainer berhasil.";
			} else {
				$bol=false;
				$msg="Add data Kontainer GAGAL.";
			}

		} else {
		
			$pk=array(
				'matin_id' 		=> $form_data['matin_id'],
				'NOMOR_KONTAINER' 		=> $form_data['NOMOR_KONTAINER']
				);

				$success =$this->mdl->editDetKon($form_data,$pk);
			if ($success){				
				$bol=true;
				$msg="Edit data Kontainer berhasil.";
			} else {
				$bol=false;
				$msg="Edit data Kontainer GAGAL.";
			}
	
		}
		echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}

	function getformDetDok($cmd){
		$form_data = $this->input->post();
		
		$pk=array(
			'matin_no' 		=> $form_data['matin_id'],
			'dok_no' 		=> $form_data['dok_no']
			);
		if ($cmd=="add"){	
			$success =	$this->mdl->addDetDok($form_data);	
	
			if ($success){				
				$bol=true;
				$msg="Add data Kontainer berhasil.";
			} else {
				$bol=false;
				$msg="Add data Kontainer GAGAL.";
			}

		} else {
		
			$pk=array(
				'matin_no' 		=> $form_data['matin_id'],
				'dok_no' 		=> $form_data['dok_no']
				);

				$success =$this->mdl->editDetDok($form_data,$pk);
			if ($success){				
				$bol=true;
				$msg="Edit data Kontainer berhasil.";
			} else {
				$bol=false;
				$msg="Edit data Kontainer GAGAL.";
			}
	
		}
		echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}

		function getformDetjaminan($cmd){
		$form_data = $this->input->post();
		
		$pk=array(
			'matin_no' 		=> $form_data['matin_no'],
			'nomorJaminan' 		=> $form_data['nomorJaminan']
			);
		if ($cmd=="add"){	
			$success =	$this->mdl->addDetJaminan($form_data);
			
			if ($success){				
				$bol=true;
				$msg="Add data Jaminan berhasil.";
			} else {
				$bol=false;
				$msg="Add data Jaminan GAGAL.";
			}

		} else {
		
			$pk=array(
				'matin_no' 		=> $form_data['matin_no'],
				'nomorJaminan' 		=> $form_data['nomorJaminan']
				);

				$success =$this->mdl->editDetJaminan($form_data,$pk);
			if ($success){				
				$bol=true;
				$msg="Edit data Jaminan berhasil.";
			} else {
				$bol=false;
				$msg="Edit data Jaminan GAGAL.";
			}
	
		}
		echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}
	
	
	// Create Journal #ir
	function create_journal(){
		$id=$_REQUEST['id'];
		$created_journal=$_REQUEST['created_journal'];
		
		if($created_journal == 'yes'){
			$bol=false;
			$msg="Data ini sudah dibuatkan jurnalnya!";
		} else {
			$success = $this->mdl->createJournal($id);
			if ($success){				
				$bol=true;
				$msg="Create Journal berhasil.";
			} else {
				$bol=false;
				$msg="Create Journal GAGAL.";
			}
		}
		echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}
	
	// Lock Item --ir
	function lock2(){
		$matin_id=$_REQUEST['matin_id'];
		$child_no=$_REQUEST['child_no'];
		$mat_id=$_REQUEST['mat_id'];
		$locked=$_REQUEST['locked'];
		$pk=array(
			$this->pk 	=> $matin_id,
			$this->pk2 	=> $child_no,
			'mat_id' 		=> $mat_id
		);
		$getDetRow = $this->mdl->getDetRow($matin_id, $child_no, $mat_id);
		foreach ($getDetRow as $getDetRow) {
			if($locked == "no") $locked="yes"; else $locked="no";
			$dataDet = array(
				'locked'=> $locked
			);
			$success = $this->mdl->editDet($dataDet,$pk);
		}
		if ($success){				
			$bol=true;
			if($_REQUEST['locked'] == "no") $msg="Item berhasil dikunci"; else $msg="Item berhasil dibuka";
		} else {
			$bol=false;
			$msg="Gagal Dirubah.";
		}
		echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}

	// Save / Reset Adjustment --ir
	function saveAdj(){
		$matin_id=$_REQUEST['matin_id'];
		$child_no=$_REQUEST['child_no'];
		$mat_id=$_REQUEST['mat_id'];
		$pk=array(
			$this->pk 	=> $matin_id,
			$this->pk2 	=> $child_no,
			'mat_id' 		=> $mat_id
		);
		$getDetRow = $this->mdl->getDetRow($matin_id, $child_no, $mat_id);
		foreach ($getDetRow as $getDetRow) {
			if($getDetRow->adj_qty == 0 && $getDetRow->balance < 0 && $getDetRow->has_edited == "yes") {
				$balance = 0;
				$adj_qty = $getDetRow->balance * (-1);
			}else{
				$adj_qty = 0;
				$balance = $getDetRow->poqty - $getDetRow->Dqty;
			}
			$dataDet = array(
				'adj_qty'=> $adj_qty,
				'balance'=> $balance
			);
			$success = $this->mdl->editDet($dataDet,$pk);
		}
		if ($success){				
			$bol=true;
			if($adj_qty != 0) $msg="Adjustment berhasil dimasukan! "; else $msg="Adjustment berhasil direset!";
		} else {
			$bol=false;
			$msg="Adjustment gagal!";
		}
		echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}

	// Reset Qty --ir
	function reset_qty(){
		$matin_id=$_REQUEST['matin_id'];
		$child_no=$_REQUEST['child_no'];
		$mat_id=$_REQUEST['mat_id'];
		$po_id=$_REQUEST['po_id'];
		$partial=$_REQUEST['partial'];
		$affect=$_REQUEST['affect'];

		$pk=array(
			$this->pk 	=> $matin_id,
			$this->pk2 	=> $child_no,
			'mat_id' 		=> $mat_id
		);

		// CALCULATE QTY IN DETAIL #ir
		$getDetRow = $this->mdl->getDetRow($matin_id, $child_no, $mat_id);
		foreach ($getDetRow as $getDetRow) {
			$Dqty 		= ($getDetRow->Dqty) - ($getDetRow->qty);
			$balance 	= ($getDetRow->balance) + ($getDetRow->qty) - ($getDetRow->adj_qty);
			$dataDet = array(
				'qty'			 	=> 0,
				'amount'		=> 0,
				'adj_ref'	 	=> '',
				'adj_qty'	 	=> 0,
				'Dqty'			=> $Dqty,
				'balance'		=> $balance,
				'has_edited'=> "no",
				'all_in'		=> "no"
			);
			$success = $this->mdl->editDet($dataDet,$pk);

			$lastQty = $getDetRow->qty;

			// RECALCULATE OTHER ITEM ON THE NEXT PARTIAL --ir
			if($affect == "yes"){
				$getDetRowAllPartial = $this->mdl->getDetRowAllPartial($po_id, $mat_id, $partial, $child_no);
				foreach ($getDetRowAllPartial as $getDetRowAllPartial) {
					$oldBalance = $getDetRowAllPartial->balance;
					$newDqty 		= ($getDetRowAllPartial->Dqty) - ($lastQty);
					$newbalance 	= ($getDetRowAllPartial->balance) + ($lastQty);

					// IF BALANCE GO BACK FROM ZERO THEN STATUS BACK TO 1 --ir
					if($newbalance > 0 && $getDetRowAllPartial->qty == 0 ) {
						$status="1";
						$all_in = "no";
						$has_edited = "no";
					}else if($newbalance > 0 && $getDetRowAllPartial->qty > 0) {
						$status="1";
						$all_in = "no";
						$has_edited = "yes";
					}else{
						$status="0";
						$all_in = "yes";
						$has_edited = "yes";
					}
						
					$dataDet = array(
						'Dqty'			=> $newDqty,
						'balance'		=> $newbalance,
						'has_edited'=> $has_edited,
						'all_in'		=> $all_in,
						'status'		=> $status
					);
					$pk2=array(
						$this->pk 	=> $getDetRowAllPartial->matin_id,
						$this->pk2 	=> $getDetRowAllPartial->child_no,
						'mat_id' 		=> $mat_id
					);
					$success = $this->mdl->editDet($dataDet,$pk2);
				}	
			}

			// CALCULATE TOTAL AMOUNT #ir
			$getTotAmount = $this->mdl->getTotAmount2($matin_id);
			foreach ($getTotAmount as $getTotAmount) {
			 	$tot_amount 	= $getTotAmount->tot_amount;
			 	$tot_qty	 	= $getTotAmount->tot_qty;
			 	break;
			}
			// GET ITEM COUNT #ir
			$getCountDetailIn = $this->mdl->getCountDetailIn($matin_id);
			foreach ($getCountDetailIn as $y) {
				$countItem = $y->matin_id;
				break;
			}			
			// UPDATE HEADER TRANSACRION #ir
			$amount = $getDetRow->qty * $getDetRow->price;
			$updateHeader = array(
				'tot_amount'			=> $tot_amount,
				'tot_qty'				=> $tot_qty,
				'HargaSerah'			=> $tot_amount,
				'JmlBarang'				=> $countItem - 1
			);
			
			$pk2 = $matin_id;
			$success2 = $this->mdl->editHdr($updateHeader, $pk2);
		}
		if ($success && $success2){				
			$bol=true;
			$msg="Reset Incoming Qty berhasil.";
		} else {
			$bol=false;
			$msg="Reset Incoming Qty GAGAL.";
		}
		echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}

	// Reset Qty All Items --ir
	function reset_qty_all(){
		$matin_id=$_REQUEST['matin_id'];
		$po_id=$_REQUEST['po_id'];
		$partial=$_REQUEST['partial'];
		$affect=$_REQUEST['affect'];

		$has_edited = 'yes';
		// CALCULATE QTY DETAIL #ir
		$getDetRow = $this->mdl->getDetRowAll($matin_id,$has_edited);
		foreach ($getDetRow as $getDetRow) {
			$Dqty 		= ($getDetRow->Dqty) - ($getDetRow->qty);
			$balance 	= ($getDetRow->balance) + ($getDetRow->qty) - ($getDetRow->adj_qty);
			$dataDet = array(
				'qty'			=> 0,
				'amount'		=> 0,
				'adj_ref'		=> '',
				'adj_qty'		=> 0,
				'Dqty'			=> $Dqty,
				'balance'		=> $balance,
				'has_edited'=> "no",
				'all_in'		=> "no"
			);
			$pk=array(
				$this->pk 	=> $matin_id,
				$this->pk2 	=> $getDetRow->child_no,
				'mat_id' 		=> $getDetRow->mat_id
			);
			$success = $this->mdl->editDet($dataDet,$pk);

			$lastQty = $getDetRow->qty;
			$mat_id = $getDetRow->mat_id;
			$child_no = $getDetRow->child_no;

			// RECALCULATE OTHER ITEM ON THE NEXT PARTIAL --ir
			if($affect == "yes"){
				$getDetRowAllPartial = $this->mdl->getDetRowAllPartial($po_id, $mat_id, $partial, $child_no);
				foreach ($getDetRowAllPartial as $getDetRowAllPartial) {
					$oldBalance = $getDetRowAllPartial->balance;
					$newDqty 		= ($getDetRowAllPartial->Dqty) - ($lastQty);
					$newbalance 	= ($getDetRowAllPartial->balance) + ($lastQty);

					// IF BALANCE GO BACK FROM ZERO THEN STATUS BACK TO 1 --ir
					if($oldBalance >= 0 && $newbalance > 0 && $getDetRowAllPartial->qty == 0 ) {
						$status="1";
						$all_in = "no";
						$has_edited = "no";
					}else if($newbalance > 0 && $getDetRowAllPartial->qty > 0) {
						$status="1";
						$all_in = "no";
						$has_edited = "yes";
					}
					else{
						$status="0";
						$all_in = "yes";
						$has_edited = "yes";
					} 

					$dataDet = array(
						'Dqty'			=> $newDqty,
						'balance'		=> $newbalance,
						'has_edited'=> $has_edited,
						'all_in'		=> $all_in,
						'status'		=> $status
					);
					$pk2=array(
						$this->pk 	=> $getDetRowAllPartial->matin_id,
						$this->pk2 	=> $getDetRowAllPartial->child_no,
						'mat_id' 		=> $mat_id
					);
					$success = $this->mdl->editDet($dataDet,$pk2);
					$matin_id2 = $getDetRowAllPartial->matin_id;

					// CALCULATE TOTAL AMOUNT #ir
					$getTotAmount2 = $this->mdl->getTotAmount2($matin_id2);
					foreach ($getTotAmount2 as $getTotAmount2) {
						$tot_amount	 	= $getTotAmount2->tot_amount;
						$tot_qty 		= $getTotAmount2->tot_qty;
					 	break;
					}
				
					// GET ITEM COUNT #ir
					$getCountDetailIn2 = $this->mdl->getCountDetailIn($matin_id2);
					foreach ($getCountDetailIn2 as $z) {
						$countItem = $z->matin_id;
					}		

					// UPDATE HEADER TRANSACTIONS #ir
					$updateHeader = array(
						'tot_amount'			=> $tot_amount,
						'tot_qty'				=> $tot_qty,
						'HargaSerah'			=> $tot_amount,
						'JmlBarang'				=> $countItem
					);

					$success2 = $this->mdl->editHdr($updateHeader, $matin_id2);
				}
			}

			// CALCULATE TOTAL AMOUNT #ir
			$getTotAmount = $this->mdl->getTotAmount2($matin_id);
			foreach ($getTotAmount as $getTotAmount) {
			 	$tot_amount	 	= $getTotAmount->tot_amount;
			 	$tot_qty 		= $getTotAmount->tot_qty;
			 	break;
			}
			// GET ITEM COUNT #ir
			$getCountDetailIn = $this->mdl->getCountDetailIn($matin_id);
			foreach ($getCountDetailIn as $x) {
				$countItem = $x->matin_id;
			}			
			// UPDATE DETAIL TRANSACTIONS
			$amount = $getDetRow->qty * $getDetRow->price;
			$updateHeader = array(
				'tot_amount'			=> $tot_amount,
				'tot_qty'				=> $tot_qty,
				'HargaSerah'			=> $tot_amount,
				'JmlBarang'				=> $countItem - 1
			);
			
			$pk2 = $matin_id;
			$success2 = $this->mdl->editHdr($updateHeader, $pk2);
		}
		if ($success && $success2){				
			$bol=true;
			$msg="Reset Incoming Qty SEMUA Item berhasil.";
		} else {
			$bol=false;
			$msg="Reset Incoming Qty SEMUA Item GAGAL.";
		}
		echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}

	// All Qty All Items --ir
	function all_in_qty(){
		$matin_id=$_REQUEST['matin_id'];
		$child_no=$_REQUEST['child_no'];
		$mat_id=$_REQUEST['mat_id'];
		$po_id=$_REQUEST['po_id'];
		$partial=$_REQUEST['partial'];
		$affect=$_REQUEST['affect'];

		$pk=array(
			$this->pk 	=> $matin_id,
			$this->pk2 	=> $child_no,
			'mat_id' 		=> $mat_id
		);
		
		// CALCULATE QTY DETAIL #ir
		$getDetRow = $this->mdl->getDetRow($matin_id, $child_no, $mat_id);
		foreach ($getDetRow as $getDetRow) {
			$qty = ($getDetRow->qty) + ($getDetRow->balance);
			$Dqty = ($getDetRow->Dqty) + ($getDetRow->balance);
			$amount = ($getDetRow->amount) + ($getDetRow->amountpo);
			$dataDet = array(
				'qty'			 	=> $qty,
				'amount'			=> $amount,
				'Dqty'			=> $Dqty,
				'balance'		=> 0,
				'has_edited'=> "yes",
				'all_in'		=> "yes"
			);
			$success = $this->mdl->editDet($dataDet,$pk);

			$lastQty = $getDetRow->qty;

			// RECALCULATE OTHER ITEM ON THE NEXT PARTIAL --ir
			if($affect == "yes"){
				$getDetRowAllPartial = $this->mdl->getDetRowAllPartial($po_id, $mat_id, $partial, $child_no);
				foreach ($getDetRowAllPartial as $getDetRowAllPartial) {
					$oldBalance = $getDetRowAllPartial->balance;
					$newDqty 		= ($getDetRowAllPartial->Dqty) - ($lastQty);
					$newbalance 	= ($getDetRowAllPartial->balance) + ($lastQty);
						
					$dataDet = array(
						'qty'				=> 0,
						'Dqty'			=> $getDetRowAllPartial->poqty,
						'balance'		=> 0,
						'has_edited'=> 'no',
						'all_in'		=> 'yes',
						'status'		=> '0',
						'amount'		=> '0'
					);

					$pk2=array(
						$this->pk 	=> $getDetRowAllPartial->matin_id,
						$this->pk2 	=> $getDetRowAllPartial->child_no,
						'mat_id' 		=> $mat_id
					);
					$success = $this->mdl->editDet($dataDet,$pk2);
					$matin_id2 = $getDetRowAllPartial->matin_id;

					// CALCULATE TOTAL AMOUNT #ir
					$getTotAmount2 = $this->mdl->getTotAmount2($matin_id2);
					foreach ($getTotAmount2 as $getTotAmount) {
					 	$tot_amount 	= $getTotAmount->tot_amount;
					 	$tot_qty	 	= $getTotAmount->tot_qty;
					 	break;
					}
				
					// GET ITEM COUNT #ir
					$getCountDetailIn2 = $this->mdl->getCountDetailIn($matin_id2);
					foreach ($getCountDetailIn2 as $z) {
						$countItem = $z->matin_id;
					}		

					// UPDATE HEADER TRANSACRION #ir
					$updateHeader = array(
						'tot_amount'			=> $tot_amount,
						'tot_qty'				=> $tot_qty,
						'HargaSerah'			=> $tot_amount,
						'JmlBarang'				=> $countItem - 1
					);

					$success2 = $this->mdl->editHdr($updateHeader, $matin_id2);
				}	
			}

			// CALCULATE TOTAL AMOUNT #ir
			$getTotAmount = $this->mdl->getTotAmount2($matin_id);
			foreach ($getTotAmount as $getTotAmount) {
			 	$tot_amount = $getTotAmount->tot_amount;
			 	$tot_qty 	= $getTotAmount->tot_qty;
			 	break;
			}

			// GET ITEM COUNT #ir
			$getCountDetailIn = $this->mdl->getCountDetailIn($matin_id);
			foreach ($getCountDetailIn as $x) {
				$countItem = $x->matin_id;
			}		
			
			// UPDATE HEADER TRANSACTIONS #ir
			$amount = ($qty * $getDetRow->price) - ($getDetRow->qty * $getDetRow->price);
			if($getDetRow->qty == 0) $countItem = $countItem;
			else $countItem = $countItem;
			$updateHeader = array(
				'tot_amount'			=> $tot_amount,
				'tot_qty'				=> $tot_qty,
				'HargaSerah'			=> $tot_amount,
				'JmlBarang'				=> $countItem
			);
			
			$pk2 = $matin_id;
			$success2 = $this->mdl->editHdr($updateHeader, $pk2);
		}
		if ($success && $success2){				
			$bol=true;
			$msg="Input All In Qty berhasil.";
		} else {
			$bol=false;
			$msg="Input All In Qty GAGAL.";
		}
		echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}

	// All In Qty All Items --ir
	function all_in_qty_all(){
		$matin_id=$_REQUEST['matin_id'];
		$po_id=$_REQUEST['po_id'];
		$partial=$_REQUEST['partial'];
		$affect=$_REQUEST['affect'];

		$all_in = 'no';
		// CALCULATE QTY DETAIL #ir 
		$getDetRow = $this->mdl->getDetRowAll2($matin_id,$all_in);
		foreach ($getDetRow as $getDetRow) {
			$qty = ($getDetRow->qty) + ($getDetRow->balance);
			$Dqty = ($getDetRow->Dqty) + ($getDetRow->balance);
			$amount = ($getDetRow->amountpo) + ($getDetRow->amount);
			$dataDet = array(
				'qty'			 	=> $qty,
				'amount'			=> $amount,
				'Dqty'			=> $Dqty,
				'balance'		=> 0,
				'has_edited'=> "yes",
				'all_in'		=> "yes"
			);
			$pk=array(
				$this->pk 	=> $matin_id,
				$this->pk2 	=> $getDetRow->child_no,
				'mat_id' 		=> $getDetRow->mat_id
			);
			$success = $this->mdl->editDet($dataDet,$pk);

			$mat_id = $getDetRow->mat_id;
			$child_no = $getDetRow->child_no;

			// RECALCULATE OTHER ITEM ON THE NEXT PARTIAL --ir
			if($affect == "yes"){
				$getDetRowAllPartial = $this->mdl->getDetRowAllPartial($po_id, $mat_id, $partial, $child_no);
				foreach ($getDetRowAllPartial as $getDetRowAllPartial) {
					$oldBalance = $getDetRowAllPartial->balance;
					$newDqty 		= ($getDetRowAllPartial->Dqty) - ($lastQty);
					$newbalance 	= ($getDetRowAllPartial->balance) + ($lastQty);
						
					$dataDet = array(
						'qty'				=> 0,
						'Dqty'			=> $getDetRowAllPartial->poqty,
						'balance'		=> 0,
						'has_edited'=> 'no',
						'all_in'		=> 'yes',
						'status'		=> '0',
						'amount'		=> '0'
					);

					$pk2=array(
						$this->pk 	=> $getDetRowAllPartial->matin_id,
						$this->pk2 	=> $getDetRowAllPartial->child_no,
						'mat_id' 		=> $mat_id
					);
					$success = $this->mdl->editDet($dataDet,$pk2);
					$matin_id2 = $getDetRowAllPartial->matin_id;

					// CALCULATE TOTAL AMOUNT #ir
					$getTotAmount2 = $this->mdl->getTotAmount2($matin_id2);
					foreach ($getTotAmount2 as $getTotAmount2) {
						$tot_amount	 	= $getTotAmount2->tot_amount;
						$tot_qty 		= $getTotAmount2->tot_qty;
					 	break;
					}
				
					// GET ITEM COUNT #ir
					$getCountDetailIn2 = $this->mdl->getCountDetailIn($matin_id2);
					foreach ($getCountDetailIn2 as $z) {
						$countItem = $z->matin_id;
					}		

					// UPDATE HEADER TRANSACTIONS #ir
					$updateHeader = array(
						'tot_amount'			=> $tot_amount,
						'tot_qty'				=> $tot_qty,
						'HargaSerah'			=> $tot_amount,
						'JmlBarang'				=> $countItem
					);

					$success2 = $this->mdl->editHdr($updateHeader, $matin_id2);
				}	
			}

			// CALCULATE TOTAL AMOUNT #ir
			$getTotAmount = $this->mdl->getTotAmount2($matin_id);
			foreach ($getTotAmount as $getTotAmount) {
			 	$tot_amount	 	= $getTotAmount->tot_amount;
			 	$tot_qty 		= $getTotAmount->tot_qty;
			 	break;
			}
			// GET ITEM COUNT #ir
			$getCountDetailIn = $this->mdl->getCountDetailIn($matin_id);
			foreach ($getCountDetailIn as $x) {
				$countItem = $x->matin_id;
			}		
			// UPDATE DETAIL TRANSACTIONS #ir
			$amount = ($qty * $getDetRow->price) - ($getDetRow->qty * $getDetRow->price); 
			if($getDetRow->qty == 0) $countItem = $countItem;
			else $countItem = $countItem;
			$updateHeader = array(
				'tot_amount'			=> $tot_amount,
				'tot_qty'				=> $tot_qty,
				'HargaSerah'			=> $tot_amount,
				'JmlBarang'				=> $countItem
			);
			
			$pk2 = $matin_id;
			$success2 = $this->mdl->editHdr($updateHeader, $pk2);
		}
		if ($success && $success2){				
			$bol=true;
			$msg="Input All Incoming Qty SEMUA Item berhasil.";
		} else {
			$bol=false;
			$msg="Input All Incoming Qty SEMUA Item GAGAL.";
		}
		echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}


	function daftar_ceisa() {
		 // Send the data to Ceisa via a webhook
		 $jsonString = json_encode($jsonData, JSON_PRETTY_PRINT);
		 $url = "https://apis-gw.beacukai.go.id/openapi/document";
		 $success = $this->mdl->sendToCeisa($jsonString, $url,$id);
		
		 if ($success == true){			
				 
			 $bol=true;
			 $msg="Send data to Ceisa berhasil.";
		 } else {
			 $bol=false;
			 $msg="Send data to Ceisa GAGAL.";
		 }
		 echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}
	// Transfer to Ceisa 
	function transfer_ceisa() {
		$status = "";
		$id = $_REQUEST['id'];

		$transfer_ceisa = $_REQUEST['transfer_ceisa'];
		$dataHd = $this->mdl->getHdrDet_1($id);
		$data = $dataHd["rows"][0];

		if ($data->UrJnsDok == '') {
			$bol = false;
			$msg = "Jenis BC belum di pilih !";
			echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
		}else {
	
		if ($transfer_ceisa == 'yes1') {
			$bol = false;
			$msg = "Data ini sudah ditransfer ke Ceisa!";
			echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
		} else {
						// Fetch entitas data from the database
						$entitasDataPengusaha =  $this->mdl->getEntitasData($data->supplier);
						$entitasData2 =  $this->mdl->getEntitasData();
						$entitasData3 =  $this->mdl->getEntitasData($data->supplier);
						$dokData =  $this->mdl->getDokData($data->matin_id);
						$konData =  $this->mdl->getKonData($data->matin_id);
						$jaminanData =  $this->mdl->getJaminanData($data->matin_id);

			$kdBrngAsal = "";
			$dokJns = "";
			$jsonData = [];
	
			if ($data->UrJnsDok == "BC 2.7") {
				$dokJns = "27";
				$jsonData = [
					"asalData" => "S",
					"asuransi" => 0.00,
					"bruto" => (int) $data->Bruto,
					"cif" =>(int) $data->cif,
					"disclaimer" => "1",
					"kodeJenisTpb" => "1",
					"freight" => 0,
					"hargaPenyerahan" =>(int) $data->HargaSerah,
					"jabatanTtd" => $data->jabatanTtd,
					"jumlahKontainer" => 0,
					"kodeDokumen" => $dokJns,
					"kodeKantor" => $data->kodeKantor,
					"kodeKantorTujuan" =>  $data->kodeKantorTujuan,
					"kodeTps" =>  $data->kodeTps,
					"kodeTujuanPengiriman" => $data->matin_type,
					"kodeTujuanTpb" => "1",
					"kodeValuta" => $data->currency,
					"kotaTtd" => $data->kotaTtd,
					"namaTtd" => $data->namaTtd,
					"ndpbm" => 0.00,
					"netto" => (int) $data->Netto,
					"nik" => "0",
					"nilaiBarang" => 0,
					"nomorAju" => $data->NoAju,
					"seri" => 0,
					"tanggalAju" => dmys2ymd($data->FTgAju),
					"tanggalTtd" => $data->TgTTD,
					"biayaTambahan" => 0,
					"biayaPengurang" => 0,
					"vd" => 0,
					"uangMuka" => 0,
					"nilaiJasa" => 0,
					"entitas" => [], // Initialize as an empty array
					"dokumen" => [],
					"pengangkut" => [
						[
							"namaPengangkut" => $data->namaPengangkut,
							"nomorPengangkut" => $data->noPengangkut,
							"seriPengangkut" => "1"
						]
					],
					"kemasan" => [
						[
							"jumlahKemasan" =>(int) $data->JmlBarang,
							"kodeJenisKemasan" => $data->packing,
							"merkKemasan" => "-",
							"seriKemasan" => 1
						]
					],
					"kontainer" => [],
					"pungutan" => [],
					"barang" => []
				];
			} else if ($data->UrJnsDok == "BC 2.3") {
				$dokJns = "23";
			$jsonData = [
					"asalData" => "S",
					"asuransi" => 0.00,
					"bruto" => (int) $data->Bruto,
					"cif" => (int)$data->cif,
					"kodeJenisTpb" => "1",
					"freight" => 0,
					"hargaPenyerahan" =>(int) $data->HargaSerah,
					"idPengguna"=>"0010619179057000",
					"jabatanTtd" => $data->jabatanTtd,
					"jumlahKontainer" => 0,
					"kodeDokumen" => $dokJns,
					"kodeKantor" => $data->kodeKantor,
					"kodeTujuanPengiriman" => $data->matin_type,
					"kodeTujuanTpb" => "1",
				//kosong data belum jadi {
					"fob"=>0,
					"kodeAsuransi"=>"DN",
					"kodeIncoterm"=>"CIF",
					"kodeKantorBongkar"=>$data->kodeKantor,
					"kodePelBongkar"=>$data->kodeKantor,
					"kodePelBongkar"=>$data->kodeKantor,
					"kodePelMuat"=>$data->kodeKantor,
					"kodePelTransit"=>$data->kodeKantor,
					"kodeTps"=>$data->kodeKantor,
					"kodeTutupPu"=>"11",
					"kodeValuta"=>"$data->currency",
					"ndpbm"=>(int)"$data->kurs",
					"nilaiBarang"=> (int)"$data->HargaSerah",
					"nomorBc11"=>"",
					"posBc11"=>"",
					"subposBc11"=>"",
					"tanggalBc11"=>"",
					"tanggalTiba"=>$data->TgTTD,
					// } kosong data belum jadi
					"kotaTtd" => $data->kotaTtd,
					"namaTtd" => $data->namaTtd,
			
					"netto" => (int) $data->Netto,
					"nik" => "0",
			
					"nomorAju" => $data->NoAju,
					"seri" => 0,
					"tanggalAju" => dmys2ymd($data->FTgAju),
					"tanggalTtd" => $data->TgTTD,
					"volume" => (int) $data->tot_volume,
					"biayaTambahan" => 0,
					"biayaPengurang" => 0,
					"vd" => 0,
					"uangMuka" => 0,
					"nilaiJasa" => 0,
					"entitas" => [], // Initialize as an empty array
					"dokumen" => [],
					"pengangkut" => [
						[
							"namaPengangkut" => $data->namaPengangkut,
							"nomorPengangkut" => $data->noPengangkut,
							"seriPengangkut" => 1,
							"kodeBendera" =>"ID",
							"kodeCaraAngkut"=>"1"
						]
					],
					"kemasan" => [
						[
							"jumlahKemasan" =>(int) $data->JmlBarang,
							"kodeJenisKemasan" => $data->packing,
							"merkKemasan" => "-",
							"seriKemasan" => 1
						]
					],
					"kontainer" => [],
					"pungutan" => [
	
					],
					"barang" => []
				];
			
			} else if ($data->UrJnsDok == "BC 2.6.2") {
				$dokJns = "262";
						$jsonData = [
					"asalData" => "S",
					"asuransi" => 0.00,
					"bruto" => (int) $data->Bruto,
					"cif" =>(int) $data->cif,
					"disclaimer" => "1",
					"kodeJenisTpb" => "1",
					"freight" => 0,
					"hargaPenyerahan" =>(int) $data->HargaSerah,
					"jabatanTtd" => $data->jabatanTtd,
					"jumlahKontainer" => 0,
					"kodeDokumen" => $dokJns,
					"kodeKantor" => $data->kodeKantor,
					"kodeKantorTujuan" =>  $data->kodeKantorTujuan,
					"kodeTps" =>  $data->kodeTps,
					"kodeTujuanPengiriman" => $data->matin_type,
					"kodeTujuanPemasukan"=>$data->matin_type, //bc 262 
					"kodeTujuanTpb" => "1",
					"kodeValuta" => $data->currency,
					"kotaTtd" => $data->kotaTtd,
					"namaTtd" => $data->namaTtd,
					"ndpbm" => 0.00,
					"netto" => (int) $data->Netto,
					"nik" => "0",
					"nilaiBarang" => 0,
					"nomorAju" => $data->NoAju,
					"seri" => 0,
					"tanggalAju" => dmys2ymd($data->FTgAju),
					"tanggalTtd" => $data->TgTTD,
					"biayaTambahan" => 0,
					"biayaPengurang" => 0,
					"vd" => 0,
					"uangMuka" => 0,
					"nilaiJasa" => 0,
					"entitas" => [], // Initialize as an empty array
					"dokumen" => [],
					 "jaminan" => [],
					"pengangkut" => [
						[	"idPengangkut" => "1",
							"kodeCaraAngkut"=>"3",
							"namaPengangkut" => $data->namaPengangkut,
							"nomorPengangkut" => $data->noPengangkut,
							"seriPengangkut" => 1
						]
					],
					"kemasan" => [
						[
							"jumlahKemasan" =>(int) $data->JmlBarang,
							"kodeJenisKemasan" => $data->packing,
							"merkKemasan" => "-",
							"seriKemasan" => 1
						]
					],
					"kontainer" => [],
					"pungutan" => [],
					"barang" => []
				];
				
			} else {
				$dokJns ="40";
				$jsonData = [
					"asalData" => "S",
					"asuransi" => 0.00,
					"bruto" => (int) $data->Bruto,
					"cif" => (int)$data->cif,
					"kodeJenisTpb" => "1",
					"freight" => 0,
					"hargaPenyerahan" =>(int) $data->HargaSerah,
					"idPengguna"=>"0010619179057000",
					"jabatanTtd" => $data->jabatanTtd,
					"jumlahKontainer" => 0,
					"kodeDokumen" => $dokJns,
					"kodeKantor" => $data->kodeKantor,
					"kodeTujuanPengiriman" => $data->matin_type,
					"kodeTujuanTpb" => "1",
	
					"kotaTtd" => $data->kotaTtd,
					"namaTtd" => $data->namaTtd,
			
					"netto" => (int) $data->Netto,
					"nik" => "0",
			
					"nomorAju" => $data->NoAju,
					"seri" => 0,
					"tanggalAju" => dmys2ymd($data->FTgAju),
					"tanggalTtd" => $data->TgTTD,
					"volume" => (int) $data->tot_volume,
					"biayaTambahan" => 0,
					"biayaPengurang" => 0,
					"vd" => 0,
					"uangMuka" => 0,
					"nilaiJasa" => 0,
					"entitas" => [], // Initialize as an empty array
					"dokumen" => [],
					"pengangkut" => [
						[
							"namaPengangkut" => $data->namaPengangkut,
							"nomorPengangkut" => $data->noPengangkut,
							"seriPengangkut" => 1
						]
					],
					"kemasan" => [
						[
							"jumlahKemasan" =>(int) $data->JmlBarang,
							"kodeJenisKemasan" => $data->packing,
							"merkKemasan" => "-",
							"seriKemasan" => 1
						]
					],
					"kontainer" => [],
					"pungutan" => [
	
					],
					"barang" => []
				];
			}
	

			// Prepare the data as an associative array
			foreach ($dokData as $row) {
				$jsonData["dokumen"][] = [
					"kodeDokumen" => $row->kodeDokumen,
					"nomorDokumen" => $row->nomorDokumen,
					"seriDokumen" =>(int) $row->seriDokumen,
					"tanggalDokumen" => dmys2ymd($row->tanggalDokumen)
				];
			}

			foreach ($konData as $row) {
				$jsonData["kontainer"][] = [
					"kodeTipeKontainer" => $row->kodeTipeKontainer,
					"kodeUkuranKontainer" => $row->kodeUkuranKontainer,
					"nomorKontainer" => $row->nomorKontainer,
					"seriKontainer" =>(int) $row->seriKontainer,
					"kodeJenisKontainer" => $row->kodeJenisKontainer
				];
			}
		$idjam = 0;
	//	var_dump($jaminanData);
				foreach ($jaminanData as $row) {
				$jsonData["jaminan"][] = [
										
				"idJaminan" => (string)$idjam,
				"nomorBpj" => $row->nomorBpj,
				"kodeJenisBpj" => $row->kodeJenisBpj,
				"tanggalBpj" => $row->tanggalBpj,
				"kodeJenisJaminan" => $row->kodeJenisJaminan,
				"nomorJaminan" => $row->nomorJaminan,
				"tanggalJaminan" => $row->tanggalJaminan,
				"tanggalJatuhTempo" => $row->tanggalJatuhTempo,
				"penjamin" => $row->penjamin,
				"nilaiJaminan" => (float) $row->nilaiJaminan
			];
			$idjam++;
			}


			if ($data->UrJnsDok == "BC 2.7") {
			
				foreach ($entitasDataPengusaha as $entitas) {
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas->AlmtPrshn,
						"kodeEntitas" =>"3",
						"kodeJenisApi"=>"2",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"namaEntitas" => $entitas->NmPrshn,
						"nibEntitas" => $entitas->nibEntitas,
						"nomorIdentitas" => $entitas->nomorIdentitas,
						"nomorIjinEntitas" => $entitas->nomorIjinEntitas,
						"seriEntitas" => 3,
						"tanggalIjinEntitas" => $entitas->tanggalIjinEntitas
					];
				}
			
				// Populate the entitas section with data from the database
				foreach ($entitasData2 as $entitas2) {
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas2->AlmtPrshn,
						"kodeEntitas" => "7",
						"kodeJenisApi"=>"2",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"namaEntitas" => $entitas2->NmPrshn,
						"nibEntitas" => $entitas2->nibEntitas,
						"nomorIdentitas" => $entitas2->nomorIdentitas,
						"nomorIjinEntitas" => $entitas2->nomorIjinEntitas,
						"seriEntitas" => 7,
						"tanggalIjinEntitas" => $entitas2->tanggalIjinEntitas
					];
				
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas2->AlmtPrshn,
						"kodeEntitas" => "8",
						"kodeJenisApi"=>"2",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"namaEntitas" => $entitas2->NmPrshn,
						"nibEntitas" => $entitas2->nibEntitas,
						"nomorIdentitas" => $entitas2->nomorIdentitas,
						"nomorIjinEntitas" => $entitas2->nomorIjinEntitas,
						"seriEntitas" => 8,
						"tanggalIjinEntitas" => $entitas2->tanggalIjinEntitas
					];
				}
				

			} else if ($data->UrJnsDok == "BC 2.3") {
				$dokJns = "23";
				
			
				foreach ($entitasData2 as $entitas) {
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas->AlmtPrshn,
						"kodeEntitas" =>"3",
						"kodeJenisApi"=>"2",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"kodeNegara"=>"ID",
						"namaEntitas" => $entitas->NmPrshn,
						"nibEntitas" => $entitas->nibEntitas,
						"nomorIdentitas" => $entitas->nomorIdentitas,
						"nomorIjinEntitas" => $entitas->nomorIjinEntitas,
						"seriEntitas" => 3,
						"tanggalIjinEntitas" => $entitas->tanggalIjinEntitas
					];
				}
			
				// Populate the entitas section with data from the database
				foreach ($entitasData3 as $entitas3) {
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas3->AlmtPrshn,
						"kodeEntitas" => "5",
						"kodeJenisApi"=>"2",
								"kodeNegara"=>"ID",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"namaEntitas" => $entitas3->NmPrshn,
						"nibEntitas" => $entitas3->nibEntitas,
						"nomorIdentitas" => $entitas3->nomorIdentitas,
						"nomorIjinEntitas" => $entitas3->nomorIjinEntitas,
						"seriEntitas" => 5,
						"tanggalIjinEntitas" => $entitas3->tanggalIjinEntitas
					];
				}
			
				foreach ($entitasData2 as $entitas) {
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas->AlmtPrshn,
						"kodeEntitas" =>"7",
						"kodeJenisApi"=>"2",
								"kodeNegara"=>"ID",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"namaEntitas" => $entitas->NmPrshn,
						"nibEntitas" => $entitas->nibEntitas,
						"nomorIdentitas" => $entitas->nomorIdentitas,
						"nomorIjinEntitas" => $entitas->nomorIjinEntitas,
						"seriEntitas" => 7,
						"tanggalIjinEntitas" => $entitas->tanggalIjinEntitas
					];
				}

			} else if ($data->UrJnsDok == "BC 2.6.2") {
				$dokJns = "262";

				foreach ($entitasData2 as $entitas) {
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas->AlmtPrshn,
						"kodeEntitas" =>"3",
						"kodeJenisApi"=>"2",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"namaEntitas" => $entitas->NmPrshn,
						"nibEntitas" => $entitas->nibEntitas,
						"nomorIdentitas" => $entitas->nomorIdentitas,
						"nomorIjinEntitas" => $entitas->nomorIjinEntitas,
						"seriEntitas" => 3,
						"tanggalIjinEntitas" => $entitas->tanggalIjinEntitas
					];
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas->AlmtPrshn,
						"kodeEntitas" => "7",
						"kodeJenisApi"=>"2",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"namaEntitas" => $entitas->NmPrshn,
						"nibEntitas" => $entitas->nibEntitas,
						"nomorIdentitas" => $entitas->nomorIdentitas,
						"nomorIjinEntitas" => $entitas->nomorIjinEntitas,
						"seriEntitas" => 7,
						"tanggalIjinEntitas" => $entitas->tanggalIjinEntitas
					];
				}
			
				// Populate the entitas section with data from the database
				foreach ($entitasData3 as $entitas3) {
			
				
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas3->AlmtPrshn,
						"kodeEntitas" => "9",
						"kodeJenisApi"=>"2",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"namaEntitas" => $entitas3->NmPrshn,
						"nibEntitas" => $entitas3->nibEntitas,
						"nomorIdentitas" => $entitas3->nomorIdentitas,
						"nomorIjinEntitas" => $entitas3->nomorIjinEntitas,
						"seriEntitas" => 9,
						"tanggalIjinEntitas" => $entitas3->tanggalIjinEntitas
					];
				}
			} else {
				$dokJns = "40";
				
			
				foreach ($entitasData2 as $entitas) {
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas->AlmtPrshn,
						"kodeEntitas" =>"3",
						"kodeJenisApi"=>"2",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"namaEntitas" => $entitas->NmPrshn,
						"nibEntitas" => $entitas->nibEntitas,
						"nomorIdentitas" => $entitas->nomorIdentitas,
						"nomorIjinEntitas" => $entitas->nomorIjinEntitas,
						"seriEntitas" => 3,
						"tanggalIjinEntitas" =>$entitas->tanggalIjinEntitas
					];
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas->AlmtPrshn,
						"kodeEntitas" => "7",
						"kodeJenisApi"=>"2",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"namaEntitas" => $entitas->NmPrshn,
						"nibEntitas" => $entitas->nibEntitas,
						"nomorIdentitas" => $entitas->nomorIdentitas,
						"nomorIjinEntitas" => $entitas->nomorIjinEntitas,
						"seriEntitas" => 7,
						"tanggalIjinEntitas" =>$entitas->tanggalIjinEntitas
					];
				}
			
				// Populate the entitas section with data from the database
				foreach ($entitasData3 as $entitas3) {
			
				
					$jsonData["entitas"][] = [
						"alamatEntitas" => $entitas3->AlmtPrshn,
						"kodeEntitas" => "9",
						"kodeJenisApi"=>"2",
						"kodeJenisIdentitas" => "6",
						"kodeStatus"=>"5",
						"namaEntitas" => $entitas3->NmPrshn,
						"nibEntitas" => $entitas3->nibEntitas,
						"nomorIdentitas" => $entitas3->nomorIdentitas,
						"nomorIjinEntitas" => $entitas3->nomorIjinEntitas,
						"seriEntitas" => 9,
						"tanggalIjinEntitas" =>$entitas3->tanggalIjinEntitas
					];
				}
			}
		
	
			// Populate the barang section
			if (!empty($dataHd)) {
				$rowNum = 1;

				foreach ($dataHd["rows"] as $row) {
					$bahanBaku = [];
					//$bahanBakuData = $this->mdl->getBahanBakuData($row->KdBarang); // Fetch Bahan Baku data for each item
					// foreach ($bahanBakuData as $bahanRow) {
					 // // Add Bahan Baku data to the array 
					 // $bahanBaku[] = [ 
					 // "cif" => 1234567, 
					 // "cifRupiah" => 0,
					  // "hargaPenyerahan" => 1234567, 
					  // "hargaPerolehan" => 0, 
					  // "jumlahSatuan" => 10.00, 
					  // "kodeSatuanBarang" => "PCE", 
					  // "kodeAsalBahanBaku" => "0", 
					  // "kodeBarang" => "BRG123",
					   // "kodeDokAsal" => "27",
					    // "kodeKantor" => "050900", 
						// "merkBarang" => "",
						 // "ndpbm" => 0, 
						 // "netto" => 131, 
						 // "nomorAjuDokAsal" => $data->NoAju, 
						 // "nomorDaftarDokAsal" => "123456", 
						 // "posTarif" => "85299099",
						  // "seriBahanBaku" => 1, 
						  // "seriBarang" => 1, 
						  // "seriBarangDokAsal" => 1, 
						  // "seriIjin" => 0, 
						  // "spesifikasiLainBarang" => "", 
						  // "tanggalDaftarDokAsal" => dmys2ymd($data->matin_date), 
						  // "tipeBarang" => "", // "ukuranBarang" => "", 
						  // "uraianBarang" => "COVER", 
						  // "nilaiJasa" => 0 
						  // ]; 
						  // } 
						  // Populate the "barang" section with raw materials (bahan baku)
					// Populate the "barang" section with raw materials (bahan baku)
					if ($data->UrJnsDok == "BC 2.7") {
					$jsonData["barang"][] = [
						"cif" => (int)  0,
						"cifRupiah" => 0,
						"hargaEkspor" => 0,
						"hargaPenyerahan" =>(int) $row->price,
						"isiPerKemasan" => 0,
						"jumlahSatuan" => (int)  $row->qty,
						"kodeBarang" => $row->KdBarang,
						"kodeDokumen" => $dokJns,
						"kodeSatuanBarang" => $row->Sat,
						"merk" => "",
						"netto" => (int) $row->weight,
						"nilaiBarang" => 0,
						"posTarif" => "0",
						"seriBarang" => (string)$rowNum,
						"spesifikasiLain" => "",
						"tipe" => "",
						"ukuran" => "",
						"uraian" => $row->NmBarang,
						"hargaPerolehan" => (int)$row->price,
						"kodeAsalBahanBaku" => $kdBrngAsal,
						"ndpbm" => 0,
						"uangMuka" => 0,
						"nilaiJasa" => 0,
						"bahanBaku" => $bahanBaku 
						
					
					];
				}	if ($data->UrJnsDok == "BC 2.6.2") {
					$jsonData["barang"][] = [
						"cif" => (int)  0,
						"cifRupiah" => 0,
						"hargaEkspor" => 0,
						"hargaPenyerahan" =>(int) $row->price,
						"jumlahKemasan" => (int)  $row->qty,
						"isiPerKemasan" => 0,
						"jumlahSatuan" => (int)  $row->qty,
						"kodeBarang" => $row->KdBarang,
						"kodeDokumen" => $dokJns,
						"kodeSatuanBarang" => $row->Sat,
						"merk" => "",
						"netto" => (int) $row->weight,
						"nilaiBarang" => 0,
						"posTarif" => "0",
						"seriBarang" => (int)$rowNum,
						"spesifikasiLain" => "",
						"tipe" => "",
						"ukuran" => "",
						"uraian" => $row->NmBarang,
						"hargaPerolehan" => (int)$row->price,
						"kodeAsalBarang" =>"3",
						"kodeAsalBahanBaku" => $kdBrngAsal,
						"kodeJenisKemasan"=> "1A",
						"kodeNegaraAsal" => "ID",
						"ndpbm" => 0,
						"uangMuka" => 0,
						"nilaiJasa" => 0,
						"bahanBaku" => $bahanBaku 
						
					
					];
				}	if ($data->UrJnsDok == "BC 2.3") {
						$dokJns = "23";
					$jsonData["barang"][] = [
						"cif" => (int)  0,
						"asuransi"=>0,
						"diskon"=>0,
						"fob"=>0,
						"freight"=>0,
						"kodeKategoriBarang"=>"23",

						"cifRupiah" => 0,
						"hargaEkspor" => 0,
						"hargaSatuan"=>(int) $row->price,
						"hargaPenyerahan" =>(int) $row->price,
						"jumlahKemasan" => (int)  $row->qty,
						"kodeJenisKemasan"=>"1D",
						"kodeNegaraAsal"=>"ID",
						"kodeAsalBahanBaku"=> 1,
						"kodePerhitungan"=>"0",
						"nilaiTambah"=> 0,
					  "barangTarif"=> [
        [
            "kodeJenisTarif"=> "1",
            "jumlahSatuan"=> 0,
            "kodeFasilitasTarif"=> "01",
            "kodeSatuanBarang"=> "KG",
            "kodeJenisPungutan"=> "BM",
            "nilaiBayar"=> 0,
            "nilaiFasilitas"=> 0.00,
            "nilaiSudahDilunasi"=> 0,
            "seriBarang"=> $rowNum,
            "tarif"=> 0.00,
            "tarifFasilitas"=> 0.00
					  ],
        [
            "kodeJenisTarif"=> "1",
            "jumlahSatuan"=> 0,
            "kodeFasilitasTarif"=> "02",
            "kodeSatuanBarang"=> "KG",
            "kodeJenisPungutan"=> "PPH",
            "nilaiBayar"=> 0,
            "nilaiFasilitas"=> 0.00,
            "nilaiSudahDilunasi"=> 0.00,
            "seriBarang"=> $rowNum,
            "tarif"=> 0,
            "tarifFasilitas"=> 0.00
					],
        [
            "kodeJenisTarif"=> "1",
            "jumlahSatuan"=> 0,
            "kodeFasilitasTarif"=> "03",
            "kodeSatuanBarang"=> "KG",
            "kodeJenisPungutan"=> "PPN",
            "nilaiBayar"=> 0.00,
            "nilaiFasilitas"=> 0.00,
            "nilaiSudahDilunasi"=> 0.00,
            "seriBarang"=> $rowNum,
            "tarif"=> 0.00,
            "tarifFasilitas"=> 0.00
		],
        [
            "kodeJenisTarif"=> "2",
            "jumlahSatuan"=> 2,
            "kodeFasilitasTarif"=> "04",
            "kodeJenisPungutan"=> "PPNBM",
            "nilaiBayar"=> 0.00,
            "seriBarang"=> $rowNum,
            "tarif"=> 0.00,
            "tarifFasilitas"=> 0.00,
            "nilaiFasilitas"=> 0.00
		]
    ],
						    "barangDokumen"=> [
                [
                    "kodeDokumen"=> "740",
                    "nomorDokumen"=> "INV-2023-001",
                    "tanggalDokumen"=> "2023-05-15"
				]
            ],
						"isiPerKemasan" => 0,
						"jumlahSatuan" => (int)  $row->qty,
						"kodeBarang" => $row->KdBarang,
						"kodeDokumen" => $dokJns,
						"kodeSatuanBarang" => $row->Sat,
						"merk" => "",
						"netto" => (int) $row->weight,
						"nilaiBarang" => 0,
						"posTarif" => "0",
						"seriBarang" => $rowNum,
						"spesifikasiLain" => "",
						"tipe" => "",
						"ukuran" => "",
						"uraian" => $row->NmBarang,
						"hargaPerolehan" => (int)$row->price,
						"kodeAsalBahanBaku" => $kdBrngAsal,
						"ndpbm" => 0,
						"uangMuka" => 0,
						"nilaiJasa" => 0,
						"bahanBaku" => $bahanBaku 
						
					
					];
				}else if ($data->UrJnsDok == "BC 4.0") {
					$priceString_ = $row->price; 
					$price_ = floatval($priceString_); 
					$nilaiFasi = $price_ * 0.11;
					
					$jsonData["barang"][] = [
						"asuransi" => 0.00,
						"bruto" => 0,
						"cif" =>(int) 0.00,
						"diskon" => 0.00,
						"hargaEkspor" => 0.00,
						"hargaPenyerahan" => (int) $row->price,
						"hargaSatuan" => 0.00,
						"isiPerKemasan" => 0,
						"jumlahKemasan" => 0.00,
						"jumlahRealisasi" => 0.00,
						"jumlahSatuan" =>  (int)  $row->qty,
						"kodeBarang" =>$row->KdBarang,
						"kodeDokumen" => "40",
						"kodeJenisKemasan" => "-",
						"kodeSatuanBarang" => $row->Sat,
						"merk" => "-",
						"netto" =>(int) $row->weight,
						"nilaiBarang" => 0.00,
						"posTarif" => "0",
						"seriBarang" => $rowNum,
						"spesifikasiLain" => "-",
						"tipe" => "-",
						"ukuran" => "",
						"uraian" =>  $row->KdBarang,
						"volume" => 0,
						"cifRupiah" => 0.00,
						"hargaPerolehan" => 0.00,
						"kodeAsalBahanBaku" => "1",
						"ndpbm" => 0.00,
						"uangMuka" => 0.00,
						"nilaiJasa" => 0,
						"barangTarif" => [
							[
								"kodeJenisTarif" => "1",
								"jumlahSatuan" =>  (int)  $row->qty,
								"kodeFasilitasTarif" => "3",
								"kodeSatuanBarang" => $row->Sat,
								"nilaiBayar" => 0,
								"nilaiFasilitas" => $nilaiFasi,
								"nilaiSudahDilunasi" => 0.00,
								"seriBarang" => 1,
								"tarif" => 11.00,
								"tarifFasilitas" => 100.00,
								"kodeJenisPungutan" => "PPN"
							]
						]
					];
					
				} 

					$rowNum++;

				}
			}
	
			

			// Send the data to Ceisa via a webhook
			$jsonString = json_encode($jsonData, JSON_PRETTY_PRINT);
			$url = "https://apis-gw.beacukai.go.id/openapi/document";
			// $url = "https://webhook.site/f62f27fe-e10c-4aa2-97aa-fa908ef8c3e6";
			
			$success = $this->mdl->sendToCeisa($jsonString, $url,$id);
			if ($success !="Failed to get token." ){			
					
				$bol=true;
				$msg=$success;
			} else {
				$bol=false;
				$msg=$success;
			}
			echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	} }
}

function formExcel2() {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_FILES['excelFile2'])) {
            $file = $_FILES['excelFile2']['tmp_name'];
            $this->load->library('excel'); // Load library excelnya
            $excel = PHPExcel_IOFactory::load($file);

            // Check if sheet exists
            $dataSheet = $excel->getSheetByName('Sheet1');
            
            if (!$dataSheet) {
                echo json_encode(['status' => 'error', 'message' => 'Missing sheet: Sheet1']);
                return;
            }
            
            // Extract data from sheet
            $excelData = $dataSheet->toArray(null, true, true, true);
            
            // Initialize counters
            $incoming_count = 0;
            $outgoing_count = 0;
            $errors = [];
            
            // Start database transaction
            $this->db->trans_start();
            
            try {
                // Group rows by document number
                $groupedData = [];
                foreach ($excelData as $key => $row) {
                    if ($key === 1) continue; // Skip header row
                    
                    $docNo = $row['L']; // Material Document number
                    if (!isset($groupedData[$docNo])) {
                        $groupedData[$docNo] = [];
                    }
                    $groupedData[$docNo][] = $row;
                }
                
                // Process each document group
                foreach ($groupedData as $docNo => $rows) {
                    // Use first row for header information
                    $firstRow = $rows[0];
                    $qty = $firstRow['E'];
                    $is_incoming = ($qty > 0);
                    $current_date = date('Y-m-d H:i:s');
                    $document_date = date('Y-m-d', strtotime($firstRow['M']));
                    $total_qty = 0;
                    $total_amount = 0;
                    
                    // Calculate totals
                    foreach ($rows as $row) {
                        $total_qty += abs($row['E']);
                        $total_amount += abs($row['Q']);
                    }
                    
                    if ($is_incoming) {
                        // ========== INCOMING HEADER ==========
                        $header_data = [
                            'matin_type' => 0, // Movement Type
                            'matin_no' => $docNo, // Material Document
                            'matin_date' => $document_date,
                            'currency' => $firstRow['R'],
                            'po_no' => $firstRow['B'], // Order
                            'supplier' => $firstRow['W'],
                            'KdJnsDok' => $firstRow['C'], // Material
                            'tot_qty' => $total_qty,
                            'tot_weight' => $total_qty, // Assuming weight = quantity
                            'tot_amount' => $total_amount,
                            'Bruto' => $total_qty,
                            'HargaSerah' => $total_amount,
                            'Netto' => $total_qty,
                            'partial' => 1,
                            'kodeKantor' => $firstRow['J'], // Plant
                            'kodeTps' => $firstRow['I'], // Storage Location
                            'namaTtd' => $firstRow['K'], // User Name
                            'created_at' => $current_date,
                            'in' => 'yes',
                            'locked' => 'no',
                            // Default values for required fields
                            'mat_type' => 0,
                            'kurs' => 1,
                            'po_id' => 0,
                            'wh_id' => 0,
                            'TgTTD' => $document_date,
                            'JmlBarang' => count($rows) // Number of detail items
                        ];
                        
                        $this->db->insert('mat_inchdr_sub', $header_data);
                        $header_id = $this->db->insert_id();
                        
                        // ========== INCOMING DETAILS ==========
                        $child_no = 1;
                        foreach ($rows as $row) {
                            $detail_qty = abs($row['E']);
                            $detail_amount = abs($row['Q']);
                            
                            $detail_data = [
                                'matin_id' => $header_id,
                                'child_no' => $child_no,
                                'mat_id' => $row['C'], // Material
                                'weight' => $detail_qty,
                                'Dqty' => $detail_qty,
                                'qty' => $detail_qty,
                                'price' => ($detail_amount && $detail_qty) ? $detail_amount/$detail_qty : 0,
                                'poqty' => $detail_qty,
                                'balance' => $detail_qty,
                                'has_edited' => 'no',
                                'all_in' => 'no',
                                'locked' => 'no',
                                'status' => '1'
                            ];
                            
                            $this->db->insert('mat_incdet_sub', $detail_data);
                            $child_no++;
                            $incoming_count++;
                        }
                        
                    } else {    }
                }
                
                // Complete transaction
                $this->db->trans_complete();
                
                if ($this->db->trans_status() === FALSE) {
                    throw new Exception('Database transaction failed');
                }
                
                $response = [
                    'status' => 'success',
                    'message' => 'Data imported successfully',
                    'incoming_records' => $incoming_count,
                    'outgoing_records' => $outgoing_count,
                    'incoming_documents' => count(array_filter($groupedData, function($rows) {
                        return $rows[0]['E'] > 0;
                    })),
                    'outgoing_documents' => count(array_filter($groupedData, function($rows) {
                        return $rows[0]['E'] <= 0;
                    }))
                ];
                
            } catch (Exception $e) {
                $this->db->trans_rollback();
                $response = [
                    'status' => 'error',
                    'message' => 'Error: ' . $e->getMessage(),
                    'errors' => $errors
                ];
            }
            
            echo json_encode($response);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No file uploaded']);
        }
    }
}
function formExcel() {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_FILES['excelFile'])) {
            $file = $_FILES['excelFile']['tmp_name'];
			$this->load->library('excel');//Load library excelnya
            $excel = PHPExcel_IOFactory::load($file);
            
           // Check if sheets exist
		   $missingSheets = [];
		   $headerSheet = $excel->getSheetByName('HEADER');
		   $barangSheet = $excel->getSheetByName('BARANG');
		   $entitasSheet = $excel->getSheetByName('ENTITAS');
		   $dokumenSheet = $excel->getSheetByName('DOKUMEN');
		   $pengangkutSheet = $excel->getSheetByName('PENGANGKUT');
		   $kemasanSheet = $excel->getSheetByName('KEMASAN');
		   $kontainerSheet = $excel->getSheetByName('KONTAINER');

		   if (!$headerSheet) $missingSheets[] = 'HEADER';
		   if (!$barangSheet) $missingSheets[] = 'BARANG';
		   if (!$entitasSheet) $missingSheets[] = 'ENTITAS';
		   if (!$dokumenSheet) $missingSheets[] = 'DOKUMEN';
		   if (!$pengangkutSheet) $missingSheets[] = 'PENGANGKUT';
		   if (!$kemasanSheet) $missingSheets[] = 'KEMASAN';
		   if (!$kontainerSheet) $missingSheets[] = 'KONTAINER';

		   if (!empty($missingSheets)) {
			   echo json_encode(['status' => 'error', 'message' => 'Missing sheets: ' . implode(', ', $missingSheets)]);
			   return;
		   }
            // Extract data from sheets
            $headerData = $headerSheet->toArray(null, true, true, true);
            $barangData = $barangSheet->toArray(null, true, true, true);
            $entitasData = $entitasSheet->toArray(null, true, true, true);
			$dokumenData = $dokumenSheet->toArray(null, true, true, true);
			$pengangkutData = $pengangkutSheet->toArray(null, true, true, true);
			$kemasanData = $kemasanSheet->toArray(null, true, true, true);
			$kontainerData = $kontainerSheet->toArray(null, true, true, true);

            // Clean and process data if necessary
            $headerData = array_filter($headerData);
            $barangData = array_filter($barangData);
            $entitasData = array_filter($entitasData);
			$dokumenData = array_filter($dokumenData);
			$pengangkutData = array_filter($pengangkutData);
			$kemasanData = array_filter($kemasanData);
			$kontainerData = array_filter($kontainerData);

		//
		$form_data2	= [];
		$form_data3	= [];
		$form_data = [];
		$getPodata = [];
		$new_matin_no = "";
			

		
		foreach ($headerData as $key => $row) {
			if ($key !== 1) { // Skip header row
				$form_data['NoAju'][] = $row['A'];
				$form_data['tglAju'][] = $row['AK'];
				if ($row['B'] == 23) {
					$kdJnsDok = '1';
				} elseif ($row['B'] == 24) {
					$kdJnsDok = '2';
				} elseif ($row['B'] == 25) {
					$kdJnsDok = '3';
				} elseif ($row['B'] == 261) {
					$kdJnsDok = '4';
				} elseif ($row['B'] == 262) {
					$kdJnsDok = '5';
				} elseif ($row['B'] == 27) {
					$kdJnsDok = '6';
				} elseif ($row['B'] == 30) {
					$kdJnsDok = '7';
				} elseif ($row['B'] == 40) {
					$kdJnsDok = '8';
				} elseif ($row['B'] == 41) {
					$kdJnsDok = '9';
				} elseif ($row['B'] == 270) {
					$kdJnsDok = '10';
				} else {
					$kdJnsDok = 'Unknown'; // Handle cases where the value doesn't match
				}
				$form_data['KdJnsDok'][] = $kdJnsDok;
				$form_data['kodeKantor'][] = $row['C'];
				$form_data['noBc'][] = $row['CP'];
				$form_data['kodeKantorTujuan'][] = $row['D'];
				$form_data['tot_amount'][] = $row['BL'];
				$form_data['HargaSerah'][] = $row['BL'];
				$form_data['Netto'][] = $row['CB'];
				$form_data['Bruto'][] = $row['CC'];
				$form_data['currency'][] = $row['CI'];
				$form_data['tot_weight'][] = $row['CD'];
				$form_data['matin_type'][] = 1;
				
				$form_data['matin_date'][] = $row['CQ'];
				$form_data['TgTTD'][] = $row['CF'];
				$form_data['kotaTtd'][] = $row['CE'];
				$form_data['namaTtd'][] = $row['CG'];
				$form_data['jabatanTtd'][] = $row['CH'];
				$form_data['kodeTps'][] = $row['AT'];
				$form_data['cif'][] = $row['BU'];
				$form_data['plbMuat'][] = $row['AO'];
				$form_data['PlbBongkar'][] = $row['AN'];
			}
		}
	
		foreach ($pengangkutData as $key => $row) {
			if ($key !== 1) { // Skip header row
				$form_data['noPengangkut'][] = $row['E'];
				$form_data['namaPengangkut'][] = $row['D'];
			}
		}
		
		foreach ($kemasanData as $key => $row) {
			if ($key !== 1) { // Skip header row
				$form_data['packing'][] = $row['C'];
			}
		}
		
	
		
		foreach ($dokumenData as $key => $row) {
			if ($key !== 1) { // Skip header row
				if ($row["C"] == "315") {
					$form_data['tglPo'][] = $row['E'];
					$form_data['po_no'][] = $row['D'];
					$getPodata = $this->mdl->getPoDetAll($row["D"]);
				}
				if ($row["C"] == "380") {
					$form_data['tglInv'][] = $row['E'];
					$form_data['supl_inv'][] = $row['D'];
				}
				if ($row["C"] == "705") {
					$form_data['tglBl'][] = $row['E'];
					$form_data['noBl'][] = $row['D'];
				}
			}
		}


	
	if (empty($getPodata[1]->po_id) || $getPodata[1]->po_id == null ){
	
		$bol=false;
					$msg="tidak dapat menemukan PO!.";
					echo json_encode(array('success'=>$bol,'msg'=>$msg)); 
	}else{
		// Ensure $getPodata is set and contains the expected data
		if (!empty($getPodata) && isset($getPodata[1]->supplier)) {
			$form_data['supplier'] = $getPodata[1]->supplier;
		} else {
			$form_data['supplier'] = null; // Handle the case when supplier data is not available
		}
		if (!empty($getPodata) && isset($getPodata[1]->po_id)) {
			$form_data['po_id'] = $getPodata[1]->po_id;
		} else {
			$form_data['po_id'] = null; // Handle the case when supplier data is not available
		}
		$data_to_insert = [];

					// Query to get the latest matin_no
					$query = $this->db->select('matin_no')
					->order_by('matin_id', 'DESC')
					->limit(1)
					->get('mat_inchdr_sub');
		
					if ($query->num_rows() > 0) {
					$latest_matin_no = $query->row()->matin_no;
		
					// Extract the numeric part of matin_no and increment it
					$latest_matin_no_int = intval($latest_matin_no); // Convert to integer
					$new_matin_no_int = $latest_matin_no_int + 1; // Increment by 1
		
					// Pad the incremented value with leading zeros to maintain the format
					$new_matin_no = str_pad($new_matin_no_int, strlen($latest_matin_no), '0', STR_PAD_LEFT);
		
					// Debugging: Check the new matin_no
				
				
					} else {
					// Handle the case when there is no existing data
					$new_matin_no = str_pad(1, 6, '0', STR_PAD_LEFT); // Start from "000001"
		
					// Debugging: Check the new matin_no when no existing data
				
				
					}
				
		// Insert each set of values into the database
		for ($i = 0; $i < count($form_data['NoAju']); $i++) {
			$data_to_insert = [
				'NoAju' => $form_data['NoAju'][$i],
				'tgAju' => $form_data['tglAju'][$i],
				'KdJnsDok' => $form_data['KdJnsDok'][$i],
				'kodeKantor' => $form_data['kodeKantor'][$i],
				'noBc' => $form_data['noBc'][$i],
				'kodeKantorTujuan' => $form_data['kodeKantorTujuan'][$i],
				'tot_amount' => $form_data['tot_amount'][$i],
				'HargaSerah' => $form_data['HargaSerah'][$i],
				'Netto' => $form_data['Netto'][$i],
				'Bruto' => $form_data['Bruto'][$i],
				'currency' => $form_data['currency'][$i],
				'tot_weight' => $form_data['tot_weight'][$i],
				'matin_type' => $form_data['matin_type'][$i],
				'matin_no' =>  $new_matin_no,
				'matin_date' => $form_data['matin_date'][$i],
				'TgTTD' => $form_data['TgTTD'][$i],
				'kotaTtd' => $form_data['kotaTtd'][$i],
				'namaTtd' => $form_data['namaTtd'][$i],
				'jabatanTtd' => $form_data['jabatanTtd'][$i],
				'kodeTps' => $form_data['kodeTps'][$i],
				'cif' => $form_data['cif'][$i],
				'plbMuat' => $form_data['plbMuat'][$i],
				'PlbBongkar' => $form_data['PlbBongkar'][$i],
				'noPengangkut' => $form_data['noPengangkut'][$i],
				'namaPengangkut' => $form_data['namaPengangkut'][$i],
				'packing' => $form_data['packing'][$i],
				'tglInv' => isset($form_data['tglInv'][$i]) ? $form_data['tglInv'][$i] : null,
				'supl_inv' => isset($form_data['supl_inv'][$i]) ? $form_data['supl_inv'][$i] : null,
				'tglPo' => isset($form_data['tglPo'][$i]) ? $form_data['tglPo'][$i] : null,
				'po_no' => isset($form_data['po_no'][$i]) ? $form_data['po_no'][$i] : null,
				'tglBl' => isset($form_data['tglBl'][$i]) ? $form_data['tglBl'][$i] : null,
				'noBl' => isset($form_data['noBl'][$i]) ? $form_data['noBl'][$i] : null,
				'supplier' => $form_data['supplier'],
				'po_id' => $form_data['po_id'],
				'mat_type' => $this->mat_type
			];
		
		}

		$this->add($data_to_insert);
		$getCountPO= 0;
			$po_id = $data_to_insert['po_id'];
			$key = $data_to_insert['matin_no'];
			$key2 = $data_to_insert['po_no'];
			if($po_id != ""){
				$getCountPO = $this->mdl->getCountPO($po_id);
				foreach ($getCountPO as $getCountPO) {
					$countPO = $getCountPO->po_id;
				}			
			}else{
				$getCountPO1 = $this->mdl->getCountPO1($key);
				foreach ($getCountPO1 as $getCountPO1) {
					$countPO = $getCountPO1->matin_no;
				}			
			}		
			$getPartial = $this->mdl->getPartial2($key2);
			foreach ($getPartial as $getPartial) {
				$getPart = $getPartial->partial;
			}			
		
			if($countPO <= 1){
			
				$getPodet = $this->mdl->getPodet($key);
				
				// ARRAY DETAIL INCOMING -ir
				
				$child_no = 1;
				foreach ($getPodet as $getPodet) {
					$dataDet = array(
						'matin_id'	=> $getPodet->matin_id,
						'child_no'	=> $child_no,
						'mat_id'		=> $getPodet->mat_id,
						'weight'		=> $getPodet->netto,
						'poqty'			=> $getPodet->qty,
						'balance'		=> $getPodet->qty,
						'qty'				=> 0,
						'price'			=> $getPodet->price
					);
					$child_no++;
					
					// INSERT DETAIL INCOMING -ir
					$this->mdl->addDet($dataDet);
				}

					foreach ($kontainerData as $key => $row) {
						if ($key !== 1) { // Skip header row
							$form_data2['NOMOR_AJU'][] = $row['A'];
							$form_data2['SERI'][] = $row['B'];
							$form_data2['NOMOR_KONTAINER'][] = $row['C'];
							$form_data2['KODE_UKURAN_KONTAINER'][] = $row['D'];
							$form_data2['KODE_JENIS_KONTAINER'][] = $row['E'];
							$form_data2['KODE_TIPE_KONTAINER'][] = $row['F'];
							$form_data2['MATIN_ID'][] = $getPodet->matin_id;
						}
					}

					foreach ($dokumenData as $key => $row) {
						if ($key !== 1) {
						$form_data3['seri_dok'][]=$row['C'];
						$form_data3['no_dok'][]=$row['B'];
						$form_data3['tgl_dok'][]=$row['E'];
						$form_data3['dok_no'][]=$row['D'];
						$form_data3['matin_no'][]=$getPodet->matin_id;
						}
						}
						$this->mdl->addDetP($form_data2,$form_data3);

			} else if($countPO > 1) {
				$child_no = 1;
				
				// ARRAY DETAIL INCOMING -ir
				$getMatin = $this->mdl->getMatin($key);
				foreach ($getMatin as $getMatin) {
					$matin_id = $getMatin->matin_id;
				}
				
				$getPodet = $this->mdl->getPodet2($key2,$getPart);
				foreach ($getPodet as $getPodet) {
					if($getPodet->balance == 0 && $getPodet->all_in == "yes") {
						$has_edited="yes";
						$all_in="yes";
						$status="0";
					} else {
						$has_edited="no";
						$all_in="no";
						$status="1";
					} 
					$dataDet = array(
						'matin_id' 	=> $matin_id,
						'child_no'	=> $child_no,
						'mat_id'		=> $getPodet->mat_id,
						'weight'		=> $getPart,
						'poqty'			=> $getPodet->poqty,
						'qty'			=> 0,
						'Dqty'			=> $getPodet->Dqty,
						'balance'		=> $getPodet->balance,
						'price'			=> $getPodet->price,
						'has_edited'=> $has_edited,
						'all_in'		=> $all_in,
						'status'		=> $status
					);
					$child_no++;
					
					// INSERT DETAIL INCOMING -ir
					$success = $this->mdl->addDet($dataDet);

					foreach ($kontainerData as $key => $row) {
						if ($key !== 1) { // Skip header row
							$form_data2['NOMOR_AJU'][] = $row['A'];
							$form_data2['SERI'][] = $row['B'];
							$form_data2['NOMOR_KONTAINER'][] = $row['C'];
							$form_data2['KODE_UKURAN_KONTAINER'][] = $row['D'];
							$form_data2['KODE_TIPE_KONTAINER'][] = $row['F'];
							$form_data2['KODE_JENIS_KONTAINER'][] = $row['E'];
							$form_data2['MATIN_ID'][] = $getPodet->matin_id;
						}
					}
	
					foreach ($dokumenData as $key => $row) {
						if ($key !== 1) {
						$form_data3['seri_dok'][]=$row['C'];
						$form_data3['no_dok'][]=$row['B'];
						$form_data3['tgl_dok'][]=$row['E'];
						$form_data3['dok_no'][]=$row['D'];
						$form_data3['matin_no'][]=$getPodet->matin_id;
					}
						}
						$this->mdl->addDetP($form_data2,$form_data3);
				}
				if ($success){				
					$id					= $matin_id;	
					$partial		= $getPodet->partial;

					// UPDATE +1 PARTIAL ON NEW HEADER --IR
					$updatePartial = array(
						'partial'			=> $getPodet->partial + 1
					);
					$this->mdl->editPartial($updatePartial, $id);

					// LOCK PREVIOUS PARTIAL WHEN AFTER ADDING HEADER --IR
					$updateLocked = array(
						'locked'			=> 'yes'
					);
					$this->mdl->editLocked($updateLocked, $po_id, $partial);
				} else {
					$bol=false;
					$msg="Item di Incoming ini sudah masuk semua!.";
				}
			}
        } }
    }
}	
	function addBarScan(){
		$form_data = $this->input->post();
		$mat_id=substr($form_data,0,14);
		$qty=substr($form_data,14,5);
		
		$pk=array(
			'matin_id' => $form_data[$this->pk]
			);
			
		$this->addDet($form_data);	
	}
	
	function getCek(){
		$id=$_REQUEST['id'];
		$pk=$id['po_no'];
		$pk2=$id['matin_id'];
		$data = array(
			'rs' 	=> 	$this->mdl->cariPartial($pk,$pk2)
		);
		echo json_encode($data);
	}

	public function getLatestDoc() {
		$data = $this->mdl->getAndReserveLatestDoc();
	
		// Check for errors
		if (isset($data['error'])) {
			echo json_encode(['error' => $data['error']]);
		} else {
			echo json_encode($data);
		}
	}
	
	
	function aksi($cmd){
		ini_set('memory_limit', '-1');
		
		$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
		$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 99999;	
		$key = $_REQUEST["q"];
		
		$data = array(
			'rs' 	=> 	$this->mdl->getHdrDet($page,$rows,$key)
		);	
		
		if ($cmd=='excel'){
			$filename =$this->title.date(Ymd).".xls";
			header('Content-type: application/ms-excel');
			header('Content-Disposition: attachment; filename='.$filename);
		}
		
		$this->load->view($this->pmodul.'/print',$data);
		
	}
	
	function slip($id)
	{
		$data = array(
			'cmpy_nm'=>$this->session->userdata('nm_cmpy'),
			'rhdr' 	=> 	$this->mdl->getRow($id),
			'rdet' 	=> 	$this->mdl->getDetAll($id)
		);
		
		$this->load->library('pdf');
		$this->load->view($this->pmodul.'/slip',$data);
		
	}
	
	function barcode($id)
	{
		$data = array(
			'rhdr' 	=> 	$this->mdl->getRow($id)
		);
		
		$this->load->library('pdf');
		$this->load->view($this->pmodul.'/slip2',$data);
		
	}
	function excelCeisa($id){
		$rh =	$this->mdl->getRow($id);
		$rsd = $this->mdl->getDetAll($id);
		$inputFileName = FCPATH . '/template/BC27K.xls';
		$inputFileType = IOFactory::identify($inputFileName);
		$reader = IOFactory::createReader($inputFileType);
		$spreadsheet = $reader->load($inputFileName);
		$writer = IOFactory::createWriter($spreadsheet, $inputFileType);
		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$spreadsheet->setActiveSheetIndexByName('Header');
		$FNoAju = '150327005860'.$rh->F2TgAju.$rh->NoAju;
		$spreadsheet->getActiveSheet()->setCellValue('A2', $FNoAju);
		$spreadsheet->getActiveSheet()->setCellValue('T2', $rh->Bruto);
		$spreadsheet->getActiveSheet()->setCellValue('AD2', $rh->HargaSerah);
		$spreadsheet->getActiveSheet()->setCellValue('AN2', $rh->JmlBarang);
		$spreadsheet->getActiveSheet()->setCellValue('CT2', $rh->Netto);
		$spreadsheet->getActiveSheet()->setCellValue('DT2', $rh->FTgTTD);
		$y = 2;
        $y_bb = 2;
		$seri_barang = 1;
		foreach($rsd as $rd){
			$spreadsheet->setActiveSheetIndexByName('Barang');
			$spreadsheet->getActiveSheet()->setCellValue('A'.$y, $FNoAju);
			$spreadsheet->getActiveSheet()->setCellValue('B'.$y, $seri_barang);
			$spreadsheet->getActiveSheet()->setCellValue('L'.$y, $rd->amount);
			$spreadsheet->getActiveSheet()->setCellValue('O'.$y, $rd->JmlMat);
			$spreadsheet->getActiveSheet()->setCellValue('Q'.$y, $rd->qty);
			$spreadsheet->getActiveSheet()->setCellValue('U'.$y, $rd->mat_id);
			$spreadsheet->getActiveSheet()->setCellValue('AB'.$y, $rd->Sat);
			$spreadsheet->getActiveSheet()->setCellValue('AG'.$y, '');
			$spreadsheet->getActiveSheet()->setCellValue('AK'.$y, '');
			$spreadsheet->getActiveSheet()->setCellValue('AQ'.$y, $rd->NmBarang);
			$spreadsheet->setActiveSheetIndexByName('BahanBaku');
			$rsb = $this->mdl->getBomAll($rd->mat_id, $rh->ref_id);
			
			foreach($rsb as $rb){
				$no_aju_dok_asal = '150327005860'.$rb->FTgAju.$rb->NoAju;
				$seri_bb = 1;
				$JmlSatuan = $rb->qty * $rd->qty;
				$spreadsheet->getActiveSheet()->setCellValue('A'.$y_bb, $FNoAju);
				$spreadsheet->getActiveSheet()->setCellValue('B'.$y_bb, $seri_barang);
				$spreadsheet->getActiveSheet()->setCellValue('C'.$y_bb, $seri_bb);
				$spreadsheet->getActiveSheet()->setCellValue('H'.$y_bb, $rb->Sat);
				$spreadsheet->getActiveSheet()->setCellValue('I'.$y_bb, $JmlSatuan);
				$spreadsheet->getActiveSheet()->setCellValue('K'.$y_bb, $rb->mat_id);
				$spreadsheet->getActiveSheet()->setCellValue('T'.$y_bb, $no_aju_dok_asal);
				$spreadsheet->getActiveSheet()->setCellValue('U'.$y_bb, $rb->NoDaf);
				$spreadsheet->getActiveSheet()->setCellValue('V'.$y_bb, '');
				$spreadsheet->getActiveSheet()->setCellValue('Y'.$y_bb, $rb->FTgDaf);
				$spreadsheet->getActiveSheet()->setCellValue('AB'.$y_bb, $rb->NmBarang);
				$y_bb += 1;
				$seri_bb += 1;
			}
			$y += 1;
			$seri_barang += 1;
		}
		// Redirect output to a client’s web browser (Xlsx)
		$filename = "BC27K_".date('YmdHis').".xls";
		header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
		// header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="'.$filename.'"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');
		// If you're serving to IE over SSL, then the following may be needed
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
		header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header('Pragma: public'); // HTTP/1.0
		$writer->save('php://output');
		exit;
		// $data = array(
		// 	'cmpy_nm'=>$this->session->userdata('nm_cmpy'),
		// 	'rhdr' 	=> 	$this->mdl->getRow($id),
		// 	'rdet' 	=> 	$this->mdl->getDetAll($id)
		// );
		
		// $this->load->library('pdf');
		// $this->load->view($this->pmodul.'/slip',$data);
		
	}
}