<?php
session_start();
class Trxin_mdl extends Base_Model {
	
	function __construct() {
		
		parent::__construct();
		$this->pk = 'matin_id';
	}
	function buat_kodeIn()   {
		$this->db->select("RIGHT(mat_inchdr_sub.matin_no,4) as kode", FALSE);
		$this->db->order_by('matin_no','DESC');    
		$this->db->limit(1);    
		$query = $this->db->get('mat_inchdr_sub');      //cek dulu apakah ada sudah ada kode di tabel.    
		if($query->num_rows() <> 0){      
		 //jika kode ternyata sudah ada.      
		 $data = $query->row();      
		 $kode = intval($data->kode) + 1;    
		}
		else {      
		 //jika kode belum ada      
		 $kode = 1;    
		}
		$kodemax = str_pad($kode, 4, "0", STR_PAD_LEFT); // angka 4 menunjukkan jumlah digit angka 0
		$kodejadi = "IM-".date('Ym')."-".$kodemax;    // hasilnya SO-TahunTanggal-0001 dst.
		return $kodejadi;  
  }
	function getHdr($page,$rows,$key='',$KdJnsDok=''){
		$offset = ($page-1)*$rows;
		$result = array();
		$cond_KdJnsDok = "";
		if ($KdJnsDok != ""){
			$cond_KdJnsDok = " AND a.KdJnsDok = '$KdJnsDok' ";
		}

		if ($this->matin_type != ""){
			$cond_matin_type = " AND a.matin_type = '$this->matin_type' ";
		}
		
		$q = "SELECT distinct a.*,a.".$this->pk." AS id,
			  DATE_FORMAT(matin_date,'%d/%m/%Y') AS Fmatin_date,
			  DATE_FORMAT(TgDaf,'%d/%m/%Y') AS FTgDaf,
			  DATE_FORMAT(TgAju,'%d/%m/%Y') AS FTgAju,
			  c.matin_name,d.NmPrshn,f.UrJnsDok,
			  g.NmPrshn AS company,
			  FORMAT(cif,2) AS cif,
			  FORMAT(tot_amount,2) AS tot_amount,
			  a.tot_volume
			  FROM ".$this->tbl." a
			  LEFT JOIN ".$this->tbl3." c ON c.".$this->pk3."=a.".$this->pk3."
			  LEFT JOIN ".$this->tbl4." d ON d.".$this->pk4."=a.supplier
			  LEFT JOIN ".$this->tbl6." f ON f.".$this->pk6."=a.".$this->pk6."
			  LEFT JOIN ".$this->tbl4." g ON g.".$this->pk4."=a.kd_cmpy
			 WHERE mat_type IN (".$this->mat_type.")
			 $cond_matin_type	
			 $cond_KdJnsDok";
		$q .= " AND (a.matin_no LIKE '%$key%' OR d.NmPrshn LIKE '%$key%' 
				OR a.NoDaf LIKE '%$key%' OR a.po_no LIKE '%$key%')
			  ORDER BY matin_id DESC";
		$rstot=$this->db->query($q)->result();
		//echo $q;
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}

	// finished goods subkon --dim
	function getHdrFGS($page,$rows,$key='',$KdJnsDok=''){
		$offset = ($page-1)*$rows;
		$result = array();
		$cond_KdJnsDok = "";
		if ($KdJnsDok != ""){
			$cond_KdJnsDok = " AND a.KdJnsDok = '$KdJnsDok' ";
		}

		if ($this->matin_type != ""){
			$cond_matin_type = " AND a.matin_type = '$this->matin_type' ";
		}
		
		$q = "SELECT distinct a.*,a.".$this->pk." AS id,
			  DATE_FORMAT(matin_date,'%d/%m/%Y') AS Fmatin_date,
			  DATE_FORMAT(TgDaf,'%d/%m/%Y') AS FTgDaf,
			  DATE_FORMAT(TgAju,'%d/%m/%Y') AS FTgAju,
			  c.matin_name,d.NmPrshn,f.UrJnsDok,
			  g.NmPrshn AS company,
			  FORMAT(cif,2) AS cif,
			  FORMAT(tot_amount,2) AS tot_amount,
			  a.tot_volume
			  FROM ".$this->tbl." a
			  LEFT JOIN ".$this->tbl3." c ON c.".$this->pk3."=a.".$this->pk3."
			  LEFT JOIN ".$this->tbl4." d ON d.".$this->pk4."=a.supplier
			  LEFT JOIN ".$this->tbl6." f ON f.".$this->pk6."=a.".$this->pk6."
			  LEFT JOIN ".$this->tbl4." g ON g.".$this->pk4."=a.kd_cmpy
			 WHERE mat_type IN (".$this->mat_type.")
			 $cond_matin_type	
			 $cond_KdJnsDok";
		$q .= " AND (a.matin_no LIKE '%$key%' OR d.NmPrshn LIKE '%$key%' 
				OR a.NoDaf LIKE '%$key%' OR a.po_no LIKE '%$key%')
			  ORDER BY matin_id DESC";
		$rstot=$this->db->query($q)->result();
		//echo $q;
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}
	
	// finished goods plating --dim
	function getHdrFGP($page,$rows,$key='',$KdJnsDok=''){
		$offset = ($page-1)*$rows;
		$result = array();
		$cond_KdJnsDok = "";
		if ($KdJnsDok != ""){
			$cond_KdJnsDok = " AND a.KdJnsDok = '$KdJnsDok' ";
		}

		if ($this->matin_type != ""){
			$cond_matin_type = " AND a.matin_type = '$this->matin_type' ";
		}
		
		$q = "SELECT distinct a.*,a.".$this->pk." AS id,
			  DATE_FORMAT(matin_date,'%d/%m/%Y') AS Fmatin_date,
			  DATE_FORMAT(TgDaf,'%d/%m/%Y') AS FTgDaf,
			  DATE_FORMAT(TgAju,'%d/%m/%Y') AS FTgAju,
			  c.matin_name,d.NmPrshn,f.UrJnsDok,
			  g.NmPrshn AS company,
			  FORMAT(cif,2) AS cif,
			  FORMAT(tot_amount,2) AS tot_amount,
			  a.tot_volume
			  FROM ".$this->tbl." a
			  LEFT JOIN ".$this->tbl3." c ON c.".$this->pk3."=a.".$this->pk3."
			  LEFT JOIN ".$this->tbl4." d ON d.".$this->pk4."=a.supplier
			  LEFT JOIN ".$this->tbl6." f ON f.".$this->pk6."=a.".$this->pk6."
			  LEFT JOIN ".$this->tbl4." g ON g.".$this->pk4."=a.kd_cmpy
			 WHERE mat_type IN (".$this->mat_type.")
			 and proses in ('FG-P')
			 $cond_matin_type	
			 $cond_KdJnsDok";
		$q .= " AND (a.matin_no LIKE '%$key%' OR d.NmPrshn LIKE '%$key%' 
				OR a.NoDaf LIKE '%$key%' OR a.po_no LIKE '%$key%')
			  ORDER BY matin_id DESC";
		$rstot=$this->db->query($q)->result();
		//echo $q;
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}

	// finished goods non plating --dim
	function getHdrFGNP($page,$rows,$key='',$KdJnsDok=''){
		$offset = ($page-1)*$rows;
		$result = array();
		$cond_KdJnsDok = "";
		if ($KdJnsDok != ""){
			$cond_KdJnsDok = " AND a.KdJnsDok = '$KdJnsDok' ";
		}

		if ($this->matin_type != ""){
			$cond_matin_type = " AND a.matin_type = '$this->matin_type' ";
		}
		
		$q = "SELECT distinct a.*,a.".$this->pk." AS id,
			  DATE_FORMAT(matin_date,'%d/%m/%Y') AS Fmatin_date,
			  DATE_FORMAT(TgDaf,'%d/%m/%Y') AS FTgDaf,
			  DATE_FORMAT(TgAju,'%d/%m/%Y') AS FTgAju,
			  c.matin_name,d.NmPrshn,f.UrJnsDok,
			  g.NmPrshn AS company,
			  FORMAT(cif,2) AS cif,
			  FORMAT(tot_amount,2) AS tot_amount,
			  a.tot_volume
			  FROM ".$this->tbl." a
			  LEFT JOIN ".$this->tbl3." c ON c.".$this->pk3."=a.".$this->pk3."
			  LEFT JOIN ".$this->tbl4." d ON d.".$this->pk4."=a.supplier
			  LEFT JOIN ".$this->tbl6." f ON f.".$this->pk6."=a.".$this->pk6."
			  LEFT JOIN ".$this->tbl4." g ON g.".$this->pk4."=a.kd_cmpy
			 WHERE mat_type IN (".$this->mat_type.")
			 $cond_matin_type	
			 $cond_KdJnsDok";
		$q .= " AND (a.matin_no LIKE '%$key%' OR d.NmPrshn LIKE '%$key%' 
				OR a.NoDaf LIKE '%$key%' OR a.po_no LIKE '%$key%')
			  ORDER BY matin_id DESC";
		$rstot=$this->db->query($q)->result();
		//echo $q;
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}

	function getRow($key=''){		
		$q = "SELECT a.*,a.".$this->pk." AS id,
			  DATE_FORMAT(matin_date,'%d/%m/%Y') AS Fmatin_date,
			  DATE_FORMAT(TgDaf,'%d/%m/%Y') AS FTgDaf,
			  DATE_FORMAT(TgAju,'%d/%m/%Y') AS FTgAju,
			  c.matin_name,d.NmPrshn,e.NmPrshn as perusahaan,f.UrJnsDok  
			  FROM ".$this->tbl." a
			  LEFT JOIN ".$this->tbl3." c ON c.".$this->pk3."=a.".$this->pk3."
				LEFT JOIN ".$this->tbl4." d ON d.".$this->pk4."=a.supplier
				LEFT JOIN ".$this->tbl4." e ON e.".$this->pk4."=a.kd_cmpy
			  LEFT JOIN ".$this->tbl6." f ON f.".$this->pk6."=a.".$this->pk6."
			  WHERE a.".$this->pk."='$key'
			  LIMIT 1";
		$rs=$this->db->query($q)->result();
		
		return $rs[0];
	}

	function cariPartial($key){		
		$q = "	SELECT a.po_no, a.partial, a.matin_id 
				FROM mat_inchdr_sub a 
				WHERE a.po_no='$key' 
				order by a.partial desc 
				LIMIT 1	";
		$rs=$this->db->query($q)->result();
		
		return $rs[0];
	}

	public function getAndReserveLatestDoc() {
		// Start transaction
		$this->db->trans_start();
	
		// Fetch the latest document number and BC number
		$q = "SELECT noAju, matin_no FROM mat_inchdr_sub ORDER BY matin_id DESC LIMIT 1";
		$rs = $this->db->query($q)->row_array();
	
		// Increment the matin_no by 1
		$latestMatinNo = (int) $rs['matin_no'] + 1;
		$newMatinNo = str_pad($latestMatinNo, 6, '0', STR_PAD_LEFT); // Zero pad to maintain format
	
		// Increment the noAju by 1 based on its current format
		$currentDate = date('Ymd');
		if (empty($rs)) {
			// Handle case where there are no records yet
			$newNoAju = sprintf("DRAFT-010619-%s-%06d", $currentDate, 1);
		} else {
			$noAjuParts = explode('-', $rs['noAju']);
			if ($noAjuParts[2] === $currentDate) {
				$newSequenceNo = (int) $noAjuParts[3] + 1;
			} else {
				$newSequenceNo = 1; // Reset sequence for new day
			}
			$newNoAju = sprintf("DRAFT-010619-%s-%06d", $currentDate, $newSequenceNo);
		}
	
		// Prepare data for the new draft document
		$newDoc = [
			'noAju' => $newNoAju,
			'matin_no' => $newMatinNo,
	
		];
	
		// Insert the new draft document
		$this->db->insert('mat_inchdr_sub', $newDoc);
		$newDocId = $this->db->insert_id();
	
		// Complete the transaction
		$this->db->trans_complete();
	
		// Check if the transaction was successful
		if ($this->db->trans_status() === FALSE) {
			// Handle transaction failure
			return ['error' => 'Failed to reserve document.'];
		}
	
		// Return the new draft document ID and details
		return [
			'doc_id' => $newDocId,
			'noAju' => $newDoc['noAju'],
			'matin_no' => $newDoc['matin_no']
		];
	}
	
	
	
	function getDet($page,$rows,$matin_id='',$key=''){
		$offset = ($page-1)*$rows;
		$result = array();
		
		$q="SELECT a.matin_id AS id, a.poqty, a.qty,
			a.price, a.amount, a.ng_qty,
			a.mat_id, a.has_edited, a.all_in, 
			a.locked, a.adj_qty, a.child_no,
			FORMAT(a.poqty, 2) AS POqty,
			FORMAT(a.qty, 2) AS Fqty,
			FORMAT(a.Dqty, 2) AS Dqty,
			FORMAT(a.ng_qty, 2) AS NGqty,
			FORMAT(a.balance,2) AS Bqty,
			FORMAT(a.price, 4) AS Fprice,
			FORMAT(a.amount, 2) AS amount,
			b.NmBarang,b.Sat,b.PartNo,a.volume
		  	FROM ".$this->tbl2." a 
		  	LEFT JOIN ".$this->tbl5." b ON KdBarang = a.mat_id 
				WHERE ".$this->pk." = '$matin_id' 
				AND a.status = '1'
				AND (a.mat_id LIKE '%$key%' OR b.NmBarang LIKE '%$key%' )
		  	ORDER BY a.child_no DESC";
		$rstot=$this->db->query($q)->result();
		// die($q);
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}


	function getDetDok($page,$rows,$matin_id='',$key=''){
		$offset = ($page-1)*$rows;
		$result = array();
		
		$q="SELECT a.id,a.seri_dok,b.UrKdJnsDok as doc_name, a.tgl_dok,a.dok_no,a.matin_no,c.noAju 
		FROM mat_dokumen a left join kode_jenis_dok b on b.KdKdJnsDok=a.seri_dok left join mat_inchdr_sub c on c.matin_id=a.matin_no
				WHERE a.matin_no = '$matin_id' 
		  	ORDER BY a.seri_dok ASC";
		$rstot=$this->db->query($q)->result();
		// die($q);
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}


	function getDetKon($page,$rows,$matin_id='',$key=''){
		$offset = ($page-1)*$rows;
		$result = array();
		
		$q="SELECT c.noAju, a.SERI, a.NOMOR_KONTAINER, a.ID, a.KODE_UKURAN_KONTAINER, a.KODE_JENIS_KONTAINER, a.KODE_TIPE_KONTAINER, a.MATIN_ID,
		b.NAMA_JENIS_KONTAINER,e.NAMA_UKURAN_KONTAINER,d.NAMA_TIPE_KONTAINER
		FROM mat_kontainer a 
		left join mst_jenis_kontainer b on b.KODE_JENIS_KONTAINER=a.KODE_JENIS_KONTAINER 
		left join mst_ukuran_kontainer e on e.KODE_UKURAN_KONTAINER=a.KODE_UKURAN_KONTAINER 
		left join mst_type_kontainer d on d.KODE_TIPE_KONTAINER=a.KODE_TIPE_KONTAINER 
		left join mat_inchdr_sub c on c.matin_id=a.matin_id
				WHERE a.matin_id = '$matin_id' 
		  	ORDER BY a.seri ASC";
		$rstot=$this->db->query($q)->result();
		// die($q);
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}

