<?php
	defined('BASEPATH') or exit('No direct script access allowed');
	
	class Main extends CI_Controller
	{
		public function __construct()
		{
			parent::__construct();
			// cek_tabel();
			cek_session_login();
			$this->perPage = 10; 
			$this->title = info()['title']; 
			$this->tools = info()['dev_tools']; 
			$this->iduser = $this->session->idu; 
			$this->akses = $this->session->type_akses; 
			
		}
		
		public function cek_akses(){
			$id = decrypt_url($this->input->post('id'));
			$mod = $this->db->escape_str($this->input->post('mod'));
			cek_type_akses(6,$this->iduser,$id,$mod);
		}
		public function ambildata(){
			$data['record'] = $this->model_app->view_ordering('tb_users','nama_lengkap','DESC');
			$arr = $this->load->view('main/user/ambildata',$data);
			$msg = array('hasil'=>$arr);
			echo json_encode($msg);
		}
		
		public function cek_order(){
			$id = $this->db->escape_str($this->input->post('id'));
			$total = $this->model_app->sum_data('jml_bayar','bayar_invoice_detail',['id_invoice'=>$id]);
			$cek = $this->model_app->view_where('invoice',['id_invoice'=>$id]);
			if($cek->num_rows() > 0){
				$row = $cek->row();
				$msg = array('status'=>'ok','id'=>$id,'notrx'=>get_id_transaksi($id)['nomor_order'],'total'=>$total,'ket'=>$row->history);
				}else{
				$msg = array('status'=>'error','id'=>0,'notrx'=>0);
			}
			echo json_encode($msg);
		}
		
		public function simpan_batal(){
			simpan_demo("Simpan");
			$id = $this->db->escape_str($this->input->post('no_order'));
			$mod = $this->db->escape_str($this->input->post('mod_batal'));
			
			$keterangan = $this->db->escape_str($this->input->post('keterangan'));
			$query_cek = $this->model_cek->cek_akses(5,$this->iduser);
			if ($query_cek->num_rows()>0){
				$this->session->unset_userdata("cart");
				$id_konsumen = get_id_transaksi($id)['idkonsumen'];
				$nama = cekKonsumen($id_konsumen)['nama'];
				$get_id_transaksi = get_id_transaksi($id)['nomor_order'];
				$catatan =  "ORDER NO#".$get_id_transaksi.' - '.$nama;
				$_catatan =  "BAYAR ORDER NO#".$get_id_transaksi.' - '.$nama;
				
				$cek_count =$this->model_jurnal->cek_count($id);
				$where = array('id_invoice' => $id);
				$cek_invoice = $this->model_app->view_where('stok_keluar',$where);
				if($cek_invoice->num_rows() > 0){
					
					$data = array('status'=>'batal','oto'=>5,'history' => $keterangan);
					$res= $this->model_app->update('invoice', $data, $where);
					if($res['status']=='ok'){
						
						$query_stok_keluar = $this->model_app->pilih_where('id_invoice,id_bahan,jumlah','stok_keluar',['id_invoice'=>$id])->result();
						
						foreach($query_stok_keluar AS $row){
							$cek_jenis_bahan = $this->model_app->pilih_where('kunci,status_stok','bahan',['id'=>$row->id_bahan])->row();
							if($cek_jenis_bahan->status_stok=='Y' AND $cek_jenis_bahan->kunci==1){
								$_data = [
								'id_bahan'=>$row->id_bahan,
								'jumlah'=>$row->jumlah,
								'create_date'=>today(),
								'ket'=>'Retur penjualan No.'.$row->id_invoice
								];
								$this->model_app->insert('stok_masuk',$_data);
							}
						}
						
						$this->model_app->update('bayar_invoice_detail', ['hapus'=>1], $where);
						$this->model_app->update('tb_users', ['last_invoice'=>0], ['id_user'=>$this->iduser]);
						$this->model_app->delete("stok_keluar", $where);
						$this->model_app->delete("jurnal", ['keterangan'=>$catatan]);
						$this->model_app->delete("jurnal", ['keterangan'=>$_catatan]);
						
						$msg = array('status'=>'ok','msg'=>'No. Order '. get_id_transaksi($id)['nomor_order'].' dibatalkan');
						}else{
						$msg = array('status'=>'err','msg'=>'Gagal');
					}
					}else{
					$data = array('status'=>'batal','oto'=>5,'history' => $keterangan);
					$res= $this->model_app->update('invoice', $data, $where);
					if($res['status']=='ok'){
						$this->model_app->update('bayar_invoice_detail', ['hapus'=>1], $where);
						$this->model_app->delete("stok_keluar", $where);
						$this->model_app->delete("jurnal", ['keterangan'=>$catatan]);
						$this->model_app->delete("jurnal", ['keterangan'=>$_catatan]);
						$msg = array('status'=>'ok','msg'=>'No. Order '. get_id_transaksi($id)['nomor_order'].' dibatalkan');
						}else{
						$msg = array('status'=>'err','msg'=>'Gagal');
					}
				}
				}else{
				$msg = array('status'=>400,'msg'=>'Akses ditolak');
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($msg));
		}
		public function simpan_batalx(){
			simpan_demo("Simpan");
			$id = $this->db->escape_str($this->input->post('no_order'));
			$mod = $this->db->escape_str($this->input->post('mod_batal'));
			$id_byrbatal = $this->db->escape_str($this->input->post('id_byrbatal'));
			$sumber_kas_batal = $this->db->escape_str($this->input->post('sumber_kas_batal'));
			$rekening_bayar = $this->db->escape_str($this->input->post('rekening_bayar'));
			$rekening_bayar = !empty($rekening_bayar) ? $rekening_bayar : 0;
			
			$total_batal = $this->db->escape_str($this->input->post('total_batal'));
			$total_batal = convert_to_number($total_batal);
			$keterangan = $this->db->escape_str($this->input->post('keterangan'));
			$query_cek = $this->model_cek->cek_akses(5,$this->iduser);
			if ($query_cek->num_rows()>0){
				$this->session->unset_userdata("cart");
				$where = array('id_invoice' => $id);
				
				$_where = ["catatan" => "Pendapatan INVOICE NO.#" . $id];
				$cek_invoice = $this->model_app->view_where('stok_keluar',$where);
				if($cek_invoice->num_rows() > 0){
					$data = array('status'=>'batal','oto'=>5,'history' => $keterangan);
					$res= $this->model_app->update('invoice', $data, $where);
					if($res['status']=='ok'){
						if($sumber_kas_batal!=211){
							$query_stok_keluar = $this->model_app->pilih_where('id_invoice,id_bahan,jumlah','stok_keluar',['id_invoice'=>$id])->result();
							
							foreach($query_stok_keluar AS $row){
								$cek_jenis_bahan = $this->model_app->pilih_where('kunci,status_stok','bahan',['id'=>$row->id_bahan])->row();
								if($cek_jenis_bahan->status_stok=='Y' AND $cek_jenis_bahan->kunci==1){
									$_data = [
									'id_bahan'=>$row->id_bahan,
									'jumlah'=>$row->jumlah,
									'create_date'=>today(),
									'ket'=>'Retur penjualan No.'.$row->id_invoice
									];
									$this->model_app->insert('stok_masuk',$_data);
								}
							}
							
							$this->model_app->update('bayar_invoice_detail', ['hapus'=>1], $where);
							$this->model_app->update('tb_users', ['last_invoice'=>0], ['id_user'=>$this->iduser]);
							$this->model_app->delete("deposit", $where);
							$this->model_app->delete("stok_keluar", $where);
							$this->model_app->delete("kas_masuk", $_where);
							$this->model_app->delete("jurnal_transaksi", ['reff'=>'O-'.$id]);
							$this->model_app->delete("jurnal_transaksi", ['reff'=>'I-'.$id]);
							
						}
						$msg = array('status'=>'ok','msg'=>'No. Order '. get_id_transaksi($id)['nomor_order'].' dibatalkan');
						}else{
						$msg = array('status'=>'err','msg'=>'Gagal');
					}
					}else{
					$data = array('status'=>'batal','oto'=>5,'history' => $keterangan);
					$res= $this->model_app->update('invoice', $data, $where);
					if($res['status']=='ok'){
						$this->model_app->update('bayar_invoice_detail', ['hapus'=>1], $where);
						$this->model_app->delete("stok_keluar", $where);
						// $this->model_app->delete("kas_masuk", $_where);
						$this->model_app->delete("jurnal_transaksi", ['reff'=>'O-'.$id]);
						
						$autoNumber = autoNumber(NOMOR_REFF,DIGIT_REFF,'id_generate','kas_masuk');
						$this->model_app->insert("kas_masuk", [
                        "id_bayar" => $id_byrbatal,
                        "id_sub_bayar" => $rekening_bayar,
                        "no_reff" => $sumber_kas_batal,
                        "id_user" => $this->iduser,
                        "id_generate" => $autoNumber,
                        "pengeluaran" => $total_batal,
                        "catatan" => "Batal Order No.#" . $id,
                        ]);
						$msg = array('status'=>'ok','msg'=>'No. Order '. get_id_transaksi($id)['nomor_order'].' dibatalkan');
						}else{
						$msg = array('status'=>'err','msg'=>'Gagal');
					}
				}
				}else{
				$msg = array('status'=>400,'msg'=>'Akses ditolak');
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($msg));
		}
		public function logout(){
			$this->session->sess_destroy();
			redirect('adm');
		}
		
		public function menuadmin()
		{
			cek_menu_akses();
			$this->load->model('Komisi_sales_model', 'komisi_sales');
			$this->load->model('model_dropshiper', 'dropship');
			$this->load->model('Komisi_penjualan_model', 'komisi_penjualan');
			$this->komisi_sales->ensureMenuEntry();
			$this->dropship->ensureMenuEntry();
			$this->komisi_penjualan->ensureMenuEntry();
			$data['title'] = 'Menu Admin | ' .$this->title;
			$data['result'] = $this->model_app->view_where('hak_akses',['publish'=>'Y']);
			$this->template->load('main/themes','main/menuadmin',$data);
		}
		
		public function info()
		{
			cek_menu_akses();
			cek_crud_akses(8);
			$this->ensure_transaction_number_settings();
			$this->ensure_product_item_image_setting();
			$this->ensure_chat_settings();
			$this->ensure_timezone_setting();
			$this->ensure_job_status_settings();
			$this->load->model('Komisi_sales_model', 'komisi_sales');
			$this->load->model('model_dropshiper', 'dropship');
			$this->load->model('Komisi_penjualan_model', 'komisi_penjualan');
			$this->komisi_sales->ensureInfoSetting();
			$this->komisi_sales->syncMenuVisibility($this->komisi_sales->isFeatureEnabled());
			$this->dropship->ensureInfoSetting();
			$this->dropship->syncMenuVisibility($this->dropship->isFeatureEnabled());
			$this->komisi_penjualan->ensureSchema();
			$this->komisi_penjualan->ensureMenuEntry($this->komisi_penjualan->isFeatureEnabled());
			$data['title'] = 'Pengaturan Aplikasi';
			$data['rows'] = $this->model_app->views('info')->row_array();
			$data['rows']['komisi_sales_aktif'] = isset($data['rows']['komisi_sales_aktif']) ? (int) $data['rows']['komisi_sales_aktif'] : 1;
			$data['rows']['dropshipper_aktif'] = isset($data['rows']['dropshipper_aktif']) ? (int) $data['rows']['dropshipper_aktif'] : 1;
			$data['rows']['komisi_penjualan_aktif'] = isset($data['rows']['komisi_penjualan_aktif']) ? (int) $data['rows']['komisi_penjualan_aktif'] : 0;
			$data['rows']['trx_prefix'] = !empty($data['rows']['trx_prefix']) ? $data['rows']['trx_prefix'] : 'TRX';
			$data['rows']['trx_digits'] = isset($data['rows']['trx_digits']) ? (int) $data['rows']['trx_digits'] : 5;
			$data['rows']['gambar_item_aktif'] = isset($data['rows']['gambar_item_aktif']) ? (int) $data['rows']['gambar_item_aktif'] : 1;
			$data['rows']['chat_aktif'] = isset($data['rows']['chat_aktif']) ? (int) $data['rows']['chat_aktif'] : 1;
			$data['rows']['chat_suara'] = $this->valid_chat_sound($data['rows']['chat_suara'] ?? 'classic');
			$data['rows']['timezone'] = $this->valid_timezone($data['rows']['timezone'] ?? 'Asia/Jakarta');
			$data['job_statuses'] = job_statuses(false);
			$data['api_key'] = maskString($data['rows']['api_key']);
			$data['license_state'] = app_license_state();
			$this->template->load('main/themes','main/website/info',$data);
		}
		
		public function info_save(){
			// dump($_POST);
			if (isset($_POST['submit'])){
				cek_crud_akses(9);
				save_demo_redirect('main/info');
				$this->load->model('Komisi_sales_model', 'komisi_sales');
				$this->load->model('model_dropshiper', 'dropship');
				$this->load->model('Komisi_penjualan_model', 'komisi_penjualan');
				$this->ensure_transaction_number_settings();
				$this->ensure_product_item_image_setting();
				$this->ensure_chat_settings();
				$this->ensure_timezone_setting();
				$this->ensure_job_status_settings();
				$this->komisi_sales->ensureInfoSetting();
				$this->dropship->ensureInfoSetting();
				$this->komisi_penjualan->ensureSchema();
				$config['upload_path'] = 'uploads/';
				$config['allowed_types'] = 'gif|jpg|jpeg|png|webp|ico|svg';
				$config['max_size'] = '1000'; // kb
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				$search=$this->model_app->view_where('info',array('id'=>1));
				
				if($search->num_rows()>0){
					$datas=$search->row();
					$nama_logo=$datas->logo;
					$nama_logo_bw=$datas->logo_bw;
					$nama_icon=$datas->favicon;
					$lunas=$datas->stamp_l;
					$blunas=$datas->stamp_b;
					$token_api=$datas->api_key;
				}
				
				if(info()['demo']=='N')
				{
					if(!empty($_FILES["logo_struk_thermal"]["name"])){
						try {
							$this->save_thermal_receipt_logo($_FILES["logo_struk_thermal"]);
						} catch (RuntimeException $e) {
							$this->session->set_flashdata('message', '<script>notif('.json_encode($e->getMessage()).',"danger");</script>');
							redirect('main/info');
							return;
						}
					}

					if(!empty($_FILES["logo"]["name"])){
						$_logo=FCPATH."uploads/".$nama_logo;
						if (file_exists($_logo)) {
							unlink($_logo);
						}
						if(!$this->upload->do_upload('logo'))  
						{  
							echo $this->upload->display_errors();  
						}  
						else  
						{  
							$data = bm_finalize_ci_upload_as_webp($this->upload->data(), 82);
							if ($data['status']) $nama_logo = $data["file_name"];
						}  
					}
					
					if(!empty($_FILES["logo_bw"]["name"])){
						$_logo=FCPATH."uploads/".$nama_logo_bw;
						if (file_exists($_logo)) {
							unlink($_logo);
						}
						if(!$this->upload->do_upload('logo_bw'))  
						{  
							echo $this->upload->display_errors();  
						}  
						else  
						{  
							$data = bm_finalize_ci_upload_as_webp($this->upload->data(), 82);
							if ($data['status']) $nama_logo_bw = $data["file_name"];
						}  
					}
					if(!empty($_FILES["icon"]["name"])){
						$favicon=FCPATH."uploads/".$nama_icon;
						if (file_exists($favicon)) {
							unlink($favicon);
						}
						if(!$this->upload->do_upload('icon'))  
						{  
							echo $this->upload->display_errors();  
						}  
						else  
						{  
							$data = bm_finalize_ci_upload_as_webp($this->upload->data(), 82);
							if ($data['status']) $nama_icon = $data["file_name"];
						}  
					}
					if(!empty($_FILES["lunas"]["name"])){
						$favicon=FCPATH."uploads/".$lunas;
						if (file_exists($favicon)) {
							unlink($favicon);
						}
						if(!$this->upload->do_upload('lunas'))  
						{  
							echo $this->upload->display_errors();  
						}  
						else  
						{  
							$data = bm_finalize_ci_upload_as_webp($this->upload->data(), 82);
							if ($data['status']) $lunas = $data["file_name"];
						}  
					}
					if(!empty($_FILES["blunas"]["name"])){
						$favicon=FCPATH."uploads/".$blunas;
						if (file_exists($favicon)) {
							unlink($favicon);
						}
						if(!$this->upload->do_upload('blunas'))  
						{  
							echo $this->upload->display_errors();  
						}  
						else  
						{  
							$data = bm_finalize_ci_upload_as_webp($this->upload->data(), 82);
							if ($data['status']) $blunas = $data["file_name"];
						}  
					}
				}
				$qris = $this->input->post('qris');
				
				if(empty($qris)){
				$qris = '';
				}else{
				$qris = $qris;
				$this->generate_qrcode($qris);
				}
				//dump($qris);
				if($this->input->post('checkbox') == 'on'){
					$token_api = $this->input->post('token_api');
				}
				
				$komisi_sales_aktif = ((int) $this->input->post('komisi_sales_aktif', TRUE) === 1) ? 1 : 0;
				$dropshipper_aktif = ((int) $this->input->post('dropshipper_aktif', TRUE) === 1) ? 1 : 0;
				$komisi_penjualan_aktif = ((int) $this->input->post('komisi_penjualan_aktif', TRUE) === 1) ? 1 : 0;
				$gambar_item_aktif = ((int) $this->input->post('gambar_item_aktif', TRUE) === 1) ? 1 : 0;
				$chat_aktif = ((int) $this->input->post('chat_aktif', TRUE) === 1) ? 1 : 0;
				$chat_suara = $this->valid_chat_sound($this->input->post('chat_suara', TRUE));
				$trx_prefix = strtoupper(trim((string) $this->input->post('trx_prefix', TRUE)));
				$trx_prefix = preg_replace('/[^A-Z0-9]/', '', $trx_prefix);
				$trx_prefix = substr($trx_prefix, 0, 20);
				if ($trx_prefix === '') {
					$trx_prefix = 'TRX';
				}
				$trx_digits = (int) $this->input->post('trx_digits', TRUE);
				$trx_digits = max(1, min(12, $trx_digits));
				$timezone = $this->valid_timezone($this->input->post('timezone', TRUE));
				$job_statuses = $this->sanitize_job_statuses($this->input->post('job_statuses'));
				
				$data = array('title'=>$this->input->post('title')
				,'deskripsi'=>base64_encode($this->input->post('deskripsi'))
				,'ket'=>base64_encode($this->input->post('ket'))
				,'footer_invoice'=>base64_encode($this->input->post('footer'))
				,'email'=>$this->input->post('email')
				,'perusahaan'=>$this->input->post('perusahaan')
				,'phone'=>$this->input->post('phone')
				,'fb'=>$this->input->post('fb')
				,'ig'=>$this->input->post('ig')
				,'api_key'=>$token_api
				,'logo'=>$nama_logo
				,'logo_bw'=>$nama_logo_bw
				,'stamp_l'=>$lunas
				,'stamp_b'=>$blunas
				,'warna_lunas'=>$this->input->post('warna_lunas')
				,'warna_blunas'=>$this->input->post('warna_blunas')
				,'tema'=>$this->input->post('tema')
				,'keywords'=>$this->input->post('keywords')
				,'kode_qris'=>$qris
				,'dev_tools'=>$this->input->post('devtools', TRUE)
				,'komisi_sales_aktif'=>$komisi_sales_aktif
				,'dropshipper_aktif'=>$dropshipper_aktif
				,'komisi_penjualan_aktif'=>$komisi_penjualan_aktif
				,'gambar_item_aktif'=>$gambar_item_aktif
				,'chat_aktif'=>$chat_aktif
				,'chat_suara'=>$chat_suara
				,'trx_prefix'=>$trx_prefix
				,'trx_digits'=>$trx_digits
				,'timezone'=>$timezone
				,'job_statuses'=>json_encode($job_statuses, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
				,'favicon'=>$nama_icon);	
				
				// dump($data);
				$where = array('id' => 1);
				$res= $this->model_app->update('info', $data, $where);
				if($res['status']=='ok'){
					$this->cache->file->delete('app_info_v1');
					$this->komisi_sales->syncMenuVisibility($komisi_sales_aktif === 1);
					$this->dropship->syncMenuVisibility($dropshipper_aktif === 1);
					$this->komisi_penjualan->ensureMenuEntry($komisi_penjualan_aktif === 1);
					$this->session->set_flashdata('message', '<script>notif("Data di simpan","success");</script>');
					redirect('main/info');
					}else{
					$this->session->set_flashdata('message', '<script>notif("Data gagal di simpan","danger");</script>');
					redirect('main/info');
				}
			}
		}

		private function ensure_transaction_number_settings()
		{
			$this->load->dbforge();
			if ($this->db->table_exists('info')) {
				if (!$this->db->field_exists('trx_prefix', 'info')) {
					$this->dbforge->add_column('info', ['trx_prefix' => [
						'type' => 'VARCHAR', 'constraint' => 20, 'null' => false, 'default' => 'TRX',
					]]);
				}
				if (!$this->db->field_exists('trx_digits', 'info')) {
					$this->dbforge->add_column('info', ['trx_digits' => [
						'type' => 'INT', 'constraint' => 2, 'null' => false, 'default' => 5,
					]]);
				}
			}

			if ($this->db->table_exists('invoice') && $this->db->field_exists('id_transaksi', 'invoice')) {
				$fields = $this->db->field_data('invoice');
				foreach ($fields as $field) {
					if ($field->name === 'id_transaksi' && (int) $field->max_length < 50) {
						$this->dbforge->modify_column('invoice', ['id_transaksi' => [
							'name' => 'id_transaksi', 'type' => 'VARCHAR', 'constraint' => 50, 'null' => true,
						]]);
						break;
					}
				}
			}
		}

		private function ensure_product_item_image_setting()
		{
			$this->load->dbforge();
			if ($this->db->table_exists('info') && !$this->db->field_exists('gambar_item_aktif', 'info')) {
				$this->dbforge->add_column('info', ['gambar_item_aktif' => [
					'type' => 'TINYINT',
					'constraint' => 1,
					'null' => false,
					'default' => 1,
				]]);
				$this->cache->file->delete('app_info_v1');
			}
		}

		private function ensure_chat_settings()
		{
			$this->load->dbforge();
			if (!$this->db->table_exists('info')) return;
			$changed = false;
			if (!$this->db->field_exists('chat_aktif', 'info')) {
				$this->dbforge->add_column('info', ['chat_aktif' => [
					'type' => 'TINYINT', 'constraint' => 1, 'null' => false, 'default' => 1,
				]]);
				$changed = true;
			}
			if (!$this->db->field_exists('chat_suara', 'info')) {
				$this->dbforge->add_column('info', ['chat_suara' => [
					'type' => 'VARCHAR', 'constraint' => 20, 'null' => false, 'default' => 'classic',
				]]);
				$changed = true;
			}
			if ($changed) $this->cache->file->delete('app_info_v1');
		}

		private function valid_chat_sound($sound)
		{
			$sound = strtolower(trim((string)$sound));
			return in_array($sound, ['classic', 'soft', 'double', 'silent'], true) ? $sound : 'classic';
		}

		private function ensure_timezone_setting()
		{
			$this->load->dbforge();
			if ($this->db->table_exists('info') && !$this->db->field_exists('timezone', 'info')) {
				$this->dbforge->add_column('info', ['timezone' => [
					'type' => 'VARCHAR',
					'constraint' => 50,
					'null' => false,
					'default' => 'Asia/Jakarta',
				]]);
				$this->cache->file->delete('app_info_v1');
			}
		}

		private function ensure_job_status_settings()
		{
			$this->load->dbforge();
			if ($this->db->table_exists('info') && !$this->db->field_exists('job_statuses', 'info')) {
				$this->dbforge->add_column('info', ['job_statuses' => [
					'type' => 'TEXT', 'null' => true,
				]]);
				$this->db->where('id', 1)->update('info', [
					'job_statuses' => json_encode(job_status_defaults(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
				]);
				$this->cache->file->delete('app_info_v1');
			}
		}

		private function sanitize_job_statuses($input)
		{
			$rows = is_array($input) ? $input : [];
			$clean = [];
			$seen = [];
			foreach ($rows as $index => $row) {
				$code = isset($row['code']) ? (int)$row['code'] : -1;
				$label = trim(strip_tags((string)($row['label'] ?? '')));
				$color = strtolower(trim((string)($row['color'] ?? '#64748b')));
				if ($code < 0 || $code > 99 || $label === '' || isset($seen[$code])) continue;
				if (!preg_match('/^#[0-9a-f]{6}$/', $color)) $color = '#64748b';
				$seen[$code] = true;
				$clean[] = ['code'=>$code, 'label'=>mb_substr($label, 0, 40), 'color'=>$color,
					'icon'=>preg_replace('/[^a-z0-9-]/', '', strtolower((string)($row['icon'] ?? 'circle'))),
					'active'=>isset($row['active']) && (int)$row['active'] === 1 ? 1 : 0, 'order'=>$index];
			}
			if (!isset($seen[0])) array_unshift($clean, job_status_defaults()[0]);
			return $clean ?: job_status_defaults();
		}

		private function valid_timezone($timezone)
		{
			$allowed = ['Asia/Jakarta', 'Asia/Makassar', 'Asia/Jayapura', 'UTC'];
			return in_array($timezone, $allowed, true) ? $timezone : 'Asia/Jakarta';
		}

		/**
		 * Mengubah logo upload menjadi PNG hitam-putih yang aman untuk printer thermal.
		 * Nama output dipertahankan karena seluruh jalur cetak memakai file ini.
		 */
		private function save_thermal_receipt_logo($file)
		{
			if (!is_array($file) || (int)($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
				throw new RuntimeException('Upload logo struk thermal gagal. Silakan pilih file gambar yang valid.');
			}

			$tmpPath = (string)($file['tmp_name'] ?? '');
			$fileSize = (int)($file['size'] ?? 0);
			if ($tmpPath === '' || !is_uploaded_file($tmpPath)) {
				throw new RuntimeException('File logo struk thermal tidak valid.');
			}
			if ($fileSize < 1 || $fileSize > (5 * 1024 * 1024)) {
				throw new RuntimeException('Ukuran logo struk thermal maksimal 5 MB.');
			}
			if (!function_exists('imagecreatefromstring') || !function_exists('imagepng')) {
				throw new RuntimeException('Konversi logo membutuhkan ekstensi GD pada server.');
			}

			$imageInfo = @getimagesize($tmpPath);
			$imageWidth = (int)($imageInfo[0] ?? 0);
			$imageHeight = (int)($imageInfo[1] ?? 0);
			if ($imageWidth < 1 || $imageHeight < 1 || $imageWidth > 8000 || $imageHeight > 8000 || ($imageWidth * $imageHeight) > 25000000) {
				throw new RuntimeException('Dimensi logo terlalu besar atau tidak valid. Maksimal 25 megapiksel.');
			}

			$blob = @file_get_contents($tmpPath);
			$source = $blob !== false ? @imagecreatefromstring($blob) : false;
			if (!$source) {
				throw new RuntimeException('Format gambar tidak didukung. Gunakan PNG, JPG, WEBP, atau GIF.');
			}

			$sourceWidth = imagesx($source);
			$sourceHeight = imagesy($source);
			if ($sourceWidth < 1 || $sourceHeight < 1) {
				imagedestroy($source);
				throw new RuntimeException('Dimensi logo struk thermal tidak valid.');
			}
			if (function_exists('imageistruecolor') && function_exists('imagepalettetotruecolor') && !imageistruecolor($source)) {
				imagepalettetotruecolor($source);
			}

			// Buang area transparan/putih di tepi agar logo memenuhi lebar struk dengan rapi.
			$left = $sourceWidth;
			$top = $sourceHeight;
			$right = -1;
			$bottom = -1;
			for ($y = 0; $y < $sourceHeight; $y++) {
				for ($x = 0; $x < $sourceWidth; $x++) {
					$rgba = imagecolorat($source, $x, $y);
					$alpha = ($rgba >> 24) & 0x7F;
					$r = ($rgba >> 16) & 0xFF;
					$g = ($rgba >> 8) & 0xFF;
					$b = $rgba & 0xFF;
					$luma = (int)round(($r * 0.299) + ($g * 0.587) + ($b * 0.114));
					if ($alpha < 120 && $luma < 248) {
						$left = min($left, $x);
						$top = min($top, $y);
						$right = max($right, $x);
						$bottom = max($bottom, $y);
					}
				}
			}

			if ($right < $left || $bottom < $top) {
				imagedestroy($source);
				throw new RuntimeException('Logo terlihat kosong. Gunakan gambar dengan objek yang jelas.');
			}

			$cropWidth = $right - $left + 1;
			$cropHeight = $bottom - $top + 1;
			$maxWidth = 250;
			$maxHeight = 120;
			$scale = min($maxWidth / $cropWidth, $maxHeight / $cropHeight);
			$targetWidth = max(1, (int)round($cropWidth * $scale));
			$targetHeight = max(1, (int)round($cropHeight * $scale));

			$target = imagecreatetruecolor($targetWidth, $targetHeight);
			$white = imagecolorallocate($target, 255, 255, 255);
			$black = imagecolorallocate($target, 0, 0, 0);
			imagefilledrectangle($target, 0, 0, $targetWidth, $targetHeight, $white);
			imagealphablending($source, true);
			imagecopyresampled(
				$target,
				$source,
				0,
				0,
				$left,
				$top,
				$targetWidth,
				$targetHeight,
				$cropWidth,
				$cropHeight
			);
			imagedestroy($source);

			// Printer thermal membutuhkan kontras hitam-putih yang tegas.
			for ($y = 0; $y < $targetHeight; $y++) {
				for ($x = 0; $x < $targetWidth; $x++) {
					$rgb = imagecolorat($target, $x, $y);
					$r = ($rgb >> 16) & 0xFF;
					$g = ($rgb >> 8) & 0xFF;
					$b = $rgb & 0xFF;
					$luma = (int)round(($r * 0.299) + ($g * 0.587) + ($b * 0.114));
					imagesetpixel($target, $x, $y, $luma < 190 ? $black : $white);
				}
			}

			$destination = FCPATH . 'uploads/logo struk.png';
			$tempDestination = FCPATH . 'uploads/.logo_struk_' . uniqid('', true) . '.png';
			if (!@imagepng($target, $tempDestination, 9)) {
				imagedestroy($target);
				throw new RuntimeException('Logo struk thermal tidak dapat disimpan.');
			}
			imagedestroy($target);

			$backupDestination = $destination . '.bak';
			@unlink($backupDestination);
			if (is_file($destination) && !@rename($destination, $backupDestination)) {
				@unlink($tempDestination);
				throw new RuntimeException('Logo struk thermal lama tidak dapat diganti.');
			}
			if (!@rename($tempDestination, $destination)) {
				@unlink($tempDestination);
				if (is_file($backupDestination)) {
					@rename($backupDestination, $destination);
				}
				throw new RuntimeException('Logo struk thermal baru tidak dapat dipasang.');
			}
			@unlink($backupDestination);
		}
		
		private function generate_qrcode($data)
		{
			/* Load QR Code Library */
			$this->load->library('ciqrcode');
			
			/* Data */
			$hex_data   = bin2hex($data);
			$save_name  = 'qris.webp';
			$temp_name  = 'qris_'.uniqid('', true).'.png';
			
			/* QR Code File Directory Initialize */
			$dir = './uploads/qrcode/';
			if (!file_exists($dir)) {
				mkdir($dir, 0775, true);
			}
			
			/* QR Configuration  */
			$config['cacheable']    = true;
			$config['imagedir']     = $dir;
			$config['quality']      = true;
			$config['size']         = '1024';
			$config['black']        = array(255,255,255);
			$config['white']        = array(255,255,255);
			$this->ciqrcode->initialize($config);
			
			/* QR Data  */
			$params['data']     = $data;
			$params['level']    = 'L';
			$params['size']     = 10;
			$params['savename'] = FCPATH.$config['imagedir']. $temp_name;
			
			$this->ciqrcode->generate($params);
			$converted = bm_convert_image_path_to_webp(
				FCPATH.$config['imagedir'].$temp_name,
				FCPATH.$config['imagedir'].$save_name,
				90,
				'png',
				'image/png'
			);
			@unlink(FCPATH.$config['imagedir'].$temp_name);
			if (!$converted['status']) {
				throw new RuntimeException($converted['message']);
			}
			@unlink(FCPATH.$config['imagedir'].'qris.png');
			
			/* Return Data */
			$return = array(
            'content' => $data,
            'file'    => $dir. $save_name
			);
			return $return;
		}
		
		public function json_chart(){
			$data=$this->model_data->get_chart();
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		public function crud(){
			
			$type = $this->input->get('type', TRUE);
			$gdata = $this->input->get('data', TRUE);
			$id = $this->input->get('id', TRUE);('id');
			$label = $this->input->get('label', TRUE);
			$link = $this->input->get('link', TRUE);
			$eclass = $this->input->get('eclass', TRUE);
			$treeview = $this->input->get('parentc', TRUE);
			$target = $this->input->get('target', TRUE);
			$aktif = $this->input->get('aktif', TRUE);
			$submenu = $this->input->get('submenu', TRUE);
			if($type=='get'){
				$data = array();
				$return = $this->db->query("SELECT * FROM menuadmin WHERE idmenu='".$id."'")->row_array();	
				$data = array(
				'id' => $return['idmenu'],
				'label' => $return['nama_menu'],
				'link' => $return['link'],
				'target' => $return['target'],
				'eclass' => $return['icon'],
				'parentc' => $return['treeview'],
				'aktif' => $return['aktif'],
				'level' => $return['id_level'],
				'submenu' => $return['link_on']
				);	
				$this->output
				->set_content_type('application/json')
				->set_output(json_encode($data));
				}elseif($type=='simpan'){
				menu_demo();
				$data = json_decode($this->input->get('data', TRUE));
				function parseJsonArray($jsonArray, $parentID = 0) {
					$return = array();
					foreach ($jsonArray as $subArray) {
						$returnSubSubArray = array();
						if (isset($subArray->children)) {
							$returnSubSubArray = parseJsonArray($subArray->children, $subArray->id);
						}
						$return[] = array('id' => $subArray->id, 'parentID' => $parentID);
						$return = array_merge($return, $returnSubSubArray);
					}
					return $return;
				}
				
				$readbleArray = parseJsonArray($data);
				
				$i=0;
				foreach($readbleArray as $row){
					$qry = $this->db->query("update menuadmin set idparent = '".$row['parentID']."', urutan='$i' where idmenu = '".$row['id']."' ");
					$i++;
				}
				$this->clear_sidebar_menu_cache();
				}elseif($type=='hapus'){
				menu_demo();
				function recursiveDeleteMenu($id) {
					$ci = & get_instance();
					$data = array('hapus'=>'hapus');
					$query = $ci->model_app->view_where('menuadmin',['idparent' =>$id]);
					if ($query->num_rows >0) {
						foreach ($query->result_array() as $current){
							recursiveDeleteMenu($current['idmenu']);
						}
					}
					
					$qry =$ci->model_app->hapus('menuadmin',['idmenu'=>$id]);
					if($qry['status']=='ok'){
						$data = array(0=>'ok');;
						$ci->clear_sidebar_menu_cache();
						}else{
						$data = array(0=>'error');;
					}
					return json_encode($data);
				}
				echo recursiveDeleteMenu($id);
			}
		}
		public function save_menu(){
			menu_demo();
			
			$type = $this->input->get('type', TRUE);
			$id = $this->input->get('id', TRUE);('id');
			$label = $this->input->get('label', TRUE);
			$link = $this->input->get('link', TRUE);
			$target = $this->input->get('target', TRUE);
			$eclass = $this->input->get('eclass', TRUE);
			$treeview = $this->input->get('parentc', TRUE);
			$aktif = $this->input->get('aktif', TRUE);
			$submenu = $this->input->get('submenu', TRUE);
			$level = $this->input->get('level', TRUE);
			
			
			///
			if($type=='simpan'){
				if($id != ''){
					$data_update = [
					'nama_menu'=>$label,
					'link'=>$link,
					'icon'=>$eclass,
					'treeview'=>$treeview,
					'id_level'=>$level,
					'target'=>$target,
					'aktif'=>$aktif,
					'link_on'=>$submenu
					];
					$this->model_app->update('menuadmin', $data_update, ['idmenu'=>$id]);
					$this->clear_sidebar_menu_cache();
					
					$id_level = $this->model_app->pilih_where('id_level','hak_akses',['publish'=>'Y'])->result();
					$_level = explode(',',$level);
					foreach ($id_level as $rows){
						foreach ($_level as $row){
							if($rows->id_level==$row){
								$data_user = atur_menu($row);
								$this->model_app->update('tb_users', ['idmenu'=>$data_user], ['id_level'=>$row]);
								}else{
								$data_user = atur_menu($rows->id_level);
								$this->model_app->update('tb_users', ['idmenu'=>$data_user], ['id_level'=>$rows->id_level]);
							}
						}
					}
					
					$arr['type']  = 'edit';
					$arr['msg'] = 'Data di Updated';
					$arr['label'] = $label;
					$arr['link']  = $link;
					$arr['eclass']  = $eclass;
					$arr['parentc']  = $treeview;
					$arr['aktif']  = $aktif;
					$arr['submenu']  = $submenu;
					$arr['target']  = $target;
					$arr['level']  = $level;
					$arr['id']    = $id;
					} else {
					$row = $this->db->query("SELECT max(urutan)+1 as urutan FROM menuadmin")->row_array();
					$qry = $this->db->query("insert into menuadmin (nama_menu,link,icon,id_level,treeview,aktif,target,link_on,urutan) values ('".$label."', '".$link."', '".$eclass."', '".$level."', '".$treeview."', '".$aktif."','".$target."','".$submenu."','".$row['urutan']."')");
					if($qry){
						$this->clear_sidebar_menu_cache();
						$arr['ok'] = 'ok';
						$lastid = $this->db->insert_id();
						
						$id_level = $this->model_app->pilih_where('id_level','hak_akses',['publish'=>'Y'])->result();
						$_level = explode(',',$level);
						foreach ($id_level as $rows){
							foreach ($_level as $row){
								if($rows->id_level==$row){
									$data_user = atur_menu($row);
									$this->model_app->update('tb_users', ['idmenu'=>$data_user], ['id_level'=>$row]);
									}else{
									$data_user = atur_menu($rows->id_level);
									$this->model_app->update('tb_users', ['idmenu'=>$data_user], ['id_level'=>$rows->id_level]);
								}
							}
						}
						
						$arr['menu'] = '<li class="dd-item dd3-item '.$aktif.'" data-id="'.$lastid.'" >
						<div class="dd-handle dd3-handle"></div>
						<div class="ns-row">
						<div class="ns-title" id="label_show'.$lastid.'">'.$label.'</div>
						<div class="ns-url" id="link_show'.$lastid.'">'.$link.'</div> 
						<div class="ns-class" id="eclass_show'.$lastid.'">'.$eclass.'</div>
						<div class="ns-actions">
						<a class="edit-button" id="'.$lastid.'" label="'.$label.'" link="'.$link.'" eclass="'.$eclass.'" parentc="'.$treeview.'"><i class="fa fa-pencil"></i></a>
						<a href="#" class="confirm-delete" data-id="'.$lastid.'" id="'.$lastid.'"><i class="fa fa-trash"></i></a>
						</div> 
						</div>
						<script>
						$(".confirm-delete").on("click", function(e) {
						e.preventDefault();
						var id = $(this).data("id");
						$("#myModalDel").data("id", id).modal("show");
						});
						</script>';
						}else{
						$arr['type'] = 'error';
					}
					$arr['type'] = 'add';
					$arr['msg'] = 'Data di simpan';
				}
			}
			
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($arr));
		}
		
		
		
		public function printer()
		{
			cek_menu_akses();
			// Pastikan preset printer penting tersedia (tidak mengubah data existing)
			$this->_ensure_printer_presets();
			$this->_ensure_one_active_printer();
			$data['title'] = 'Pengaturan printer |' .$this->title;
			$data['judul'] ='Pengaturan printer';
			
			$this->template->load('main/themes','main/printer',$data);
		}
		public function data_printer()
		{
			$this->_ensure_one_active_printer();
			$data['record'] = $this->model_app->view_ordering('printer','id','DESC');
			$this->load->view('main/data_printer',$data);
		}
		public function edit_printer(){
			$id= $this->db->escape_str($this->input->post('id'));
			if($id>0){
				$where = array('id' => $id);
				$row = $this->model_app->edit('printer',$where)->row_array();
				$hasAutoCut = $this->db->field_exists('auto_cut', 'printer');
				$hasLogoMode = $this->db->field_exists('logo_mode', 'printer');
				
				$data = array(
				'id'    =>$id,
				'jenis' =>$row['name'],
				'shared'=>$row['shared_name'],
				'ukuran'=>$row['ukuran_kertas'],
				'font_size'=>$row['ukuran_font'],
				'posisi'=>$row['posisi'],
				'item'  =>$row['max_item'],
				'aktif' =>$row['pub'],
				'show_footer' =>$row['show_footer'],
				'auto_cut' => $hasAutoCut ? (int)$row['auto_cut'] : 1,
				'logo_mode' => $hasLogoMode ? ($row['logo_mode'] ?: 'auto') : 'auto'
				);
				
				}else{
				$data = array('id'=>0,'jenis'=>"",'shared'=>'','ukuran'=>'','posisi'=>'','item'=>'',"aktif"=>"",'show_footer'=>0,'auto_cut'=>1,'logo_mode'=>'auto');
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}
		
		public function save_printer()
		{
			cek_nput_post('GET');
			// simpan_demo('Simpan');
			$id    = $this->db->escape_str($this->input->post('id'));
			$type  = $this->db->escape_str($this->input->post('type'));
			$judul = $this->db->escape_str($this->input->post('judul'));
			$shared= $this->db->escape_str($this->input->post('shared'));
			$ukuran= $this->db->escape_str($this->input->post('ukuran'));
			$font_size= $this->db->escape_str($this->input->post('font_size'));
			$posisi= $this->db->escape_str($this->input->post('posisi'));
			$item  = $this->db->escape_str($this->input->post('item'));
			$aktif = $this->db->escape_str($this->input->post('aktif'));
			$show_footer = $this->db->escape_str($this->input->post('show_footer'));
			$hasAutoCut = $this->db->field_exists('auto_cut', 'printer');
			$hasLogoMode = $this->db->field_exists('logo_mode', 'printer');
			$auto_cut = $hasAutoCut ? (int)$this->db->escape_str($this->input->post('auto_cut')) : 1;
			$logo_mode = $hasLogoMode ? $this->db->escape_str($this->input->post('logo_mode')) : 'auto';
			if (empty($logo_mode)) $logo_mode = 'auto';
			
			$data = array('status'=>400,'msg'=>'Data gagal disimpan');
			
			if($id > 0 AND $type=='on'){
				if($this->_active_printer_count_except($id) < 1){
					$data = array('status'=>400,'msg'=>'Minimal harus ada 1 printer aktif');
					$this->output
					->set_content_type('application/json')
					->set_output(json_encode($data));
					return;
				}
				$this->model_app->update('printer',array('pub'=>0),array('id'=>$id));
				$data = array('status'=>200,'msg'=>'Data berhasil update');
			}elseif($id > 0 AND $type=='off')
			{
				$res=  $this->model_app->update('printer',array('pub'=>1),array('id'=>$id));
				$data = array('status'=>200,'msg'=>'Data berhasil update');
			}elseif($id > 0 AND $type=='edit')
			{
				if((int)$aktif === 0 AND $this->_active_printer_count_except($id) < 1){
					$data = array('status'=>400,'msg'=>'Minimal harus ada 1 printer aktif');
					$this->output
					->set_content_type('application/json')
					->set_output(json_encode($data));
					return;
				}
				$_data = array('name'=>$judul,'shared_name'=>$shared,'ukuran_kertas'=>$ukuran,'ukuran_font'=>$font_size,'posisi'=>$posisi,'max_item'=>$item,'pub'=>$aktif,'show_footer'=>$show_footer);
				if($hasAutoCut) $_data['auto_cut'] = $auto_cut;
				if($hasLogoMode) $_data['logo_mode'] = $logo_mode;
				$res=  $this->model_app->update('printer',$_data,array('id'=>$id));
				///data update
				if($res['status']=='ok'){
					$data = array('status'=>200,'msg'=>'Data berhasil update');
					}else{
					$data = array('status'=>400);
				}
			}
			$this->output
			->set_content_type('application/json')
			->set_output(json_encode($data));
		}

		/**
		 * Membuat preset printer yang dibutuhkan (tanpa merusak data yang sudah ada).
		 * - Menambahkan opsi printer Dotmatrix Epson TM-U220 (kertas 80mm)
		 * - Menambahkan opsi printer Inkjet Epson L3110 untuk invoice A5/A4
		 * - Menambahkan opsi printer Inkjet Epson WF5890 untuk invoice A5/A4
		 */
		private function _ensure_printer_presets()
		{
			// hanya kalau tabel printer ada
			if (!$this->db->table_exists('printer')) return;

			// Preset: Dotmatrix Epson TM-U220 80mm
			$exists = $this->db->get_where('printer', ['slug' => 'tmu220'])->num_rows();
			if ($exists < 1) {
				$max = $this->db->select_max('id')->get('printer')->row();
				$nextId = (isset($max->id) ? (int)$max->id : 0) + 1;

				$data = [
					'id' => $nextId,
					'name' => 'Dotmatrix TM-U220 80mm',
					'ukuran_kertas' => '80',
					'ukuran_font' => 10,
					'posisi' => 'potrait',
					'max_item' => 100,
					'shared_name' => 'EPSON TM-U220',
					'slug' => 'tmu220',
					'pub' => 0,
					'show_footer' => 0
				];

				// kolom opsional (jika sudah ditambahkan via SQL)
				if ($this->db->field_exists('auto_cut', 'printer')) $data['auto_cut'] = 1;
				if ($this->db->field_exists('logo_mode', 'printer')) $data['logo_mode'] = 'column';

				@$this->db->insert('printer', $data);
			}

			// Preset: Inkjet Epson L3110 untuk cetak invoice A5/A4
			$exists = $this->db
				->like('name', 'L3110')
				->or_like('shared_name', 'L3110')
				->get('printer')
				->num_rows();
			if ($exists < 1) {
				$max = $this->db->select_max('id')->get('printer')->row();
				$nextId = (isset($max->id) ? (int)$max->id : 0) + 1;

				$data = [
					'id' => $nextId,
					'name' => 'Inkjet Epson L3110',
					'ukuran_kertas' => 'A4',
					'ukuran_font' => 11,
					'posisi' => 'potrait',
					'max_item' => 33,
					'shared_name' => 'EPSON L3110 Series',
					'slug' => 'in',
					'pub' => 0,
					'show_footer' => 0
				];

				if ($this->db->field_exists('auto_cut', 'printer')) $data['auto_cut'] = 0;
				if ($this->db->field_exists('logo_mode', 'printer')) $data['logo_mode'] = 'auto';

				@$this->db->insert('printer', $data);
			}

			// Preset: Inkjet Epson WF5890 untuk cetak invoice A5/A4
			$exists = $this->db
				->like('name', 'WF5890')
				->or_like('name', 'WF-5890')
				->or_like('shared_name', 'WF5890')
				->or_like('shared_name', 'WF-5890')
				->get('printer')
				->num_rows();
			if ($exists < 1) {
				$max = $this->db->select_max('id')->get('printer')->row();
				$nextId = (isset($max->id) ? (int)$max->id : 0) + 1;

				$data = [
					'id' => $nextId,
					'name' => 'Inkjet Epson WF5890',
					'ukuran_kertas' => 'A4',
					'ukuran_font' => 11,
					'posisi' => 'potrait',
					'max_item' => 33,
					'shared_name' => 'EPSON WF-5890 Series',
					'slug' => 'in',
					'pub' => 0,
					'show_footer' => 0
				];

				if ($this->db->field_exists('auto_cut', 'printer')) $data['auto_cut'] = 0;
				if ($this->db->field_exists('logo_mode', 'printer')) $data['logo_mode'] = 'auto';

				@$this->db->insert('printer', $data);
			}
		}

		private function _active_printer_count_except($id = 0)
		{
			if (!$this->db->table_exists('printer')) return 0;
			$this->db->where('pub', 1);
			if ((int)$id > 0) {
				$this->db->where('id !=', (int)$id);
			}
			return (int)$this->db->count_all_results('printer');
		}

		private function _ensure_one_active_printer()
		{
			if (!$this->db->table_exists('printer')) return;
			$active = $this->db->where('pub', 1)->count_all_results('printer');
			if ((int)$active > 0) return;

			$row = $this->db
				->like('name', 'L3110')
				->or_like('shared_name', 'L3110')
				->order_by('id', 'DESC')
				->get('printer')
				->row_array();

			if (!$row) {
				$row = $this->db
					->where('slug', 'in')
					->order_by('id', 'DESC')
					->get('printer')
					->row_array();
			}

			if (!$row) {
				$row = $this->db
					->order_by('id', 'DESC')
					->get('printer')
					->row_array();
			}

			if ($row && !empty($row['id'])) {
				$this->model_app->update('printer', array('pub'=>1), array('id'=>(int)$row['id']));
			}
		}
		public function folder()
		{
			cek_menu_akses();
			$data['title'] = 'Pengaturan Folder | ' .$this->title;
			
			$this->cek_folder();
			
			$data['rows'] = ["computer_name"  =>pengaturan('computer_name'),
			"folder_af" =>pengaturan('folder_af'),
			"folder_gm" =>pengaturan('folder_gm'),
			"folder_ns" =>pengaturan('folder_ns'),
			"folder_tz" =>pengaturan('folder_tz'),
			"ukuran" =>!empty(pengaturan('ukuran')) ? pengaturan('ukuran') : 'U',
			"qty" =>!empty(pengaturan('qty')) ? pengaturan('qty') : 'Q',
			"bahan" =>!empty(pengaturan('bahan')) ? pengaturan('bahan') : 'B',
			"produk" =>!empty(pengaturan('produk')) ? pengaturan('produk') : 'P',
			"tanggal" =>!empty(pengaturan('tanggal')) ? pengaturan('tanggal') : 'TGL',
			"fo" =>!empty(pengaturan('fo')) ? pengaturan('fo') : 'FO',
			];
			$this->template->load('main/themes','main/website/folder',$data);
		}
		
		private function cek_folder()
		{
			$query = $this->model_app->view_where('shared_folder',['id' =>6]);
			if ($query->num_rows() < 1) {
				$this->model_app->input('shared_folder',['id'=>6,'nama'=>'ukuran','isi'=>'U']);
				$this->model_app->input('shared_folder',['id'=>7,'nama'=>'qty','isi'=>'Q']);
				$this->model_app->input('shared_folder',['id'=>8,'nama'=>'bahan','isi'=>'B']);
				$this->model_app->input('shared_folder',['id'=>9,'nama'=>'produk','isi'=>'P']);
				$this->model_app->input('shared_folder',['id'=>10,'nama'=>'tanggal','isi'=>'TGL']);
				$this->model_app->input('shared_folder',['id'=>11,'nama'=>'fo','isi'=>'FO']);
			}
		}
		// public function c3d6fa211a7c7a(){
			// $data['tools'] = $this->tools;
			// $this->c3d6fas11a7c7a($data);
		// }
		
		// private function c3d6fas11a7c7a($data){
			// return $this->load->view('home',$data);
		// }
		
		public function save_folder()
		{
			simpan_demo('Simpan');
			if (isset($_POST['submit'])){
				
				$computer_name = array('isi'=>xss_filter($this->input->post('computer_name'),'folder'));
				// dump($computer_name,'print_r','exit');
				$computer_where = array('nama'=>'computer_name');	
				$update = $this->model_app->update('shared_folder',$computer_name,$computer_where);
				
				$ukuran_name = array('isi'=>xss_filter($this->input->post('ukuran_folder'),'xss'));
				$ukuran_where = array('nama'=>'ukuran');	
				$this->model_app->update('shared_folder',$ukuran_name,$ukuran_where);
				
				$qty_name = array('isi'=>xss_filter($this->input->post('qty_folder'),'xss'));
				$qty_where = array('nama'=>'qty');	
				$this->model_app->update('shared_folder',$qty_name,$qty_where);
				
				$bahan_name = array('isi'=>xss_filter($this->input->post('bahan_folder'),'xss'));
				$bahan_where = array('nama'=>'bahan');	
				$this->model_app->update('shared_folder',$bahan_name,$bahan_where);
				
				$produk_name = array('isi'=>xss_filter($this->input->post('produk_folder'),'xss'));
				$produk_where = array('nama'=>'produk');	
				$this->model_app->update('shared_folder',$produk_name,$produk_where);
				
				$tanggal_name = array('isi'=>xss_filter($this->input->post('tgl_folder'),'xss'));
				$tanggal_where = array('nama'=>'tanggal');	
				$this->model_app->update('shared_folder',$tanggal_name,$tanggal_where);
				
				$fo_name = array('isi'=>xss_filter($this->input->post('fo_folder'),'xss'));
				$fo_where = array('nama'=>'fo');	
				$this->model_app->update('shared_folder',$fo_name,$fo_where);
				
				if($update['status']=='ok'){
					$this->session->set_flashdata('message', '<script>notif("Data di simpan","success");</script>');
					redirect('main/folder');
					}else{
					$this->session->set_flashdata('message', '<script>notif("Data gagal di simpan","danger");</script>');
					redirect('main/folder');
				}
			}
			
		}

		public function clear_sidebar_menu_cache()
		{
			$cacheDir = APPPATH . 'cache' . DIRECTORY_SEPARATOR;
			foreach (glob($cacheDir . 'sidebar_menu_*') ?: array() as $file) {
				if (is_file($file)) {
					@unlink($file);
				}
			}
		}
		
	}				
