<?php
	defined('BASEPATH') or exit('No direct script access allowed');
	
	class Operator extends CI_Controller
	{
		public function __construct()
		{
			parent::__construct();
			// cek_tabel();
			cek_session_login();
			$this->info = info();
			$this->perPage = 10; 
			$this->iduser = $this->session->idu;
			$this->title       = info()['title']; 
		}
		public function list_pekerjaan()
		{
			
			
			$conditions['where'] = array(
			'invoice.status!=' => 'batal',
			'invoice.status!=' => 'baru'
			);
			
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->get_operator($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataListPekerjaan'; 
			$config['base_url']    = base_url('laporan/ajaxOperator'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			// $config['link_func']   = 'search_Operator'; 
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array( 
            'limit' => $this->perPage 
			); 
			
			$conditions['where'] = array(
			'invoice.status!=' => 'batal',
			'invoice.status!=' => 'baru'
			);
			$data['posts'] = $this->model_data->get_operator($conditions); 
			$this->load->view('laporan/list_pekerjaan', $data);
		}
		
		public function baru()
		{
			$conditions['where'] = array(
			'status' => 0,
			'id_operator' => 0
			);
			$data = $this->model_app->counter('invoice_detail', $conditions);
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		public function proses()
		{
			$conditions['where'] = array(
			'status >' => 0,
			'status <' => 3,
			'id_operator' => $this->iduser
			);
			 
			$data = $this->model_app->counter('invoice_detail', $conditions);
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		public function selesai()
		{
			$conditions['where'] = array(
			'status >' => 2,
			'id_operator' => $this->iduser
			);
			$data = $this->model_app->counter('invoice_detail', $conditions);
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		public function diambil()
		{
			$conditions['where'] = array(
			'status' => 4,
			'id_operator' => $this->iduser
			);
			$data = $this->model_app->counter('invoice_detail', $conditions);
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		public function print_invoice($noid=null){
			
			$data['title'] = 'Print SPK | '.$this->title;
			$noid = decrypt_url($noid);
			$id = array('id_invoice' => $noid);
			$pub = array('pub' =>1);//printer aktif
			$cek_printer = $this->model_app->view_where('printer', $pub);
		    $rowc = $cek_printer->row_array();
			
			$search = $this->model_app->view_where('invoice', $id);
			
			//icon
			$data['waicon'] 	= ['color'=>FCPATH.'assets/img/wa_icon.png','bw'=>FCPATH.'assets/img/wa_icon_bw.png'];
			$data['mail'] 		= ['color'=>FCPATH.'assets/img/gmail_icon.png','bw'=>FCPATH.'assets/img/gmail_icon_bw.png'];
			$data['fbicon'] 	= ['color'=>FCPATH.'assets/img/fb_icon.png','bw'=>FCPATH.'assets/img/fb_icon_bw.png'];
			$data['igicon'] 	= ['color'=>FCPATH.'assets/img/ig_icon.png','bw'=>FCPATH.'assets/img/ig_icon_bw.png'];
			
			$data['logo_lunas'] = FCPATH.'uploads/'.info()['logo'];
			$data['logo_blunas'] = FCPATH.'uploads/'.info()['logo_bw'];
			$data['lunas'] = FCPATH.'uploads/'.info()['stamp_l'];
			$data['blunas'] = FCPATH.'uploads/'.info()['stamp_b'];
			$data['favicon'] = FCPATH.'uploads/'.info()['favicon'];
			$data['html'] = 'N';
			$data['color'] = '';
			if($search->num_rows()>0){
				$this->session->unset_userdata('cart');
				$row = $search->row();
				$jml =$row->cetak+1;
				$this->model_app->update('tb_users', array("last_invoice"=>0),array('id_user'=>$this->session->idu));
				if($row->status!='batal'){
					$this->model_app->update('invoice',array('cetak'=>$jml,'status'=>'simpan','pos'=>'Y','oto'=>6),array('id_invoice'=>$noid));
				}
				//cek sisa
				$_total = 'ROUND(SUM((`invoice_detail`.`jumlah` * harga) - (`invoice_detail`.`jumlah` * harga) * (`invoice_detail`.`diskon`/100))) AS sisa';
				$cari_total= $this->model_app->cek_total('invoice_detail',$_total,array('id_invoice'=>$noid));
				$data['sisanya'] = $cari_total->sisa;
				//
				$data['cetak'] = $row;
				$data['info'] = info();
				$konsumen = $this->model_app->view_where('konsumen', array('id' => $row->id_konsumen))->row_array();
				
				if($konsumen['max_utang'] >0 AND $jml <=1){
					$max_utang = $konsumen['max_utang'] - 1;
					$this->model_app->update('konsumen',array('max_utang'=>$max_utang),array('id'=>$row->id_konsumen));
				}
				
				$data['konsumen']    = $konsumen;
				$data['marketing']   = $this->model_app->view_where('tb_users', array('id_user' => $row->id_marketing))->row_array();
				$data['detail']      = $this->model_app->produk_cart(array('invoice_detail.id_invoice' => $noid));
				$data['total']       =$this->model_app->total_bayar(array('bayar_invoice_detail.id_invoice'=>$noid))->row();
				$select              = 'pajak, total_bayar AS total';
				$where               = array('id_invoice'=>$noid);
				$tdetail             = $this->model_app->cek_total('invoice',$select,$where);
				$data['tdetail']     = $tdetail->total;
				$data['pajak']       = $tdetail->pajak;
				$_diskon             = 'SUM(diskon) AS `disc`';
				$cdiskon             = $this->model_app->cek_total('invoice_detail',$_diskon,$where);
				$data['cdiskon']     = $cdiskon->disc;
				$_select             = 'COUNT(id) AS `jml`';
				$cdetail             = $this->model_app->cek_total('bayar_invoice_detail',$_select,$where);
				$data['cdetail']     = $cdetail->jml;
				//bayar detail
				$data['bdetail']     = $this->model_app->view_where('bayar_invoice_detail', $id)->result_array();
				///
				$data['cara']        = $this->model_app->cara_bayar([
    'jb.publish'    => 'Y',
    'bid.id_invoice'=> $noid,
]);

				$data['bank']        = $this->model_app->view_where('rekening_bank',['footer_invoice'=>1,'publish'=>'Y'])->result();
				
				$this->load->library('pdf');
				$this->pdf->setPaper('A5', 'portrait');
				$this->pdf->filename = "invoice_".$noid."_".$row->tgl_trx;
				$this->pdf->load_view('laporan/print_laporan_spk', $data);
				// $this->load->view('laporan/print_laporan_spk',$data);
				}else{
				$data['cetak']       = 'error';
				$this->load->view('errors/404',$data);
			}
			
			
		}
		
		public function print_spk($noid=null){
			if ($noid === null || $noid === '') $noid = (string)$this->input->get('token', true);
			$noid = decrypt_url($noid);
			$id = array('id_invoice' => $noid);
			$data['spk_drafts'] = array();
			if ($noid && $this->db->table_exists('spk_produksi_draft')) {
				$draftRows = $this->db->select('d.id_rincianinvoice, d.data_json')->from('spk_produksi_draft d')->join('invoice_detail i', 'i.id_rincianinvoice=d.id_rincianinvoice')->where('i.id_invoice', $noid)->get()->result_array();
				foreach ($draftRows as $draftRow) {
					$decoded = json_decode($draftRow['data_json'], true);
					if (is_array($decoded)) $data['spk_drafts'][(int)$draftRow['id_rincianinvoice']] = $decoded;
				}
			}
			$pub = array('pub' =>1);//printer aktif
			$cek_printer = $this->model_app->view_where('printer', $pub);
		    $rowc = $cek_printer->row_array();
			
			$search = $this->model_app->view_where('invoice', $id);
			
			//icon
			$data['title'] 	= "CETAK";
			$data['waicon'] 	= ['color'=>FCPATH.'assets/img/wa_icon.png','bw'=>FCPATH.'assets/img/wa_icon_bw.png'];
			$data['mail'] 		= ['color'=>FCPATH.'assets/img/gmail_icon.png','bw'=>FCPATH.'assets/img/gmail_icon_bw.png'];
			$data['fbicon'] 	= ['color'=>FCPATH.'assets/img/fb_icon.png','bw'=>FCPATH.'assets/img/fb_icon_bw.png'];
			$data['igicon'] 	= ['color'=>FCPATH.'assets/img/ig_icon.png','bw'=>FCPATH.'assets/img/ig_icon_bw.png'];
			
			$data['logo_lunas'] = FCPATH.'uploads/'.info()['logo'];
			$data['logo_blunas'] = FCPATH.'uploads/'.info()['logo_bw'];
			$data['lunas'] = FCPATH.'uploads/'.info()['stamp_l'];
			$data['blunas'] = FCPATH.'uploads/'.info()['stamp_b'];
			$data['favicon'] = FCPATH.'uploads/'.info()['favicon'];
			$data['html'] = 'N';
			if($search->num_rows()>0){
				$this->session->unset_userdata('cart');
				$row = $search->row();
				$jml =$row->cetak+1;
				$this->model_app->update('tb_users', array("last_invoice"=>0),array('id_user'=>$this->session->idu));
				if($row->status!='batal'){
					$this->model_app->update('invoice',array('cetak'=>$jml,'status'=>'simpan','pos'=>'Y','oto'=>6),array('id_invoice'=>$noid));
				}
				//cek sisa
				$_total = 'ROUND(SUM((`invoice_detail`.`jumlah` * harga) - (`invoice_detail`.`jumlah` * harga) * (`invoice_detail`.`diskon`/100))) AS sisa';
				$cari_total= $this->model_app->cek_total('invoice_detail',$_total,array('id_invoice'=>$noid));
				$data['sisanya'] = $cari_total->sisa;
				//
				$data['cetak'] = $row;
				$data['info'] = info();
				$konsumen = $this->model_app->view_where('konsumen', array('id' => $row->id_konsumen))->row_array();
				
				if($konsumen['max_utang'] >0 AND $jml <=1){
					$max_utang = $konsumen['max_utang'] - 1;
					$this->model_app->update('konsumen',array('max_utang'=>$max_utang),array('id'=>$row->id_konsumen));
				}
				
				$data['konsumen']    = $konsumen;
				$data['marketing']   = $this->model_app->view_where('tb_users', array('id_user' => $row->id_marketing))->row_array();
				$data['detail']      = $this->model_app->produk_cart(array('invoice_detail.id_invoice' => $noid));
				$data['total']       =$this->model_app->total_bayar(array('bayar_invoice_detail.id_invoice'=>$noid))->row();
				$select              = 'pajak, total_bayar AS total';
				$where               = array('id_invoice'=>$noid);
				$tdetail             = $this->model_app->cek_total('invoice',$select,$where);
				$data['tdetail']     = $tdetail->total;
				$data['pajak']       = $tdetail->pajak;
				$_diskon             = 'SUM(diskon) AS `disc`';
				$cdiskon             = $this->model_app->cek_total('invoice_detail',$_diskon,$where);
				$data['cdiskon']     = $cdiskon->disc;
				$_select             = 'COUNT(id) AS `jml`';
				$cdetail             = $this->model_app->cek_total('bayar_invoice_detail',$_select,$where);
				$data['cdetail']     = $cdetail->jml;
				//bayar detail
				$data['bdetail']     = $this->model_app->view_where('bayar_invoice_detail', $id)->result_array();
				///
				$data['cara']        = $this->model_app->cara_bayar([
    'jb.publish'    => 'Y',
    'bid.id_invoice'=> $noid,
]);

				$data['bank']        = $this->model_app->view_where('rekening_bank',['footer_invoice'=>1,'publish'=>'Y'])->result();
				
				$this->load->library('pdf');
				$this->pdf->setPaper('A4', 'portrait');
				$this->pdf->filename = "DOKUMEN-SPK-".$noid.tgl_spk($row->tgl_trx);
				$this->pdf->load_view('laporan/print_spk', $data);
				// $this->load->view('laporan/print_spk',$data);
				}else{
				$data['cetak']       = 'error';
				$this->load->view('errors/404',$data);
			}
			
			
		}
		
		public function print_spk_thermal_raw($enc=null)
		{
			if (empty($enc)) {
				show_404();
				return;
			}

			$data['token'] = $enc;
			$data['printer_id'] = (int) $this->input->get('printer_id', true);
			$this->load->view('laporan/print_spk_thermal_raw', $data);
		}

		public function spk_raw_cmd($enc=null)
		{
			$id_invoice = decrypt_url($enc);
			if (!$id_invoice) {
				show_404();
				return;
			}

			$printer_id = (int) $this->input->get('printer_id', true);
			$printer = $this->_active_printer_profile($printer_id);

			try {
				$b64 = $this->_build_spk_raw_b64($id_invoice, $printer);
				$rawLen = strlen(base64_decode($b64));

				$this->output
					->set_content_type('application/json')
					->set_output(json_encode([
						'ok' => true,
						'bytes' => $rawLen,
						'b64' => $b64,
						'profile' => [
							'slug' => $printer ? ($printer['slug'] ?: '') : '',
							'name' => $printer ? $printer['name'] : 'Thermal',
							'shared_name' => $printer ? ($printer['shared_name'] ?: '') : ''
						]
					]));
			} catch (Exception $e) {
				$this->output
					->set_status_header(500)
					->set_content_type('application/json')
					->set_output(json_encode([
						'ok' => false,
						'message' => $e->getMessage()
					]));
			}
		}

		private function _active_printer_profile($printer_id = 0)
		{
			$row = null;
			$printer_id = (int) $printer_id;
			if ($printer_id > 0) {
				$row = $this->db->get_where('printer', ['id' => $printer_id, 'pub' => 1])->row_array();
			}
			if (!$row) {
				$row = $this->db->order_by('id', 'DESC')->get_where('printer', ['pub' => 1])->row_array();
			}
			if (!$row) {
				$row = $this->db->order_by('id', 'DESC')->get_where('printer', ['slug' => 'th58'])->row_array();
			}
			return $row;
		}

		private function _is_tmu220_profile($printerProfile)
		{
			if (!is_array($printerProfile) || empty($printerProfile)) {
				return false;
			}

			$slug = strtolower(trim((string)($printerProfile['slug'] ?? '')));
			if ($slug === 'tmu220') {
				return true;
			}

			$name = strtolower(trim((string)($printerProfile['name'] ?? '')));
			$shared = strtolower(trim((string)($printerProfile['shared_name'] ?? '')));
			$needle = $name . ' ' . $shared;

			return (strpos($needle, 'tm-u220') !== false)
				|| (strpos($needle, 'tmu220') !== false)
				|| (strpos($needle, 'u220') !== false);
		}

		private function _spk_chars_per_line($printerProfile)
		{
			if ($this->_is_tmu220_profile($printerProfile)) {
				return 40;
			}

			$paperWidth = is_array($printerProfile) ? trim((string)($printerProfile['ukuran_kertas'] ?? '')) : '';
			if ($paperWidth === '85') {
				return 48;
			}
			if ($paperWidth === '80') {
				return 42;
			}
			return 32;
		}

		private function _build_spk_raw_b64($noid, $printerProfile = null)
		{
			$this->load->library('escpos');

			$PrinterClass = class_exists('Escpos\\Printer') ? 'Escpos\\Printer' : (class_exists('Mike42\\Escpos\\Printer') ? 'Mike42\\Escpos\\Printer' : null);
			$FileConnClass = class_exists('Escpos\\PrintConnectors\\FilePrintConnector')
				? 'Escpos\\PrintConnectors\\FilePrintConnector'
				: (class_exists('Mike42\\Escpos\\PrintConnectors\\FilePrintConnector')
					? 'Mike42\\Escpos\\PrintConnectors\\FilePrintConnector'
					: null);

			if (!$PrinterClass || !$FileConnClass) {
				throw new Exception("Library ESC/POS tidak lengkap. Pastikan FilePrintConnector/Printer tersedia.");
			}

			$row = $this->model_app->view_where('invoice', ['id_invoice' => $noid])->row_array();
			if (!$row) {
				throw new Exception("Invoice tidak ditemukan.");
			}

			$this->session->unset_userdata('cart');
			$jml = (int)$row['cetak'] + 1;
			$this->model_app->update('tb_users', ['last_invoice' => 0], ['id_user' => $this->session->idu]);
			if ($row['status'] != 'batal') {
				$this->model_app->update(
					'invoice',
					['cetak' => $jml, 'status' => 'simpan', 'pos' => 'Y', 'oto' => 6],
					['id_invoice' => $noid]
				);
			}

			$marketing = $this->model_app->view_where('tb_users', ['id_user' => $row['id_marketing']])->row_array();
			if (empty($marketing)) {
				$marketing = ['nama_lengkap' => 'Admin'];
			}

			$konsumen = $this->model_app->view_where('konsumen', ['id' => $row['id_konsumen']])->row_array();
			$nama_pelanggan = $konsumen ? $konsumen['nama'] : 'Umum';
			$cek = cekKonsumen($row['id_konsumen']);
			$panggilan = isset($cek['panggilan']) ? trim((string)$cek['panggilan']) : '';
			$detail = $this->model_app->produk_cart(['invoice_detail.id_invoice' => $noid]);

			$tmpDir = FCPATH . 'uploads/tmp/';
			if (!is_dir($tmpDir)) {
				@mkdir($tmpDir, 0775, true);
			}
			if (!is_dir($tmpDir) || !is_writable($tmpDir)) {
				$tmpDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR;
			}
			$tmpFile = $tmpDir . 'raw_spk_' . (int)$noid . '_' . time() . '.bin';

			$connector = new $FileConnClass($tmpFile);
			$printer = new $PrinterClass($connector);
			$W = $this->_spk_chars_per_line($printerProfile);
			$separator = str_repeat("=", $W) . "\n";
			$separatorThin = str_repeat("_", $W) . "\n";
			$separatorDash = str_repeat("-", $W) . "\n";

			$clean = function($text) {
				$text = strip_tags((string)$text);
				$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
				$text = preg_replace('/[ \t]+/', ' ', $text);
				return trim($text);
			};
			$strLen = function($text) {
				$text = (string)$text;
				return function_exists('mb_strlen') ? mb_strlen($text, 'UTF-8') : strlen($text);
			};
			$subStr = function($text, $start, $len) {
				$text = (string)$text;
				return function_exists('mb_substr') ? mb_substr($text, $start, $len, 'UTF-8') : substr($text, $start, $len);
			};
			$fit = function($text, $len, $padType = STR_PAD_RIGHT) use ($clean, $strLen, $subStr) {
				$text = $clean($text);
				if ($strLen($text) > $len) {
					$text = $subStr($text, 0, $len);
				}
				$pad = max(0, $len - $strLen($text));
				if ($padType === STR_PAD_LEFT) {
					return str_repeat(' ', $pad) . $text;
				}
				return $text . str_repeat(' ', $pad);
			};
			$wrap = function($text, $prefix = '') use ($clean, $strLen, $subStr, $W) {
				$text = $clean($text);
				$prefix = $clean($prefix);
				if ($text === '') {
					return [];
				}

				$lines = [];
				$firstWidth = $W - $strLen($prefix);
				if ($firstWidth < 8) {
					$firstWidth = $W;
					$prefix = '';
				}

				while ($text !== '') {
					$width = empty($lines) ? $firstWidth : $W;
					if ($strLen($text) <= $width) {
						$lines[] = $text;
						break;
					}

					$slice = $subStr($text, 0, $width);
					$cutPos = strrpos($slice, ' ');
					if ($cutPos === false || $cutPos < (int)($width / 2)) {
						$cutPos = $width;
					}

					$lines[] = rtrim($subStr($text, 0, $cutPos));
					$text = ltrim($subStr($text, $cutPos, $strLen($text)));
				}

				if ($prefix !== '' && !empty($lines)) {
					$lines[0] = $prefix . $lines[0];
				}
				return $lines;
			};

			$autoCut = (is_array($printerProfile) && isset($printerProfile['auto_cut'])) ? (int)$printerProfile['auto_cut'] : 1;

			try {
				$printer->initialize();
				$printer->setJustification($PrinterClass::JUSTIFY_CENTER);
				$printer->selectPrintMode($PrinterClass::MODE_DOUBLE_HEIGHT);
				$printer->text($clean($this->info['title']) . "\n");

				$printer->initialize();
				$printer->setJustification($PrinterClass::JUSTIFY_CENTER);
				$deskripsi = strip_word_html(base64_decode($this->info['deskripsi']));
				$descLines = preg_split('/\r\n|\r|\n/', (string)$deskripsi);
				foreach ($descLines as $descLine) {
					$descLine = $clean($descLine);
					if ($descLine !== '') {
						$printer->text($descLine . "\n");
					}
				}
				$printer->text("\n");

				$printer->initialize();
				$printer->setJustification($PrinterClass::JUSTIFY_CENTER);
				$printer->selectPrintMode($PrinterClass::MODE_DOUBLE_HEIGHT);
				$printer->selectPrintMode($PrinterClass::MODE_DOUBLE_WIDTH);
				$printer->setEmphasis(true);
				$printer->text($clean($row['id_transaksi']) . "\n");
				$printer->setEmphasis(false);
				$printer->text("\n");

				$printer->initialize();
				$printer->setJustification($PrinterClass::JUSTIFY_LEFT);
				$printer->text('Kasir     : ' . $clean($marketing['nama_lengkap']) . "\n");
				$printer->text('Tanggal   : ' . $clean(tgl_indo($row['tgl_trx'])) . "\n");
				$printer->text('Jam       : ' . $clean(invoice_order_time($row)) . "\n");
				$printer->text('Pelanggan : ' . $clean(trim($panggilan . ' ' . $nama_pelanggan)) . "\n");

				$printer->initialize();
				$printer->text($separator);

				$itemCount = is_array($detail) ? count($detail) : 0;
				$currentIndex = 0;
				if ($itemCount > 0) {
					foreach ($detail as $val) {
						$currentIndex++;

						$finishingData = [];
						if (isset($val['detail']) && $val['detail'] !== '') {
							$decoded = json_decode($val['detail']);
							if (is_object($decoded) && isset($decoded->data) && is_array($decoded->data)) {
								$finishingData = $decoded->data;
							}
						}

						$bahan = !empty($val['nbahan']) ? $val['nbahan'] : (!empty($val['title']) ? $val['title'] : 'Item');
						$ukuran = isset($val['ukuran']) ? $val['ukuran'] : '';
						$jumlah = isset($val['jumlah']) ? $val['jumlah'] : '';
						$qtyText = 'Qty:' . $clean($jumlah);
						$ukuranWidth = ($W === 32) ? 20 : max(8, $W - strlen($qtyText));

						$printer->text($fit($bahan, $W) . "\n");
						$printer->text($fit('Ukuran:' . $ukuran, $ukuranWidth) . $qtyText . "\n");
						$printer->text('Ket:' . $clean(isset($val['keterangan']) ? $val['keterangan'] : '') . "\n");

						if (!empty($finishingData)) {
							$printer->text("Catatan:\n");
							foreach ($finishingData as $fn) {
								$t = isset($fn->title) ? trim((string)$fn->title) : '';
								$i = isset($fn->isi) ? trim((string)$fn->isi) : '';
								$lineTxt = trim($t . ($i !== '' ? ' ' . $i : ''));
								if ($lineTxt === '') {
									continue;
								}
								foreach ($wrap($lineTxt) as $noteLine) {
									$printer->text($noteLine . "\n");
								}
							}
						}

						if ($currentIndex < $itemCount) {
							$printer->text($separatorThin);
						}
					}
				} else {
					$printer->text("Item tidak tersedia.\n");
				}

				$printer->text($separator);
				$printer->setJustification($PrinterClass::JUSTIFY_CENTER);
				$printer->setEmphasis(true);
				$printer->text("QC CHECKLIST\n");
				$printer->setEmphasis(false);
				$printer->text($separatorDash);

				$printer->setJustification($PrinterClass::JUSTIFY_LEFT);
				$printer->text("PRINTING          FINISHING\n");
				$printer->text($separatorDash);

				$rows = [
					["Bahan", "Bahan"],
					["Ukuran", "Ukuran"],
					["Qty", "Qty"],
					["Hasil Cetak", "Hsil Finish"],
				];

				foreach ($rows as $qcRow) {
					$left = "[ ] " . str_pad($clean($qcRow[0]), 11);
					$right = "[ ] " . str_pad($clean($qcRow[1]), 8);
					$printer->text($left . "  " . $right . "\n");
				}

				$printer->text($separatorDash);
				$printer->text("    Checker           Checker\n");
				$printer->text("\n");
				$printer->text("\n");
				$printer->text($separatorDash);

				$printer->initialize();
				$printer->setJustification($PrinterClass::JUSTIFY_CENTER);
				$printer->text("PERIKSA DENGAN DETAIL\n");
				$printer->text("SEBELUM PESANAN DI BERIKAN\n");
				$printer->feed(3);

				if ($autoCut === 1 && method_exists($printer, 'cut')) {
					try { $printer->cut(); } catch (Exception $e) {}
				}
				$printer->close();

				$raw = @file_get_contents($tmpFile);
				@unlink($tmpFile);
				if ($raw === false || $raw === '') {
					throw new Exception("RAW SPK kosong. Cek permission folder tmp atau proses build.");
				}

				return base64_encode($raw);
			} catch (Exception $e) {
				@unlink($tmpFile);
				try { $printer->close(); } catch (Exception $x) {}
				throw $e;
			}
		}

		public function print_invoice_html($noid=null){
			$noid = decrypt_url($noid);
			$id = array('id_invoice' => $noid);
			$printer_id = (int) $this->input->get('printer_id', true);
			$pub = array('pub' =>1);//printer aktif
			$search = $this->model_app->view_where('invoice', $id);
			
			if ($printer_id > 0) {
				$cek_printer = $this->db->get_where('printer', ['id' => $printer_id, 'pub' => 1]);
				if($cek_printer->num_rows() < 1){
					$cek_printer = $this->model_app->view_where('printer', $pub);
				}
			}else{
				$cek_printer = $this->model_app->view_where('printer', $pub);
			}
			if($cek_printer->num_rows()>0){
				$rowc = $cek_printer->row_array();
				//print thermal
				if($rowc['slug']=='th' AND $rowc['pub']==1){
					
					if($search->num_rows()>0){
						
						$this->session->unset_userdata('cart');
						$row = $search->row_array();
						$jml =$row['cetak']+1;
						$this->model_app->update('tb_users', array("last_invoice"=>0),array('id_user'=>$this->session->idu));
						
						//marketing 
						$marketing = $this->model_app->view_where('tb_users', array('id_user' => $row['id_marketing']))->row_array();
						//bayar detail
						$detail = $this->model_app->produk_cart(array('invoice_detail.id_invoice' => $noid));
						//total bayar
						$total=$this->model_app->total_bayar(array('bayar_invoice_detail.id_invoice'=>$noid))->row();
						$bdetail =  $this->model_app->view_where('bayar_invoice_detail', $id)->result_array();
						
						//load library
						$this->load->library('escpos');
						// membuat connector printer ke shared printer bernama "printer_a" (yang telah disetting sebelumnya)
						$connector = new Escpos\PrintConnectors\WindowsPrintConnector($rowc['shared_name']);
						
						// membuat objek $printer agar dapat di lakukan fungsinya
						$printer = new Escpos\Printer($connector);
						// Get status
						$printer->initialize();
						$printer->selectPrintMode(Escpos\Printer::MODE_DOUBLE_HEIGHT); // Setting teks menjadi lebih besar
						$printer->setJustification(Escpos\Printer::JUSTIFY_CENTER); // Setting teks menjadi rata tengah
						$printer->text($this->info['title']."\n");
						
						$printer->initialize();
						$printer->setJustification(Escpos\Printer::JUSTIFY_CENTER);
						$printer->text(strip_word_html(base64_decode($this->info['deskripsi']))."\n");
						$printer->text("\n");
						
						// Data transaksi
						$printer->initialize();
						$printer->text("Invoice : #".$row['id_invoice']."\n");
						$printer->text("Kasir : ".$marketing['nama_lengkap']."\n");
						$printer->text("Waktu : ".tgl_indo($row['tgl_trx'])."\n");
						
						// Membuat tabel
						$printer->initialize(); // Reset bentuk/jenis teks
						
						$printer->text("-----------------------------------------------\n");
						$printer->text(buatBaris4Kolom("Deskripsi", "QTY", "Harga", "Subtotal"));
						$printer->text("-----------------------------------------------\n");
						$no=1; 
						$totalb=0; 
						$subtotal=0; 
						$sisa=0; 
						$diskon=0; 
						foreach($detail  AS $val){
							$diskon = $val['jumlah'] * $val['harga'] * $val['diskon']/100;
							$totalb = $val['jumlah'] * $val['harga'] - $diskon;
							$subtotal += $totalb;
							
							$printer->text(buatBaris4Kolom($val['title'].' '.$val['ukuran'], $val['jumlah'].$val['satuan'], rp($val['harga']), rp($totalb)));
							$printer->text("Ket: ".$val['nbahan'] .' '.$val['keterangan'] ."\n");
							//
							$pajak = ($subtotal * $row['pajak']) /100;
							$sisa = $pajak + $subtotal - $total->total;
							$cek_bayar = $pajak + $subtotal;
						}
						
						$printer->text("-----------------------------------------------\n");
						$printer->text(buatBaris4Kolom('', '', "TOTAL", rp($subtotal)));
						
						if($sisa==0){
							$printer->text(buatBaris4Kolom('', '', "BAYAR", rp($total->total)));
							}else{
							$printer->text("\n");
							$printer->text(buatBaris4Kolom('', '', "BAYAR", rp($total->total)));
							$printer->text(buatBaris4Kolom('', '', "SISA", rp($sisa)));
						}
						
						$printer->text("\n");
						// Pesan penutup
						$printer->initialize();
						$printer->setJustification(Escpos\Printer::JUSTIFY_CENTER);
						$printer->text("Terima kasih\n");
						$printer->text("HP: ".$this->info['phone']."\n");
						$printer->text(" EMAIL : ".$this->info['email']."\n");
						$printer->feed(3); // mencetak 5 baris kosong agar terangkat (pemotong kertas saya memiliki jarak 5 baris dari toner)
						// echo "ok";
						
						$printer->close();
						}else{
						echo "gagal";
					}
					//print thermal 58
					}elseif($rowc['slug']=='th58' AND $rowc['pub']==1){
					
					if($search->num_rows()>0){
						
						$this->session->unset_userdata('cart');
						$row = $search->row_array();
						$jml =$row['cetak']+1;
						$this->model_app->update('tb_users', array("last_invoice"=>0),array('id_user'=>$this->session->idu));
						
						//marketing 
						$marketing = $this->model_app->view_where('tb_users', array('id_user' => $row['id_marketing']))->row_array();
						//bayar detail
						$detail = $this->model_app->produk_cart(array('invoice_detail.id_invoice' => $noid));
						//total bayar
						$total=$this->model_app->total_bayar(array('bayar_invoice_detail.id_invoice'=>$noid))->row();
						$bdetail =  $this->model_app->view_where('bayar_invoice_detail', $id)->result_array();
						
						//load library
						$this->load->library('escpos');
						// membuat connector printer ke shared printer bernama "printer_a" (yang telah disetting sebelumnya)
						$connector = new Escpos\PrintConnectors\WindowsPrintConnector($rowc['shared_name']);
						
						// membuat objek $printer agar dapat di lakukan fungsinya
						$printer = new Escpos\Printer($connector);
						// Get status
						$printer->initialize();
						$printer->selectPrintMode(Escpos\Printer::MODE_DOUBLE_HEIGHT); // Setting teks menjadi lebih besar
						$printer->setJustification(Escpos\Printer::JUSTIFY_CENTER); // Setting teks menjadi rata tengah
						$printer->text($this->info['title']."\n");
						
						$printer->initialize();
						$printer->setJustification(Escpos\Printer::JUSTIFY_CENTER);
						$printer->text(strip_word_html(base64_decode($this->info['deskripsi']))."\n");
						$printer->text("\n");
						
						// Ambil data pelanggan dari database
                        $konsumen = $this->model_app->view_where('konsumen', ['id' => $row['id_konsumen']])->row_array();
                        $nama_pelanggan = $konsumen ? $konsumen['nama'] : 'Umum';

                        $printer->initialize();
						$printer->setJustification(Escpos\Printer::JUSTIFY_CENTER);
						$printer->selectPrintMode(Escpos\Printer::MODE_DOUBLE_HEIGHT); // Setting teks menjadi lebih besar
						$printer->selectPrintMode(Escpos\Printer::MODE_DOUBLE_HEIGHT); // Setting teks menjadi lebih besar
						$printer->selectPrintMode(Escpos\Printer::MODE_DOUBLE_WIDTH); // Setting teks menjadi lebih besar
						$printer->setEmphasis(true);
						$printer->text(''.$row['id_transaksi']."\n");
						$printer->setEmphasis(true);
						$printer->text("\n");


                        // Data transaksi
                        $printer->initialize();
                        $printer->text('Kasir     : '.$marketing['nama_lengkap']."\n");
                        //$printer->text('Waktu     : '.date('H:i - d/m/Y')."\n");
                        $printer->text('Tanggal   : '.tgl_indo($row['tgl_trx'])."\n");
                        $printer->text('Jam       : '.invoice_order_time($row)."\n");
                        //$waktu_trx = date('H:i - d/m/Y', strtotime($row['tgl_trx']));
                        //$printer->text('Waktu     : '.$waktu_trx."\n");

                        $idkonsumen = $row['id_konsumen'];
                        $cek = cekKonsumen($idkonsumen); // Pastikan ini mengembalikan array
                        $panggilan = isset($cek['panggilan']) ? $cek['panggilan'] : '';
                        $printer->text('Pelanggan : '.$panggilan.' '.$nama_pelanggan."\n");
						
											// Membuat tabel
											/*$printer->initialize();
					                        $printer->text("--------------------------------\n");

					                        $totalb = 0;
					                        $subtotal = 0;
					                        $sisa = 0;
					                        $diskon = 0;

					                        foreach ($detail as $val) {
					                        // Hitung diskon dan total
					                        $diskon = $val['jumlah'] * $val['harga'] * $val['diskon'] / 100;
					                        $totalb = $val['jumlah'] * $val['harga'] - $diskon;
					                        $subtotal += $totalb;

					                        // Tampilkan nama bahan dan ukuran
					                        $printer->text(Text::fill($val['nbahan'], 32)."\n");
					                        $printer->text(Text::fill('Ukuran:'.$val['ukuran'], 32)."\n");
					                        $printer->text('Ket:'.$val['keterangan']."\n");

					                        // Format jumlah, satuan, harga dan total
					                        $printer->text(
					                        Text::fill('  '.$val['jumlah'].' '.get_satuan($val['satuan']), 12).
					                        Text::fill('x', 3).
					                        Text::fill(number_format($val['harga'], 0, ',', '.'), 7).
					                        Text::fillRight(number_format($totalb, 0, ',', '.'), 10)."\n"
					                        );
					                        }

					                        // Hitung pajak dan sisa
					                        $pajak = ($subtotal * $row['pajak']) / 100;
					                        $sisa = $pajak + $subtotal - $total->total;
					                        $cek_bayar = $pajak + $subtotal;

					                                            
					                        $printer->text("--------------------------------\n");
					                        $printer->text(buatBaris2Kolom58('TOTAL', '', '', rp($subtotal)));
					                        $select = 'pajak, total_bayar AS total, jumlah_bayar, kembalian';
					                        $where = ['id_invoice' => $noid];
					                        $tdetail = $this->model_app->cek_total('invoice', $select, $where);
					                        
					                        if ($sisa == 0) {
					                            if ($tdetail->jumlah_bayar > $total->total) {
					                                $jumlah_bayar = $tdetail->jumlah_bayar;
					                                $sisa = $tdetail->kembalian;
					                                } else {
					                                $jumlah_bayar = $total->total;
					                                $sisa = $tdetail->kembalian;
					                            }
					                            //$printer->text("\n");
					                            $printer->text(buatBaris2Kolom58('BAYAR', '', '', rp($total->total)));
					                            $printer->text(buatBaris2Kolom58('KEMBALIAN', '', '', rp($sisa)));
					                            } else {
					                            //$printer->text("\n");
					                            $printer->text(buatBaris2Kolom58('BAYAR', '', '', rp($total->total)));
					                            $printer->text(buatBaris2Kolom58('SISA', '', '', rp($sisa)));
					                        }
					                        $printer->text("--------------------------------\n");*/

						// Membuat tabel
						$printer->initialize();
						$printer->text("================================\n");

						$totalb = 0;
						$subtotal = 0;
						$sisa = 0;
						$diskon = 0;
						$itemCount = count($detail); // jumlah total item
						$currentIndex = 0;

						foreach ($detail as $val) {
						    $currentIndex++;

						    // (Tetap hitung di backend jika perlu, tapi tidak dicetak)
						    $diskon = $val['jumlah'] * $val['harga'] * $val['diskon'] / 100;
						    $totalb = $val['jumlah'] * $val['harga'] - $diskon;
						    $subtotal += $totalb;

						    // --- Ambil data FINISHING / CATATAN persis dari kirim_invoice.php terbaru ---
				            // decode $val['detail'] -> object { data: [ {title, isi}, ... ] }
				            $finishingData = [];
				            if (isset($val['detail']) && $val['detail'] !== '') {
				                $decoded = json_decode($val['detail']);
				                if (is_object($decoded) && isset($decoded->data) && is_array($decoded->data)) {
				                    $finishingData = $decoded->data; // array of objects
				                }
				            }
				            $hasNotes = !empty($finishingData);

						    // Tampilkan nama bahan
						    $printer->text(Text::fill($val['nbahan'], 32)."\n");
						    // Tampilkan ukuran + qty dalam 1 baris
						    $printer->text(
						        Text::fill('Ukuran:'.$val['ukuran'], 20) .
						        'Qty:'.$val['jumlah']."\n"
						    );
						    // Tampilkan keterangan
						    $printer->text('Ket:'.$val['keterangan']."\n");

						    // === CATATAN FINISHING (WAJIB SAMA POLA DENGAN kirim_invoice.php terbaru) ===
				            if ($hasNotes) {
				                // header "Catatan:"
				                $printer->text("Catatan:\n");

				                // looping setiap detail finishing
				                foreach ($finishingData as $fn) {
				                    $t = isset($fn->title) ? trim($fn->title) : '';
				                    $i = isset($fn->isi)   ? trim($fn->isi)   : '';
				                    $lineTxt = trim($t . ($i !== '' ? ' '.$i : ''));
				                    if ($lineTxt === '') continue;

				                    // tiap baris catatan finishing dicetak seperti di kirim_invoice.php
				                    $printer->text($lineTxt."\n");
				                }
				            }

						    // Tambahkan garis pemisah jika bukan item terakhir
						    if ($currentIndex < $itemCount) {
						        $printer->text("________________________________\n");
						    }
						}

						// Garis akhir
						$printer->text("================================\n");



						$printer->setJustification(Escpos\Printer::JUSTIFY_CENTER);
						$printer->setEmphasis(true);
						$printer->text("QC CHECKLIST\n");
						$printer->setEmphasis(false);
						$printer->text("--------------------------------\n");

						// Header
						$printer->setJustification(Escpos\Printer::JUSTIFY_LEFT);
						$printer->text("PRINTING          FINISHING\n");
						$printer->text("--------------------------------\n");

						// Data Printing & Finishing (checklist di kiri teks)
						$rows = [
						    ["Bahan", "Bahan"],
						    ["Ukuran", "Ukuran"],
						    ["Qty", "Qty"],
						    ["Hasil Cetak", "Hsil Finish"],
						];

						foreach ($rows as $row) {
						    // Kolom kiri: checklist + teks kiri
						    $left  = "[ ] " . str_pad($row[0], 11);

						    // Kolom kanan: checklist + teks kanan
						    $right = "[ ] " . str_pad($row[1], 8);

						    // Cetak
						    $printer->text($left . "  " . $right . "\n");
						}

						$printer->text("--------------------------------\n");
						$printer->setJustification(Escpos\Printer::JUSTIFY_LEFT);
						$printer->text("    Checker           Checker\n");
						$printer->text("\n");
						$printer->text("\n");
						$printer->text("--------------------------------\n");


						// Pesan penutup
						$printer->initialize();
						$printer->setJustification(Escpos\Printer::JUSTIFY_CENTER);
						$printer->text("PERIKSA DENGAN DETAIL\n");
						$printer->text("SEBELUM PESANAN DI BERIKAN\n");
						//$printer->text("HP: ".$this->info['phone']."\n");
						//$printer->text(" EMAIL : ".$this->info['email']."\n");
						$printer->feed(3);  
						
						$printer->close();
						}else{
						echo "gagal";
					}
					}elseif(($rowc['slug']=='direct58' or $rowc['slug']=='direct85') AND $rowc['pub']==1){
					
					$data['waicon'] 	= ['color'=>base_url().'assets/img/wa_icon.png','bw'=>base_url().'assets/img/wa_icon_bw.png'];
					$data['mail'] 		= ['color'=>base_url().'assets/img/gmail_icon.png','bw'=>base_url().'assets/img/gmail_icon_bw.png'];
					$data['fbicon'] 	= ['color'=>base_url().'assets/img/fb_icon.png','bw'=>base_url().'assets/img/fb_icon_bw.png'];
					$data['igicon'] 	= ['color'=>base_url().'assets/img/ig_icon.png','bw'=>base_url().'assets/img/ig_icon_bw.png'];
					
					$data['logo_lunas'] = base_url().'uploads/'.info()['logo'];
					$data['logo_blunas'] = base_url().'uploads/'.info()['logo_bw'];
					$data['lunas'] = base_url().'uploads/'.info()['stamp_l'];
					$data['blunas'] = base_url().'uploads/'.info()['stamp_b'];
					$data['favicon'] = base_url().'uploads/'.info()['favicon'];
					$data['html'] = 'Y';
					
					$data['ukuran'] =$rowc['ukuran_kertas'];
					$data['font_size'] =$rowc['ukuran_font'];
					
					if($search->num_rows()>0){
						$this->session->unset_userdata('cart');
						$row = $search->row();
						$jml =$row->cetak+1;
						$this->model_app->update('tb_users', array("last_invoice"=>0),array('id_user'=>$this->session->idu));
						
						//cek sisa
						$_total = 'ROUND(SUM((`invoice_detail`.`jumlah` * harga) - (`invoice_detail`.`jumlah` * harga) * (`invoice_detail`.`diskon`/100))) AS sisa';
						$cari_total= $this->model_app->cek_total('invoice_detail',$_total,array('id_invoice'=>$noid));
						$data['sisanya'] = $cari_total->sisa;
						//
						$data['cetak'] = $row;
						$data['info'] = info();
						$konsumen = $this->model_app->view_where('konsumen', array('id' => $row->id_konsumen))->row_array();
						
						if($konsumen['max_utang'] >0 AND $jml <=1){
							$max_utang = $konsumen['max_utang'] - 1;
							$this->model_app->update('konsumen',array('max_utang'=>$max_utang),array('id'=>$row->id_konsumen));
						}
						
						$data['konsumen']    = $konsumen;
						$data['marketing']   = $this->model_app->view_where('tb_users', array('id_user' => $row->id_marketing))->row_array();
						$data['detail']      = $this->model_app->produk_cart(array('invoice_detail.id_invoice' => $noid));
						$data['total']       =$this->model_app->total_bayar(array('bayar_invoice_detail.id_invoice'=>$noid))->row();
						$select              = 'pajak, total_bayar AS total';
						$where               = array('id_invoice'=>$noid);
						$tdetail             = $this->model_app->cek_total('invoice',$select,$where);
						$data['tdetail']     = $tdetail->total;
						$data['pajak']       = $tdetail->pajak;
						$_diskon             = 'SUM(diskon) AS `disc`';
						$cdiskon             = $this->model_app->cek_total('invoice_detail',$_diskon,$where);
						$data['cdiskon']     = $cdiskon->disc;
						$_select             = 'COUNT(id) AS `jml`';
						$cdetail             = $this->model_app->cek_total('bayar_invoice_detail',$_select,$where);
						$data['cdetail']     = $cdetail->jml;
						//bayar detail
						$data['bdetail']     = $this->model_app->view_where('bayar_invoice_detail', $id)->result_array();
						///
						$data['cara']        = $this->model_app->cara_bayar([
    'jb.publish'    => 'Y',
    'bid.id_invoice'=> $noid,
]);

						$data['bank']        = $this->model_app->view_where('rekening_bank',['footer_invoice'=>1,'publish'=>'Y'])->result();
						
						$this->load->view('laporan/print_invoice_direct58',$data);
						}else{
						$data['cetak'] = 'error';
						$this->load->view('errors/404',$data);
					}
					//print html
					}else{
					//icon
					$data['waicon'] 	= ['color'=>base_url().'assets/img/wa_icon.png','bw'=>base_url().'assets/img/wa_icon_bw.png'];
					$data['mail'] 		= ['color'=>base_url().'assets/img/gmail_icon.png','bw'=>base_url().'assets/img/gmail_icon_bw.png'];
					$data['fbicon'] 	= ['color'=>base_url().'assets/img/fb_icon.png','bw'=>base_url().'assets/img/fb_icon_bw.png'];
					$data['igicon'] 	= ['color'=>base_url().'assets/img/ig_icon.png','bw'=>base_url().'assets/img/ig_icon_bw.png'];
					
					$data['logo_lunas'] = base_url().'uploads/'.info()['logo'];
					$data['logo_blunas'] = base_url().'uploads/'.info()['logo_bw'];
					$data['lunas'] = base_url().'uploads/'.info()['stamp_l'];
					$data['blunas'] = base_url().'uploads/'.info()['stamp_b'];
					$data['favicon'] = base_url().'uploads/'.info()['favicon'];
					$data['html'] = 'Y';
					if($search->num_rows()>0){
						$this->session->unset_userdata('cart');
						$row = $search->row();
						$jml =$row->cetak+1;
						$this->model_app->update('tb_users', array("last_invoice"=>0),array('id_user'=>$this->session->idu));
						if($row->status!='batal'){
							$this->model_app->update('invoice',array('cetak'=>$jml,'status'=>'simpan','pos'=>'Y','oto'=>6),array('id_invoice'=>$noid));
						}
						//cek sisa
						$_total = 'ROUND(SUM((`invoice_detail`.`jumlah` * harga) - (`invoice_detail`.`jumlah` * harga) * (`invoice_detail`.`diskon`/100))) AS sisa';
						$cari_total= $this->model_app->cek_total('invoice_detail',$_total,array('id_invoice'=>$noid));
						$data['sisanya'] = $cari_total->sisa;
						//
						$data['cetak'] = $row;
						$data['info'] = info();
						$konsumen = $this->model_app->view_where('konsumen', array('id' => $row->id_konsumen))->row_array();
						
						if($konsumen['max_utang'] >0 AND $jml <=1){
							$max_utang = $konsumen['max_utang'] - 1;
							$this->model_app->update('konsumen',array('max_utang'=>$max_utang),array('id'=>$row->id_konsumen));
						}
						
						$data['konsumen']    = $konsumen;
						$data['marketing']   = $this->model_app->view_where('tb_users', array('id_user' => $row->id_marketing))->row_array();
						$data['detail']      = $this->model_app->produk_cart(array('invoice_detail.id_invoice' => $noid));
						$data['total']       =$this->model_app->total_bayar(array('bayar_invoice_detail.id_invoice'=>$noid))->row();
						$select              = 'pajak, total_bayar AS total';
						$where               = array('id_invoice'=>$noid);
						$tdetail             = $this->model_app->cek_total('invoice',$select,$where);
						$data['tdetail']     = $tdetail->total;
						$data['pajak']       = $tdetail->pajak;
						$_diskon             = 'SUM(diskon) AS `disc`';
						$cdiskon             = $this->model_app->cek_total('invoice_detail',$_diskon,$where);
						$data['cdiskon']     = $cdiskon->disc;
						$_select             = 'COUNT(id) AS `jml`';
						$cdetail             = $this->model_app->cek_total('bayar_invoice_detail',$_select,$where);
						$data['cdetail']     = $cdetail->jml;
						//bayar detail
						$data['bdetail']     = $this->model_app->view_where('bayar_invoice_detail', $id)->result_array();
						///
						$data['cara']        = $this->model_app->cara_bayar([
    'jb.publish'    => 'Y',
    'bid.id_invoice'=> $noid,
]);

						$data['bank']        = $this->model_app->view_where('rekening_bank',['footer_invoice'=>1,'publish'=>'Y'])->result();
						
						$this->load->view('laporan/print_laporan_spk',$data);
						}else{
						$data['cetak'] = 'error';
						$this->load->view('errors/404',$data);
					}
				}
			}
		}
	}			