function getDetJaminan($page,$rows,$matin_id='',$key=''){
		$offset = ($page-1)*$rows;
		$result = array();
		
		$q="select * from jaminan
				WHERE matin_no = '$matin_id' 
		  	ORDER BY nomorJaminan ASC";
		$rstot=$this->db->query($q)->result();
		// die($q);
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}

	function getDetRow($matin_id='', $child_no='', $mat_id=''){
		$q="SELECT a.*, IF(a.Dqty = '', c.amount, a.balance * a.price) AS amountpo
		  	FROM mat_incdet_sub a 
		  	LEFT JOIN mst_barang b ON KdBarang = mat_id
			LEFT join pur_podet c ON c.mat_id = a.mat_id 
				WHERE matin_id = '$matin_id'
				AND a.status = '1'
				AND a.child_no = '$child_no'
				AND a.mat_id = '$mat_id'
				AND a.poqty = c.qty
				AND a.price = c.price
				GROUP BY child_no
				LIMIT 1";
		$rs=$this->db->query($q)->result();
		
		return $rs;
	}

	// GET JUST ONE ITEM ROW DETAIL ON EVERY PARTIAL --ir 
	function getDetRowAllPartial($po_id='', $mat_id='', $partial='', $child_no = ''){
		$q="SELECT a.*
		  	FROM mat_incdet_sub a
		  	LEFT JOIN mst_barang b ON KdBarang = mat_id 
		  	LEFT JOIN mat_inchdr_sub c ON a.matin_id = c.matin_id 
				WHERE mat_id = '$mat_id'
				AND child_no = '$child_no'
				AND c.po_id = '$po_id'
				AND c.partial > $partial";
		$rs=$this->db->query($q)->result();
		
		return $rs;
	}
	
	// GET ALL ROWS IN DETAIL WHICH HAS BEEN EDITED --ir 
	function getDetRowAll($matin_id='',$has_edited=''){
		$q="SELECT a.*
		  	FROM mat_incdet_sub a 
		  	LEFT JOIN mst_barang b ON KdBarang = mat_id 
				WHERE matin_id = $matin_id
				AND a.status = '1'
				AND has_edited = '$has_edited'
				AND locked = 'no'";
		$rs=$this->db->query($q)->result();
		
		return $rs;
	}
	function getDetRowAll2($matin_id='',$all_in=''){
		$q="SELECT a.*, IF(a.Dqty = '', c.amount, a.balance * a.price) AS amountpo
		  	FROM mat_incdet_sub a 
			  	LEFT JOIN mst_barang b ON KdBarang = mat_id
				LEFT join pur_podet c ON c.mat_id = a.mat_id 
				WHERE matin_id = $matin_id
				AND a.status = '1'
				AND all_in = '$all_in'
				AND locked = 'no'
				AND a.poqty = c.qty
				AND a.price = c.price
				GROUP BY child_no";
		$rs=$this->db->query($q)->result();
		
		return $rs;
	}
	function getDetWip($page,$rows,$matin_id='',$key=''){
		$offset = ($page-1)*$rows;
		$result = array();
		
		$q="SELECT * 
			FROM ".$this->tbl." a, ".$this->tbl2." b, ".$this->tbl5." c 
			WHERE a.".$this->pk." = b.".$this->pk2." 
			AND b.fg_id = c.".$this->pk5." 
			AND b.ref_type = 0";
		$rstot=$this->db->query($q)->result();
		// die($q);
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}
	
	function getDetAll($key=''){
		
		$q="SELECT a.*,matin_id AS id,
			FORMAT(poqty, 2) AS POqty,
			FORMAT(qty, 2) AS Fqty,
			FORMAT(Dqty, 2) AS Dqty,
			FORMAT(balance, 2) AS Bqty,
			FORMAT(ng_qty, 2) AS Ngqty,
			FORMAT(price, 4) AS Fprice,
			FORMAT(qty*price, 2) AS amount,
			b.NmBarang,b.Sat,b.PartNo
		  	FROM ".$this->tbl2." a 
		  	LEFT JOIN ".$this->tbl5." b ON KdBarang = mat_id 
				WHERE ".$this->pk."='$key' 
				AND a.status = '1'
				AND qty > 0 
		  	ORDER BY child_no ASC";
		$rs=$this->db->query($q)->result();
		
		return $rs;
	}


	function getPoDetAll($key=''){
		
		$q="SELECT *
		  	FROM pur_pohdr a 
		  	LEFT JOIN pur_podet b ON a.po_id = b.po_id 
				WHERE po_no='$key'  
		  	ORDER BY child_no ASC";
		$rs=$this->db->query($q)->result();
		
		return $rs;
	}
	
	function getHdrDet($page,$rows,$key='',$dtdari='',$dtsampai=''){
		$offset = ($page-1)*$rows;
		$result = array();
		
		$q="SELECT distinct a.".$this->pk." AS id,
			a.matin_no, a.po_no, a.supl_do, 
			a.supl_inv, a.currency, b.mat_id,
			a.kurs, a.NoDaf, a.NoAju,
			DATE_FORMAT(a.matin_date,'%d/%m/%Y') AS Fmatin_date,
			DATE_FORMAT(a.TgDaf,'%d/%m/%Y') AS FTgDaf,
			DATE_FORMAT(a.TgAju,'%d/%m/%Y') AS FTgAju,
			FORMAT(b.qty, 2) AS Fqty,
			FORMAT(b.price, 4) AS Fprice,
			FORMAT(b.ng_qty, 2) AS Ngqty,
			FORMAT(b.qty*b.price, 2) AS amount,
			c.matin_name,d.NmPrshn,f.UrJnsDok,
			e.NmBarang,e.Sat,g.NmPrshn AS company, b.volume 
			FROM ".$this->tbl." a
			LEFT JOIN ".$this->tbl2." b ON b.".$this->pk."=a.".$this->pk."
			LEFT JOIN ".$this->tbl3." c ON c.".$this->pk3."=a.matin_type
			LEFT JOIN ".$this->tbl4." d ON d.".$this->pk4."=a.supplier
			LEFT JOIN ".$this->tbl5." e ON e.".$this->pk5."= b.mat_id 
			LEFT JOIN ".$this->tbl6." f ON f.".$this->pk6."= a.KdJnsDok
			LEFT JOIN ".$this->tbl4." g ON g.".$this->pk4."=a.kd_cmpy
			WHERE a.mat_type = '".$this->mat_type."'
			 ";
			
		// if ($this->session->userdata('kd_cmpy') != "0001"){
		// 	$q .= " AND kd_cmpy = '".$this->session->userdata('kd_cmpy')."'";	
		// }
			  
		if ($key != ""){  
			$q .= " AND (a.matin_no LIKE '%$key%' OR g.NmPrshn LIKE '%$key%' OR e.KdBarang LIKE '%$key%')";
		}	
			  
		if($dtdari != '' && $dtsampai != ''):
			$q .= " AND a.matin_date BETWEEN '".$this->dmys2ymd($dtdari)."' AND '".$this->dmys2ymd($dtsampai)."'";
		endif;
		
		$q .= " ORDER BY a.matin_date DESC";
		$rstot=$this->db->query($q)->result();
		//echo $q;
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}



	function getHdrDet_1($key=''){
		
		$result = array();
		
		$q="SELECT distinct *	,a.".$this->pk." AS id,
			a.matin_no, a.po_no, a.supl_do, 
			a.supl_inv, a.currency, b.mat_id,
			a.kurs, a.NoDaf, a.NoAju,
			DATE_FORMAT(a.matin_date,'%d/%m/%Y') AS Fmatin_date,
			DATE_FORMAT(a.TgDaf,'%d/%m/%Y') AS FTgDaf,
			DATE_FORMAT(a.TgAju,'%d/%m/%Y') AS FTgAju,
			FORMAT(b.qty, 2) AS Fqty,
			FORMAT(b.price, 4) AS Fprice,
			FORMAT(b.ng_qty, 2) AS Ngqty,
			FORMAT(b.qty*b.price, 2) AS amount,
			c.matin_name,d.NmPrshn,f.UrJnsDok,
			e.NmBarang,e.Sat,g.NmPrshn AS company, b.volume
			FROM ".$this->tbl." a
			LEFT JOIN ".$this->tbl2." b ON b.".$this->pk."=a.".$this->pk."
			LEFT JOIN ".$this->tbl3." c ON c.".$this->pk3."=a.matin_type
			LEFT JOIN ".$this->tbl4." d ON d.".$this->pk4."=a.supplier
			LEFT JOIN ".$this->tbl5." e ON e.".$this->pk5."= b.mat_id 
			LEFT JOIN ".$this->tbl6." f ON f.".$this->pk6."= a.KdJnsDok
			LEFT JOIN ".$this->tbl4." g ON g.".$this->pk4."=a.kd_cmpy
			WHERE a.mat_type = '".$this->mat_type."'
			 ";
			
		// if ($this->session->userdata('kd_cmpy') != "0001"){
		// 	$q .= " AND kd_cmpy = '".$this->session->userdata('kd_cmpy')."'";	
		// }
			  
		if ($key != ""){  
			$q .= " AND (a.matin_id LIKE '%$key%')";
		}	
			  

		
		$q .= " ORDER BY a.matin_date DESC";
		
		
	
		$rs=$this->db->query($q)->result();
		$result["rows"] = $rs;
	
		return $result;
	}

	function getHdrDetFGP($page,$rows,$key='',$dtdari='',$dtsampai=''){
		$offset = ($page-1)*$rows;
		$result = array();
		
		$q="SELECT distinct a.".$this->pk." AS id,
			a.matin_no, a.po_no, a.supl_do, 
			a.supl_inv, a.currency, b.mat_id,
			a.kurs, a.NoDaf, a.NoAju,
			DATE_FORMAT(a.matin_date,'%d/%m/%Y') AS Fmatin_date,
			DATE_FORMAT(a.TgDaf,'%d/%m/%Y') AS FTgDaf,
			DATE_FORMAT(a.TgAju,'%d/%m/%Y') AS FTgAju,
			FORMAT(b.qty, 2) AS Fqty,
			FORMAT(b.price, 4) AS Fprice,
			FORMAT(b.ng_qty, 2) AS Ngqty,
			FORMAT(b.qty*b.price, 2) AS amount,
			c.matin_name,d.NmPrshn,f.UrJnsDok,
			e.NmBarang,e.Sat,g.NmPrshn AS company, b.volume 
			FROM ".$this->tbl." a
			LEFT JOIN ".$this->tbl2." b ON b.".$this->pk."=a.".$this->pk."
			LEFT JOIN ".$this->tbl3." c ON c.".$this->pk3."=a.matin_type
			LEFT JOIN ".$this->tbl4." d ON d.".$this->pk4."=a.supplier
			LEFT JOIN ".$this->tbl5." e ON e.".$this->pk5."= b.mat_id 
			LEFT JOIN ".$this->tbl6." f ON f.".$this->pk6."= a.KdJnsDok
			LEFT JOIN ".$this->tbl4." g ON g.".$this->pk4."=a.kd_cmpy
			WHERE a.mat_type = '".$this->mat_type."'
			and a.proses = 'FG-P' ";
			
		// if ($this->session->userdata('kd_cmpy') != "0001"){
		// 	$q .= " AND kd_cmpy = '".$this->session->userdata('kd_cmpy')."'";	
		// }
			  
		if ($key != ""){  
			$q .= " AND (a.matin_no LIKE '%$key%' OR g.NmPrshn LIKE '%$key%' OR e.KdBarang LIKE '%$key%')";
		}	
			  
		if($dtdari != '' && $dtsampai != ''):
			$q .= " AND a.matin_date BETWEEN '".$this->dmys2ymd($dtdari)."' AND '".$this->dmys2ymd($dtsampai)."'";
		endif;
		
		$q .= " ORDER BY a.matin_date DESC";
		$rstot=$this->db->query($q)->result();
		//echo $q;
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}

	function getHdrDetFGNP($page,$rows,$key='',$dtdari='',$dtsampai=''){
		$offset = ($page-1)*$rows;
		$result = array();
		
		$q="SELECT distinct a.".$this->pk." AS id,
			a.matin_no, a.po_no, a.supl_do, 
			a.supl_inv, a.currency, b.mat_id,
			a.kurs, a.NoDaf, a.NoAju,
			DATE_FORMAT(a.matin_date,'%d/%m/%Y') AS Fmatin_date,
			DATE_FORMAT(a.TgDaf,'%d/%m/%Y') AS FTgDaf,
			DATE_FORMAT(a.TgAju,'%d/%m/%Y') AS FTgAju,
			FORMAT(b.qty, 2) AS Fqty,
			FORMAT(b.price, 4) AS Fprice,
			FORMAT(b.ng_qty, 2) AS Ngqty,
			FORMAT(b.qty*b.price, 2) AS amount,
			c.matin_name,d.NmPrshn,f.UrJnsDok,
			e.NmBarang,e.Sat,g.NmPrshn AS company, b.volume 
			FROM ".$this->tbl." a
			LEFT JOIN ".$this->tbl2." b ON b.".$this->pk."=a.".$this->pk."
			LEFT JOIN ".$this->tbl3." c ON c.".$this->pk3."=a.matin_type
			LEFT JOIN ".$this->tbl4." d ON d.".$this->pk4."=a.supplier
			LEFT JOIN ".$this->tbl5." e ON e.".$this->pk5."= b.mat_id 
			LEFT JOIN ".$this->tbl6." f ON f.".$this->pk6."= a.KdJnsDok
			LEFT JOIN ".$this->tbl4." g ON g.".$this->pk4."=a.kd_cmpy
			WHERE a.mat_type = '".$this->mat_type."'
			and a.proses = 'FG-NP' ";
			
		// if ($this->session->userdata('kd_cmpy') != "0001"){
		// 	$q .= " AND kd_cmpy = '".$this->session->userdata('kd_cmpy')."'";	
		// }
			  
		if ($key != ""){  
			$q .= " AND (a.matin_no LIKE '%$key%' OR g.NmPrshn LIKE '%$key%' OR e.KdBarang LIKE '%$key%')";
		}	
			  
		if($dtdari != '' && $dtsampai != ''):
			$q .= " AND a.matin_date BETWEEN '".$this->dmys2ymd($dtdari)."' AND '".$this->dmys2ymd($dtsampai)."'";
		endif;
		
		$q .= " ORDER BY a.matin_date DESC";
		$rstot=$this->db->query($q)->result();
		//echo $q;
		$q .= " LIMIT $offset,$rows";
		$rs=$this->db->query($q)->result();
		
		$result["total"] = count($rstot);
		$result["rows"] = $rs;
		
		return $result;
	}
	
	function getNewNo(){
		$q="SELECT MAX(".$this->pk.") AS auto_no FROM ".$this->tbl." LIMIT 1";
		$rs=$this->db->query($q)->result();
		$autono=($rs)?$rs[0]->auto_no+1:1;
		
		return $autono;
	}
	
	function add($data){
	
		$run = $this->db->insert($this->tbl, $data); 

		if ($this->db->affected_rows()>0){
			$rs=true;
			$log=$this->addLog($data['nama_user'],"Tambah Header".$this->title.", NO = ".$data[$this->pkh]);	
		} else {
			$rs=false;
		}
		
		return $rs;
	}
	
	// GET COUNT ITEM WHERE HAS EDITED --ir
	function getCountDetailIn($key=''){		
		$q = "SELECT COUNT(matin_id) as matin_id
						FROM mat_incdet_sub
						WHERE has_edited = 'yes'
						AND status = '1'
						AND matin_id = '$key'
						LIMIT 1";
		$rs=$this->db->query($q)->result();		
		return $rs;
	}
			// GET PARTIAL FROM INCOMING NUMBER --ir
			function getCountPO($key=''){		
				$q = "SELECT COUNT(a.po_id) as po_id
								FROM mat_inchdr_sub a, pur_pohdr b
								WHERE a.po_id = b.po_id
								AND a.po_id = '$key'
								ORDER BY a.po_id DESC
								LIMIT 1";
				$rs=$this->db->query($q)->result();		
				return $rs;
			}

		// GET PARTIAL FROM INCOMING NUMBER --ir
		function getCountPO1($key=''){		
			$q = "SELECT COUNT(a.matin_no) as matin_no
							FROM mat_inchdr_sub a, pur_pohdr b
							WHERE a.po_id = b.po_id
							AND a.po_no = '$key'
							ORDER BY a.matin_no DESC
							LIMIT 1";
			$rs=$this->db->query($q)->result();		
			return $rs;
		}

	// GET COUNT INCOMING DETAIL --ir
	function getCountDet($key=''){		
		$q = "SELECT COUNT(a.matin_id) as matin_id
						FROM mat_incdet_sub a, mat_inchdr_sub b
						WHERE a.matin_id = b.matin_id
						AND a.matin_id = '$key'
						ORDER BY a.matin_id DESC
						LIMIT 1";
		$rs=$this->db->query($q)->result();		
		return $rs;
	}
	// GET PARTIAL FROM INCOMING NUMBER --ir
	function getPartial2($key=''){		
		$q = "SELECT a.partial
						FROM mat_inchdr_sub a, pur_pohdr b
						WHERE a.po_id = b.po_id
						AND a.po_no = '$key'
						ORDER BY a.partial DESC
						LIMIT 1";
		$rs=$this->db->query($q)->result();		
		return $rs;
	}
	// GET INCOMING NUMBER --ir
	function getMatin($key=''){		
		$q = "SELECT matin_id
						FROM mat_inchdr_sub
						WHERE matin_no = '$key'
						ORDER BY matin_id DESC
						LIMIT 1";
		$rs=$this->db->query($q)->result();		
		return $rs;
	}
	// GET DETAIL ITEM FROM PO NUMBER --ir
	function getPodet($key=''){		
		$q = "SELECT y.*, x.po_no, z.matin_id, z.matin_no, z.partial
						FROM pur_pohdr x, pur_podet y, mat_inchdr_sub z
						WHERE x.po_id = y.po_id
						AND z.po_id = y.po_id	
						AND z.matin_no = '$key'";
		$rs=$this->db->query($q)->result();		
		return $rs;
	}
	// GET DETAIL ITEM FROM INCOMING NUMBER --ir
	function getPodet2($key='',$getPart=''){		
		$q = "SELECT y.*, z.matin_id, z.matin_no, z.partial
						FROM mat_incdet_sub y, mat_inchdr_sub z
						WHERE y.matin_id = z.matin_id
						AND z.po_no = '$key'
						AND z.partial = '$getPart'
						-- AND y.all_in = 'no'
						ORDER BY y.child_no ASC";
		$rs=$this->db->query($q)->result();		
		return $rs;
	}
	
	function addDet($data){
		unset($data['NmBarang']);
		unset($data['Sat']);
		//unset($data['amount']);
		$run = $this->db->insert($this->tbl2, $data); 
		if ($this->db->affected_rows()>0){
			$rs=true;
			$log=$this->addLog($data['nama_user'],"Tambah Detail ".$this->title.", MATIN ID = ".$data['matin_id'].", MAT ID = ".$data['mat_id']);	
		} else {
			$rs=false;
		}
		
		return $rs;
	}

	function addDetKon($data){
		// Fetch the latest seri value based on MATIN ID and NOMOR_KONTAINER
		$this->db->select('MAX(seri) as latest_seri');
		$this->db->from('mat_kontainer');
		$this->db->where('matin_id', $data['matin_id']);
		$this->db->where('NOMOR_KONTAINER', $data['NOMOR_KONTAINER']);
		$query = $this->db->get();
		$result = $query->row_array();
	
		// If latest_seri is null or zero, start with 1
		$data['seri'] = (!empty($result['latest_seri']) && $result['latest_seri'] > 0) ? $result['latest_seri'] + 1 : 1;
	
		// Insert the data into mat_kontainer
		$run = $this->db->insert('mat_kontainer', $data); 
		if ($this->db->affected_rows() > 0) {
			$rs = true;
			$log = $this->addLog($data['nama_user'], "Tambah Detail kontiner " . $this->title . ", MATIN ID = " . $data['matin_id'] . ", NOMOR_KONTAINER = " . $data['NOMOR_KONTAINER']);
		} else {
			$this->db->trans_rollback(); // Rollback on failure
			$rs = false;
		}
	
		return $rs;
	}
	

	function addDetDok($data){
		// Fetch the latest seri value based on matin_id and NOMOR_KONTAINER
		$this->db->select('MAX(no_dok) as latest_seri');
		$this->db->from('mat_dokumen');
		$this->db->where('matin_no', $data['matin_no']); // Assuming matin_no is the column for matin_id
		$query = $this->db->get();
		$result = $query->row_array();
	
		// If latest_seri is null or zero, start with 1
		$data['no_dok'] = (!empty($result['latest_seri']) && $result['latest_seri'] > 0) ? $result['latest_seri'] + 1 : 1;
	
		// Insert the data into mat_dokumen
		$run = $this->db->insert('mat_dokumen', $data); 
		if ($this->db->affected_rows() > 0){
			$rs = true;
			$log = $this->addLog($data['nama_user'], "Tambah Detail dokumen " . $this->title . ", MATIN ID = " . $data['matin_no'] . ", NOMOR_DOKUMEN = " . $data['dok_no']);
		} else {
			$this->db->trans_rollback(); // Rollback on failure
			$rs = false;
		}
	
		return $rs;
	}
	

	function addDetJaminan($data){	
		    $data['tanggalJaminan'] = !empty($data['tanggalJaminan']) ? date('Y-m-d', strtotime($data['tanggalJaminan'])) : null;
    $data['tanggalBpj'] = !empty($data['tanggalBpj']) ? date('Y-m-d', strtotime($data['tanggalBpj'])) : null;
    $data['tanggalJatuhTempo'] = !empty($data['tanggalJatuhTempo']) ? date('Y-m-d', strtotime($data['tanggalJatuhTempo'])) : null;

		// Fetch the latest seri value based on matin_id and NOMOR_KONTAINER
		$this->db->select('MAX(nomorJaminan) as latest_seri');
		$this->db->from('jaminan');
		$this->db->where('matin_no', $data['matin_no']); // Assuming matin_no is the column for matin_id
		$query = $this->db->get();
		$result = $query->row_array();
	
		// If latest_seri is null or zero, start with 1
		$data['nomorJaminan'] = (!empty($result['latest_seri']) && $result['latest_seri'] > 0) ? $result['latest_seri'] + 1 : 1;

		// Insert the data into mat_dokumen
		$run = $this->db->insert('jaminan', $data); 
		if ($this->db->affected_rows() > 0){
			$rs = true;
			$log = $this->addLog($data['nama_user'], "Tambah Detail jaminan " . $this->title . ", MATIN ID = " . $data['matin_no'] . ", NOMOR_JAMINAN = " . $data['nomorJaminan']);
		} else {
			$this->db->trans_rollback(); // Rollback on failure
			$rs = false;
		}
	
		return $rs;
	}
	

	function addDetP($data1, $data2) {
		// Start a database transaction
		$this->db->trans_begin();
	
		// Handle $data1 (mat_kontainer data)
		if (!empty($data1)) {
			$rowCount = count($data1['NOMOR_AJU']); // Get the number of rows
			for ($i = 0; $i < $rowCount; $i++) {
				$row = [
					'NOMOR_AJU' => $data1['NOMOR_AJU'][$i],
					'SERI' => $data1['SERI'][$i],
					'NOMOR_KONTAINER' => $data1['NOMOR_KONTAINER'][$i],
					'KODE_UKURAN_KONTAINER' => $data1['KODE_UKURAN_KONTAINER'][$i],
					'KODE_TIPE_KONTAINER' => $data1['KODE_TIPE_KONTAINER'][$i],
					'KODE_JENIS_KONTAINER' => $data1['KODE_JENIS_KONTAINER'][$i],
					'MATIN_ID' => $data1['MATIN_ID'][$i]
				];
	
				$run = $this->db->insert("mat_kontainer", $row);
				if ($this->db->affected_rows() <= 0) {
					$this->db->trans_rollback(); // Rollback on failure
					return false;
				} else {
					$log = $this->addLog("Excel", "Tambah Detail kontiner " . $this->title . ", MATIN ID = " . $row['MATIN_ID']);
				}
			}
		}
	
		// Handle $data2 (mat_dokumen data)
		if (!empty($data2)) {
			foreach ($data2['seri_dok'] as $key => $value) { // Loop through multiple rows in data2
				$row = [
					'seri_dok' => $data2['seri_dok'][$key],
					'no_dok' => $data2['no_dok'][$key],
					'tgl_dok' => $data2['tgl_dok'][$key],
					'dok_no' => $data2['dok_no'][$key],
					'matin_no' => $data2['matin_no'][$key]
				];
	
				$run = $this->db->insert("mat_dokumen", $row);
				if ($this->db->affected_rows() <= 0) {
					$this->db->trans_rollback(); // Rollback on failure
					return false;
				} else {
					$log = $this->addLog("Excel", "Tambah Detail Dokumen " . $this->title . ", MATIN ID = " . $row['matin_no']);
				}
			}
		}
	
		// Commit transaction if everything is successful
		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			return false;
		} else {
			$this->db->trans_commit();
			return true;
		}
	}
	
	// Create Journal --ir
	function createJournal($id){
		$rhdr = $this->getRow($id);
		$rdet = $this->getDetAll($rhdr->id);
		
		$accdb = $this->load->database('accounting', TRUE);
		$data = array (
			'kd_cmpy' => '01',
			'slipdate' => $rhdr->matin_date,
			'sliptype' => '1',
			'slipcode' => 'JI',
			'slipnum' 	=> $rhdr->notes,
			'slipcurr' => $rhdr->currency,
			'slipdesc' => ""
			// 'slipdesc' => $rhdr->description
		);
		$run = $accdb->insert('accsliphdr', $data);
		if ($accdb->affected_rows()>0){
			$slipid = $accdb->insert_id();
			$data_det_d = array (
				'header_id' => $slipid,
				'acctnum' => $rhdr->accountd_id,
				'currency' => $rhdr->currency,
				'kurs' => 'pajak',
				'rate' => "",
				'rate' => $rhdr->kurs,
				'dbcd' => 'D',
				'desc' => $rhdr->acctnamed,
				'amount' => $rhdr->tot_amount,
				'valconvert' => $rhdr->tot_amount
			);
			$run = $accdb->insert('accslipdet', $data_det_d);
			$data_det_c = array (
				'header_id' => $slipid,
				'acctnum' => $rhdr->accountc_id,
				'currency' => $rhdr->currency,
				'kurs' => 'pajak',
				'rate' => $rhdr->kurs,
				'dbcd' => 'C',
				'desc' => $rhdr->acctnamec,
				'amount' => $rhdr->tot_amount,
				'valconvert' => $rhdr->tot_amount
			);
			$run = $accdb->insert('accslipdet', $data_det_c);
			$this->load->database('default', TRUE);
			$data = array (
				'created_journal' => 'yes'
			);
			$pk[$this->pk] = $id; 
		
			$run = $this->db->update($this->tbl, $data, $pk); 
			$rs=true;
		} else {
			$rs=false;
		}
		
		return $rs;
	}
	// Get Row for TPB --ir
	function getRow4Tpb($key=''){		
		$q = "SELECT a.*,a.".$this->pk." AS id,
			  DATE_FORMAT(matin_date,'%d/%m/%Y') AS Fmatin_date,
			  DATE_FORMAT(TgDaf,'%d/%m/%Y') AS FTgDaf,
			  DATE_FORMAT(TgAju,'%d/%m/%Y') AS FTgAju,
				c.matin_name,d.NmPrshn,e.NmPrshn as perusahaan,f.UrJnsDok,
				g.ID as id_supp, g.NAMA as nama_supp, g.ALAMAT as alamat_supp, g.NPWP as npwp_supp, g.KODE_ID as kode_id_supp,
				h.ID as id_perusahaan, h.NAMA as nama_perusahaan, h.ALAMAT as alamat_perusahaan, h.NPWP as npwp_perusahaan, h.KODE_ID as kode_id_perusahaan 
			  FROM ".$this->tbl." a
			  LEFT JOIN ".$this->tbl3." c ON c.".$this->pk3."=a.".$this->pk3."
				LEFT JOIN ".$this->tbl4." d ON d.".$this->pk4."=a.supplier
				LEFT JOIN ".$this->tbl4." e ON e.".$this->pk4."=a.kd_cmpy
				LEFT JOIN ".$this->tbl6." f ON f.".$this->pk6."=a.".$this->pk6."
				LEFT JOIN tpbdb.referensi_pemasok g ON g.".$this->tpb_pk_id."=d.".$this->tpb_fk_id."
				LEFT JOIN tpbdb.referensi_pengusaha h ON h.".$this->tpb_pk_id."=d.".$this->tpb_fk_id."
			  WHERE a.".$this->pk."='$key'
			  LIMIT 1";
		$rs=$this->db->query($q)->result();
		
		return $rs[0];
	}


	// Get CB Entitas 
	function getEntitasData($kdsupplier = ""){			
		$kdPenerima = '';
		$where = '';
		$kdPenerima = $this->session->userdata('kd_cmpy');
		if($kdsupplier != "") {
			$where = "  WHERE kdPrshn in ('".$kdsupplier."' )";
		}else{
			$where = "  WHERE kdPrshn in ('".$kdPenerima."' )";
		};
		$q = "SELECT *,KdPrshn AS id FROM mst_perusahaan a
			  LEFT JOIN mst_negara c ON c.KdNegara=a.Negara
			".$where."
			  ORDER BY KdPrshn";
		$rs=$this->db->query($q)->result();
		
		return $rs;
	}
	function getDokData($matin_no = ""){			
						
		$where = "WHERE matin_no IN ('" . $this->db->escape_str($matin_no) . "')";
		$q = "SELECT seri_dok AS kodeDokumen , dok_no AS nomorDokumen ,no_dok AS seriDokumen, tgl_dok AS tanggalDokumen
			  FROM mat_dokumen
			  " . $where . "
			  ORDER BY no_dok ASC";
		
		$rs = $this->db->query($q)->result();
		
		return $rs;
		
	}
	// Get Kontainer Data
	function getKonData($matin_no = ""){			
						
		$where = "WHERE matin_id IN ('" . $this->db->escape_str($matin_no) . "')";
		$q = "SELECT SERI as seriKontainer, NOMOR_KONTAINER as nomorKontainer, KODE_UKURAN_KONTAINER as kodeUkuranKontainer, KODE_JENIS_KONTAINER as kodeJenisKontainer, KODE_TIPE_KONTAINER as kodeTipeKontainer
			  FROM mat_kontainer
			  " . $where . "
			  ORDER BY SERI ASC";
		$rs = $this->db->query($q)->result();

		return $rs;

	}
	// Get Jaminan Data 
	function getJaminanData($matin_no = ""){			
		$where = "WHERE matin_no IN ('" . $this->db->escape_str($matin_no) . "')";
		$q = "SELECT nomorBpj, tanggalBpj, kodeJenisJaminan, nomorJaminan, tanggalJaminan, tanggalJatuhTempo, penjamin, nilaiJaminan, matin_no, idJaminan
FROM jaminan	
			  " . $where . "
			  ORDER BY idJaminan ASC";
		$rs = $this->db->query($q)->result();

		return $rs;

	}
	// Get All Detail for TPB --ir
	function getDetAll4Tpb($key=''){
		
		$q="SELECT a.*,matin_id AS id,
			FORMAT(qty, 2) AS Fqty,
			FORMAT(Dqty, 2) AS Dqty,
			FORMAT(qty,2)-FORMAT(Dqty, 2) AS Bqty,
			FORMAT(price, 4) AS Fprice,
			FORMAT(qty*price, 2) AS amount,
			b.NmBarang,b.Sat
		  	FROM ".$this->tbl2." a 
		  	LEFT JOIN ".$this->tbl5." b ON KdBarang = mat_id 
		  	WHERE ".$this->pk."='$key' 
		  	ORDER BY child_no ASC";
		$rs=$this->db->query($q)->result();
		
		return $rs;
	}
	// Count Item for TPB --ir
	function countItem4Tpb($key=''){
		$q="SELECT COUNT(".$this->pk.") as count
		  	FROM ".$this->tbl2."
		  	WHERE ".$this->pk."='$key'"; 
		$rs=$this->db->query($q)->result();
		
		return $rs;
	}
	// Get ID Bahan Baku TPB --ir
	function getIDheaderTpb(){	
		$tpbdb = $this->load->database('tpb', TRUE);
		$q = "SELECT MAX(ID) as ID, NOMOR_AJU from tpb_header";
		$rs=$tpbdb->query($q)->result();
		
		return $rs[0];
	}
	// Get ID Bahan Baku TPB --ir
	function getIDbarangTpb(){	
		$tpbdb = $this->load->database('tpb', TRUE);
		$q = "SELECT MAX(ID) as ID from tpb_barang";
		$rs=$tpbdb->query($q)->result();
		
		return $rs[0];
	}
	// Get ID Bahan Baku TPB --ir
	function getIDbahanbakuTpb(){	
		$tpbdb = $this->load->database('tpb', TRUE);
		$q = "SELECT MAX(ID) as ID from tpb_bahan_baku";
		$rs=$tpbdb->query($q)->result();
		
		return $rs[0];
	}
	// Get Bahan Baku FG --ir
	function getBahanbaku($key=''){
		$q="SELECT b.mat_id 
		FROM mat_bomhdr_sub a, mat_bomdet_sub b 
		WHERE a.bom_id = b.bom_id 
		AND a.fg_id = '$key'";
		$rs=$this->db->query($q)->result();
		
		return $rs;
	}
	
	// Transfer to Ceisa --ir
	// function transferCeisa($id){
	// 	$rhdr = $this->getRow4Tpb($id);
	// 	$rdet = $this->getDetAll($rhdr->id);
	// 	$countItem = $this->countItem4Tpb($rhdr->id);
		
	// 	$idheader = $this->getIDheaderTpb();
	// 	$NOMOR_AJU	=	$idheader->NOMOR_AJU;
	// 	$front 	= substr($NOMOR_AJU,0,-14);
	// 	$date  	= date("Ymd");
	// 	$back  	= substr($NOMOR_AJU,-6);
	// 	$back 	= str_pad($back+1, 6, "0", STR_PAD_LEFT);
	// 	$NOMOR_AJU	= $front.$date.$back;
	// 	$tpbdb = $this->load->database('tpb', TRUE);
	// 	$kd_bc = "";
	// 	$bc = $rhdr->KdJnsDok;
	// 	if($bc == "1" ) $kd_bc = "23";
	// 	else if($bc == "2" ) $kd_bc = "24";
	// 	else if($bc == "3" ) $kd_bc = "25";
	// 	else if($bc == "4" ) $kd_bc = "261";
	// 	else if($bc == "5" ) $kd_bc = "262";
	// 	else if($bc == "6" ) $kd_bc = "27";
	// 	else if($bc == "7" ) $kd_bc = "30";
	// 	else if($bc == "8" ) $kd_bc = "40";
	// 	else if($bc == "9" ) $kd_bc = "41";
	// 	else if($bc == "10" ) $kd_bc = "27";
	// 	else $kd_bc == "";
		
	// 	$dataheader = array (
	// 		'ID'												=> '',
	// 		'ALAMAT_PEMASOK'						=> $rhdr->alamat_supp,
	// 		'ALAMAT_PEMILIK'						=> $rhdr->alamat_perusahaan,
	// 		'ALAMAT_PENERIMA_BARANG'		=> $rhdr->alamat_perusahaan,
	// 		'ALAMAT_PENGIRIM'						=> $rhdr->alamat_supp,
	// 		'ALAMAT_PENGUSAHA'					=> $rhdr->alamat_perusahaan,
	// 		'ALAMAT_PPJK'								=> '',
	// 		'API_PEMILIK'								=> '',
	// 		'API_PENERIMA'							=> '',
	// 		'API_PENGUSAHA'							=> '',
	// 		'ASAL_DATA'									=> '',
	// 		'ASURANSI'									=> '',
	// 		'BIAYA_TAMBAHAN'						=> '',
	// 		'BRUTO'											=> $rhdr->Bruto,
	// 		'CIF'												=> $rhdr->cif,
	// 		'CIF_RUPIAH'								=> '',
	// 		'DISKON'										=> '',
	// 		'FLAG_PEMILIK'							=> '',
	// 		'FLAG_URL_DOKUMEN_PABEAN'		=> '',
	// 		'FOB'												=> '',
	// 		'FREIGHT'										=> '',
	// 		'HARGA_BARANG_LDP'					=> '',
	// 		'HARGA_INVOICE'							=> '',
	// 		'HARGA_PENYERAHAN'					=> $rhdr->HargaSerah,
	// 		'HARGA_TOTAL'								=> '',
	// 		'ID_MODUL'									=> '',
	// 		'ID_PEMASOK'								=> $rhdr->id_supp,
	// 		'ID_PEMILIK'								=> $rhdr->id_perusahaan,
	// 		'ID_PENERIMA_BARANG'				=> $rhdr->id_perusahaan,
	// 		'ID_PENGIRIM'								=> $rhdr->id_supp,
	// 		'ID_PENGUSAHA'							=> $rhdr->npwp_perusahaan,
	// 		'ID_PPJK'										=> '',
	// 		'JABATAN_TTD'								=> 'SUPERVISOR',
	// 		'JUMLAH_BARANG'							=> $rhdr->JmlBarang,
	// 		'JUMLAH_KEMASAN'						=> '',
	// 		'JUMLAH_KONTAINER'					=> '',
	// 		'KESESUAIAN_DOKUMEN'				=> '',
	// 		'KETERANGAN'								=> '',
	// 		'KODE_ASAL_BARANG'					=> '',
	// 		'KODE_ASURANSI'							=> '',
	// 		'KODE_BENDERA'							=> '',
	// 		'KODE_CARA_ANGKUT'					=> '',
	// 		'KODE_CARA_BAYAR'						=> '',
	// 		'KODE_DAERAH_ASAL'					=> '',
	// 		'KODE_DOKUMEN_PABEAN'				=> $kd_bc,
	// 		'KODE_FASILITAS'						=> '',
	// 		'KODE_FTZ'									=> '',
	// 		'KODE_HARGA'								=> '',
	// 		'KODE_ID_PEMASOK'						=> $rhdr->kode_id_supp,
	// 		'KODE_ID_PEMILIK'						=> $rhdr->kode_id_perusahaan,
	// 		'KODE_ID_PENERIMA_BARANG'		=> $rhdr->kode_id_perusahaan,
	// 		'KODE_ID_PENGIRIM'					=> $rhdr->kode_id_supp,
	// 		'KODE_ID_PENGUSAHA'					=> $rhdr->kode_id_perusahaan,
	// 		'KODE_ID_PPJK'							=> '',
	// 		'KODE_JENIS_API'						=> '',
	// 		'KODE_JENIS_API_PEMILIK'		=> '',
	// 		'KODE_JENIS_API_PENERIMA'		=> '',
	// 		'KODE_JENIS_API_PENGUSAHA'	=> '',	
	// 		'KODE_JENIS_BARANG'					=> '',
	// 		'KODE_JENIS_BC25'						=> '',
	// 		'KODE_JENIS_NILAI'					=> '',
	// 		'KODE_JENIS_PEMASUKAN01'		=> '',
	// 		'KODE_JENIS_PEMASUKAN02'		=> '',
	// 		'KODE_JENIS_TPB'						=> '1',
	// 		'KODE_KANTOR'								=> '051000',
	// 		'KODE_KANTOR_BONGKAR'				=> '',
	// 		'KODE_KANTOR_TUJUAN'				=> '050900',
	// 		'KODE_LOKASI_BAYAR'					=> '',
	// 		'KODE_NEGARA_PEMASOK'				=> '',
	// 		'KODE_NEGARA_PEMILIK'				=> '',
	// 		'KODE_NEGARA_PENGIRIM'			=> '',
	// 		'KODE_NEGARA_TUJUAN'				=> '',
	// 		'KODE_PEL_BONGKAR'					=> '',
	// 		'KODE_PEL_MUAT'							=> '',
	// 		'KODE_PEL_TRANSIT'					=> '',
	// 		'KODE_PEMBAYAR'							=> '',
	// 		'KODE_STATUS'								=> '',
	// 		'KODE_STATUS_PENGUSAHA'			=> '',
	// 		'KODE_STATUS_PERBAIKAN'			=> '',
	// 		'KODE_TPS'									=> '',
	// 		'KODE_TUJUAN_PEMASUKAN'			=> '',
	// 		'KODE_TUJUAN_PENGIRIMAN'		=> '',
	// 		'KODE_TUJUAN_TPB'						=> '',
	// 		'KODE_TUTUP_PU'							=> '',
	// 		'KODE_VALUTA'								=> $rhdr->currency,
	// 		'KOTA_TTD'									=> 'CIKARANG',
	// 		'LOKASI_ASAL'								=> '',
	// 		'LOKASI_TUJUAN'							=> '',
	// 		'NAMA_PEMASOK'							=> $rhdr->nama_supp,
	// 		'NAMA_PEMILIK'							=> $rhdr->nama_perusahaan,
	// 		'NAMA_PENERIMA_BARANG'			=> $rhdr->nama_perusahaan,
	// 		'NAMA_PENGANGKUT'						=> '',
	// 		'NAMA_PENGIRIM'							=> $rhdr->nama_supp,
	// 		'NAMA_PENGUSAHA'						=> $rhdr->nama_perusahaan,
	// 		'NAMA_PPJK'									=> '',
	// 		'NAMA_TTD'									=> '',
	// 		'NDPBM'											=> '',
	// 		'NETTO'											=> $rhdr->Netto,
	// 		'NILAI_INCOTERM'						=> '',
	// 		'NIPER_PENERIMA'						=> '',
	// 		'NOMOR_AJU'									=> $NOMOR_AJU,
	// 		'NOMOR_API'									=> '',
	// 		'NOMOR_BC11'								=> '',
	// 		'NOMOR_BILLING'							=> '',
	// 		'NOMOR_DAFTAR'							=> '',
	// 		'NOMOR_IJIN_BPK_PEMASOK'		=> '',
	// 		'NOMOR_IJIN_BPK_PENGUSAHA'	=> '',
	// 		'NOMOR_IJIN_TPB'						=> '',
	// 		'NOMOR_IJIN_TPB_PENERIMA'		=> '',
	// 		'NOMOR_POLISI'							=> '',
	// 		'NOMOR_VOY_FLIGHT'					=> '',
	// 		'NPPPJK'										=> '',
	// 		'NPWP_BILLING'							=> '',
	// 		'POS_BC11'									=> '',
	// 		'SERI'											=> '',
	// 		'SUBPOS_BC11'								=> '',
	// 		'SUBSUBPOS_BC11'						=> '',
	// 		'TANGGAL_AJU'								=> date("Y-m-d h:i:sa"),
	// 		'TANGGAL_BC11'							=> '',
	// 		'TANGGAL_BERANGKAT'					=> '',
	// 		'TANGGAL_BILLING'						=> '',
	// 		'TANGGAL_DAFTAR'						=> '',
	// 		'TANGGAL_IJIN_BPK_PEMASOK'	=> '',
	// 		'TANGGAL_IJIN_BPK_PENGUSAHA'=> '',
	// 		'TANGGAL_IJIN_TPB'					=> '',
	// 		'TANGGAL_NPPPJK'						=> '',
	// 		'TANGGAL_TIBA'							=> '',
	// 		'TANGGAL_TTD'								=> date("Y-m-d h:i:sa"),
	// 		'TGL_JATUH_TEMPO_BILLING'		=> '',
	// 		'TOTAL_BAYAR'								=> '',
	// 		'TOTAL_BEBAS'								=> '',
	// 		'TOTAL_DILUNASI'						=> '',
	// 		'TOTAL_JAMIN'								=> '',
	// 		'TOTAL_SUDAH_DILUNASI'			=> '',
	// 		'TOTAL_TANGGUH'							=> '',
	// 		'TOTAL_TANGGUNG'						=> '',
	// 		'TOTAL_TIDAK_DIPUNGUT'			=> '',
	// 		'URL_DOKUMEN_PABEAN'				=> '',
	// 		'VERSI_MODUL'								=> '3.1.6',
	// 		'VOLUME'										=> '',
	// 		'WAKTU_BONGKAR'							=> '',
	// 		'WAKTU_STUFFING'							=> ''
	// 	);
		
		
	// 	$idheader = $this->getIDheaderTpb();
	// 	$dataDokumen = array (
	// 		'FLAG_URL_DOKUMEN'  	=> "",
	// 		'KODE_JENIS_DOKUMEN'  => $kd_bc,
	// 		'NOMOR_DOKUMEN'				=> $rhdr->NoDaf,
	// 		'SERI_DOKUMEN' 				=> '',
	// 		'TANGGAL_DOKUMEN' 		=> $rhdr->TgDaf,
	// 		'TIPE_DOKUMEN'  			=> "",
	// 		'URL_DOKUMEN' 				=> "",
	// 		'ID_HEADER' 					=> $idheader->ID
	// 	);
	
		
	// 	// $data = array (
	// 	// 	'ID_HEADER' 					=> $idheader->ID
	// 	// );
	// 	// $run = $tpbdb->insert('tpb_detil_status', $data);
	// 	// $data = array (
	// 	// 	'ID_HEADER' 					=> $idheader->ID
	// 	// );
	// 	// $run = $tpbdb->insert('tpb_respon', $data);
		
	// 	// $data = array (
	// 	// 	'ID_HEADER' 					=> $idheader->ID
	// 	// );
	// 	// $run = $tpbdb->insert('tpb_npwp_billing', $data);
		
	// 	// $data = array (
	// 	// 	'ID_HEADER' 					=> $idheader->ID
	// 	// );
	// 	// $run = $tpbdb->insert('tpb_pungutan', $data);
		
	// 	// $data = array (
	// 	// 	'ID_HEADER' 					=> $idheader->ID
	// 	// );
	// 	// $run = $tpbdb->insert('tpb_kontainer', $data);
		
	// 	// $data = array (
	// 	// 	'ID_HEADER' 					=> $idheader->ID
	// 	// );
	// 	// $run = $tpbdb->insert('tpb_jaminan', $data);
	// 	// $data = array (
	// 	// 	'ID'								=> "",
	// 	// 	'JUMLAH_KEMASAN'		=> "",
	// 	// 	'KESESUAIAN_DOKUMEN'=> "",
	// 	// 	'KETERANGAN'				=> "",
	// 	// 	'KODE_JENIS_KEMASAN'=> $rhdr->packing,
	// 	// 	'MERK_KEMASAN'			=> "",
	// 	// 	'NIP_GATE_IN'				=> "",
	// 	// 	'NIP_GATE_OUT'			=> "",
	// 	// 	'NO_POLISI'					=> "",
	// 	// 	'NOMOR_SEGEL'				=> "",
	// 	// 	'SERI_KEMASAN'			=> "",
	// 	// 	'WAKTU_GATE_IN'			=> "",
	// 	// 	'WAKTU_GATE_OUT'		=> "", 
	// 	// 	'ID_HEADER'					=> $idheader->ID
	// 	// );
	// 	// $run = $tpbdb->insert('tpb_kemasan', $data);
	// 	foreach($rdet as $rdet){
	// 		$databarang  = array (
	// 			'KODE_BARANG' 		=> $rdet->mat_id,
	// 			'HARGA_SATUAN'  	=> $rdet->price,
	// 			'HARGA_INVOICE'  	=> $rdet->qty*$rdet->price,
	// 			'ID_HEADER'				=> $idheader->ID
	// 		);

	// 		var_dump($dataheader);
	// 		var_dump($dataDokumen);
	// 		var_dump($databarang)	;

		
	// 		// $idbarang = $this->getIDbarangTpb();
	// 		// $data = array (
	// 		// 	'ID_BARANG' 			=> $idbarang->ID,
	// 		// 	'ID_HEADER'				=> $idheader->ID
	// 		// );
	// 		// $run = $tpbdb->insert('tpb_barang_tarif', $data);
			
	// 		// $data = array (
	// 		// 	'ID_BARANG' 			=> $idbarang->ID,
	// 		// 	'ID_HEADER'				=> $idheader->ID
	// 		// );
		
						
	// 		$bahanbaku = $this->getBahanBaku($rdet->mat_id);
	// 		// if(empty($bahanbaku)){
	// 		// 	$data = array (
	// 		// 		'KODE_BARANG' 		=> $rdet->mat_id,
	// 		// 		'ID_BARANG'				=> $idbarang->ID,
	// 		// 		'ID_HEADER'				=> $idheader->ID
	// 		// 	);
	// 		// 	$run = $tpbdb->insert('tpb_bahan_baku', $data);
				
	// 		// 	$idbahanbaku = $this->getIDbahanbakuTpb();
	// 		// 	$data = array (
	// 		// 		'ID_BAHAN_BAKU'		=> $idbahanbaku->ID,
	// 		// 		'ID_BARANG'				=> $idbarang->ID,
	// 		// 		'ID_HEADER'				=> $idheader->ID
	// 		// 	);
	// 		// 	$run = $tpbdb->insert('tpb_bahan_baku_tarif', $data);
				
	// 		// 	$data = array (
	// 		// 		'ID_BAHAN_BAKU'		=> $idbahanbaku->ID,
	// 		// 		'ID_BARANG'				=> $idbarang->ID,
	// 		// 		'ID_HEADER'				=> $idheader->ID
	// 		// 	);
	// 		// 	$run = $tpbdb->insert('tpb_bahan_baku_dokumen', $data);
	// 		// }else{
	// 		// 	foreach($bahanbaku as $bahanbaku){
	// 		// 		$data = array (
	// 		// 			'KODE_BARANG' 		=> $bahanbaku->mat_id,
	// 		// 			'ID_BARANG'				=> $idbarang->ID,
	// 		// 			'ID_HEADER'				=> $idheader->ID
	// 		// 		);
	// 		// 		$run = $tpbdb->insert('tpb_bahan_baku', $data);
	// 		// 		$idbahanbaku = $this->getIDbahanbakuTpb();
	// 		// 		$data = array (
	// 		// 			'ID_BAHAN_BAKU'		=> $idbahanbaku->ID,
	// 		// 			'ID_BARANG'				=> $idbarang->ID,
	// 		// 			'ID_HEADER'				=> $idheader->ID
	// 		// 		);
	// 		// 		$run = $tpbdb->insert('tpb_bahan_baku_tarif', $data);
	// 		// 		$data = array (
	// 		// 			'ID_BAHAN_BAKU'		=> $idbahanbaku->ID,
	// 		// 			'ID_BARANG'				=> $idbarang->ID,
	// 		// 			'ID_HEADER'				=> $idheader->ID
	// 		// 		);
	// 		// 		$run = $tpbdb->insert('tpb_bahan_baku_dokumen', $data);
	// 		// 	}
	// 		// }
	// 	}
	// 	// if ($tpbdb->affected_rows()>0){
	// 	// 	$this->load->database('default', TRUE);
	// 	// 	$data = array (
	// 	// 		'transfer_ceisa' => 'yes'
	// 	// 	);
	// 	// 	$pk[$this->pk] = $id; 
		
	// 	// 	$run = $this->db->update($this->tbl, $data, $pk);
	// 	// 	$rs=true;
	// 	// } else {
	// 	// 	$rs=false;
	// 	// }
		
	// 	// return $rs;
	// }

	function editHdr($data,$id){
		$run = $this->db->update($this->tbl, $data, array($this->pk => $id)); 
		if ($this->db->affected_rows()>0){
			$rs=true;
			$log=$this->addLog($id,"Ubah ".$this->title." Header, ID = ".$id.", TOTAL AMOUNT = ".$data['tot_amount'].", TOTAL QTY = ".$data['tot_qty']);	
		} else {
			$rs=false;
		}		
		
		return $rs;
	}
	function editAmount($tot_amount,$id){
		$run = $this->db->update($this->tbl, $tot_amount, array($this->pk => $id)); 
		if ($this->db->affected_rows()>0){
			$rs=true;
			$log=$this->addLog($id,"Ubah ".$this->title." Header, ID = ".$id);	
		} else {
			$rs=false;
		}		
		
		return $rs;
	}
	function editQty($tot_qty,$id){
		$run = $this->db->update($this->tbl, $tot_qty, array($this->pk => $id)); 
		if ($this->db->affected_rows()>0){
			$rs=true;
			$log=$this->addLog($id,"Ubah ".$this->title." Header".$id);	
		} else {
			$rs=false;
		}		
		
		return $rs;
	}
	function editPartial($updatePartial,$id){
		$run = $this->db->update($this->tbl, $updatePartial, array($this->pk => $id)); 
		if ($this->db->affected_rows()>0){
			$rs=true;
			$log=$this->addLog($id,"Edit Partial ".$this->title." Header, ID = ".$id.", PARTIAL = ".$updatePartial['partial']);	
		} else {
			$rs=false;
		}		
		
		return $rs;
	}

	// Locked Previous Partial when Adding New Partial --ir
	function editLocked($updateLocked,$po_id,$partial){
		$run = $this->db->update($this->tbl, $updateLocked, array('po_id' => $po_id, 'partial' => $partial)); 
		if ($this->db->affected_rows()>0){
			$rs=true;
		} else {
			$rs=false;
		}		
		
		return $rs;
	}

	function editChildNo($updateChildNo,$pk){
		$run = $this->db->update($this->tbl2, $updateChildNo, $pk); 
		if ($this->db->affected_rows()>0){
			$rs=true;
		} else {
			$rs=false;
		}		
		
		return $rs;
	}
	function editDetail($updateDetail,$pk){
		$run = $this->db->update($this->tbl2, $updateDetail, $pk); 
		if ($this->db->affected_rows()>0){
			$rs=true;
			$log=$this->addLog($id,"Ubah ".$this->title." Detail, ID = ".$id);	
		} else {
			$rs=false;
		}		
		
		return $rs;
	}
	// GET DETAIL ITEM FROM MATOUT NUMBER --ir
	function getTotAmount($key=''){		
		$q = "SELECT FORMAT(tot_amount,2) as tot_amount,
					 FORMAT(SUM(qty),2) as tot_qty,
						FROM mat_inchdr_sub
						WHERE matin_id = '$key'";
		$rs=$this->db->query($q)->result();		
		return $rs;
	}

	function getTotAmount2($key=''){	
		$q = "SELECT SUM(amount) as tot_amount,
					SUM(volume) as tot_volume,
					FORMAT(SUM(qty),2) as tot_qty,
					y.po_id, y.partial, y.locked
						FROM mat_incdet_sub z, mat_inchdr_sub y
						WHERE z.matin_id = '$key'
						AND z.matin_id = y.matin_id";
		$rs=$this->db->query($q)->result();		
		return $rs;
	}

	function editDet($data,$pk){
		unset($data['NmBarang']);
		unset($data['Sat']);
		//unset($data['amount']);
		//print_r($data);
		$run = $this->db->update($this->tbl2, $data, $pk); 
		//echo $this->db->last_query();
		if ($this->db->affected_rows() > 0){
			$rs=true;
			$log=$this->addLog($pk,"Ubah ".$this->title." Detail, MATIN ID = ".$pk['matin_id'].", MAT ID = ".$pk['mat_id']);	
		} else {
			$rs=false;
		}
		
		return $rs;
	}

	function editDetKon($data,$pk){
	
		//unset($data['amount']);
		//print_r($data);
		$run = $this->db->update('mat_kontainer', $data, $pk); 
		//echo $this->db->last_query();
		if ($this->db->affected_rows() > 0){
			$rs=true;
			$log=$this->addLog($pk,"Ubah ".$this->title." Detail, MATIN ID = ".$pk['matin_id'].", MAT ID = ".$pk['mat_id']);	
		} else {
			$rs=false;
		}
		
		return $rs;
	}

	function editDetDok($data,$pk){
	
		//unset($data['amount']);
		//print_r($data);
		$run = $this->db->update('mat_dokumen', $data, $pk); 
		//echo $this->db->last_query();
		if ($this->db->affected_rows() > 0){
			$rs=true;
			$log=$this->addLog($pk,"Ubah ".$this->title." Detail, MATIN ID = ".$pk['matin_id'].", MAT ID = ".$pk['mat_id']);	
		} else {
			$rs=false;
		}
		
		return $rs;
		
	}

