<?php
	defined('BASEPATH') or exit('No direct script access allowed');
	
	class Laporan extends CI_Controller
	{
		public function __construct()
		{
			parent::__construct();
			// cek_tabel();
			cek_session_login();
			$this->info = info();
			$this->back = $this->agent->referrer();
			$this->iduser = $this->session->idu;
			$this->perPage = 10; 
			$this->title = info()['title']; 
		}

		private function can_manage_progress_status()
		{
			$level = isset($this->session->level) ? strtolower(trim((string)$this->session->level)) : '';
			$allowed = ['admin', 'owner', 'operator', 'desain', 'kasir', 'keuangan'];
			$idu = isset($this->session->idu) ? (int)$this->session->idu : 0;
			return $idu > 0 && in_array($level, $allowed, true);
		}
		
		public function omset_penjualan()
		{
			cek_menu_akses();
			$data['title'] ='Laporan Omset Penjualan | '.info()['title'];
			
			$data['dari'] = tgl_dari_slash();	
			$this->template->load('main/themes','laporan/omset_penjualan',$data);
		}
		
		public function penjualan()
		{
			cek_menu_akses();
			$data['title'] ='Laporan Penjualan | '.info()['title'];
			
			$data['dari'] = tgl_dari_slash();	
			$data['jenis'] = $this->model_app->view_where('jenis_cetakan',['pub'=>'Y','kunci'=>0])->result(); 
			$this->template->load('main/themes','laporan/penjualan',$data);
		}
		//bahan
		public function produk(){
			cek_nput_post('GET');
			$dari = $this->input->post('dari'); 
			$sampai = $this->input->post('sampai'); 
			$page = $this->input->post('page');
			
			
			if(!$page){ 
				$offset = 0; 
				}else{ 
				$offset = $page; 
			} 
			$data['dari'] = $dari;
			$data['sampai'] = $sampai;
			
			// Pagination configuration 
			$config['target']      = '#dataProduk'; 
			$config['base_url']    = base_url('laporan/produk'); 
			
			$config['link_func']   = 'search_LaporanProduk'; 
			
			
			if(!empty($dari)){ 
				$dari = date_slash($this->input->post('dari')); 
				$conditions['search']['dari'] = $dari; 
			} 
			if(!empty($sampai)){ 
				$sampai = date_slash($this->input->post('sampai')); 
				$conditions['search']['sampai'] = $sampai; 
			} 
			$conditions["where"]= [
			'invoice.pos'=>'Y',
			'invoice.status'=>'simpan',
			]; 
			// dump($conditions);
			$data['result'] = $this->model_data->getLaporanPenjualan($dari,$sampai);
			
			$this->load->view('laporan/laporan-produk', $data, false); 
		}
		
		public function pergrup(){
			cek_nput_post('GET');
			
			$dari = $this->input->post('dari'); 
			$sampai = $this->input->post('sampai'); 
			$page = $this->input->post('page'); 
			$jenis = $this->input->post('jenis'); 
			if(!$page){ 
				$offset = 0; 
				}else{ 
				$offset = $page; 
			} 
			$data['dari'] = $dari;
			$data['sampai'] = $sampai;
			// dump($_POST);
			if(!empty($dari)){ 
				$dari = date_slash($this->input->post('dari')); 
				$conditions['search']['dari'] = $dari; 
			} 
			if(!empty($sampai)){ 
				$sampai = date_slash($this->input->post('sampai')); 
				$conditions['search']['sampai'] = $sampai; 
			} 
			if(!empty($jenis)){ 
				$conditions['where'] = array(
				"produk.id_jenis" => $jenis,
				'invoice.pos'=>'Y',
				"invoice.status" => 'simpan'
				); 
				}else{
				$conditions['where'] = array(
				'invoice.pos'=>'Y',
				"invoice.status" => 'simpan'
				); 
			}
			
			// Get record count 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getLaporanPergrup($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataKategori'; 
			$config['base_url']    = base_url('laporan/pergrup'); 
			$config['total_rows']  = $totalRec; 
			// $config['per_page']    = $this->perPage; 
			$config['link_func']   = 'search_LaporanGrup'; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions['start'] = $offset; 
			$conditions['limit'] = $this->perPage;
			if(!empty($jenis)){ 
				$conditions['where'] = array(
				"produk.id_jenis" => $jenis,
				'invoice.pos'=>'Y',
				"invoice.status" => 'simpan'
				); 
				}else{
				$conditions['where'] = array(
				'invoice.pos'=>'Y',
				"invoice.status" => 'simpan'
				); 
			}
			if(!empty($dari)){ 
				$dari = date_slash($this->input->post('dari')); 
				$conditions['search']['dari'] = $dari; 
			} 
			if(!empty($sampai)){ 
				$sampai = date_slash($this->input->post('sampai')); 
				$conditions['search']['sampai'] = $sampai; 
			}  
			unset($conditions['returnType']); 
			$data['id_jenis'] = $jenis;
			$data['jenis'] = $this->model_app->view_where('jenis_cetakan',['pub'=>'Y','kunci'=>0])->result(); 
			$data['result'] = $this->model_data->getLaporanPergrup($conditions); 
			
			// Load the data list view 
			$this->load->view('laporan/laporan-pergrup', $data, false); 
		}
		
		public function perkategori(){	
			cek_nput_post('GET');
			$dari = $this->input->post('dari'); 
			$sampai = $this->input->post('sampai'); 
			$page = $this->input->post('page'); 
			if(!$page){ 
				$offset = 0; 
				}else{ 
				$offset = $page; 
			} 
			
			$data['dari'] = $dari;
			$data['sampai'] = $sampai;
			if(!empty($dari)){ 
				$dari = date_slash($this->input->post('dari')); 
				$conditions['search']['dari'] = $dari; 
			} 
			if(!empty($sampai)){ 
				$sampai = date_slash($this->input->post('sampai')); 
				$conditions['search']['sampai'] = $sampai; 
			} 
			
			// Get record count 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getLaporanPerkategori($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataKategori'; 
			$config['base_url']    = base_url('laporan/perkategori'); 
			$config['total_rows']  = $totalRec; 
			// $config['per_page']    = $this->perPage; 
			$config['link_func']   = 'search_LaporanKategori'; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			// $conditions['start'] = $offset; 
			// $conditions['limit'] = $this->perPage;
			$conditions["where"]= [
			'invoice.pos'=>'Y',
			'invoice.status'=>'simpan',
			];
			if(!empty($dari)){ 
				$dari = date_slash($this->input->post('dari')); 
				$conditions['search']['dari'] = $dari; 
			} 
			if(!empty($sampai)){ 
				$sampai = date_slash($this->input->post('sampai')); 
				$conditions['search']['sampai'] = $sampai; 
			}  
			unset($conditions['returnType']); 
			$data['result'] = $this->model_data->getLaporanPerkategori($conditions); 
			
			// Load the data list view 
			$this->load->view('laporan/laporan-perkategori', $data, false); 
		}
		
		public function perbahan(){	
			cek_nput_post('GET');
			$dari = $this->input->post('dari'); 
			$sampai = $this->input->post('sampai'); 
			$page = $this->input->post('page'); 
			if(!$page){ 
				$offset = 0; 
				}else{ 
				$offset = $page; 
			} 
			$data['dari'] = $dari;
			$data['sampai'] = $sampai;
			
			if(!empty($dari)){ 
				$dari = date_slash($this->input->post('dari')); 
				$conditions['search']['dari'] = $dari; 
			} 
			if(!empty($sampai)){ 
				$sampai = date_slash($this->input->post('sampai')); 
				$conditions['search']['sampai'] = $sampai; 
			} 
			
			// Get record count 
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getLaporanPerBahan($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataKategori'; 
			$config['base_url']    = base_url('laporan/perkategori'); 
			$config['total_rows']  = $totalRec; 
			// $config['per_page']    = $this->perPage; 
			$config['link_func']   = 'search_LaporanKategori'; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			// $conditions['start'] = $offset; 
			// $conditions['limit'] = $this->perPage;
			$conditions["where"]= [
			'invoice.pos'=>'Y',
			'invoice.status'=>'simpan',
			];
			if(!empty($dari)){ 
				$dari = date_slash($this->input->post('dari')); 
				$conditions['search']['dari'] = $dari; 
			} 
			if(!empty($sampai)){ 
				$sampai = date_slash($this->input->post('sampai')); 
				$conditions['search']['sampai'] = $sampai; 
				
			}  
			unset($conditions['returnType']); 
			$data['result'] = $this->model_data->getLaporanPerBahan($conditions); 
			
			// Load the data list view 
			$this->load->view('laporan/laporan-perbahan', $data, false); 
		}
		
		public function cariPendapatan()
		{
			cek_nput_post('GET');
			$dari = $this->input->post('dari'); 
			$sampai = $this->input->post('sampai'); 
			
			if(!empty($dari)){ 
				$dari = date_dmy($this->input->post('dari')); 
				$conditions['search']['dari'] = $dari; 
			} 
			if(!empty($sampai)){ 
				$sampai = date_dmy($this->input->post('sampai')); 
				$conditions['search']['sampai'] = $sampai; 
			}
			
			$data['penjualan'] 		= $this->model_data->getLabaRugi($conditions);
			$data['pengeluaran'] 	= $this->model_data->getLabaRugiBiaya($conditions);
			$this->load->view('laporan/laporan-labarugi', $data, false);
		}
		
		
		public function cetak_laporan_penjualan(){
			$jenis = $this->input->post('jenis'); 
			$id_jenis = $this->input->post('id_jenis'); 
			// dump($_POST);
			if(isset($jenis)){
				$dari = $this->input->post('startdate'); 
				$sampai = $this->input->post('enddate'); 
				if(!empty($dari)){ 
					$dari = date_slash($this->input->post('startdate')); 
				} 
				if(!empty($sampai)){ 
					$sampai = date_slash($this->input->post('enddate')); 
				} 
				
				$data['logo'] = FCPATH.'uploads/'.info()['logo_bw'];			
				$data['info'] = info();
				$data['dari'] = $dari;
				$data['sampai'] = $sampai;
				$data['user'] = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
				$this->load->library('pdf');				
				$this->pdf->setPaper('A4', 'landscape');
				$this->pdf->filename = "laporan_penjualan";	
				if($jenis=='produk'){ 
					$data['detail'] = $this->model_data->getLaporanPenjualan($dari,$sampai);
				}
				if($jenis=='kategori'){ 
					$data['detail'] = $this->model_data->getLaporanPenjualanJenis($dari,$sampai);
				}
				if($jenis=='grup'){ 
					$data['detail'] = $this->model_data->getLaporanPenjualanGrup($id_jenis,$dari,$sampai);
				}
				if($jenis=='bahan'){ 
					$conditions['search']['dari'] = $dari; 
					$conditions['search']['sampai'] = $sampai; 
					$conditions['where'] = array(
					"invoice.status" => 'simpan'
					); 
					$data['detail'] = $this->model_data->getLaporanPerBahan($conditions);
				}
				$this->pdf->load_view('laporan/cetak_laporan_penjualan', $data);	
				
				// $this->load->view('laporan/cetak_laporan_penjualan', $data);				
				
				}else{
				$data['cetak']       = 'error';
				$this->load->view('errors/404',$data);
			}
		}
		
		public function cetak_laporan_pendapatan(){
			$dari = $this->input->post('startdate'); 
			$sampai = $this->input->post('enddate'); 
			// echo $dari;
			if(isset($dari)){
				
				if(!empty($dari)){ 
					$dari = date_dmy($this->input->post('startdate')); 
					$data['search']['dari'] = $dari; 
				} 
				if(!empty($sampai)){ 
					$sampai = date_dmy($this->input->post('enddate')); 
					$data['search']['sampai'] = $sampai; 
				} 
				
				$data['logo']           = FCPATH.'uploads/'.info()['logo_bw'];			
				$data['info']           = info();
				$data['user']           = $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
				$data['penjualan'] 		= $this->model_data->getLabaRugi($data);
				$data['pengeluaran'] 	= $this->model_data->getLabaRugiBiaya($data);
				
				$this->load->library('pdf');				
				$this->pdf->setPaper('A5', 'landscape');				
				$this->pdf->filename = "laporan_penjualan";				
				$this->pdf->load_view('laporan/cetak_laporan_pendapatan', $data);	
				
				}else{
				$data['cetak']       = 'error';
				$this->load->view('errors/404',$data);
			}
		}
		
		public function cetak_data_bahan(){
			$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_blunas']	= FCPATH.'uploads/'.info()['logo_bw'];
			$data['info']			= info();
			$data['tanggal']		= today();
			$data['user']			= $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			$data['laporan']		= $this->model_app->view_where('bahan',['id >'=>1])->result(); 
			
			$this->load->library('pdf');				
			$this->pdf->setPaper('A4', 'landscape');					
			$this->pdf->filename = "laporan_data_bahan_".date('d_F_Y');				
			$this->pdf->load_view('laporan/cetak_data_bahan', $data);	
		}
		
		public function cetak_stok_bahan(){
			$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_blunas']	= FCPATH.'uploads/'.info()['logo_bw'];
			$data['info']			= info();
			$data['tanggal']		= today();
			$data['user']			= $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
			$data['laporan']		= $this->model_app->view_where('bahan',['id >'=>1,'status_stok'=>'Y'])->result(); 
			
			$mod = modul_cetak('cetak_stok');
			$this->load->library('pdf');				
			$this->pdf->setPaper($mod['ukuran'], $mod['posisi']);					
			$this->pdf->filename = "laporan_stok_bahan_".date('d_F_Y');				
			$this->pdf->load_view('laporan/cetak_stok_bahan', $data);	
			// $this->load->view('laporan/cetak_stok_bahan', $data);	
		}
		
		public function cetak_order_harian(){
			
			if(!empty($_POST)){
				$sortby = ($this->input->post('sortby_cetak')); 
				$status = ($this->input->post('trx_cetak')); 
				$tanggal = $this->input->post('tanggal_cetak'); 
				
				$date = date_ranges($tanggal);
				$dari = date_replace_slash($date['dari']);
				$sampai = date_replace_slash($date['sampai']);
				$data['periode']	= 'Tanggal Order';
				$data['tanggal']	= today();
				if(!empty($sortby)){ 
					$conditions['search']['sortBy'] = $sortby; 
				} 
				if(!empty($status)){ 
					$conditions['search']['trx'] = $status; 
				} 
				if(!empty($tanggal)){
					$conditions["search"]["dari"] = $dari;
					$conditions["search"]["sampai"] = $sampai;
					if(strtotime($dari)==strtotime($sampai)){
						$data['periode']	= 'Tanggal Order';
						$data['tanggal']	= $date['dari'];
						}else{
						$data['periode']	= 'Peroide Order';
						$data['tanggal']	= $date['dari'].' - '.$date['sampai'];
					}
				} 
				$conditions['where']= array(
				'i.status !='=>'baru'
				); 
				
				
				$show_footer = $this->model_app->view_where('printer', ['slug' => 'in'])->row()->show_footer;
				//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_blunas']	= FCPATH.'uploads/'.info()['logo_bw'];
				$data['info']			= info();
				$data['show_footer']	= $show_footer;
				
				$data['user']			= $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
				$data['laporan']		= $this->model_data->getRows($conditions); 
				// $data['penjualan']		= $this->model_data->getLabaRugi($data);
				// $data['pengeluaran']	= $this->model_data->getLabaRugiBiaya($data);
				
				$mod = modul_cetak('cetak_order');
				$this->load->library('pdf');				
				$this->pdf->setPaper($mod['ukuran'], $mod['posisi']);					
				$this->pdf->filename = "laporan_penjualan";				
				$this->pdf->load_view('laporan/cetak_order_harian', $data);	
				// $this->load->view('laporan/cetak_order_harian', $data);	
				}else{
				$data['cetak']       = 'error';
				$this->load->view('errors/404',$data);
			}
		}
		public function cetak_piutang()
		{
			// dump($_POST);
			$iduser= $this->db->escape_str($this->input->post('user'));		
			$periode= $this->db->escape_str($this->input->post('range'));		
			
			$keywords= $this->db->escape_str($this->input->post('keywords'));		
			
			if($iduser !='' AND !empty($periode)){
				$date = date_ranges($periode);
				$dari = date_replace_slash($date['dari']);
				$sampai = date_replace_slash($date['sampai']);
				
				$waktu = 'invoice.tgl_trx BETWEEN "'. date('Y-m-d', strtotime($dari)). '" and "'. date('Y-m-d', strtotime($sampai)).'"';				
				
				if ( substr($keywords,0,1 )== '0' )			
				{
					$whereSQL = "AND konsumen.no_hp LIKE '%$keywords%'";				
					}elseif($keywords!=''){
					$whereSQL = "AND konsumen.nama LIKE '%$keywords%'";				
					}elseif(is_numeric($keywords)){				
					$whereSQL = "AND invoice.id_invoice =".$keywords;				
					}else{				
					$whereSQL = "";				
				}			
				
				if ($iduser=='0' AND $keywords==''){
					$data['user'] = 'SEMUA KASIR';			
					$where = "WHERE $waktu AND `invoice`.`status` = 'simpan'";				
					}elseif ($iduser=='0' AND $keywords!=''){				
					$data['user'] = 'SEMUA KASIR';			
					$where = "WHERE $waktu  $whereSQL  AND `invoice`.`status` = 'simpan'";				
					}else{				
					$_user = $this->model_app->view_where('tb_users', array('id_user' => $iduser))->row();
					$data['user'] = $_user->nama_lengkap;			
					$where = "WHERE $waktu AND `invoice`.`id_user` = '$iduser' $whereSQL  AND `invoice`.`status` = 'simpan'" ;				
				}						
				
				$tgl    = date("Y-m-d H:i:s");
				$data['logo'] = FCPATH.'uploads/'.info()['logo'];
				$data['logop'] = base_url().'uploads/'.info()['logo'];
				$data['info'] = info();
				$data['tgl'] = date('d/m/Y'); 
				
				if(strtotime($dari)==strtotime($sampai)){
					$data['periode']	= 'Tanggal';
					$data['tanggal']	= $date['dari'];
					}else{
					$data['periode']	= 'Peroide';
					$data['tanggal']	= $date['dari'].' - '.$date['sampai'];
				}
				
				$data['detail'] = $this->model_data->piutang($where);	
				$this->load->library('pdf');
				$this->pdf->setPaper('A5', 'landscape');
				$this->pdf->filename = "rekap_".$tgl;
				$this->pdf->load_view('pembukuan/cetak_piutang', $data);
				// $this->load->view('pembukuan/cetak_piutang',$data);
				}else{
				$data['cetak']       = 'error';
				
				$this->load->view('errors/404',$data);
			}
		}
		
		public function desain(){
			cek_menu_akses();
			$data['title'] = 'Data Desain | '.info()['title'];
			$data['tgl_awal'] = date('01/m/Y');	
			$data['tgl'] = date('d/m/Y');	
			$params =  ['id'=>'id_user','title'=>'nama_lengkap']; 
			if($this->session->level=='admin'){
				$desain[] = $this->model_app->view_where('tb_users',['aktif'=>'Y'])->result();	
				$data['select'] = select_box($desain,0,0,'',$params);
				}else{
				$desain[] = $this->model_app->view_where('tb_users',['aktif'=>'Y'])->result();
				$data['select'] = select_box($desain,0,0,$this->iduser,$params);	
			}
			
			
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getDesain($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataDesain'; 
			$config['base_url']    = base_url('laporan/ajaxdesain'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			$config['link_func']   = 'search_Desain'; 
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array( 
            'limit' => $this->perPage 
			); 
			// $conditions['where'] = array(
			// 'invoice.status' => 'pending'
			// );
			
			$data['posts'] = $this->model_data->getDesain($conditions); 
			// dump($data['posts']);
			$this->template->load('main/themes','laporan/desain',$data);
		}
		public function ajaxDesain(){
			cek_nput_post('GET');
			$dari = date_slash($this->input->post('dari')); 
			$sampai = date_slash($this->input->post('sampai')); 
			
			$page = $this->input->post('page'); 
			if(!$page){ 
				$offset = 0; 
				}else{ 
				$offset = $page; 
			} 
			$limits = $this->input->post("limits");
			if (!empty($limits)) {
				$limit = $limits;
				} else {
				$limit = $this->perPage;
			}
			
			if(!empty($dari)){ 
				$conditions['search']['dari'] = $dari; 
			} 
			
			if(!empty($sampai)){ 
				$conditions['search']['sampai'] = $sampai; 
			} 
			$user = $this->input->post('user'); 
			
			// $conditions['search']['user'] = $user; 
			// print_r($conditions);
			$jenis = $this->input->post('jenis'); 
			
			if(empty($jenis) AND !empty($user)){
				$conditions['where'] = array(
				'invoice.id_user' => $user
				);
			} 
			
			if(!empty($jenis) AND !empty($user)){
				$conditions['where'] = array(
				'invoice.id_desain' => $user,
				'invoice.status' => $jenis
				);
			} 
			
			
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getDesain($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataDesain'; 
			$config['base_url']    = base_url('laporan/ajaxDesain'); 
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $limit; 
			$config['link_func']   = 'search_Desain'; 
			
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records
			$conditions["start"] = $offset;
			$conditions["limit"] = $limit;
			
			
			unset($conditions['returnType']); 
			$data['result'] = $this->model_data->getDesain($conditions); 
			
			// Load the data list view 
			$this->load->view('laporan/laporan-desain', $data, false); 
		}
		
		public function operator(){
			$data['title'] ='Laporan operator | '.$this->title;
			
			$data['pilihan'] = $this->model_app->pilih('id_user, nama_lengkap','tb_users')->result_array();		

			$data['dari'] = tgl_dari_slash();
			$data['sampai'] = tgl_sampai_slash();
			$data['produk'] = $this->model_app->view_where('produk',['pub'=>1])->result_array(); 
			$this->template->load('main/themes','laporan/operator',$data);
		}
		//23:15 08/10/2023
		public function spk(){
			$data['title'] ='Laporan operator | '.$this->title;
			
			$data['pilihan'] = $this->model_app->pilih('id_user, nama_lengkap','tb_users')->result_array();		
			
			$conditions['where'] = array(
			'invoice.status' => 'simpan'
			);
			
			$dari 	= date('Y-m-').'01';				
			$conditions['search']['dari'] = $dari; 
			$conditions['search']['sampai'] = date("Y-m-d"); 
			
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->get_operator($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataListOmset'; 
			$config['base_url']    = base_url('laporan/ajaxSpk'); 
			$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' => 'simpan'
			);
			$dari 	= date('Y-m-').'01';				
			$conditions['search']['dari'] = $dari; 
			$conditions['search']['sampai'] = date("Y-m-d"); 
			$data['dari'] = tgl_dari_slash();
			$data['sampai'] = tgl_sampai_slash();
			$data['posts'] = $this->model_data->get_operator($conditions); 
			// print_r($data['posts']);
			$this->template->load('main/themes','laporan/spk',$data);
		}
		
		//19:45 07/19/2023
		public function ajaxSpk()
		{
			
			$page = $this->input->post('page');
			if (!$page) {
				$offset = 0;
				} else {
				$offset = $page;
			}
			$sortBy = $this->input->post('sortBy');
			if (!empty($sortBy)) {
				$conditions['search']['sortBy'] = $sortBy;
			}
			$limits = $this->input->post('limits');
			if (!empty($limits)) {
				$limit = $limits;
				} else {
				$limit = $this->perPage;
			}
			// Set conditions for search and filter
			$user = $this->input->post('user');
			$dari = date_slash($this->input->post('dari'));
			$sampai = date_slash($this->input->post('sampai'));
			
			$conditions['where'] = array(
			'invoice.status' => 'simpan'
			);
			
			if (!empty($user)) {
				$conditions['where'] = array(
				'invoice.id_user' => $user
				);
			}
			
			if (!empty($dari)) {
				$conditions['search']['dari'] = $dari;
			}
			if (!empty($sampai)) {
				$conditions['search']['sampai'] = $sampai;
			}
			
			
			
			// Get record count
			$conditions['returnType'] = 'count';
			$totalRec = $this->model_data->get_operator($conditions);
			
			// Pagination configuration
			$config['target'] = '#dataListOmset';
			$config['base_url'] = base_url('laporan/ajaxSpk');
			$config['total_rows'] = $totalRec;
			$config['per_page'] = $limit;
			$config['link_func'] = 'search_Operator';
			
			// Initialize pagination library
			$this->ajax_pagination->initialize($config);
			
			// Get records
			$conditions['start'] = $offset;
			$conditions['limit'] = $limit;
			
			$conditions['where'] = array(
			'invoice.status' => 'simpan'
			);
			if (!empty($user)) {
				$conditions['where'] = array(
				'invoice.id_user' => $user
				);
			}
			
			unset($conditions['returnType']);
			
			$data['posts'] = $this->model_data->get_operator($conditions);
			$data['user'] = $user;
			$data['status_order'] = $this->input->post('status');
			// Load the data list view 
			$this->load->view('laporan/ajax-spk', $data, false); 
		}
		//19:45 07/19/2023
		public function ajaxOperator()
{
	if (!$this->input->is_ajax_request()) {
		show_404();
	}

	// =========================
	// Pagination
	// =========================
	$page   = $this->input->post('page');
	$offset = (!empty($page) ? (int)$page : 0);

	$limits = $this->input->post('limits');
	$limit  = (!empty($limits) ? (int)$limits : (int)$this->perPage);
	if ($limit <= 0) { $limit = (int)$this->perPage; }

	// =========================
	// Filters
	// =========================
	$user   = trim((string)$this->input->post('user'));
	$produk = trim((string)$this->input->post('produk'));
	$dari   = trim((string)$this->input->post('dari'));
	$sampai = trim((string)$this->input->post('sampai'));
	$kw     = trim((string)$this->input->post('invoice_op'));
	$status = $this->input->post('status');

	$conditions = [];
	$conditions['where'] = [
		'invoice.status' => 'simpan'
	];

	// Operator filter
	if ($user !== '' && $user !== '0') {
		$conditions['where']['invoice_detail.id_operator'] = $user;
	}

	// Produk filter (INI FIX UTAMA: filter di query header, bukan hanya di detail)
	if ($produk !== '' && $produk !== '0') {
		$conditions['search']['produk'] = $produk;
	}

	// Keyword filter
	if ($kw !== '') {
		$conditions['search']['keywords'] = $kw;
	}

	// Date filters
	if ($dari !== '') {
		$conditions['search']['dari'] = date_slash($dari);
	}
	if ($sampai !== '') {
		$conditions['search']['sampai'] = date_slash($sampai);
	}

	// Status filter (harus support string '0')
	if ($status !== null && $status !== '' && $status !== 'semua') {
		$conditions['search']['status'] = (string)$status;
	}

	// =========================
	// Count + Pagination
	// =========================
	$conditions['returnType'] = 'count';
	$totalRec = $this->model_data->get_operator($conditions);

	$config['target']     = '#dataListOmset';
	$config['base_url']   = base_url('laporan/ajaxOperator');
	$config['total_rows'] = $totalRec;
	$config['per_page']   = $limit;
	$config['link_func']  = 'search_Operator';
	$this->ajax_pagination->initialize($config);

	// =========================
	// Data
	// =========================
	unset($conditions['returnType']);
	$conditions['start'] = $offset;
	$conditions['limit'] = $limit;

	$posts = $this->model_data->get_operator($conditions);
	$posts = is_array($posts) ? $posts : [];
	$this->ensure_progress_proof_table();
	$invoiceIds = array_map(static function($row) {
		return isset($row['id_invoice']) ? (int)$row['id_invoice'] : 0;
	}, $posts);
	$preload = $this->model_data->get_operator_preload($invoiceIds, $produk);

	$data['posts']        = $posts;
	$data['produk']       = $produk;
	$data['status_order'] = $status;
	$data['operator_preload'] = $preload;

	$this->load->view('laporan/ajax-operator', $data, false);
}

		
		public function simpan_laporan()
		{
			if ($this->input->is_ajax_request()) 
			{
				if (!$this->can_manage_progress_status()) {
					echo json_encode([
						'status' => 403,
						'title' => 'Akses Ditolak',
						'msg' => 'Anda tidak memiliki akses untuk update status.'
					]);
					return;
				}

				$id = $this->input->post('id');
				$id = decrypt_url($id);
				$arr = ['Error request'];
				if (!empty($id)) {
					$type = $this->input->post('type');
					$status = (int)$this->input->post('status');
					$allowedStatuses = array_map(static function($item){ return (int)$item['code']; }, job_statuses(true));
					if ($status === 0 || !in_array($status, $allowedStatuses, true)) {
						echo json_encode(['status'=>400, 'title'=>'Simpan Status', 'msg'=>'Status pekerjaan tidak aktif atau tidak valid.']);
						return;
					}
					
					$data = ['status' => $status, 'id_operator' => $this->iduser];
					if ($this->db->field_exists('update_date', 'invoice_detail')) {
						$data['update_date'] = date('Y-m-d H:i:s');
					}
					$arr = $this->update_status_laporan($data,$id);
					if (stok_keluar_should_trigger($status)) {
						$row = $this->model_app
							->view_where('invoice_detail', ['id_rincianinvoice' => $id])
							->row();
						if (!empty($row)) {
							input_stok_keluar_produk($id, $row->id_invoice);
						}
					}
					} else {
					$arr = ['Error request'];
				}
				echo json_encode($arr);
				
			}
		}
		
		private function update_status_laporan($data,$id){
			$this->db->trans_begin();
			$update = $this->model_app->update('invoice_detail', $data, [
			'id_rincianinvoice' => $id
			]);
			$sync = true;
			if ($update) {
				$this->load->model('Komplain_model', 'komplain_sync');
				$sync = $this->komplain_sync->syncReworkProgressFromJobDetail((int)$id, (int)$data['status'], (int)$this->iduser);
			}
			if ($update && $sync && $this->db->trans_status()) {
				$this->db->trans_commit();
				$arr = [
				'status' => 200,
				'title' => 'Simpan Status',
				'msg' => 'Berhasil disimpan'
				];
				} else {
				$this->db->trans_rollback();
				$arr = [
				'status' => 400,
				'title' => 'Simpan Status',
				'msg' => 'Gagal disimpan'
				];
			}
			return $arr;
		}
		
		public function get_laporan(){
			if ($this->input->is_ajax_request()) 
			{
				$id = $this->input->post('id');
				$id = decrypt_url($id);
				if (empty($id)) {
					echo json_encode(['status' => 400, 'msg' => 'invalid id']);
					return;
				}

				$row = $this->db
					->select('
						d.id_rincianinvoice,
						d.id_invoice,
						d.status,
						COALESCE(b.kunci, 0) AS cek_bahan,
						i.id_transaksi AS nomor_order
					', false)
					->from('invoice_detail d')
					->join('invoice i', 'i.id_invoice = d.id_invoice', 'left')
					->join('bahan b', 'b.id = d.id_bahan', 'left')
					->where('d.id_rincianinvoice', (int)$id)
					->get()
					->row();

				if (!$row) {
					echo json_encode(['status' => 404, 'msg' => 'data tidak ditemukan']);
					return;
				}
				
				$data = [
				'id' => $row->id_rincianinvoice,
				'nomor_order' => $row->nomor_order,
				'idorder' => encrypt_url($row->id_rincianinvoice),
				'status' => $row->status,
				'cek_bahan' => (int)$row->cek_bahan,
				];
				echo json_encode($data);
				
			}
		}

		private function ensure_progress_proof_table()
		{
			$this->load->dbforge();

			if (!$this->db->table_exists('invoice_detail_bukti')) {
				$this->dbforge->add_field([
					'id' => [
						'type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true,
					],
					'id_rincianinvoice' => [
						'type' => 'INT', 'constraint' => 11, 'null' => false,
					],
					'filename' => [
						'type' => 'VARCHAR', 'constraint' => 255, 'null' => false,
					],
					'keterangan' => [
						'type' => 'VARCHAR', 'constraint' => 255, 'null' => true,
					],
					'id_user' => [
						'type' => 'INT', 'constraint' => 11, 'null' => true,
					],
					'created_at' => ['type' => 'DATETIME', 'null' => true],
					'updated_at' => ['type' => 'DATETIME', 'null' => true],
				]);
				$this->dbforge->add_key('id', true);
				$this->dbforge->add_key('id_rincianinvoice');
				if (!$this->dbforge->create_table('invoice_detail_bukti', true)) {
					return false;
				}
			}

			if (!$this->db->field_exists('keterangan', 'invoice_detail_bukti')) {
				$this->dbforge->add_column('invoice_detail_bukti', [
					'keterangan' => [
						'type' => 'VARCHAR',
						'constraint' => 255,
						'null' => true,
						'after' => 'filename',
					],
				]);
			}

			// Struktur lama memiliki kolom id tanpa primary key/auto increment.
			// Normalisasi ini membuat setiap upload tersimpan sebagai riwayat terpisah.
			$primary = $this->db
				->query("SHOW INDEX FROM `invoice_detail_bukti` WHERE `Key_name` = 'PRIMARY'")
				->result_array();
			$idColumn = $this->db
				->query("SHOW COLUMNS FROM `invoice_detail_bukti` LIKE 'id'")
				->row_array();
			$idIsAutoIncrement = !empty($idColumn['Extra'])
				&& stripos($idColumn['Extra'], 'auto_increment') !== false;

			if (empty($primary)) {
				if (!$this->db->query(
					'ALTER TABLE `invoice_detail_bukti` '
					. 'MODIFY `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, '
					. 'ADD PRIMARY KEY (`id`)'
				)) {
					return false;
				}
			} elseif (!$idIsAutoIncrement) {
				if (!$this->db->query(
					'ALTER TABLE `invoice_detail_bukti` '
					. 'MODIFY `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT'
				)) {
					return false;
				}
			}

			$detailIndex = $this->db
				->query("SHOW INDEX FROM `invoice_detail_bukti` WHERE `Column_name` = 'id_rincianinvoice'")
				->result_array();
			if (empty($detailIndex)) {
				$this->db->query(
					'ALTER TABLE `invoice_detail_bukti` '
					. 'ADD INDEX `idx_invoice_detail_bukti_rincian` (`id_rincianinvoice`)'
				);
			}

			return $this->db->field_exists('keterangan', 'invoice_detail_bukti');
		}

		public function upload_bukti_progress()
		{
			if (!$this->input->is_ajax_request()) {
				$this->output
					->set_content_type('application/json')
					->set_output(json_encode(['success' => false, 'message' => 'invalid request']));
				return;
			}

			if (!$this->can_manage_progress_status()) {
				$this->output
					->set_status_header(403)
					->set_content_type('application/json')
					->set_output(json_encode(['success' => false, 'message' => 'akses ditolak']));
				return;
			}

			$encId = $this->input->post('id');
			$id = decrypt_url($encId);
			if (empty($id)) {
				$this->output
					->set_content_type('application/json')
					->set_output(json_encode(['success' => false, 'message' => 'invalid id']));
				return;
			}

			if (empty($_FILES['lampiran']['name'])) {
				$this->output
					->set_content_type('application/json')
					->set_output(json_encode(['success' => false, 'message' => 'file required']));
				return;
			}

			if (!$this->ensure_progress_proof_table()) {
				$this->output
					->set_status_header(500)
					->set_content_type('application/json')
					->set_output(json_encode(['success' => false, 'message' => 'penyimpanan bukti belum siap']));
				return;
			}

			$detailExists = $this->db
				->where('id_rincianinvoice', (int)$id)
				->count_all_results('invoice_detail') > 0;
			if (!$detailExists) {
				$this->output
					->set_status_header(404)
					->set_content_type('application/json')
					->set_output(json_encode(['success' => false, 'message' => 'detail pekerjaan tidak ditemukan']));
				return;
			}

			$keterangan = trim(strip_tags((string)$this->input->post('keterangan')));
			$keterangan = preg_replace('/\s+/u', ' ', $keterangan);
			$keterangan = function_exists('mb_substr')
				? mb_substr($keterangan, 0, 255, 'UTF-8')
				: substr($keterangan, 0, 255);
			if ($keterangan === '') {
				$keterangan = 'Bukti progres';
			}

			$upload_dir = FCPATH . 'uploads/lampiran/progress/';
			if (!is_dir($upload_dir)) {
				@mkdir($upload_dir, 0755, true);
			}

			try {
				$randomSuffix = bin2hex(random_bytes(3));
			} catch (\Throwable $e) {
				$randomSuffix = substr(uniqid('', true), -6);
			}

			$config['upload_path'] = './uploads/lampiran/progress/';
			$config['allowed_types'] = 'jpeg|jpg|png|webp';
			$config['max_size'] = '5000';
			$config['file_name'] = 'progress_' . $id . '_' . date('YmdHis') . '_' . $randomSuffix;

			$this->load->library('upload', $config);
			$this->upload->initialize($config);

			if (!$this->upload->do_upload('lampiran')) {
				$error = $this->upload->display_errors('', '');
				$this->output
					->set_content_type('application/json')
					->set_output(json_encode(['success' => false, 'message' => $error]));
				return;
			}

			$uploadData = $this->upload->data();
			$finalUpload = bm_finalize_ci_upload_as_webp($uploadData, 80);
			if (!$finalUpload['status']) {
				$this->output
					->set_content_type('application/json')
					->set_output(json_encode(['success' => false, 'message' => $finalUpload['message']]));
				return;
			}

			$filename = $finalUpload['file_name'];
			$now = date('Y-m-d H:i:s');
			$stored = $this->db->insert('invoice_detail_bukti', [
				'id_rincianinvoice' => (int)$id,
				'filename' => $filename,
				'keterangan' => $keterangan,
				'id_user' => $this->iduser,
				'created_at' => $now,
				'updated_at' => $now,
			]);

			if (!$stored) {
				$storedPath = $upload_dir . $filename;
				if (is_file($storedPath)) {
					@unlink($storedPath);
				}
				$this->output
					->set_status_header(500)
					->set_content_type('application/json')
					->set_output(json_encode(['success' => false, 'message' => 'bukti gagal disimpan']));
				return;
			}

			$proofId = (int)$this->db->insert_id();
			$this->output
				->set_content_type('application/json')
				->set_output(json_encode([
					'success' => true,
					'id' => $proofId,
					'filename' => $filename,
					'url' => base_url('uploads/lampiran/progress/' . rawurlencode($filename)),
					'keterangan' => $keterangan,
					'uploaded_at' => $now,
					'uploaded_at_label' => date('d/m/Y H:i:s', strtotime($now)) . ' WIB',
				]));
		}
		
		public function load_modal(){
			$id= $this->db->escape_str($this->input->post('id'));	
			$id = decrypt_url($id);
			$iduser= $this->db->escape_str($this->input->post('user'));			
			$format = "%Y-%m-%d";			
			$mdate = mdate($format);
			$savedItems = [];
			
			$cek_invoice = $this->model_app
			->view_where('surat_jalan', ['id_invoice' => $id]);
			if($cek_invoice->num_rows() > 0){
				$row = $cek_invoice->row();
				$data['id'] = $row->id;
				$data['id_user']  = $row->id_user;
				$data['tanggal']  = $row->tanggal;
				$data['no_pol']  = $row->no_pol;
				$data['alamat_kirim']  = $row->alamat_kirim;
				$data['status'] = $row->stat;
				$storedDetail = json_decode($row->catatan, true);
				$data['nama_kendaraan'] = is_array($storedDetail) && isset($storedDetail['nama_kendaraan'])
					? $storedDetail['nama_kendaraan']
					: '';
				if (is_array($storedDetail) && isset($storedDetail['detail']) && is_array($storedDetail['detail'])) {
					foreach ($storedDetail['detail'] as $storedItem) {
						if (isset($storedItem['id'])) $savedItems[(string)$storedItem['id']] = $storedItem;
					}
				}
				}else{
				
				$datain = [
				"id_invoice" => $id,
				"tanggal" => $mdate
				];
				$input = $this->model_app->input("surat_jalan", $datain);
				if($input['status']=='ok'){
					$data['id'] = $input['id'];
					$data['id_user']  = '';
					$data['tanggal']  = $mdate;
					$data['no_pol']  = '';
					$data['alamat_kirim']  = '';
					$data['status'] = 0;
					$data['nama_kendaraan'] = '';
				}
			}
			$data['user'] = $this->model_app
			->view_where('tb_users', ['aktif' => 'Y'])
			->result();
			
			$data['row'] = $this->model_app
			->view_where('invoice', ['id_invoice' => $id])
			->row();
			// dump($data['row'],'print_r','exit');
			$data["detail"] = $this->model_app->produk_cart([
			"invoice_detail.id_invoice" => $id,
			]);
			foreach ($data['detail'] as &$detailItem) {
				$detailId = isset($detailItem['id_rincianinvoice']) ? (string)$detailItem['id_rincianinvoice'] : '';
				if ($detailId !== '' && isset($savedItems[$detailId])) {
					$detailItem['keterangan'] = isset($savedItems[$detailId]['keterangan']) ? $savedItems[$detailId]['keterangan'] : '';
				}
			}
			unset($detailItem);
			
			$this->load->view('laporan/load_modal', $data, false);
		}
		public function load_modal_spk(){
			$id= $this->db->escape_str($this->input->post('id'));	
			$id = decrypt_url($id);
			$iduser= $this->db->escape_str($this->input->post('user'));			
			$format = "%Y-%m-%d";			
			$mdate = mdate($format);
			
			
			$data['user'] = $this->model_app
			->view_where('tb_users', ['aktif' => 'Y'])
			->result();
			
			$data['row'] = $this->model_app
			->view_where('invoice', ['id_invoice' => $id])
			->row();
			// dump($data['row'],'print_r','exit');
			$data["detail"] = $this->model_app->produk_cart([
			"invoice_detail.id_invoice" => $id,
			]);
			
			$this->load->view('laporan/load_modal_spk', $data, false);
		}
		
		public function simpan_spk(){
			if ($this->input->is_ajax_request()) 
			{
				$id_invoice = (int)$this->input->post('invoice_id');
				if ($id_invoice < 1) {
					$id_invoice = (int)decrypt_url((string)$this->input->post('id_invoive', true));
				}
				if ($id_invoice < 1) {
					$id_invoice = (int)decrypt_url((string)$this->input->post('spk_invoice_token', true));
				}
				$no_order = $this->db->escape_str((string)$this->input->post('no_order', true));
				$id = $this->input->post('id', true);
				$no_spk = $this->input->post('no_spk', true);
				$id = is_array($id) ? array_values($id) : ($id !== null && $id !== '' ? [$id] : []);
				$no_spk = is_array($no_spk) ? array_values($no_spk) : ($no_spk !== null && $no_spk !== '' ? [$no_spk] : []);

				if ($id_invoice < 1 && !empty($id)) {
					$detailInvoice = $this->db->select('id_invoice')->where('id_rincianinvoice', (int)$id[0])->limit(1)->get('invoice_detail')->row();
					if ($detailInvoice) $id_invoice = (int)$detailInvoice->id_invoice;
				}

				if ($id_invoice > 0 && (empty($id) || count($id) !== count($no_spk))) {
					$invoiceRow = $this->db->select('tgl_trx')->where('id_invoice', $id_invoice)->limit(1)->get('invoice')->row();
					$detailRows = $this->db->select('id_rincianinvoice, no_spk')->where('id_invoice', $id_invoice)->order_by('id_rincianinvoice', 'ASC')->get('invoice_detail')->result_array();
					$id = [];
					$no_spk = [];
					foreach ($detailRows as $detailRow) {
						$id[] = (int)$detailRow['id_rincianinvoice'];
						$no_spk[] = !empty($detailRow['no_spk']) ? $detailRow['no_spk'] : 'SPK-'.$detailRow['id_rincianinvoice'].($invoiceRow ? tgl_spk($invoiceRow->tgl_trx) : date('dmY'));
					}
				}
				
				if ($id_invoice < 1 || empty($id) || count($id) !== count($no_spk)) {
					$this->output->set_content_type('application/json')->set_output(json_encode(['status'=>400,'msg'=>'Data invoice SPK tidak valid.']));
					return;
				}

				// Jangan mengandalkan hasil update baris terakhir. Semua detail harus
				// benar-benar tersimpan sebelum respons sukses dikirim ke halaman SPK.
				$detailIds = array_values(array_unique(array_filter(array_map('intval', $id), function ($detailId) {
					return $detailId > 0;
				})));
				$validRows = empty($detailIds) ? [] : $this->db->select('id_rincianinvoice, id_invoice')
					->where_in('id_rincianinvoice', $detailIds)
					->get('invoice_detail')->result_array();
				$validIds = array_map('intval', array_column($validRows, 'id_rincianinvoice'));
				$ownerInvoiceIds = array_values(array_unique(array_map('intval', array_column($validRows, 'id_invoice'))));

				if (count($validIds) !== count($detailIds) || count($ownerInvoiceIds) !== 1) {
					// Beberapa versi formulir lama dapat mengirim susunan id[] yang tidak
					// konsisten. Rekonsiliasi dengan detail resmi milik invoice agar data
					// yang sah tidak ditolak hanya karena bentuk payload browser.
					$invoiceExists = $id_invoice > 0 && $this->db->where('id_invoice', $id_invoice)->count_all_results('invoice') === 1;
					$invoiceDetails = $invoiceExists
						? $this->db->select('id_rincianinvoice, id_invoice, id_produk, no_spk')->where('id_invoice', $id_invoice)->order_by('id_rincianinvoice', 'ASC')->get('invoice_detail')->result_array()
						: [];
					$invoiceDetails = array_values(array_filter($invoiceDetails, function ($detailRow) {
						return jkategori($detailRow['id_produk']) != 9;
					}));
					if (empty($invoiceDetails)) {
						$this->output->set_content_type('application/json')->set_output(json_encode(['status'=>400,'msg'=>'Detail SPK tidak sesuai dengan invoice.']));
						return;
					}
					$postedSpkById = [];
					foreach ($id as $postedIndex=>$postedDetailId) {
						$postedDetailId = (int)$postedDetailId;
						if ($postedDetailId > 0) $postedSpkById[$postedDetailId] = isset($no_spk[$postedIndex]) ? $no_spk[$postedIndex] : '';
					}
					$id = [];
					$no_spk = [];
					foreach ($invoiceDetails as $detailRow) {
						$detailId = (int)$detailRow['id_rincianinvoice'];
						$id[] = $detailId;
						$no_spk[] = isset($postedSpkById[$detailId]) && trim((string)$postedSpkById[$detailId]) !== ''
							? $postedSpkById[$detailId]
							: $detailRow['no_spk'];
					}
					$detailIds = array_map('intval', array_column($invoiceDetails, 'id_rincianinvoice'));
					$ownerInvoiceIds = [$id_invoice];
				}
				// ID detail adalah identitas yang benar-benar dipilih pada tabel modal.
				// Gunakan invoice pemilik detail agar token modal lama yang tertinggal
				// tidak membuat penyimpanan ditolak atau diarahkan ke invoice lain.
				$id_invoice = (int)$ownerInvoiceIds[0];
				$invoiceRow = $this->db->select('tgl_trx')->where('id_invoice', $id_invoice)->limit(1)->get('invoice')->row();

				$this->db->trans_begin();
				foreach ($id as $index=>$detailId) {
					$detailId = (int)$detailId;
					$spkNumber = trim((string)(isset($no_spk[$index]) ? $no_spk[$index] : ''));
					if ($spkNumber === '') {
						$spkNumber = 'SPK-'.$detailId.($invoiceRow ? tgl_spk($invoiceRow->tgl_trx) : date('dmY'));
					}
					$this->db->where('id_rincianinvoice', $detailId)
						->where('id_invoice', $id_invoice)
						->update('invoice_detail', ['no_spk'=>$spkNumber]);
					if (!$this->db->trans_status()) break;
				}

				$savedCount = (int)$this->db->where('id_invoice', $id_invoice)
					->where_in('id_rincianinvoice', $detailIds)
					->where("TRIM(COALESCE(no_spk, '')) <> ''", null, false)
					->count_all_results('invoice_detail');
				$ok = $this->db->trans_status() && $savedCount === count($detailIds);
				if ($ok) $this->db->trans_commit();
				else $this->db->trans_rollback();

				$arr = $ok
					? ['status'=>200,'msg'=>'SPK berhasil disimpan.','id'=>encrypt_url($id_invoice)]
					: ['status'=>400,'msg'=>'SPK gagal disimpan ke database.'];
				$this->output
				->set_content_type('application/json')
				->set_output(json_encode($arr));
			}
		}
		
		public function simpan_surat(){
			if ($this->input->is_ajax_request()) 
			{
				$no_surat = $this->db->escape_str($this->input->post('no_surat'));
				$id_invoice = decrypt_url($this->db->escape_str($this->input->post('id_invoive')));
				$no_order = $this->db->escape_str($this->input->post('no_order'));
				$pengirim = $this->db->escape_str($this->input->post('pengirim'));
				$nama_kendaraan = $this->db->escape_str($this->input->post('nama_kendaraan'));
				$tanggal_kirim = $this->db->escape_str($this->input->post('tgl_kirim'));
				$nopol = $this->db->escape_str($this->input->post('nopol'));
				$alamat = $this->db->escape_str($this->input->post('alamat'));
				$id = $this->db->escape_str($this->input->post('id'));
				$jml = $this->db->escape_str($this->input->post('jumlah'));
				$title = $this->db->escape_str($this->input->post('title'));
				$bahan = $this->db->escape_str($this->input->post('bahan'));
				$ukuran = $this->db->escape_str($this->input->post('ukuran'));
				$keterangan = $this->db->escape_str($this->input->post('keterangan'));
				// dump($_POST,'print_r','exit');
				$data             = array();        
				$index            = 0;  
				
				foreach($id as $key){
					
					array_push($data, array(
					'id'              =>$key,
					'jumlah'          =>$jml[$index],
					'title'     	  =>$title[$index],
					'bahan' 	      =>$bahan[$index], 
					'ukuran'          =>$ukuran[$index],
					'keterangan'      =>$keterangan[$index]
					));
					
					$index++;    
				}
				
				$detail = json_encode(['nama_kendaraan'=>$nama_kendaraan, 'detail'=>$data]);
				
				$array = [
				'id_user'=>$pengirim,
				'id_invoice'=>$id_invoice,
				'tanggal'=>$tanggal_kirim,
				'no_pol'=>$nopol,
				'alamat_kirim'=>$alamat,
				'catatan'=>$detail,
				'stat'=>1,
				];
				// dump($array,'print_r','exit');
				$update = $this->model_app->update('surat_jalan',$array,['id'=>$no_surat]);
				if($update['status']=='ok'){
					$arr = ['status'=>200,'msg'=>'sukses','id'=>encrypt_url($no_surat)];
					}else{
					$arr = ['status'=>400,'msg'=>'gagal'];
				}
				$this->output
				->set_content_type('application/json')
				->set_output(json_encode($arr));
			}
		}
		
		public function suratjalan()
		{
			$data['title'] ='Laporan Surat Jalan | '.$this->title;
			
			$data['pilihan'] = $this->model_app->pilih('id_user, nama_lengkap','tb_users')->result_array();		
			
			$conditions['where'] = array('surat_jalan.stat' => 1);
			$dari = date('Y-m-').'01';
			$conditions['search']['dari'] = $dari; 
			$conditions['search']['sampai'] = date("Y-m-d"); 
			$conditions['search']['sortBy'] = 'DESC';
			
			$conditions['returnType'] = 'count'; 
			$totalRec = $this->model_data->getSurat($conditions); 
			
			// Pagination configuration 
			$config['target']      = '#dataListOmset'; 
			$config['base_url']    = base_url('laporan/ajaxSuratjalan');
			$config['total_rows']  = $totalRec; 
			$config['per_page']    = $this->perPage; 
			$config['link_func']   = 'search_surat'; 
			$config['show_count']  = false;
			// Initialize pagination library 
			$this->ajax_pagination->initialize($config); 
			
			// Get records 
			$conditions = array('limit' => $this->perPage);
			$conditions['where'] = array('surat_jalan.stat' => 1);
			$conditions['search']['dari'] = $dari; 
			$conditions['search']['sampai'] = date("Y-m-d"); 
			$conditions['search']['sortBy'] = 'DESC';
			$data['dari'] = tgl_dari_slash();
			$data['sampai'] = tgl_sampai_slash();
			$data['posts'] = $this->model_data->getSurat($conditions);
			$data['start'] = 0;
			
			$this->template->load('main/themes','laporan/surat_jalan',$data);
		}
		
		public function ajaxSuratjalan()
		{
			if ($this->input->is_ajax_request()) 
			{
				$page = $this->input->post('page');
				if (!$page) {
					$offset = 0;
					} else {
					$offset = $page;
				}
				$sortBy = strtoupper((string)$this->input->post('sortBy'));
				$conditions['search']['sortBy'] = in_array($sortBy, array('ASC', 'DESC'), true) ? $sortBy : 'DESC';
				$limits = $this->input->post('limits');
				$allowedLimits = array(10, 20, 50, 100);
				$limit = in_array((int)$limits, $allowedLimits, true) ? (int)$limits : $this->perPage;
				// Set conditions for search and filter
				$user = (int)$this->input->post('user');
				$keyword = trim((string)$this->input->post('keyword', true));
				$dari = date_slash($this->input->post('dari'));
				$sampai = date_slash($this->input->post('sampai'));
				
				$conditions['where'] = array(
				'surat_jalan.stat' => 1
				);
				
				if ($user > 0) $conditions['where']['surat_jalan.id_user'] = $user;
				if ($keyword !== '') $conditions['search']['keyword'] = $keyword;
				
				if (!empty($dari)) {
					$conditions['search']['dari'] = $dari;
				}
				if (!empty($sampai)) {
					$conditions['search']['sampai'] = $sampai;
				}
				
				// Get record count
				$conditions['returnType'] = 'count';
				$totalRec = $this->model_data->getSurat($conditions);
				
				// Pagination configuration
				$config['target'] = '#dataListOmset';
				$config['base_url'] = base_url('laporan/ajaxSuratjalan');
				$config['total_rows'] = $totalRec;
				$config['per_page'] = $limit;
				$config['link_func'] = 'search_surat';
				$config['show_count'] = false;
				
				// Initialize pagination library
				$this->ajax_pagination->initialize($config);
				
				// Get records
				$conditions['start'] = $offset;
				$conditions['limit'] = $limit;
				
				unset($conditions['returnType']);
				
				$data['posts'] = $this->model_data->getSurat($conditions);
				$data['user'] = $user;
				$data['start'] = $offset;
				
				// Load the data list view 
				$this->load->view('laporan/ajax-surat', $data, false); 
			}
		}

		public function ajaxTransaksiSurat()
		{
			if (!$this->input->is_ajax_request()) {
				show_404();
				return;
			}

			$keyword = trim((string)$this->input->post('keyword', true));
			$this->db->select("invoice.id_invoice, invoice.id_transaksi, invoice.tgl_trx, surat_jalan.id AS id_surat, surat_jalan.stat AS status_surat, CASE WHEN konsumen.tampil = 1 AND TRIM(COALESCE(konsumen.perusahaan, '')) <> '' THEN konsumen.perusahaan ELSE konsumen.nama END AS nama_pelanggan", false);
			$this->db->from('invoice');
			$this->db->join('konsumen', 'invoice.id_konsumen = konsumen.id');
			$this->db->join('surat_jalan', 'invoice.id_invoice = surat_jalan.id_invoice', 'left');
			$this->db->where("TRIM(COALESCE(invoice.id_transaksi, '')) <> ''", null, false);
			if ($keyword !== '') {
				$this->db->group_start();
				$this->db->like('invoice.id_transaksi', $keyword);
				$this->db->or_like('konsumen.nama', $keyword);
				$this->db->or_like('konsumen.perusahaan', $keyword);
				$this->db->group_end();
			}
			$this->db->order_by('invoice.id_invoice', 'DESC');
			$this->db->limit(30);
			$data['transactions'] = $this->db->get()->result_array();
			$this->load->view('laporan/ajax-transaksi-surat', $data, false);
		}

		public function cetak_surat($id='')
		{
			$id = decrypt_url($id);
			
			$cek = $this->model_app->view_where('surat_jalan',['id'=>$id]);
			if($cek->num_rows() > 0){
				$data['cetak'] = $cek->row();
				$row = $this->model_app->view_where('invoice', ['id_invoice'=>$cek->row()->id_invoice])->row();
				// dump($row,'print_r','exit');
				$data['konsumen'] = $this->model_app->view_where('konsumen', array('id' => $row->id_konsumen))->row_array();
				$data['marketing']   = $this->model_app->view_where('tb_users', array('id_user' => $cek->row()->id_user))->row_array();
				$data['order'] = $row;
				$data['info'] = info();
				//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';
				$pub = array('pub' =>1);//printer aktif
				$cek_printer = $this->model_app->view_where('printer', $pub);
				$rowc = $cek_printer->row_array();
				$this->load->library('pdf');
				$this->pdf->setPaper('A4', 'landscape');
				$this->pdf->filename = "surat_jalan_".$id."_".$cek->row()->tanggal;
				$this->pdf->load_view('laporan/print_surat_jalan', $data);
				// $this->load->view('laporan/print_surat_jalan',$data);
				}else{
				$data['cetak']       = 'error';
				$this->load->view('errors/404',$data);
			}
		}
		
		public function cetak_laporan_operator(){
			// dump($_POST);
			if(!empty($_POST)){
				
				$status = ($this->input->post('status')); 
				$operator = ($this->input->post('operator')); 
				
				$dari = date_slash($this->input->post('startdate'));
				$sampai = date_slash($this->input->post('enddate'));
				
				$conditions['where'] = array(
				'invoice.status' => 'simpan'
				);
				
				if (!empty($operator)) {
					$conditions['where'] = array(
					'invoice.id_user' => $operator
					);
				}
				
				if (!empty($dari)) {
					$conditions['search']['dari'] = $dari;
				}
				if (!empty($sampai)) {
					$conditions['search']['sampai'] = $sampai;
				}
				
				//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_blunas']	= FCPATH.'uploads/'.info()['logo_bw'];
				$data['info']			= info();
				$data['periode']		= $this->input->post('startdate') .' - '. $this->input->post('enddate');
				$data['tanggal']		= date("Y-m-d"); ;
				$data['user']			= $this->model_app->view_where('tb_users', array('id_user' => $this->iduser))->row_array();
				$data['laporan']		= $this->model_data->get_operator($conditions); 
				$mod = modul_cetak('cetak_order');
				$this->load->library('pdf');				
				$this->pdf->setPaper('A4', 'landscape');					
				$this->pdf->filename = "laporan_penjualan";				
				$this->pdf->load_view('laporan/cetak_laporan_operator', $data);	
				// $this->load->view('laporan/cetak_laporan_operator', $data);	
				}else{
				$data['cetak']       = 'error';
				$this->load->view('errors/404',$data);
			}
		}
	}																																																																																																																																																																																				
