<?php
	if ( ! function_exists('cek_printer'))
	{
		function cek_printer(){
			$ci = & get_instance();
			static $printer_row = NULL;
			if ($printer_row === NULL) {
				$printer_row = array();
				$cek_printer = $ci->model_app->view_where('printer', array('pub' =>1));
				if($cek_printer->num_rows()>0){
					$printer_row = $cek_printer->row_array();
				}
			}
			if(!empty($printer_row)){
				$row = $printer_row;
				if($row['slug']=='th' AND $row['pub']==1){
					echo "<script>
					let thermal = 1,
					max_item = ".$row['max_item'].";
					</script>";
					}elseif($row['slug']=='th58' AND $row['pub']==1){
					echo "<script>
					let thermal = 2,
					max_item = ".$row['max_item'].";
					</script>";
					}elseif($row['slug']=='direct58' AND $row['pub']==1){
					echo "<script>
					let thermal = 3,
					max_item = ".$row['max_item'].";
					</script>";
					}elseif($row['slug']=='direct85' AND $row['pub']==1){
					echo "<script>
					let thermal = 4,
					max_item = ".$row['max_item'].";
					</script>";
					}elseif($row['slug']=='dotmatrix' AND $row['pub']==1){
					echo "<script>
					let thermal = 5,
					max_item = ".$row['max_item'].";
					</script>";
					}else{
					echo "<script>
					let thermal = 0,
					max_item = ".$row['max_item'].";
					</script>";
				}
			}
		}
	}

	if ( ! function_exists('asset_version'))
	{
		/**
			* Stable asset version so browser cache remains effective.
			*
			* @param string|null $path Optional relative path from FCPATH.
			* @return string
		*/
		function asset_version($path = NULL)
		{
			static $versions = array();
			$key = $path ?: '__app__';
			if (isset($versions[$key])) {
				return $versions[$key];
			}

			$base_version = '1';
			$version_file = FCPATH.'version.json';
			if (is_file($version_file)) {
				$raw = @file_get_contents($version_file);
				$json = json_decode($raw, TRUE);
				if (!empty($json['aplikasi'][0])) {
					$meta = $json['aplikasi'][0];
					$parts = array();
					if (!empty($meta['version'])) {
						$parts[] = preg_replace('/[^0-9A-Za-z._-]/', '', (string) $meta['version']);
					}
					if (!empty($meta['updateDate'])) {
						$parts[] = preg_replace('/[^0-9]/', '', (string) $meta['updateDate']);
					}
					if (!empty($parts)) {
						$base_version = implode('-', $parts);
					}
				}
				$file_stamp = @filemtime($version_file);
				if ($file_stamp) {
					$base_version .= '-'.$file_stamp;
				}
			}

			if (!empty($path)) {
				$relative_path = ltrim(str_replace(array('\\', '../'), array('/', ''), (string) $path), '/');
				$absolute_path = FCPATH.$relative_path;
				if (is_file($absolute_path)) {
					$file_stamp = @filemtime($absolute_path);
					if ($file_stamp) {
						$base_version .= '-'.$file_stamp;
					}
				}
			}

			$versions[$key] = $base_version;
			return $versions[$key];
		}
	}
	
	if ( ! function_exists('detail_bayar'))
	{
		function detail_bayar($id,$dari,$sampai,$user,$setor){
			$ci = & get_instance();
			$query = $ci->db->query("SELECT 
			`bayar_invoice_detail`.`id_invoice`,
			`bayar_invoice_detail`.`lampiran`,
			`konsumen`.`nama`,
			`invoice`.`tgl_trx`,
			`invoice`.`id_invoice`,
			`invoice`.`id_transaksi`,
			`bayar_invoice_detail`.`tgl_bayar`,
			`bayar_invoice_detail`.`jml_bayar`,
			`jenis_bayar`.`nama_bayar`,
			`bayar_invoice_detail`.`id`,
			`bayar_invoice_detail`.`id_bayar`
			FROM
			`invoice`
			RIGHT OUTER JOIN `bayar_invoice_detail` ON (`invoice`.`id_invoice` = `bayar_invoice_detail`.`id_invoice`)
			INNER JOIN `jenis_bayar` ON (`bayar_invoice_detail`.`id_bayar` = `jenis_bayar`.`id`)
			INNER JOIN `konsumen` ON (`invoice`.`id_konsumen` = `konsumen`.`id`)
			WHERE  `bayar_invoice_detail`.id_bayar='$id' AND `bayar_invoice_detail`.`tgl_bayar` BETWEEN CAST('$dari' AS DATE) AND CAST('$sampai' AS DATE) AND `bayar_invoice_detail`.setor='$setor' AND `bayar_invoice_detail`.id_user = '$user' AND `invoice`.`status` = 'simpan' AND bayar_invoice_detail.hapus=0
			ORDER BY `bayar_invoice_detail`.`id`");
			
			$result = ($query->num_rows() > 0)?$query->result_array():FALSE; 
			return $result;
		}
	}
	
	if ( ! function_exists('kunci_harga'))
	{
		function kunci_harga($id){
			$ci = & get_instance();
			$row = $ci->model_app->pilih_where('lock_harga','produk',['id'=>$id]);
			if($row->num_rows() > 0){
				return $row->row()->lock_harga;
				}else{
				return 'N';
			}
		}
	}
	if ( ! function_exists('jumlah_satuan'))
	{
		function jumlah_satuan($tag){
			$ci = & get_instance();
			$row = $ci->model_app->view_where('satuan',['satuan'=>$tag]);
			if($row->num_rows() > 0){
				return $row->row()->jumlah;
				}else{
				return 0;
			}
		}
	}
	if ( ! function_exists('convert_to_satuan'))
	{
		function convert_to_satuan($tag,$jumlah){
			$ci = & get_instance();
			$row = $ci->model_app->view_where('satuan',['satuan'=>$tag])->row();
			$total = $jumlah * $row->jumlah;
			return $total;
		}
	}
	if ( ! function_exists('quote'))
	{
		function quote($text){
			global $CI;
			return $CI->db->escape($text);
		}
	}
	if ( ! function_exists('query'))
	{
		/**
			* Code pengaturan
			*
			@param $val array
			@return string
		*/
		function query($val){
			global $CI;
			return $CI->db->query($val);
		}
	}
	if ( ! function_exists('periode_stok'))
	{
		/**
			* Code pengaturan
			*
			@param $val array
			@return string
		*/
		function periode_stok($id=''){
			$ci = & get_instance();
			if($id==''){
				return '';
				}else{
				$result = $ci->model_app->view_where('laporan_stok',['id'=>$id])->row();
				return $result->title;
			}
		}
	}
	
	if ( ! function_exists('modul_cetak'))
	{
		/**
			* Code pengaturan
			*
			@param $val array
			@return string
		*/
		function modul_cetak($modul=''){
			$ci = & get_instance();
			if($modul==''){
				return array('ukuran'=>'A4','posisi'=>'potrait');
				}else{
				$result = $ci->model_app->view_where('pengaturan_kertas',['modul'=>$modul]);
				if($result->num_rows() > 0){
					return array('ukuran'=>$result->row()->ukuran,'posisi'=>$result->row()->posisi);
					}else{
					return array('ukuran'=>'A4','posisi'=>'potrait');
				}
			}
		}
	}
	
	if ( ! function_exists('cek_hitung'))
	{
		/**
			* Code pengaturan
			*
			@param $val array
			@return string
		*/
		function cek_hitung($id){
			$ci = & get_instance();
			$query = $ci->model_app->view_where('bahan',['id'=>$id]);
			$result = ($query->num_rows() > 0)?$query->row()->status:0; 
			return $result;
		}
	}
	if ( ! function_exists('cek_kunci'))
	{
		/**
			* Code pengaturan
			*
			@param $val array
			@return string
		*/
		function cek_kunci($id){
			$ci = & get_instance();
			$query = $ci->model_app->view_where('bahan',['id'=>$id]);
			$result = ($query->num_rows() > 0)?$query->row()->kunci:0; 
			return $result;
		}
	}
	
	if ( ! function_exists('cek_type_harga'))
	{
		/**
			* Code pengaturan
			*
			@param $val array
			@return string
		*/
		function cek_type_harga($id){
			$ci = & get_instance();
			$query = $ci->model_app->view_where('bahan',['id'=>$id]);
			$result = ($query->num_rows() > 0)?$query->row()->type_harga:0; 
			return $result;
		}
	}
	
	if ( ! function_exists('harga_beli'))
	{
		/**
			* Code pengaturan
			*
			@param $val array
			@return string
		*/
		function harga_beli($id){
			$ci = & get_instance();
			$query = $ci->model_app->view_where('bahan',['id'=>$id]);
			$result = ($query->num_rows() > 0)?$query->row()->harga_modal:0; 
			return $result;
		}
	}
	
	if ( ! function_exists('harga_hpp'))
	{
		/**
			* Code pengaturan
			*
			@param $val array
			@return string
		*/
		function harga_hpp($id){
			$ci = & get_instance();
			$query = $ci->model_app->view_where('bahan',['id'=>$id]);
			$result = ($query->num_rows() > 0)?$query->row()->harga:0; 
			return $result;
		}
	}
	
	if ( ! function_exists('input_stok_keluar'))
	{
		/**
			* Code pengaturan
			*
			@param $val array
			@return string
		*/
		function input_stok_keluar($id){
			$ci = & get_instance();
			// $result = $ci->model_app->view_where('invoice_detail',['id_invoice'=>$id])->result();
			$result = $ci->db
				->select('invoice_detail.id_bahan, invoice_detail.status_hitung, invoice_detail.tot_ukuran, invoice_detail.jumlah, invoice_detail.update_date, invoice_detail.id_satuan, satuan.jumlah AS jumlah_satuan')
				->from('bahan')
				->join('invoice_detail', 'bahan.id = invoice_detail.id_bahan', 'inner')
				->join('satuan', 'satuan.id = invoice_detail.id_satuan', 'left')
				->where('bahan.status_stok', 'Y')
				->where('invoice_detail.id_invoice', $id)
				->get()
				->result();
			if(!empty($result)){
				foreach($result AS $val){
					$jumlah = hitung_jumlah_stok_keluar($val);
					$data[] = [
					'id_bahan'=>$val->id_bahan,
					'id_invoice'=>$id,
					'jumlah'=>$jumlah,
					'create_date'=>$val->update_date
					];
					
				}
				$ci->db->insert_batch("stok_keluar",$data);
			}
			input_stok_keluar_bundle_invoice($id);
		}
	}
	
	if ( ! function_exists('input_stok_keluar_produk'))
	{
		/**
			* Code pengaturan
			*
			@param $val array
			@return string
		*/
		function input_stok_keluar_produk($id,$id_invoice){
			$ci = & get_instance();
			// $result = $ci->model_app->view_where('invoice_detail',['id_invoice'=>$id])->result();
			$val = $ci->db
				->select('invoice_detail.id_bahan, invoice_detail.status_hitung, invoice_detail.tot_ukuran, invoice_detail.jumlah, invoice_detail.update_date, invoice_detail.id_satuan, satuan.jumlah AS jumlah_satuan')
				->from('bahan')
				->join('invoice_detail', 'bahan.id = invoice_detail.id_bahan', 'inner')
				->join('satuan', 'satuan.id = invoice_detail.id_satuan', 'left')
				->where('bahan.status_stok', 'Y')
				->where('invoice_detail.id_rincianinvoice', $id)
				->get()
				->row();
			if(!empty($val)){
				$jumlah = hitung_jumlah_stok_keluar($val);
				$ket = 'Invoice Detail #'.$id;
				$exists = $ci->db
					->from('stok_keluar')
					->where('id_invoice', (int) $id_invoice)
					->where('id_bahan', (int) $val->id_bahan)
					->where('ket', $ket)
					->count_all_results();
				if ($exists > 0) {
					input_stok_keluar_bundle_produk($id,$id_invoice);
					return;
				}
				$data = [
				'id_bahan'=>$val->id_bahan,
				'id_invoice'=>$id_invoice,
				'jumlah'=>$jumlah,
				'create_date'=>$val->update_date,
				'ket'=>$ket
				];
				$ci->db->insert("stok_keluar",$data);
			}
			input_stok_keluar_bundle_produk($id,$id_invoice);
		}
	}
	if ( ! function_exists('hitung_jumlah_stok_keluar'))
	{
		function hitung_jumlah_stok_keluar($detail)
		{
			if ((int) $detail->status_hitung === 0) {
				return (float) $detail->jumlah;
			}

			$jumlah = (float) $detail->tot_ukuran;
			$faktor_satuan = isset($detail->jumlah_satuan) ? (float) $detail->jumlah_satuan : 1;
			if ($faktor_satuan <= 1) {
				return $jumlah;
			}

			if ((int) $detail->status_hitung === 2) {
				return $jumlah / $faktor_satuan;
			}

			return $jumlah / ($faktor_satuan * $faktor_satuan);
		}
	}
	if ( ! function_exists('stok_keluar_normalize_variant_text'))
	{
		function stok_keluar_normalize_variant_text($value)
		{
			$value = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
			$value = preg_replace('/\s+/', ' ', $value);
			return strtolower(trim($value));
		}
	}
	if ( ! function_exists('resolve_komposisi_variant_stok_keluar'))
	{
		function resolve_komposisi_variant_stok_keluar($ci, $component, $detail)
		{
			$target = (object) [
				'id_bahan' => (int) $component->id_bahan_komponen,
				'title' => isset($component->title) ? (string) $component->title : '',
				'status_stok' => isset($component->status_stok) ? (string) $component->status_stok : 'N',
				'is_variant' => false,
			];

			$keterangan = isset($detail->keterangan) ? stok_keluar_normalize_variant_text($detail->keterangan) : '';
			if (
				$keterangan === '' ||
				!$ci->db->field_exists('parent_bahan_id', 'bahan') ||
				!$ci->db->field_exists('varian_warna', 'bahan') ||
				!$ci->db->field_exists('varian_ukuran', 'bahan')
			) {
				return $target;
			}

			$variants = $ci->db
				->select('id,title,varian_warna,varian_ukuran,status_stok')
				->from('bahan')
				->where('parent_bahan_id', (int) $component->id_bahan_komponen)
				->where('pub', 1)
				->get()
				->result();

			if (empty($variants)) {
				return $target;
			}

			$componentTitle = isset($component->title) ? trim((string) $component->title) : '';
			foreach ($variants as $variant) {
				$warna = trim((string) $variant->varian_warna);
				$ukuran = trim((string) $variant->varian_ukuran);
				$variantParts = [];
				if ($warna !== '') {
					$variantParts[] = $warna;
				}
				if ($ukuran !== '') {
					$variantParts[] = $ukuran;
				}

				$labels = [
					(string) $variant->title,
					trim($componentTitle.' - '.implode(' / ', $variantParts)),
					trim(implode(' / ', $variantParts)),
					$ukuran,
				];

				foreach ($labels as $label) {
					if ($label !== '' && stok_keluar_normalize_variant_text($label) === $keterangan) {
						return (object) [
							'id_bahan' => (int) $variant->id,
							'title' => (string) $variant->title,
							'status_stok' => isset($variant->status_stok) ? (string) $variant->status_stok : 'N',
							'is_variant' => true,
						];
					}
				}
			}

			return $target;
		}
	}
	if ( ! function_exists('input_stok_keluar_bundle_invoice'))
	{
		function input_stok_keluar_bundle_invoice($id_invoice)
		{
			$ci = & get_instance();
			$rows = $ci->model_app
				->pilih_where('id_rincianinvoice,id_invoice', 'invoice_detail', ['id_invoice' => $id_invoice])
				->result();

			foreach ($rows as $row) {
				input_stok_keluar_bundle_produk($row->id_rincianinvoice, $row->id_invoice);
			}
		}
	}
	if ( ! function_exists('input_stok_keluar_bundle_produk'))
	{
		function input_stok_keluar_bundle_produk($id_detail,$id_invoice)
		{
			$ci = & get_instance();

			if (!$ci->db->table_exists('invoice_detail') || !$ci->db->table_exists('bahan') || !$ci->db->table_exists('stok_keluar') || !$ci->db->table_exists('bahan_komposisi')) {
				return;
			}

			$detail = $ci->db
				->select('invoice_detail.id_rincianinvoice, invoice_detail.id_invoice, invoice_detail.id_bahan, invoice_detail.jumlah, invoice_detail.update_date, invoice_detail.keterangan, bahan.title AS bahan_title')
				->from('invoice_detail')
				->join('bahan', 'invoice_detail.id_bahan = bahan.id', 'inner')
				->where('invoice_detail.id_rincianinvoice', (int) $id_detail)
				->limit(1)
				->get()
				->row();

			if (empty($detail)) {
				return;
			}

			$jumlahSet = (float) $detail->jumlah;
			if ($jumlahSet <= 0) {
				return;
			}

			$components = $ci->db
				->select('bahan_komposisi.id_bahan_komponen,bahan_komposisi.jumlah,bahan.status_stok,bahan.title')
				->from('bahan_komposisi')
				->join('bahan', 'bahan.id = bahan_komposisi.id_bahan_komponen', 'inner')
				->where('bahan_komposisi.id_bahan_parent', (int) $detail->id_bahan)
				->get()
				->result();

			if (empty($components)) {
				return;
			}

			foreach ($components as $component) {
				$stokTarget = resolve_komposisi_variant_stok_keluar($ci, $component, $detail);
				if ($stokTarget->status_stok !== 'Y') {
					continue;
				}

				$ket = 'Komposisi #'.$detail->id_rincianinvoice.': '.$detail->bahan_title;
				if (!empty($stokTarget->is_variant)) {
					$ci->db
						->where('id_invoice', (int) $id_invoice)
						->where('id_bahan', (int) $component->id_bahan_komponen)
						->where('ket', $ket)
						->delete('stok_keluar');

					$ket .= ' -> '.$stokTarget->title;
				}

				$exists = $ci->db
					->from('stok_keluar')
					->where('id_invoice', (int) $id_invoice)
					->where('id_bahan', (int) $stokTarget->id_bahan)
					->where('ket', $ket)
					->count_all_results();

				if ($exists > 0) {
					continue;
				}

				$ci->db->insert('stok_keluar', [
					'id_bahan' => (int) $stokTarget->id_bahan,
					'id_invoice' => (int) $id_invoice,
					'jumlah' => $jumlahSet * (float) $component->jumlah,
					'create_date' => !empty($detail->update_date) ? $detail->update_date : date('Y-m-d H:i:s'),
					'ket' => $ket,
				]);
			}
		}
	}
	if ( ! function_exists('sum_penjualan'))
	{
		/**
			* Code pengaturan
			*
			@param $val string
			@return string
		*/
		
		function sum_penjualan($bulan,$tahun,$id)
		{
			$ci = & get_instance();
			$ci->db->select('SUM(`bayar_invoice_detail`.`jml_bayar`) AS `total`');
			$ci->db->select('SUM(`invoice_detail`.`hpp`) AS `total_hpp`');
			$ci->db->select('SUM(`invoice_detail`.`jumlah` * `invoice_detail`.`harga`) AS `total_detail`');
			$ci->db->from('jenis_cetakan');
			$ci->db->join('invoice_detail', '`jenis_cetakan`.`id_jenis` = `invoice_detail`.`jenis_cetakan`');
			$ci->db->join('bahan', '`invoice_detail`.`id_bahan` = `bahan`.`id`');
			$ci->db->join('bayar_invoice_detail', '`invoice_detail`.`id_invoice` = `bayar_invoice_detail`.`id_invoice`');
			$ci->db->where("MONTH(invoice_detail.update_date)='$bulan'");
			$ci->db->where("YEAR(invoice_detail.update_date)='$tahun'");
			// $ci->db->where('invoice_detail.update_date BETWEEN "'. date('Y-m-d', strtotime($start_date)). '" and "'. date('Y-m-d', strtotime($end_date)).'"');
			$ci->db->where('`invoice_detail`.`jenis_cetakan`',$id);
			$query = $ci->db->get(); 
			$result = ($query->num_rows() > 0)?$query->row():0; 
			$total = ['total_jual'=>$result->total,'total_detail'=>$result->total_detail,'total_hpp'=>$result->total_hpp];
			return $total; 
		}
	}
	if ( ! function_exists('sum_hpps'))
	{
		/**
			* Code pengaturan
			*
			@param $val string
			@return string
		*/
		
		function sum_hpps($bulan,$tahun)
		{
			$ci = & get_instance();
			$ci->db->select('SUM(`invoice_detail`.`hpp`) AS `total`');
			$ci->db->from('invoice');
			$ci->db->join('invoice_detail','`invoice`.`id_invoice` = `invoice_detail`.`id_invoice`');
			$ci->db->join('bahan','`invoice_detail`.`id_bahan` = `bahan`.`id`');
			$ci->db->where("MONTH(invoice.tgl_trx)",$bulan);
			$ci->db->where("YEAR(invoice.tgl_trx)",$tahun);
			$ci->db->where("invoice.status",'simpan');
			// $ci->db->where('`bahan`.`status_stok`','Y');
			$query = $ci->db->get(); 
			$result = ($query->num_rows() > 0)?$query->row():FALSE; 
			return $result->total; 
		}
	}
	
	if ( ! function_exists('sum_hppsold'))
	{
		/**
			* Code pengaturan
			*
			@param $val string
			@return string
		*/
		function sum_hppsold($bulan,$tahun)
		{
			$ci = & get_instance();
			$ci->db->select('SUM(`invoice_detail`.`hpp`) AS `total`');
			$ci->db->from('bahan');
			$ci->db->join('invoice_detail','`bahan`.`id` = `invoice_detail`.`id_bahan`');
			$ci->db->where("MONTH(invoice_detail.update_date)",$bulan);
			$ci->db->where("YEAR(invoice_detail.update_date)",$tahun);
			// $ci->db->where('`bahan`.`status_stok`','Y');
			$query = $ci->db->get(); 
			$result = ($query->num_rows() > 0)?$query->row():FALSE; 
			return $result->total; 
		}
	}
	
	if ( ! function_exists('sum_hpp'))
	{
		/**
			* Code pengaturan
			*
			@param $val string
			@return string
		*/
		function sum_hpp($bulan,$tahun,$id)
		{
			$ci = & get_instance();
			$ci->db->select('invoice_detail.hpp, SUM(`bahan`.`harga_modal`) AS `total`');
			$ci->db->from('jenis_cetakan');
			$ci->db->join('invoice_detail', '`jenis_cetakan`.`id_jenis` = `invoice_detail`.`jenis_cetakan`');
			$ci->db->join('bahan', '`invoice_detail`.`id_bahan` = `bahan`.`id`');
			$ci->db->where("MONTH(invoice_detail.update_date)='$bulan'");
			$ci->db->where("YEAR(invoice_detail.update_date)='$tahun'");
			// $ci->db->where('invoice_detail.update_date BETWEEN "'. date('Y-m-d', strtotime($start_date)). '" and "'. date('Y-m-d', strtotime($end_date)).'"');
			$ci->db->where('`jenis_cetakan`.`id_jenis`',$id);
			$query = $ci->db->get(); 
			$result = ($query->num_rows() > 0)?$query->row():FALSE; 
			return $result; 
		}
	}
	if ( ! function_exists('sum_bayar_pembelian'))
	{
		/**
			* Code pengaturan
			*
			@param $val string
			@return string
		*/
		function sum_bayar_pembelian($id)
		{
			$ci = & get_instance();
			$ci->db->select('SUM(`bayar_pembelian`.`jml_bayar`) AS `total`');
			$ci->db->from('bayar_pembelian');
			$ci->db->where('`bayar_pembelian`.`id_pembelian`',$id);
			$query = $ci->db->get(); 
			$result = ($query->num_rows() > 0)?$query->row()->total:0; 
			return $result; 
		}
	}
	if ( ! function_exists('sum_pembelian'))
	{
		/**
			* Code pengaturan
			*
			@param $val string
			@return string
		*/
		function sum_pembelian($bulan,$tahun,$id)
		{
			$ci = & get_instance();
			$ci->db->select('id_pembelian`, SUM(jumlah * harga) AS total');
			$ci->db->from('pembelian_detail');
			$ci->db->where("MONTH(create_date)='$bulan'");
			$ci->db->where("YEAR(create_date)='$tahun'");
			$ci->db->where('id_biaya',$id);
			$query = $ci->db->get(); 
			$result = ($query->num_rows() > 0)?$query->row():FALSE; 
			return $result; 
		}
	}
	
	if ( ! function_exists('sum_pengeluaran'))
	{
		/**
			* Code pengaturan
			*
			@param $val string
			@return string
		*/
		
		function sum_pengeluaran($bulan,$tahun,$id)
		{
			$ci = & get_instance();
			$ci->db->select('SUM(jumlah * harga) AS total');
			$ci->db->from('pengeluaran_detail');
			// $ci->db->where("DATE(create_date) >=", $start_date);
			// $ci->db->where("DATE(create_date) <=", $end_date);
			$ci->db->where("MONTH(create_date)='$bulan'");
			$ci->db->where("YEAR(create_date)='$tahun'");
			$ci->db->where('id_biaya',$id);
			$query = $ci->db->get(); 
			$result = ($query->num_rows() > 0)?$query->row()->total:FALSE; 
			return $result; 
		}
	}
	
	if ( ! function_exists('stok_masuk'))
	{
		/**
			* Code pengaturan
			*
			@param $val string
			@return string
		*/
		function stok_masuk($id)
		{
			$ci = & get_instance();
			$ci->db->select_sum('jumlah');
			$ci->db->from('stok_masuk');
			$ci->db->where('id_bahan',$id);
			$ci->db->group_by('id_bahan');
			$query = $ci->db->get(); 
			$result = ($query->num_rows() > 0)?$query->row()->jumlah:0; 
			return $result; 
		}
	}
	if ( ! function_exists('stok_keluar'))
	{
		/**
			* Code pengaturan
			*
			@param $val string
			@return string
		*/
		function stok_keluar($val)
		{
			$ci = & get_instance();
			$qry = $ci->db->query("SELECT SUM(jumlah) AS jml FROM stok_keluar where id_bahan=$val GROUP BY id_bahan");
			if($qry->num_rows() >0 ){
				$data = $qry->row()->jml;
				}else{
				$data = 0;
			}
			return $data;
		}
	}
	
	
	if ( ! function_exists('cek_stok_keluar'))
	{
		/**
			* Code pengaturan
			*
			@param $val string
			@return string
		*/
		function cek_stok_keluar($val)
		{
			$ci = & get_instance();
			$qry = $ci->db->query("SELECT SUM(jumlah) AS jml FROM stok_keluar where id_invoice=$val GROUP BY id_invoice");
			if($qry->num_rows() >0 ){
				$data = $qry->row()->jml;
				}else{
				$data = 0;
			}
			return $data;
		}
	}

	if ( ! function_exists('stok_keluar_trigger_status'))
	{
		function stok_keluar_trigger_status()
		{
			$ci = & get_instance();
			$status = 3;
			if ($ci->db->table_exists('shared_folder')) {
				$row = $ci->db
					->select('isi')
					->from('shared_folder')
					->where('nama', 'stok_keluar_trigger_status')
					->limit(1)
					->get()
					->row();
				if (!empty($row) && in_array((int) $row->isi, [2, 3], true)) {
					$status = (int) $row->isi;
				}
			}
			return $status;
		}
	}

	if ( ! function_exists('stok_keluar_trigger_status_label'))
	{
		function stok_keluar_trigger_status_label($status = null)
		{
			$status = $status === null ? stok_keluar_trigger_status() : (int) $status;
			$meta = job_status_meta($status);
			return $meta['label'];
		}
	}

	if ( ! function_exists('stok_keluar_should_trigger'))
	{
		function stok_keluar_should_trigger($status)
		{
			$status = (int) $status;
			$trigger = stok_keluar_trigger_status();
			return job_status_rank($status) >= job_status_rank($trigger);
		}
	}

	if ( ! function_exists('app_license_normalize'))
	{
		function app_license_normalize($value)
		{
			$value = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
			$value = strtolower(trim($value));
			return preg_replace('/\s+/', ' ', $value);
		}
	}

	if ( ! function_exists('app_license_signature'))
	{
		function app_license_signature($perusahaan, $email)
		{
			$payload = app_license_normalize($perusahaan).'|'.app_license_normalize($email);
			return substr(hash_hmac('sha256', $payload, 'poskasirpercetakan-license-v1'), 0, 40);
		}
	}

	if ( ! function_exists('app_license_shared_value'))
	{
		function app_license_shared_value($nama)
		{
			$ci = & get_instance();
			if (!$ci->db->table_exists('shared_folder')) {
				return null;
			}

			$row = $ci->db
				->select('isi')
				->from('shared_folder')
				->where('nama', $nama)
				->limit(1)
				->get()
				->row_array();

			return $row ? $row['isi'] : null;
		}
	}

	if ( ! function_exists('app_license_save_shared_value'))
	{
		function app_license_save_shared_value($nama, $isi)
		{
			$ci = & get_instance();
			if (!$ci->db->table_exists('shared_folder')) {
				return false;
			}

			$exists = $ci->db
				->select('id')
				->from('shared_folder')
				->where('nama', $nama)
				->limit(1)
				->get()
				->row_array();

			if ($exists) {
				return $ci->db
					->where('nama', $nama)
					->update('shared_folder', ['isi' => (string) $isi]);
			}

			$last = $ci->db
				->select_max('id', 'id')
				->from('shared_folder')
				->get()
				->row_array();
			$id = isset($last['id']) ? ((int) $last['id'] + 1) : 1;

			return $ci->db->insert('shared_folder', [
				'id' => $id,
				'nama' => $nama,
				'isi' => (string) $isi,
			]);
		}
	}

	if ( ! function_exists('app_license_state'))
	{
		function app_license_state()
		{
			$ci = & get_instance();
			$valid_state = [
				'valid' => true,
				'bound' => false,
				'perusahaan' => '',
				'email' => '',
				'message' => '',
			];

			if (!$ci->db->table_exists('info') || !$ci->db->table_exists('shared_folder')) {
				return $valid_state;
			}

			$info = $ci->db
				->select('perusahaan,email')
				->from('info')
				->limit(1)
				->get()
				->row_array();

			if (!$info) {
				return $valid_state;
			}

			$perusahaan = isset($info['perusahaan']) ? $info['perusahaan'] : '';
			$email = isset($info['email']) ? $info['email'] : '';
			$actual = app_license_signature($perusahaan, $email);
			$stored = app_license_shared_value('app_license_identity');

			if (empty($stored)) {
				app_license_save_shared_value('app_license_identity', $actual);
				$stored = $actual;
			}

			$is_valid = function_exists('hash_equals')
				? hash_equals((string) $stored, (string) $actual)
				: ((string) $stored === (string) $actual);
			return [
				'valid' => $is_valid,
				'bound' => true,
				'perusahaan' => $perusahaan,
				'email' => $email,
				'message' => $is_valid ? '' : 'License aplikasi nonaktif karena Nama Perusahaan atau Email tidak sesuai dengan identitas license.',
			];
		}
	}
	
	if ( ! function_exists('pengaturan'))
	{
		/**
			* Code pengaturan
			*
			@param $val string
			@return string
		*/
		function pengaturan($val)
		{
			$ci = & get_instance();
			static $settings = NULL;
			if ($settings === NULL) {
				$settings = array();
				$query = $ci->db->get('shared_folder');
				foreach ($query->result_array() as $row) {
					$settings[$row['nama']] = $row['isi'];
				}
			}
			return isset($settings[$val]) ? $settings[$val] : '';
		}
	}
	
	if ( ! function_exists('select_box'))
	{
		/**
			* Code select_box
			*
			@param $data array
			@param $parent int
			@param $parent_id int
			@param $Nilai int / string comma
			@param params array
			@return string
		*/
		function select_box($data, $parent = 0, $parent_id = 0, $Nilai='',$params = array())
		{
			$ci = & get_instance();
			
			if (isset($data[$parent]))
			{
				$id = $params['id'];
				$title = $params['title'];
				$html = "";
				
				if ($ci->session->level=='admin'){
					$html .= '<option value="0">Semua</option>';
				}
				foreach ($data[$parent] as $v)
				{
					$_arrNilai = explode(',', $Nilai);
					$_ck = (array_search($v->$id, $_arrNilai) === false)? '' : 'selected';
					$html .= '<option value="'.$v->$id.'" '.$_ck.'>&nbsp;'.$v->$title.'</option>';
				}
				return $html;
			}
		}
	}
	
	if ( ! function_exists('select_kbox'))
	{
		/**
			* Code select_kbox
			*
			@param $data array
			@param $parent int
			@param $parent_id int
			@param $Nilai int / string comma
			@return string
		*/
		function select_kbox($data, $parent = 0, $parent_id = 0, $Nilai='')
		{
			$ci = & get_instance();
			if (isset($data[$parent]))
			{
				
				$html = "";
				foreach ($data[$parent] as $v)
				{
					$child = select_kbox($data, $v->id, $parent_id, $Nilai);
					$_arrNilai = explode(',', $Nilai);
					if ($ci->session->level=='admin'){
						$_ck = (array_search($v->id, $_arrNilai) === false)? '' : 'selected';
						$html .= '<option value="'.$v->id.'" '.$_ck.'>&nbsp;'.$v->title.'</option>';
						}else{
						if (in_array($v->id, $_arrNilai)){
							$_ck = (array_search($v->id, $_arrNilai) === false)? '' : 'selected';
							$html .= '<option value="'.$v->id.'" '.$_ck.'>&nbsp;'.$v->title.'</option>';
						}
					}
				}
				return $html;
			}
		}
	}
	
	if ( ! function_exists('select_badge'))
	{
		/**
			* Code select_badge
			*
			@param $data array
			@param $parent int
			@param $parent_id int
			@param $Nilai int / string comma
			@return string
		*/
		function select_badge($data, $parent = 0, $parent_id = 0, $Nilai='')
		{
			$ci = & get_instance();
			if (isset($data[$parent]))
			{
				
				$html = "";
				foreach ($data[$parent] as $v)
				{
					$child = select_badge($data, $v->id, $parent_id, $Nilai);
					$_arrNilai = explode(',', $Nilai);
					if ($ci->session->level=='admin' AND $parent_id==0){
						$_ck = (array_search($v->id, $_arrNilai) === false)? '' : 'selected';
						$html .= '<option value="'.$v->id.'" '.$_ck.'>&nbsp;'.$v->title.'</option>';
						}else{
						if (in_array($v->id, $_arrNilai)){
							$html .= '<button type="button" class="btn btn-secondary btn-sm flat mb-1" readonly>'.$v->title.'</button>&nbsp;';
							$html .= '<input type="hidden" name="akses[]" value="'.$v->id.'">';
							
						}
					}
				}
				return $html;
			}
		}
	}
	if ( ! function_exists('checkbox_menu'))
	{
		/**
			* Code checkbox_menu
			*
			@param $data array
			@param $parent int
			@param $parent_id int
			@param $Nilai int / string comma
			@return string
		*/
		function checkbox_menu($data, $parent = 0, $parent_id = 0, $Nilai = '')
		{
			static $i = 1;
			$ieTab = str_repeat("&nbsp;&nbsp;&nbsp;", $i * 2);
			$tab = $i * 0;
			if (isset($data[$parent])) {
				$i++;
				$html = "";
				$a = 0;
				foreach ($data[$parent] as $v) {
					$child = checkbox_menu($data, $v['id_level'], $parent_id, $Nilai);
					
					$_arrNilai = explode(',', $Nilai);
					$_ck = (array_search($v['id_level'], $_arrNilai) === false) ? '' : TRUE;
					$array = array(
					'name'          => 'idlevel[]',
					'id'            => 'idlevel'.$v['id_level'],
					'value'         => $v['id_level'],
					'checked'       => $_ck,
					'class'         => 'custom-control-input checkbox get_value'
					);
					$attributes = array(
					'class' => 'custom-control-label',
					'style' => ''
					);
					$html .= '<div class="custom-control custom-checkbox">';
					$html .= $ieTab. form_checkbox($array);
					$html .= form_label($v['nama'], 'idlevel'.$v['id_level'], $attributes);;
					$html .= "</div>";
					if ($child) {
						$i--;
						$html .= $child;
					}
					$a++;
				}
				return $html;
			}
		}
	}
	
	if ( ! function_exists('checkcard'))
	{
		/**
			* Code checkcard
			*
			@param $data array
			@param $parent int
			@param $parent_id int
			@param $Nilai int / string comma
			@return string
		*/
		function checkcard($data, $parent = 0, $parent_id = 0, $Nilai='')
		{
			static $i = 1;
			$ieTab = str_repeat("&nbsp;&nbsp;&nbsp;", $i * 2);
			$tab = $i * 0 ;
			if (isset($data[$parent]))
			{
				$i++;
				$html ="";
				foreach ($data[$parent] as $v)
				{
					$child = checkcard($data, $v['idmenu'], $parent_id, $Nilai);
					
					$_arrNilai = explode(',', $Nilai);
					$_ck = (array_search($v['idmenu'], $_arrNilai) === false)? '' : TRUE;
					$array = array(
					'name'          => 'data[]',
					'id'            => 'data',
					'value'         => $v['idmenu'],
					'checked'       => $_ck,
					'style'         => ''
					);
					
					$html .= '<div class="checkbox">';
					$html .= $ieTab. form_checkbox($array).$v['nama_menu'];
					
					$html .= "</div>";
					if ($child) { $i--; $html .= $child; }
				}
				return $html;
			}
		}
	}
	if ( ! function_exists('checkbox'))
	{
		/**
			* Code checkbox
			*
			@param $data array
			@param $parent int
			@param $parent_id int
			@param $Nilai int / string comma
			@return string
		*/
		function checkbox($data, $parent = 0, $parent_id = 0, $Nilai='',$_parent=0) {
			static $i = 1;
			$ieTab = str_repeat("&nbsp;&nbsp;&nbsp;", $i * 2);
			$tab = $i * 0 ;
			if (isset($data[$parent]))
			{
				$i++;
				$html ='';
				foreach ($data[$parent] as $v) {
					$child = checkbox($data, $v['idmenu'], $parent_id, $Nilai,$_parent);
					
					//Edit Di Item
					
					$_arrNilai = explode(',', $Nilai);
					if($_parent==1)
					{
						$_ck = (array_search($v['idmenu'], $_arrNilai) === false)? 'disabled' : TRUE;
					}
					else
					{
						$_ck = (array_search($v['idmenu'], $_arrNilai) === false)? '' : TRUE;
					}
					$array = array(
					'name'          => 'data[]',
					'id'            => 'checkb'.$v['idmenu'],
					'value'         => $v['idmenu'],
					'checked'       => $_ck,
					'class'         => 'custom-control-input checkbox'
					);
					$attributes = array(
					'class' => 'custom-control-label',
					'style' => ''
					);
					$html .= '<div class="custom-control custom-checkbox">';
					$html .= $ieTab. form_checkbox($array);
					$html .= form_label($v['nama_menu'], 'checkb'.$v['idmenu'], $attributes);
					$html .= "</div>";
					if ($child) { $i--; $html .= $child; }
				}
				return $html;
			}
		}
	}
	
	if ( ! function_exists('cek_desain'))
	{
		/**
			* Code cek_desain
			*
			@param $id int
			@return int
		*/
		function cek_desain($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('id_desain','invoice',['id_invoice'=>$id]);
			$data = 0;
			if ($query->num_rows()>0)
			{
				$row = $query->row()->id_desain;
			}
			return $row;
		}
	}
	
	if ( ! function_exists('jenis_konsumen'))
	{
		/**
			* Code cek_desain
			*
			@param $id int
			@return id
		*/
		function jenis_konsumen($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('jenis','konsumen',['id'=>$id]);
			$data = 1;
			if ($query->num_rows()>0)
			{
				$row = $query->row()->jenis;
			}
			return $row;
		}
	}
	
	if ( ! function_exists('jenis_member'))
	{
		/**
			* Code cek_desain
			*
			@param $id int
			@return id
		*/
		function jenis_member($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('jenis_member','konsumen',['id'=>$id]);
			$data = 1;
			if ($query->num_rows()>0)
			{
				$row = $query->row()->jenis_member;
			}
			return $row;
		}
	}
	
	if ( ! function_exists('member'))
	{
		/**
			* Code cek_desain
			*
			@param $id int
			@return id
		*/
		function member($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('title','member',['id'=>$id]);
			$row = 0;
			if ($query->num_rows()>0)
			{
				$row = $query->row()->title;
			}
			return $row;
		}
	}
	
	if ( ! function_exists('get_satuan'))
	{
		/**
			* Code get_satuan
			*
			@param $id int
			@return string
		*/
		function get_satuan($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('satuan','satuan',['id'=>$id]);
			$data = 'Pcs';
			if ($query->num_rows()>0)
			{
				$data = $query->row()->satuan;
			}
			return $data;
		}
	}
	
	if ( ! function_exists('getJenisBayar'))
	{
		/**
			* Code getJenisBayar
			*
			@param $id int
			@return string
		*/
		function getJenisBayar($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('nama_bayar','jenis_bayar',['id'=>$id]);
			$data = "-";
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->nama_bayar;
				
			}
			return $data;
		}
	}
	
	if ( ! function_exists('getIdAkunJenis'))
	{
		/**
			* Code getJenisBayar
			*
			@param $id int
			@return string
		*/
		function getIdAkunJenis($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('id_akun','jenis_cetakan',['id_jenis'=>$id]);
			$data = 1;
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->id_akun;
				
			}
			return $data;
		}
	}
	if ( ! function_exists('getSupplier'))
	{
		/**
			* Code getJenisBayar
			*
			@param $id int
			@return string
		*/
		function getSupplier($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('nama_perusahaan','supplier',['id_supplier'=>$id]);
			$data = 1;
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->nama_perusahaan;
				
			}
			return $data;
		}
	}
	
	if ( ! function_exists('getIdAkunPengeluaran'))
	{
		/**
			* Code getJenisBayar
			*
			@param $id int
			@return string
		*/
		function getIdAkunPengeluaran($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('id_akun','jenis_pengeluaran',['id_jenis'=>$id]);
			$data = 1;
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->id_akun;
				
			}
			return $data;
		}
	}
	
	if ( ! function_exists('getTitleAkunPengeluaran'))
	{
		/**
			* Code getJenisBayar
			*
			@param $id int
			@return string
		*/
		function getTitleAkunPengeluaran($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('title','jenis_pengeluaran',['id_jenis'=>$id]);
			$data = '-';
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->title;
				
			}
			return $data;
		}
	}
	
	if ( ! function_exists('getIdAkun'))
	{
		/**
			* Code getJenisBayar
			*
			@param $id int
			@return string
		*/
		function getIdAkun($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('id_akun','jenis_bayar',['id'=>$id]);
			$data = 0;
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->id_akun;
				
			}
			return $data;
		}
	}
	
	if ( ! function_exists('getIdAkunPendapatan'))
	{
		/**
			* Code getIdAkunPendapatan
			*
			@param $id int
			@return string
		*/
		function getIdAkunPendapatan($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('noakun','akun',['id_akun'=>$id]);
			$data = 0;
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->noakun;
				
			}
			return $data;
		}
	}
	
	if ( ! function_exists('getIdAkunBank'))
	{
		/**
			* Code getJenisBayar
			*
			@param $id int
			@return string
		*/
		function getIdAkunBank($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('id_akun','rekening_bank',['id'=>$id]);
			$data = 0;
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->id_akun;
				
			}
			return $data;
		}
	}
	
	if ( ! function_exists('getNameKas'))
	{
		/**
			* Code getNameKas
			*
			@param $id int
			@return string
		*/
		function getNameKas($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('title','jenis_kas',['id_akun'=>$id]);
			$data = "-";
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->title;;
			}
			return $data;
		}
	}
	
	if( ! function_exists('getItem'))
	{
		/**
			* Code getNameKas
			*
			@param $id int
			@return string
		*/
		function getItem($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('title','item_pembelian',['id'=>$id]);
			$data = "-";
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->title;
			}
			return $data;
		}
	}
	
	if( ! function_exists('getItemDetail'))
	{
		/**
			* Code getNameKas
			*
			@param $id int
			@return string
		*/
		function getItemDetail($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('title,id_akun','item_pembelian',['id'=>$id]);
			$data = "-";
			if ($query->num_rows()>=1)
			{
				$data = $query->row();
			}
			return $data;
		}
	}
	
	if( ! function_exists('getstatusBahan'))
	{
		/**
			* Code getNameKas
			*
			@param $id int
			@return string
		*/
		function getstatusBahan($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('status_stok','bahan',['id'=>$id]);
			$data = "-";
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->status_stok;;
			}
			return $data;
		}
	}
	
	if( ! function_exists('getDetailBahan'))
	{
		/**
			* Code getNameKas
			*
			@param $id int
			@return string
		*/
		function getDetailBahan($id)
		{
			$ci = & get_instance();
			
			$query = $ci->model_app->pilih_where('title,status,type_harga','bahan',['id'=>$id]);
			$data = (object)['title'=>'-','status'=>0,'type_harga'=>0];
			if ($query->num_rows()>0)
			{
				$data = $query->row();
			}
			return $data;
		}
	}
	
	if( ! function_exists('getBahan'))
	{
		/**
			* Code getNameKas
			*
			@param $id int
			@return string
		*/
		function getBahan($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('title','bahan',['id'=>$id]);
			$data = "-";
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->title;;
			}
			return $data;
		}
	}
	
	if( ! function_exists('pilihBahan'))
	{
		/**
			* Code getNameKas
			*
			@param $id int
			@return string
		*/
		function pilihBahan($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('title','bahan',['id'=>$id]);
			$data = '';
			if ($query->num_rows()>=1)
			{
				$data .= '<option value="'.$query->row()->id.'" selected="selected">'.$query->row()->title.'</option> ';
			}
			return $data;
		}
	}
	
	if ( ! function_exists('getAkun'))
	{
		/**
			* Code getNameKas
			*
			@param $id int
			@return string
		*/
		function getAkun($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('nama','akun',['id_akun'=>$id]);
			$data = "-";
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->nama;
			}
			return $data;
		}
	}
	
	if ( ! function_exists('getKodeAkun'))
	{
		/**
			* Code getNameKas
			*
			@param $id int
			@return string
		*/
		function getKodeAkun($id)
		{
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('id_akun,noakun','akun',['id_akun'=>$id]);
			$data = "-";
			if ($query->num_rows()>=1)
			{
				$data = $query->row()->id_akun.' - '.$query->row()->noakun;
			}
			return $data;
		}
	}
	
	
	if ( ! function_exists('jkategori'))
	{
		/**
			* Code jproduk
			*
			@param $table string
			@param $id int
			@param $title string
			@return string
		*/
		function jkategori($id){
			$ci = & get_instance();
			$query = $ci->db->query("SELECT id_jenis FROM  produk where id='$id'");
			if ($query->num_rows()>=1){
				return $query->row()->id_jenis;
				}else{
				return 'error';
			}
		}
	}
	
	if ( ! function_exists('jproduk'))
	{
		/**
			* Code jproduk
			*
			@param $table string
			@param $id int
			@param $title string
			@return string
		*/
		function jproduk($table,$id,$title){
			$ci = & get_instance();
			$query = $ci->db->query("SELECT * FROM `$table` where id_jenis='$id'");
			if ($query->num_rows()>=1){
				$tmp = $query->row_array();
				return $tmp[$title];
				}else{
				return 'error';
			}
		}
	}
	
	if ( ! function_exists('nama_produk'))
	{
		/**
			* Code nama_produk
			*
			@param $id int
			@return string
		*/
		function nama_produk($id){
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('title','produk',['id'=>$id]);
			if ($query->num_rows()>=1){
				return $query->row()->title;
				}else{
				return '-';
			}
		}
	}
	
	if ( ! function_exists('juser'))
	{
		/**
			* Code juser
			*
			@param $id int
			@return string
		*/
		function juser($id){
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('nama_lengkap','tb_users',['id_user'=>$id]);
			if ($query->num_rows()>=1){
				return $query->row()->nama_lengkap;
				}else{
				return 'error';
			}
		}
	}
	if ( ! function_exists('ttd_user'))
	{
		/**
			* Code ttd_user
			*
			@param $str string
			@return string
		*/
		function ttd_user($str){
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('nama_lengkap','tb_users',['level'=>$str]);
			if ($query->num_rows()>=1){
				return $query->row()->nama_lengkap;
				}else{
				return 'error';
			}
		}
	}
	
	if ( ! function_exists('jabatan'))
	{
		/**
			* Code ttd_user
			*
			@param $str string
			@return string
		*/
		function jabatan($str){
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('app_secret','tb_users',['level'=>$str]);
			if ($query->num_rows()>=1){
				return $query->row()->app_secret;
				}else{
				return 'error';
			}
		}
	}
	
	if ( ! function_exists('detail_user'))
	{
		/**
			* Code juser
			*
			@param $id int
			@return string
		*/
		function detail_user($id){
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('nama_lengkap,no_hp,level','tb_users',['id_user'=>$id]);
			if ($query->num_rows()>=1){
				return $query->row();
				}else{
				return 'error';
			}
		}
	}
	
	// if ( ! function_exists('jkas'))
	// {
	// /**
	// * Code jkas
	// *
	// @param $id int
	// @return int
	// */
	// function jumlahkas($id){
	// $ci = & get_instance();
	// $query = $ci->model_app->pilih_where('jumlah_uang','jenis_kas',['id_akun'=>$id]);
	// if ($query->num_rows()>=1){
	// return $query->row()->jumlah_uang;
	// }else{
	// return 0;
	// }
	// }
	// }
	
	if ( ! function_exists('saldo'))
	{
		/**
			* Code saldo
			*
			@param $id string
			@return int
		*/
		function saldo($id){
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('pemasukan','kas_masuk',['no_reff'=>$id]);
			if ($query->num_rows()>=1){
				return $query->row()->pemasukan;
				}else{
				return 0;
			}
		}
	}
	if ( ! function_exists('sum_detail'))
	{
		/**
			* Code sum_jurnal
			*
			@params int
			@return int
		*/
		function sum_detail($id_invoice){
			$ci = & get_instance();
			$sum = $ci->db->query("SELECT SUM(`invoice_detail`.`jumlah` * `invoice_detail`.`harga`) AS `total`,`invoice_detail`.`id_invoice` FROM `invoice_detail` WHERE id_invoice = '$id_invoice' GROUP BY `invoice_detail`.`id_invoice`");
			
			return $sum->row()->total;
		}
	}
	if ( ! function_exists('sum_jurnal'))
	{
		/**
			* Code sumPengeluaran
			*
			@return array
		*/
		function sum_jurnal($jenis,$where,$bulan,$tahun){
			$ci = & get_instance();
			$ci->db->select('SUM(saldo) AS `total`');
			$ci->db->where('jenis_saldo',$jenis);
			$ci->db->where('no_reff',$where);
			$ci->db->where('month(jurnal_transaksi.tgl_transaksi)',$bulan);
			$ci->db->where('year(jurnal_transaksi.tgl_transaksi)',$tahun);
			$query = $ci->db->get('jurnal_transaksi');
			$result = ($query->num_rows() > 0)?$query->row():0; 
			return $result;
		}
	}
	
	if ( ! function_exists('tags_bahan'))
	{
		/**
			* Code tags_bahan
			*
			@param int
			@return array
		*/
		function tags_bahan($id){
			$ci = & get_instance();
			$query = $ci->model_app->pilih_where('id_bahan','produk',['id'=>$id])->result();
			$TampungData = array();
			foreach ($query as $data_tags){
				$tags = explode(',',strtolower(trim($data_tags->id_bahan)));
				if(empty($data_tags->id_bahan)){echo'';}else{
					foreach($tags as $val) {
						$TampungData[] = $val;
					}}}
					$jumlah_tag = array_count_values($TampungData);
					ksort($jumlah_tag);
					$output = array();
					foreach($jumlah_tag as $key=>$val) {
						$querys = $ci->model_app->view_where('bahan',['id'=>$key,'id >'=>1]);
						foreach ($querys->result() as $row){
							$output[] = '<option selected value="'.$row->id.'">'.$row->title.'</options>';
						}
					}
					
					$tags= implode(' ',$output);
					return $tags;
		}
	}
	
	if ( ! function_exists('template'))
	{
		/**
			* Code template
			*
			@param int
			@return string
		*/
		function template(){
			$ci = & get_instance();
			$query = $ci->model_app->view_where('themes',['id'=>$key,'pub'=>0]);
			if ($query->num_rows()>=1){
				if ($this->session->level==''){
					redirect(base_url().'adm');
					exit;
				}
				return $query->row()->folder;
				}else{
				if ($this->session->level==''){
					redirect(base_url().'adm');
					exit;
				}
			}
		}
	}
	
	if ( ! function_exists('pilih'))
	{
		/**
			* Code pilih
			*
			@param string
			@param array
			@param int
			@return string
		*/
		function pilih($tbl,$where,$id){
			$ci = & get_instance();
			return $ci->db->query("SELECT * FROM `$tbl` where $where='$id'")->row_array();
		}
	}
	
	if ( ! function_exists('info'))
	{
		/**
			* Code info
			*
			@param int
			@return string
		*/
		function info(){
			$ci = & get_instance();
			static $data = NULL;
			if ($data !== NULL) {
				return $data;
			}

			$cache_key = 'app_info_v1';
			if (isset($ci->cache)) {
				$cached = $ci->cache->file->get($cache_key);
				if (is_array($cached)) {
					$data = $cached;
					$timezone = isset($data['timezone']) ? $data['timezone'] : 'Asia/Jakarta';
					date_default_timezone_set(in_array($timezone, array('Asia/Jakarta', 'Asia/Makassar', 'Asia/Jayapura', 'UTC'), true) ? $timezone : 'Asia/Jakarta');
					return $data;
				}
			}

			$data = array();
			if ($ci->db->table_exists('info'))
			{
				
				$info = $ci->db->query("SELECT * FROM info")->row_array();
				if(!empty($info)){
					$status = ['status'=>TRUE];
					$data = array_merge($info,$status);
					$timezone = isset($data['timezone']) ? $data['timezone'] : 'Asia/Jakarta';
					date_default_timezone_set(in_array($timezone, array('Asia/Jakarta', 'Asia/Makassar', 'Asia/Jayapura', 'UTC'), true) ? $timezone : 'Asia/Jakarta');
					}else{
					$data = ['status'=>FALSE,'ket'=>base64_encode('Migrate')];
				}
				if (isset($ci->cache)) {
					$ci->cache->file->save($cache_key, $data, 300);
				}
				return $data;
			}
			else
			{
				$data = ['status'=>FALSE,'ket'=>base64_encode('Migrate')];
				if (isset($ci->cache)) {
					$ci->cache->file->save($cache_key, $data, 60);
				}
				return $data;
			}
			
		}
	}

	if ( ! function_exists('product_item_image_enabled'))
	{
		/**
		 * Status fitur gambar item produk/bahan.
		 * Default aktif untuk menjaga perilaku instalasi lama sebelum kolom tersedia.
		 */
		function product_item_image_enabled()
		{
			$settings = info();
			return !array_key_exists('gambar_item_aktif', $settings)
				|| (int) $settings['gambar_item_aktif'] === 1;
		}
	}
	
	if ( ! function_exists('transaction_number_settings'))
	{
		function transaction_number_settings()
		{
			$settings = ['prefix' => 'TRX', 'digits' => 5];
			$ci = & get_instance();
			if (!$ci->db->table_exists('info')
				|| !$ci->db->field_exists('trx_prefix', 'info')
				|| !$ci->db->field_exists('trx_digits', 'info')) {
				return $settings;
			}

			$row = $ci->db->select('trx_prefix, trx_digits')->from('info')->where('id', 1)->limit(1)->get()->row_array();
			if (!empty($row['trx_prefix'])) {
				$prefix = strtoupper(preg_replace('/[^A-Z0-9]/', '', (string) $row['trx_prefix']));
				if ($prefix !== '') {
					$settings['prefix'] = substr($prefix, 0, 20);
				}
			}
			if (isset($row['trx_digits'])) {
				$settings['digits'] = max(1, min(12, (int) $row['trx_digits']));
			}
			return $settings;
		}
	}

	if ( ! function_exists('transaction_number_prefix'))
	{
		function transaction_number_prefix()
		{
			$settings = transaction_number_settings();
			return $settings['prefix'] . '-';
		}
	}

	if ( ! function_exists('transaction_number_has_prefix'))
	{
		function transaction_number_has_prefix($value)
		{
			return stripos(trim((string) $value), transaction_number_prefix()) === 0;
		}
	}

	if ( ! function_exists('format_transaction_number'))
	{
		function format_transaction_number($number)
		{
			$settings = transaction_number_settings();
			return $settings['prefix'] . '-' . str_pad((string) max(0, (int) $number), $settings['digits'], '0', STR_PAD_LEFT);
		}
	}

	if ( ! function_exists('next_transaction_number'))
	{
		function next_transaction_number()
		{
			$ci = & get_instance();
			$maxNumber = 0;
			if ($ci->db->table_exists('invoice') && $ci->db->field_exists('id_transaksi', 'invoice')) {
				$rows = $ci->db->select('id_transaksi')->from('invoice')->get()->result_array();
				foreach ($rows as $row) {
					$value = isset($row['id_transaksi']) ? (string) $row['id_transaksi'] : '';
					if (preg_match('/(\d+)$/', $value, $matches)) {
						$maxNumber = max($maxNumber, (int) $matches[1]);
					}
				}
			}
			return format_transaction_number($maxNumber + 1);
		}
	}

	if ( ! function_exists('logo'))
	{
		/**
			* Code logo
			*
			@return string
		*/
		function logo(){
			$ci = & get_instance();
			return $ci->model_app->pilih('logo','info')->row()->logo;
		}
	}
	
	if ( ! function_exists('favicon'))
	{
		/**
			* Code favicon
			*
			@return string
		*/
		function favicon(){
			$ci = & get_instance();
			return $ci->model_app->pilih('favicon','info')->row()->favicon;
		}
	}
	
	if ( ! function_exists('bank'))
	{
		/**
			* Code bank
			*
			@param int
			@return string
		*/
		function bank($id){
			$data = "-";
			if($id > 0){
				$ci = & get_instance();
				$query = $ci->db->query("SELECT inisial FROM rekening_bank WHERE id=".$id);
				if ($query->num_rows()>=1)
				{
					$data = $query->row()->inisial;
				}
			}
			return $data;
		}
	}
	
	function bayar($id){
		$ci = & get_instance();
		$ci->db->select('SUM(`bayar_invoice_detail`.`jml_bayar`) AS `Totalbayar`');
		$ci->db->from('bayar_invoice_detail');
		$ci->db->where('`bayar_invoice_detail`.id_invoice',$id);
		$ci->db->group_by("`bayar_invoice_detail`.`id_invoice`");
		return $ci->db->get()->row_array();
	}
	
	function total_bayar($id_konsumen,$id){
		$ci = & get_instance();
		$ci->db->select('SUM(`bayar_invoice_detail`.`jml_bayar`) AS `total_bayar`');
		$ci->db->from('konsumen');
		$ci->db->join('`invoice`','`konsumen`.`id` = `invoice`.`id_konsumen`');
		$ci->db->join('`bayar_invoice_detail`','`invoice`.`id_invoice` = `bayar_invoice_detail`.`id_invoice`');
		$ci->db->where('`invoice`.id_konsumen',$id_konsumen);
		// $ci->db->where('`bayar_invoice_detail`.id_invoice',$id);
		// $ci->db->group_by("`konsumen`.`id`");
		$query = $ci->db->get();
		if ($query->num_rows()>0)
		{
			return $query->row()->total_bayar;
			}else{
			return 0;
		}
	}
	
	function count_status($id){
		$ci = & get_instance();
		$ci->db->where('id_invoice',$id);
		return $ci->db->count_all_results('invoice_detail');
	}
	
	function sum_status($id){
		$ci = & get_instance();
		$ci->db->select('SUM(invoice_detail.status) AS `total`');
		$ci->db->from('invoice_detail');
		$ci->db->where('id_invoice',$id);
		return $ci->db->get()->row()->total;
	}
	
	function trx_now(){
		$ci = & get_instance();
		$ci->db->where(['tgl_trx'=>'CURDATE()','oto'=>1]);
		return $ci->db->count_all_results('invoice');
	}
	function c_acc(){
		$ci = & get_instance();
		$ci->db->where('oto',1);
		return $ci->db->count_all_results('invoice');
	}
	function c_pending(){
		$ci = & get_instance();
		$ci->db->where('oto',0);
		return $ci->db->count_all_results('invoice');
	}
	
	
	function autoNumbers($awalan,$digit)
	{
		//%06s
		$ci = & get_instance();
		$ci->db->select_max('id_member','max_id');
		$query = $ci->db->get('konsumen');
		if($query->num_rows()>0){
			$data=$query->row();
			$maxid = $data->max_id;
			$count_awalan = strlen($awalan);
			$potong_awalan = str_replace($awalan,"",$maxid);
			$count_potong_awalan = strlen($potong_awalan);
			$noUrut = (int) substr($maxid, $count_awalan, $count_potong_awalan);
			$noUrut++;
			$kode_baru = $awalan.sprintf($digit, $noUrut);
			}else{
			$kode_baru = $awalan.sprintf($digit, 1);
		}
		return $kode_baru;
	}
	function autoNumber($awalan,$digit,$id_table,$table)
	{
		//%06s
		$ci = & get_instance();
		$ci->db->select_max($id_table,'max_id');
		$query = $ci->db->get($table);
		if($query->num_rows()>0){
			$data=$query->row();
			$maxid = $data->max_id;
			$count_awalan = strlen($awalan);
			$potong_awalan = str_replace($awalan,"",$maxid);
			$count_potong_awalan = strlen($potong_awalan);
			$noUrut = (int) substr($maxid, $count_awalan, $count_potong_awalan);
			$noUrut++;
			$kode_baru = $awalan.sprintf($digit, $noUrut);
			}else{
			$kode_baru = $awalan.sprintf($digit, 1);
		}
		return $kode_baru;
	}
	
	function autoNumberJurnal($awalan,$id_table,$table)
	{
		//%06s
		$ci = & get_instance();
		$ci->db->select_max($id_table,'max_id');
		$query = $ci->db->get($table);
		if($query->num_rows()>0){
			$data=$query->row();
			$maxid = $data->max_id;
			$count_awalan = strlen($awalan);
			$potong_awalan = str_replace($awalan,"",$maxid);
			$count_potong_awalan = strlen($potong_awalan);
			$noUrut = (int) substr($maxid, $count_awalan, $count_potong_awalan);
			$noUrut++;
			$kode_baru = $awalan.$noUrut;
			}else{
			$kode_baru = $awalan.'1';
		}
		return $kode_baru;
	}
	
	function sumPiutang($id){
		$ci = & get_instance();
		$query = $ci->model_app->pilih_where('SUM(`bayar_invoice_detail`.`jml_bayar`) AS `piutang`','bayar_invoice_detail',['id_invoice'=>$id]);
		$data = [];
		if($query->num_rows() > 0){
			$data =  $query->result_array();
		}
		return $data;
	}
	
	function totalDiskon($id){
		$ci = & get_instance();
		$qry = "SELECT sum(invoice_detail.jumlah * invoice_detail.harga) AS Total,
		SUM((`invoice_detail`.`jumlah` * `invoice_detail`.`harga` * `invoice_detail`.`diskon`/100))  AS sisa
		FROM
		`invoice_detail`
		WHERE
		`invoice_detail`.`id_invoice` = $id";
		$query = $ci->db->query($qry);
		$data = 0;
		if($query->num_rows() > 0){
			$row =  $query->row();
			$data .= $row->sisa;
		}
		return $data;
	}
	
	function sumOrderDiskon($id){
		$ci = & get_instance();
		$qry = "SELECT diskon, sum(invoice_detail.jumlah * invoice_detail.harga) AS Total,
		SUM((`invoice_detail`.`jumlah` * `invoice_detail`.`harga` * `invoice_detail`.`diskon`/100))  AS sisa
		FROM
		`invoice_detail`
		WHERE
		`invoice_detail`.`id_invoice` = $id";
		$query = $ci->db->query($qry);
		$data = 0;
		if($query->num_rows() > 0){
			$data =  $query->row();
		}
		return $data;
	}
	
	function sumOrder($id){
		$ci = & get_instance();
		$qry = "SELECT ukuran,id_bahan, sum(invoice_detail.jumlah * invoice_detail.harga) AS Total,
		SUM((`invoice_detail`.`jumlah` * `invoice_detail`.`harga` * `invoice_detail`.`diskon`/100))  AS sisa
		FROM
		`invoice_detail`
		WHERE
		`invoice_detail`.`id_invoice` = $id";
		$query = $ci->db->query($qry);
		$data = 0;
		if($query->num_rows() > 0){
			$row =  $query->row();
			$data = $row->Total;
		}
		return $data;
	}
	
	function detail_order($id,$status='',$produk=0){
		$ci = & get_instance();
		if($status=='semua'){
			$status = '';
			}else{
			$status = "AND status=$status";
		}
		if($produk==0){
			$_produk = '';
			}else{
			$_produk = "AND id_produk=$produk";
		}
		
		$qry = "SELECT * FROM `invoice_detail`
		WHERE `invoice_detail`.`id_invoice` = $id $_produk";
		$query = $ci->db->query($qry);
		$data = [];
		if($query->num_rows() > 0){
			$data =  $query->result();
		}
		return $data;
	}
	
	function detail_order_cari($id,$ket=''){
		$ci = & get_instance();
		
		if(!empty($ket)){
			$ket = "AND UPPER(invoice_detail.keterangan) LIKE '%" . strtoupper($ket) . "%'";
			}else{
			$ket = '';
		}
		$qry = "SELECT * FROM `invoice_detail`
		WHERE `invoice_detail`.`id_invoice` = $id $ket";
		$query = $ci->db->query($qry);
		$data = [];
		if($query->num_rows() > 0){
			$data =  $query->result();
		}
		return $data;
	}
	
	function detail_surat_jalan($id){
		$ci = & get_instance();
		
		$qry = "SELECT * FROM `invoice_detail`
		WHERE `invoice_detail`.`id_invoice` = $id";
		$query = $ci->db->query($qry);
		$data = [];
		if($query->num_rows() > 0){
			$data =  $query->result();
		}
		return $data;
	}
	
	function detail_pekerjaan($id,$operator=''){
		$ci = & get_instance();
		$and ='';
		if(!empty($operator)){
			$and = "AND invoice_detail.id_operator=".$operator;
		}
		$qry = "SELECT * FROM `invoice_detail`
		WHERE `invoice_detail`.`id_invoice` = $id AND `invoice_detail`.`jenis_cetakan`!=9 $and";
		$query = $ci->db->query($qry);
		$data = [];
		if($query->num_rows() > 0){
			$data =  $query->result();
		}
		return $data;
	}
	
	function detail_order_desain($id,$id_desain){
		$ci = & get_instance();
		$qry = "SELECT *
		FROM
		`invoice`
		INNER JOIN `invoice_detail` ON (`invoice`.`id_invoice` = `invoice_detail`.`id_invoice`)
		WHERE `invoice_detail`.`jenis_cetakan` = 9 AND `invoice_detail`.`id_invoice` = $id AND `invoice`.`id_desain` = $id_desain";
		$query = $ci->db->query($qry);
		$data = [];
		if($query->num_rows() > 0){
			$data =  $query->result();
		}
		return $data;
	}
	
	
	function jenis_cetakan($id){
		$ci = & get_instance();
		$qry = "SELECT
		`jenis_cetakan`.`jenis_cetakan`
		FROM
		`jenis_cetakan`
		WHERE
		`jenis_cetakan`.`id_jenis` = '$id'";
		$query = $ci->db->query($qry);
		$data = '';
		if($query->num_rows() > 0){
			$row =  $query->row();
			$data .= $row->jenis_cetakan;
		}
		return $data;
	}
	//satu harga
	function detail_satu_harga($id_type,$id_bahan){
		$ci = & get_instance();
		$data = 0;
		if($id_type ==1){
			$qry = "SELECT id_satuan,harga_jual
			FROM `satu_harga`
			WHERE id_bahan = '$id_bahan'";
			$query = $ci->db->query($qry);
			if($query->num_rows() > 0){
				$data =  $query->row();
			}
		}
		
		return $data;
	}
	//harga satuan
	function detail_harga_satuan($id_type,$id_bahan){
		$ci = & get_instance();
		$data = array();
		
		if($id_type ==2){
			$where_satuan = (int) $id_satuan > 0 ? " AND id_satuan = '".(int) $id_satuan."'" : '';
			$qry = "SELECT id_satuan,harga_jual
			FROM `harga_satuan`
			WHERE id_bahan = '$id_bahan' $where_satuan";
			$query = $ci->db->query($qry);
			if($query->num_rows() > 0){
				$data =  $query->result();
			}
		}
		
		return $data;
	}
	//harga level
	function detail_harga_level($id_type,$id_bahan){
		$ci = & get_instance();
		$data = array();
		
		if($id_type ==3){
			$where_member = (int) $id_member > 0 ? " AND id_member = '".(int) $id_member."'" : '';
			$qry = "SELECT id_member,id_satuan,harga_jual
			FROM `harga_member`
			WHERE id_bahan = '$id_bahan' $where_member";
			$query = $ci->db->query($qry);
			if($query->num_rows() > 0){
				$data =  $query->result();
			}
		}
		
		return $data;
	}				
	//harga range
	function detail_harga_range($id_type,$id_bahan){
		$ci = & get_instance();
		$data = array();
		
		if($id_type ==4){
			$where_jumlah = " AND ".(float) $jumlah." BETWEEN jumlah_minimal AND jumlah_maksimal";
			$qry = "SELECT id_satuan,jumlah_minimal,jumlah_maksimal,harga_jual
			FROM `range_harga`
			WHERE id_bahan = '$id_bahan' $where_jumlah";
			$query = $ci->db->query($qry);
			if($query->num_rows() > 0){
				$data =  $query->result();
			}
		}
		
		return $data;
	}				
	//harga range member
	function detail_harga_range_level($id_type,$id_bahan){
		$ci = & get_instance();
		$data = array();
		
		if($id_type ==5){
			$where_member = (int) $id_member > 0 ? " AND id_member = '".(int) $id_member."'" : '';
			$where_jumlah = " AND ".(float) $jumlah." BETWEEN jumlah_minimal AND jumlah_maksimal";
			$qry = "SELECT id_member,id_satuan,jumlah_minimal,jumlah_maksimal,harga_jual
			FROM `harga_range_member`
			WHERE id_bahan = '$id_bahan' $where_member $where_jumlah";
			$query = $ci->db->query($qry);
			if($query->num_rows() > 0){
				$data =  $query->result();
			}
		}
		
		return $data;
	}		
	if (!function_exists('resolve_semua_metode_harga')) {
		/**
		 * Menentukan metode harga yang paling spesifik saat semua metode aktif.
		 * Prioritas: jumlah+level, jumlah, level, satuan, lalu satu harga.
		 */
		function resolve_semua_metode_harga($id_bahan, $id_member = 0, $id_satuan = 0, $jumlah = 0)
		{
			$ci = &get_instance();
			$id_bahan = (int) $id_bahan;
			$id_member = (int) $id_member;
			$id_satuan = (int) $id_satuan;
			$jumlah = (float) $jumlah;

			if ($id_bahan <= 0) {
				return 1;
			}

			if ($id_satuan <= 0) {
				$bahan = $ci->db->select('id_satuan')->where('id', $id_bahan)->get('bahan')->row();
				$id_satuan = $bahan ? (int) $bahan->id_satuan : 0;
			}

			if ($id_member > 0) {
				$ci->db->from('harga_range_member')
					->where('id_bahan', $id_bahan)
					->where('id_member', $id_member)
					->where('jumlah_minimal <=', $jumlah)
					->where('jumlah_maksimal >=', $jumlah);
				if ($ci->db->count_all_results() > 0) {
					return 5;
				}
			}

			$ci->db->from('range_harga')
				->where('id_bahan', $id_bahan)
				->where('jumlah_minimal <=', $jumlah)
				->where('jumlah_maksimal >=', $jumlah);
			if ($ci->db->count_all_results() > 0) {
				return 4;
			}

			if ($id_member > 0 && $ci->db->where([
				'id_bahan' => $id_bahan,
				'id_member' => $id_member,
			])->count_all_results('harga_member') > 0) {
				return 3;
			}

			if ($id_satuan > 0 && $ci->db->where([
				'id_bahan' => $id_bahan,
				'id_satuan' => $id_satuan,
			])->count_all_results('harga_satuan') > 0) {
				return 2;
			}

			return 1;
		}
	}

	//harga_jual
	function harga_jual($id_type, $id_bahan, $id_member = 0, $jumlah = 1, $id_satuan = 0){
		$ci = & get_instance();
		$data = 0;
		if ((int) $id_type === 6) {
			$id_type = resolve_semua_metode_harga($id_bahan, $id_member, $id_satuan, $jumlah);
		}
		if($id_type ==1){
			$qry = "SELECT id_satuan,harga_jual
			FROM `satu_harga`
			WHERE id_bahan = '$id_bahan'";
			$query = $ci->db->query($qry);
			if($query->num_rows() > 0){
				$data =  $query->row()->harga_jual;
			}
		}
		if($id_type ==2){
			$qry = "SELECT id_satuan,harga_jual
			FROM `harga_satuan`
			WHERE id_bahan = '$id_bahan'";
			$query = $ci->db->query($qry);
			if($query->num_rows() > 0){
				$data =  $query->row()->harga_jual;
			}
		}
		if($id_type ==3){
			$qry = "SELECT id_member,id_satuan,harga_jual
			FROM `harga_member`
			WHERE id_bahan = '$id_bahan'";
			$query = $ci->db->query($qry);
			if($query->num_rows() > 0){
				$data =  $query->row()->harga_jual;
			}
		}
		if($id_type ==4){
			$qry = "SELECT id_satuan,jumlah_minimal,jumlah_maksimal,harga_jual
			FROM `range_harga`
			WHERE id_bahan = '$id_bahan'";
			$query = $ci->db->query($qry);
			if($query->num_rows() > 0){
				$data =  $query->row()->harga_jual;
			}
		}
		if($id_type ==5){
			$qry = "SELECT id_member,id_satuan,jumlah_minimal,jumlah_maksimal,harga_jual
			FROM `harga_range_member`
			WHERE id_bahan = '$id_bahan'";
			$query = $ci->db->query($qry);
			if($query->num_rows() > 0){
				$data =  $query->row()->harga_jual;
			}
		}
		
		return $data;
	}		
	
	if ( ! function_exists('update_status'))
	{
		/**
			* update_status
			*
			@param $val string
			@return string
		*/
		function update_status($id,$id_status,$status="",$color="",$icon="")
		{
			$status = '<button class="btn btn-'.$color.' btn-icon-split btn-sm flat edit_baru" data-id="'.$id.'" data-status="'.$id_status.'">
			<span class="icon text-white-50">
			<i class="fa fa-'.$icon.'"></i>
			</span>
			<span class="text">'.$status.'</span>
			</button>';
			return $status; 
		}
	}
	
	if ( ! function_exists('prosess_status'))
	{
		/**
			* update_status
			*
			@param $val string
			@return string
		*/
		function prosess_status($id,$id_status,$string="",$color="",$icon="")
		{
			$status = '<button class="btn btn-'.$color.' btn-icon-split btn-sm flat edit_baru" data-id="'.$id.'" data-status="'.$id_status.'">
			<span class="icon text-white-50">
			<i class="fa fa-'.$icon.'"></i>
			</span>
			<span class="text">'.$string.'</span>
			</button>';
			return $status; 
		}
	}		
	
	if ( ! function_exists('atur_menu'))
	{
		function atur_menu($idlevel)
		{
			$CI =& get_instance();
			$sql = "SELECT idmenu FROM menuadmin WHERE FIND_IN_SET($idlevel, id_level) AND aktif='Y' order by urutan";
			$qry = $CI->db->query($sql);
			$child = $qry->result();
			
			foreach ($child as $key=>$rowz){
				$id_array[] = $rowz->idmenu;
			}
			return implode(",",$id_array);
		}	
	}		
	
	function url_https()
	{
	    // Jika CI url_helper sudah aktif, base_url() paling aman karena ngikut config base_url
	    if (function_exists('base_url')) {
	        $base = base_url(); // biasanya sudah https kalau hostingnya https
	        return rtrim($base, '/') . '/';
	    }

	    // Fallback kalau base_url() belum tersedia
	    $is_https =
	        (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
	        (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') ||
	        (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] === 'on') ||
	        (!empty($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443);

	    $scheme = $is_https ? 'https://' : 'http://';
	    $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
	    $script = $_SERVER['SCRIPT_NAME'] ?? '';
	    $path   = str_replace(basename($script), '', $script);

	    return rtrim($scheme . $host . $path, '/') . '/';
	}

	if (!function_exists('job_status_defaults')) {
		function job_status_defaults()
		{
			return [
				['code'=>0, 'label'=>'Baru',       'color'=>'#64748b', 'icon'=>'file-o',        'active'=>1, 'order'=>0],
				['code'=>1, 'label'=>'Desain',     'color'=>'#6d28d9', 'icon'=>'object-group',  'active'=>1, 'order'=>1],
				['code'=>2, 'label'=>'Proses',     'color'=>'#2563eb', 'icon'=>'refresh',       'active'=>1, 'order'=>2],
				['code'=>6, 'label'=>'Finishing',  'color'=>'#ea580c', 'icon'=>'magic',         'active'=>1, 'order'=>3],
				['code'=>3, 'label'=>'Selesai',    'color'=>'#16a34a', 'icon'=>'check',         'active'=>1, 'order'=>4],
				['code'=>4, 'label'=>'Diambil',    'color'=>'#ca8a04', 'icon'=>'archive',       'active'=>1, 'order'=>5],
				['code'=>5, 'label'=>'Dikirim',    'color'=>'#a16207', 'icon'=>'truck',         'active'=>1, 'order'=>6],
			];
		}
	}

	if (!function_exists('job_statuses')) {
		function job_statuses($activeOnly = false)
		{
			$statuses = job_status_defaults();
			$CI =& get_instance();
			if (isset($CI->db) && $CI->db->table_exists('info') && $CI->db->field_exists('job_statuses', 'info')) {
				$row = $CI->db->select('job_statuses')->where('id', 1)->get('info')->row_array();
				$decoded = json_decode((string)($row['job_statuses'] ?? ''), true);
				if (is_array($decoded) && $decoded) $statuses = $decoded;
			}
			$clean = [];
			foreach ($statuses as $index => $status) {
				$code = isset($status['code']) ? (int)$status['code'] : -1;
				$label = trim(strip_tags((string)($status['label'] ?? '')));
				$color = strtolower(trim((string)($status['color'] ?? '#64748b')));
				if ($code < 0 || $label === '' || isset($clean[$code])) continue;
				if (!preg_match('/^#[0-9a-f]{6}$/', $color)) $color = '#64748b';
				$item = [
					'code'=>$code, 'label'=>$label, 'color'=>$color,
					'icon'=>preg_replace('/[^a-z0-9-]/', '', strtolower((string)($status['icon'] ?? 'circle'))),
					'active'=>empty($status['active']) ? 0 : 1,
					'order'=>isset($status['order']) ? (int)$status['order'] : $index,
				];
				if (!$activeOnly || $item['active']) $clean[$code] = $item;
			}
			usort($clean, static function($a, $b){ return $a['order'] <=> $b['order']; });
			return array_values($clean);
		}
	}

	if (!function_exists('job_status_meta')) {
		function job_status_meta($code)
		{
			foreach (job_statuses(false) as $status) if ((int)$status['code'] === (int)$code) return $status;
			foreach (job_status_defaults() as $status) if ((int)$status['code'] === (int)$code) return $status;
			return ['code'=>(int)$code, 'label'=>'Status '.(int)$code, 'color'=>'#64748b', 'icon'=>'circle', 'active'=>0, 'order'=>999];
		}
	}

	if (!function_exists('job_status_rank')) {
		function job_status_rank($code)
		{
			$meta = job_status_meta((int)$code);
			return isset($meta['order']) ? (int)$meta['order'] : 999;
		}
	}

	if (!function_exists('job_status_slowest')) {
		function job_status_slowest(array $codes, $default = 0)
		{
			if (!$codes) return (int)$default;
			$selected = null;
			$selectedRank = PHP_INT_MAX;
			foreach ($codes as $code) {
				$code = (int)$code;
				$rank = job_status_rank($code);
				if ($rank < $selectedRank) { $selected = $code; $selectedRank = $rank; }
			}
			return $selected === null ? (int)$default : $selected;
		}
	}