function editDetJaminan($data,$pk){
				    $data['tanggalJaminan'] = !empty($data['tanggalJaminan']) ? date('Y-m-d', strtotime($data['tanggalJaminan'])) : null;
    $data['tanggalBpj'] = !empty($data['tanggalBpj']) ? date('Y-m-d', strtotime($data['tanggalBpj'])) : null;
    $data['tanggalJatuhTempo'] = !empty($data['tanggalJatuhTempo']) ? date('Y-m-d', strtotime($data['tanggalJatuhTempo'])) : null;

	
		//unset($data['amount']);
		//print_r($data);
		$run = $this->db->update('jaminan', $data, $pk); 

	//	echo $this->db->last_query();
		if ($this->db->affected_rows() > 0){
			$rs=true;
			$log=$this->addLog($pk,"Ubah ".$this->title." Detail, MATIN ID = ".$pk['matin_no'].", MAT ID = ".$pk['mat_id']);	
		} else {
			$rs=false;
		}
		
		return $rs;
	}

	function del($id,$po_id,$partial){
		$rhdr = $this->getRow($id);
		$q = "SELECT ref_id 
					FROM mat_inchdr_sub a, acc_araphdr b 
					WHERE a.matin_id='$id' 
					AND b.ref_id = '$id'
					AND b.type = 'ap'";
		$row = $this->db->query($q)->result();
		if(empty($row)){
			// $this->db->delete($this->tbl, array($this->pk => $id)); 		
			// $this->db->delete($this->tbl2, array($this->pk => $id)); 		
			// if ($this->db->affected_rows()>0){
			if ($this->db->delete($this->tbl, array($this->pk => $id)) && $this->db->delete($this->tbl2, array($this->pk => $id))){

				$updateLocked = array(
					'locked'			=> 'no'
				);
				$this->mdl->editLocked($updateLocked, $po_id, $partial-1);
				$no = $rhdr->matin_no;
				$rs="success";
				$log=$this->addLog($id,"Hapus ".$this->title.", ID = ".$id.", NO = ".$no);	
			} else {
				$rs="failed";
			}		
			return $rs;		
		}else{
			$rs="reject ap";
			return $rs;
		}
	}

	public function delKon($id) {
		$this->db->where('id', $id);
		$this->db->delete('mat_kontainer');
		return $this->db->affected_rows() > 0; // Returns true if the row was deleted
	}
	public function delDok($id) {
		$this->db->where('id', $id);
		$this->db->delete('mat_dokumen');
		return $this->db->affected_rows() > 0; // Returns true if the row was deleted
	}

	public function deljaminan($id) {
		$this->db->where('idJaminan', $id);
		$this->db->delete('jaminan');
		return $this->db->affected_rows() > 0; // Returns true if the row was deleted
	}

// function get_token( $username,$password) {
// 		// URL for getting the token
	
// 		$token_url = "https://apis-gw.beacukai.go.id/nle-oauth/v1/user/login";
	
// 		// Prepare the data for the token request
// 		$token_data = [
// 			"username" => $username,
// 			"password" => $password
// 		];
	
// 		// Initialize cURL
// 		$ch = curl_init($token_url);
// 		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 		curl_setopt($ch, CURLOPT_HTTPHEADER, [
// 			"Content-Type: application/json"
// 		]);
// 		curl_setopt($ch, CURLOPT_POST, true);
// 		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($token_data));
	
// 		// Execute the request and decode the response
// 		$response = curl_exec($ch);
// 		curl_close($ch);
	
// 		// Convert the response to an associative array
// 		$response_data = json_decode($response, true);
	
// 		// Return the access token
// 		return $response_data['item']['access_token'] ?? null;
// 	}
	
// function sendToCeisa($jsonData,$webhookUrl,$id) {

// 	$username = "";
// 	$password ="" ;
// 	    // Get the token
// 	$token = get_token($username, $password);
// 	if (!function_exists('curl_version')) {
// 		die('cURL is not installed or enabled.');
// 	}
// 	if ($token) {

//     $ch = curl_init($webhookUrl);
// 	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// 	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//     curl_setopt($ch, CURLOPT_HTTPHEADER, [
//         'Content-Type: application/json',
//         'Accept: application/json',
// 		'Authorization: Bearer $token'	
//     ]);
//     curl_setopt($ch, CURLOPT_POST, true);
//     curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    
//     $response = curl_exec($ch);
// 	$error = curl_error($ch);

//     $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//     curl_close($ch);
    

	
 


// 		 	$this->load->database('default', TRUE);
// 		 	$data = array (
// 				'transfer_ceisa' => 'yes'
// 		 	);

// 		 	$pk[$this->pk] = $id; 
			
// 		 	$run = $this->db->update($this->tbl, $data, $pk);
			
// 			return $run;
// 		} else {
// 			return "Failed to get token.";
// 		}
	
// }
// }





function get_token($username, $password) {
    // Check if the token is already stored and valid

    if (isset($_SESSION['access_token']) && isset($_SESSION['token_expiration'])) {
        if (time() < $_SESSION['token_expiration']) {
            return $_SESSION['access_token'];
        }
    }

    // URL for getting the token
    $token_url = "https://apis-gw.beacukai.go.id/nle-oauth/v1/user/login";

    // Prepare the data for the token request
    $token_data = array(
        "username" => $username,
        "password" => $password
    );

    // Initialize cURL
    $ch = curl_init($token_url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Content-Type: application/json"
    ));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($token_data));

    // Execute the request and decode the response
    $response = curl_exec($ch);
	
    $error = curl_error($ch);
    curl_close($ch);

    // Convert the response to an associative array
    $response_data = json_decode($response, true);


	
    // Check if the token is received and store it along with its expiration time
    if (isset($response_data['item']['access_token']) && isset($response_data['item']['expires_in'])) {
        $_SESSION['access_token'] = $response_data['item']['access_token'];
        $_SESSION['token_expiration'] = time() + $response_data['item']['expires_in'];
		    // Debug: Verify storage

        return $_SESSION['access_token'];
    }

    return null;
}

function sendToCeisa($jsonData, $webhookUrl, $id) {
    $username = "apri25";
    $password = "Ventora25";

    // Get the token
    $token = $this->get_token($username, $password);

    if (!function_exists('curl_version')) {
        die('cURL is not installed or enabled.');
    }

    if ($token) {
        $ch = curl_init($webhookUrl);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Accept: application/json',
            'Authorization: Bearer ' . $token
        ));
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

        $response = curl_exec($ch);
        $error = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	
	
       	 curl_close($ch);
        // Handle database update
        $this->load->database('default', true);
        $data = array(
            'transfer_ceisa' => 'yes'
        );
        $pk[$this->pk] = $id;
        $run = $this->db->update($this->tbl, $data, $pk);

        return $response ;
    } else {
        return "Failed to get token.";
    }
}
}