<?php
	defined('BASEPATH') or exit('No direct script access allowed');
	
	class Einvoice extends CI_Controller
	{
		public function __construct()
		{
			parent::__construct();
			
			$this->title = info()['title']; 
			
		}
		
		public function kirim(){
			$seo = $this->uri->segment(2);
			$noid = decrypt_url($seo);
			$is_pdf_preview = $this->input->get('pdf', true) == '1';
			$id = array('id_invoice' => $noid);
			$pub = array('pub' =>1);//printer aktif
			$search = $this->model_app->view_where('invoice', $id);
			$app_info = info();
			
			if($search->num_rows()>0){
				//icon
				$data['waicon'] 	= ['color'=>base_url().'assets/img/wa_icon.png','bw'=>base_url().'assets/img/wa_icon_bw.png'];
				$data['mail'] 		= ['color'=>base_url().'assets/img/gmail_icon.png','bw'=>base_url().'assets/img/gmail_icon_bw.png'];
				$data['fbicon'] 	= ['color'=>base_url().'assets/img/fb_icon.png','bw'=>base_url().'assets/img/fb_icon_bw.png'];
				$data['igicon'] 	= ['color'=>base_url().'assets/img/ig_icon.png','bw'=>base_url().'assets/img/ig_icon_bw.png'];
				
				$data['logo_lunas'] = base_url().'uploads/'.$app_info['logo'];
				$data['logo_blunas'] = base_url().'uploads/'.$app_info['logo_bw'];
				$data['lunas'] = base_url().'uploads/'.$app_info['stamp_l'];
				$data['blunas'] = base_url().'uploads/'.$app_info['stamp_b'];
				$data['favicon'] = base_url().'uploads/'.$app_info['favicon'];
				$data['html'] = 'Y';
				
				$pub = array('pub' =>1);//printer aktif
				$cek_printer = $this->model_app->view_where('printer', $pub);
				$rowc = $cek_printer->row_array();
				
				$data['ukuran'] =$rowc['ukuran_kertas'];
				$data['font_size'] =$rowc['ukuran_font'];
				
				$row = $search->row();
				$jml =$row->cetak+1;
				$this->model_app->update('tb_users', array("last_invoice"=>0),array('id_user'=>$this->session->idu));
				if($row->status!='batal'){
					$this->model_app->update('invoice',array('cetak'=>$jml,'status'=>'simpan','pos'=>'Y','oto'=>6),array('id_invoice'=>$noid));
				}
				$data['cetak'] = $row;
				$data['info'] = $app_info;
				$konsumen = $this->model_app->view_where('konsumen', array('id' => $row->id_konsumen))->row_array();
				
				if($konsumen['max_utang'] >0 AND $jml <=1){
					$max_utang = $konsumen['max_utang'] - 1;
					$this->model_app->update('konsumen',array('max_utang'=>$max_utang),array('id'=>$row->id_konsumen));
				}
				
				$data['konsumen']    = $konsumen;
				$data['marketing']   = $this->model_app->view_where('tb_users', array('id_user' => $row->id_marketing))->row_array();
				$data['detail']      = $this->model_app->produk_cart(array('invoice_detail.id_invoice' => $noid));
				$detail_subtotal = 0;
				$detail_diskon = 0;
				foreach ($data['detail'] as $detail_row) {
					$jumlah = isset($detail_row['jumlah']) ? (float) $detail_row['jumlah'] : 0;
					$harga = isset($detail_row['harga']) ? (float) $detail_row['harga'] : 0;
					$diskon = isset($detail_row['diskon']) ? (float) $detail_row['diskon'] : 0;
					$subtotal = $jumlah * $harga;
					$detail_subtotal += $subtotal - ($subtotal * ($diskon / 100));
					$detail_diskon += $diskon;
				}
				$data['sisanya'] = round($detail_subtotal);
				$data['total']       =$this->model_app->total_bayar(array('bayar_invoice_detail.id_invoice'=>$noid))->row();
				$data['tdetail']     = $row->total_bayar;
				$data['pajak']       = $row->pajak;
				$data['jumlah_bayar'] = $row->jumlah_bayar;
				$data['potongan_harga'] = $row->potongan_harga;
				$data['cashback'] = $row->cashback;
				$data['kembalian'] = $row->kembalian;
				$data['cdiskon']     = $detail_diskon;
				//bayar detail
				$data['bdetail']     = $this->model_app->view_where('bayar_invoice_detail', $id)->result_array();
				$data['cdetail']     = count($data['bdetail']);
				///
				$data['cara']        = $this->model_app->cara_bayar(array('`jenis_bayar`.`publish`'=>'Y','`bayar_invoice_detail`.`id_invoice`' => $noid));
				$data['bank']        = $this->model_app->view_where('rekening_bank',['footer_invoice'=>1,'publish'=>'Y'])->result();
				$invoice_qr = invoice_qr_context($noid, $app_info['kode_qris']);
				$qris_file = $invoice_qr['path'];
				$data['qris'] = $invoice_qr['content'];
				$data['kode_qris'] = $invoice_qr['url'];
				$data['qr_available'] = $invoice_qr['available'];
				$data['qr_is_tracking'] = $invoice_qr['is_tracking'];
				$data['qr_label'] = $invoice_qr['label'];
				if ($is_pdf_preview) {
					$data['is_pdf'] = true;
					$data['logo'] = 'uploads/'.$app_info['logo'];
					$data['logo_lunas'] = 'uploads/'.$app_info['logo'];
					$data['logo_blunas'] = 'uploads/'.$app_info['logo_bw'];
					$data['lunas'] = 'uploads/'.$app_info['stamp_l'];
					$data['blunas'] = 'uploads/'.$app_info['stamp_b'];
					$data['kode_qris_pdf'] = $qris_file;

					$detail_rows = is_array($data['detail']) ? $data['detail'] : array();
					$item_lines = 0;
					foreach ($detail_rows as $d) {
						// 3 baris dasar/item: nama, ukuran+qty, dan harga.
						$item_lines += 3;

						$ket = isset($d['keterangan']) ? trim((string) $d['keterangan']) : '';
						if ($ket !== '') {
							$item_lines += 1;
						}

						$raw_detail = isset($d['detail']) ? $d['detail'] : '';
						if ($raw_detail !== '') {
							$decoded_detail = json_decode($raw_detail);
							if (is_object($decoded_detail) && isset($decoded_detail->data) && is_array($decoded_detail->data) && count($decoded_detail->data) > 0) {
								// 1 baris header "Catatan" + jumlah detail finishing.
								$item_lines += 1 + count($decoded_detail->data);
							}
						}
					}
					if ($item_lines <= 0) {
						$item_lines = 4;
					}

					$paper_width_pt = 226.77; // 302px thermal width
					$font_size_pt = isset($data['font_size']) && is_numeric($data['font_size']) ? (float) $data['font_size'] : 13;
					if ($font_size_pt < 7) {
						$font_size_pt = 7;
					}
					$px_to_pt = 0.75;
					$paper_width_px = 302;
					$paper_padding_x_px = 20;
					$content_width_px = $paper_width_px - $paper_padding_x_px;
					$line_height_px = $font_size_pt * 1.35;
					$line_height_pt = $line_height_px * $px_to_pt;
					$big_font_px = max($font_size_pt + 5, round($font_size_pt * 1.38));
					$big_line_height_pt = ($big_font_px * 1.35) * $px_to_pt;
					$rule_pt = 13 * $px_to_pt;
					$rule2_pt = 14 * $px_to_pt;
					$mt6_pt = 6 * $px_to_pt;

					$logo_height_px = 135;
					$logo_file = FCPATH.'uploads/'.$app_info['logo'];
					if (is_file($logo_file)) {
						$logo_size = @getimagesize($logo_file);
						if (!empty($logo_size[0]) && !empty($logo_size[1])) {
							$logo_width_px = min(190, $paper_width_px * 0.78);
							$logo_height_px = ($logo_size[1] / $logo_size[0]) * $logo_width_px;
						}
					}
					$logo_block_pt = ($logo_height_px + 6) * $px_to_pt;

					$desc_text = isset($app_info['deskripsi']) ? trim(strip_tags(base64_decode($app_info['deskripsi']))) : '';
					$chars_per_line = max(20, (int) floor($content_width_px / max(1, $font_size_pt * 0.6)));
					$desc_lines = $desc_text !== '' ? max(1, (int) ceil(strlen($desc_text) / $chars_per_line)) : 0;
					$header_lines = 1 + $desc_lines + (!empty($app_info['phone']) ? 1 : 0);

					$item_rule_count = max(0, count($detail_rows) - 1);
					$item_block_pt = ($item_lines * $line_height_pt) + ($item_rule_count * $rule_pt);
					$summary_row_pt = (($font_size_pt * 1.2) + 4) * $px_to_pt;
					$summary_area_pt = max(88 * $px_to_pt, (8 * $px_to_pt) + (3 * $summary_row_pt) + (2 * $px_to_pt));

					$estimate_height_pt = (int) ceil(
						(16 * $px_to_pt) +                 // padding atas/bawah .paper
						$logo_block_pt +
						($header_lines * $line_height_pt) +
						(4 * $rule2_pt) +
						$big_line_height_pt +
						$mt6_pt + (4 * $line_height_pt) +   // info kasir/tanggal/jam/pelanggan
						$item_block_pt +
						$summary_area_pt +
						(($invoice_qr['is_tracking'] ? $line_height_px : 0) * $px_to_pt) +
						((120 + 8) * $px_to_pt) +           // label tracking + QR
						$mt6_pt + (5 * $line_height_pt) +
						$mt6_pt + $line_height_pt +
						6                                   // toleransi render dompdf
					);

					// Render HTML sekali untuk proses ukur + render final.
					$html = $this->load->view('produk/kirim_invoice', $data, true);
					$pdf_name = 'struk_'.$row->id_transaksi.'.pdf';
					$cache_dir = FCPATH.'uploads/cache/einvoice_pdf/';
					if (!is_dir($cache_dir)) {
						@mkdir($cache_dir, 0775, true);
					}
					$qris_cache_key = is_file($qris_file) ? @md5_file($qris_file).'|'.@filemtime($qris_file) : 'missing';
					$cache_key = md5('thermal-height-v6|'.$noid.'|'.$estimate_height_pt.'|'.$qris_cache_key.'|'.$html);
					$cache_file = $cache_dir.'struk_'.$row->id_transaksi.'_'.$cache_key.'.pdf';
					if (is_file($cache_file)) {
						$cached_pdf = @file_get_contents($cache_file);
						if ($cached_pdf !== false && $cached_pdf !== '') {
							$this->output
							->set_content_type('application/pdf')
							->set_header('Content-Disposition: inline; filename="'.$pdf_name.'"')
							->set_output($cached_pdf);
							return;
						}
					}

					$this->load->library('pdf');
					$max_height_pt = 9000;
					$final_height_pt = max(300, min(4200, $estimate_height_pt));

					$render_pdf = function($height) use ($paper_width_pt, $html) {
						$pdf = new Pdf();
						$pdf->getOptions()->setChroot(FCPATH);
						$pdf->getOptions()->isHtml5ParserEnabled(true);
						$pdf->getOptions()->isRemoteEnabled(true);
						$pdf->setPaper(array(0, 0, $paper_width_pt, (int) $height), 'portrait');
						$pdf->load_html($html);
						$pdf->render();
						return array('pdf' => $pdf, 'pages' => (int) $pdf->getCanvas()->get_page_count());
					};

					$rendered = $render_pdf($final_height_pt);
					$pdf_final = $rendered['pdf'];
					$page_count = $rendered['pages'];

					// Jika masih kepotong >1 halaman, naikkan tinggi hingga muat.
					// Dompdf mahal; batasi render ulang agar klik print struk tidak terasa menggantung.
					$adjust_iterations = 0;
					while ($page_count > 1 && $final_height_pt < $max_height_pt && $adjust_iterations < 3) {
						$final_height_pt = min($max_height_pt, $final_height_pt + (($page_count - 1) * 420) + 120);
						$rendered = $render_pdf($final_height_pt);
						$pdf_final = $rendered['pdf'];
						$page_count = $rendered['pages'];
						$adjust_iterations++;
					}

					if ($page_count <= 1) {
						$low_height = 240;
						$high_height = $final_height_pt;
						$best_height = $final_height_pt;
						$best_pdf = $pdf_final;
						$shrink_iterations = 0;
						while (($high_height - $low_height) > 8 && $shrink_iterations < 7) {
							$try_height = (int) floor(($low_height + $high_height) / 2);
							$try_rendered = $render_pdf($try_height);
							if ($try_rendered['pages'] <= 1) {
								$best_height = $try_height;
								$best_pdf = $try_rendered['pdf'];
								$high_height = $try_height;
							} else {
								$low_height = $try_height + 1;
							}
							$shrink_iterations++;
						}

						$final_height_pt = min($max_height_pt, $best_height + 6);
						$rendered = $render_pdf($final_height_pt);
						if ($rendered['pages'] <= 1) {
							$pdf_final = $rendered['pdf'];
						} else {
							$pdf_final = $best_pdf;
						}
					}
					$pdf_output = $pdf_final->output();
					if ($pdf_output !== '') {
						@file_put_contents($cache_file, $pdf_output);
					}
					$this->output
					->set_content_type('application/pdf')
					->set_header('Content-Disposition: inline; filename="'.$pdf_name.'"')
					->set_output($pdf_output);
					return;
				}
				$this->load->view('produk/kirim_invoice',$data);
				}else{
				$data['cetak'] = 'error';
				$this->load->view('errors/404',$data);
			}
			
		}
		
		public function desktop(){
			$seo = $this->uri->segment(2);
			$noid = decrypt_url($seo);
			$id = array('id_invoice' => $noid);
			$pub = array('pub' =>1);//printer aktif
			$where = ["id_invoice" => $noid];
			$id_konsumen = $this->model_app->pilih_where("id_konsumen","invoice", $where)->row()->id_konsumen;
			//$this->cek_boleh_utang($id_konsumen,$noid);
			$search = $this->model_app->view_where('invoice', $id);
			
			if($search->num_rows()>0){
				//icon
				$data['waicon'] 	= ['color'=>base_url().'assets/img/wa_icon.png','bw'=>base_url().'assets/img/wa_icon_bw.png'];
				$data['mail'] 		= ['color'=>base_url().'assets/img/gmail_icon.png','bw'=>base_url().'assets/img/gmail_icon_bw.png'];
				$data['fbicon'] 	= ['color'=>base_url().'assets/img/fb_icon.png','bw'=>base_url().'assets/img/fb_icon_bw.png'];
				$data['igicon'] 	= ['color'=>base_url().'assets/img/ig_icon.png','bw'=>base_url().'assets/img/ig_icon_bw.png'];
				
				$data['logo_lunas'] = base_url().'uploads/'.info()['logo'];
				$data['logo_blunas'] = base_url().'uploads/'.info()['logo_bw'];
				$data['lunas'] = base_url().'uploads/'.info()['stamp_l'];
				$data['blunas'] = base_url().'uploads/'.info()['stamp_b'];
				$data['favicon'] = base_url().'uploads/'.info()['favicon'];
				
				$data['html'] = 'Y';
				
				$pub = array('pub' =>1);//printer aktif
				$cek_printer = $this->model_app->view_where('printer', $pub);
				$rowc = $cek_printer->row_array();
				
				$data['ukuran'] =$rowc['ukuran_kertas'];
				$data['font_size'] =$rowc['ukuran_font'];
				$data['font_wight'] = 'normal';
				
				$row = $search->row();
				$jml =$row->cetak+1;
				$this->model_app->update('tb_users', array("last_invoice"=>0),array('id_user'=>$this->session->idu));
				if($row->status!='batal'){
					$this->model_app->update('invoice',array('cetak'=>$jml,'status'=>'simpan','pos'=>'Y','oto'=>6),array('id_invoice'=>$noid));
				}
				//cek sisa
				$_total = 'ROUND(SUM((`invoice_detail`.`jumlah` * harga) - (`invoice_detail`.`jumlah` * harga) * (`invoice_detail`.`diskon`/100))) AS sisa';
				$cari_total= $this->model_app->cek_total('invoice_detail',$_total,array('id_invoice'=>$noid));
				$data['sisanya'] = $cari_total->sisa;
				//
				$data['cetak'] = $row;
				$data['info'] = info();
				$konsumen = $this->model_app->view_where('konsumen', array('id' => $row->id_konsumen))->row_array();
				
				if($konsumen['max_utang'] >0 AND $jml <=1){
					$max_utang = $konsumen['max_utang'] - 1;
					$this->model_app->update('konsumen',array('max_utang'=>$max_utang),array('id'=>$row->id_konsumen));
				}
				
				$data['konsumen']    = $konsumen;
				$data['marketing']   = $this->model_app->view_where('tb_users', array('id_user' => $row->id_marketing))->row_array();
				$data['detail']      = $this->model_app->produk_cart(array('invoice_detail.id_invoice' => $noid));
				$data['total']       =$this->model_app->total_bayar(array('bayar_invoice_detail.id_invoice'=>$noid))->row();
				$select = 'pajak,potongan_harga,cashback, total_bayar AS total, jumlah_bayar, kembalian';
				$where               = array('id_invoice'=>$noid);
				$tdetail             = $this->model_app->cek_total('invoice',$select,$where);
				$data['tdetail']     = $tdetail->total;
				$data['pajak']       = $tdetail->pajak;
				$data['jumlah_bayar'] = $tdetail->jumlah_bayar;
				$data['potongan_harga'] = $tdetail->potongan_harga;
				$data['cashback'] = $tdetail->cashback;
				$data['kembalian'] = $tdetail->kembalian;
				$_diskon             = 'SUM(diskon) AS `disc`';
				$cdiskon             = $this->model_app->cek_total('invoice_detail',$_diskon,$where);
				$data['cdiskon']     = $cdiskon->disc;
				$_select             = 'COUNT(id) AS `jml`';
				$cdetail             = $this->model_app->cek_total('bayar_invoice_detail',$_select,$where);
				$data['cdetail']     = $cdetail->jml;
				//bayar detail
				$data['bdetail']     = $this->model_app->view_where('bayar_invoice_detail', $id)->result_array();
				///
				$data['cara']        = $this->model_app->cara_bayar(array('`jenis_bayar`.`publish`'=>'Y','`bayar_invoice_detail`.`id_invoice`' => $noid));
				$data['bank']        = $this->model_app->view_where('rekening_bank',['footer_invoice'=>1,'publish'=>'Y'])->result();
				
				$this->load->view('produk/kirim_invoice_desktop',$data);
				}else{
				$data['cetak'] = 'error';
				$this->load->view('errors/404',$data);
			}
			
		}
		
		private function cek_boleh_utang($id_konsumen,$id_invoice)
		{
			$max_utang = $this->model_app
			->pilih_where("max_utang,status","konsumen", ["id" => $id_konsumen])
			->row();
			
			$cek_bayar = $this->model_app->cek_total("bayar_invoice_detail","SUM(jml_bayar) AS `total`",['id_invoice'=>$id_invoice]);
			
			if ($max_utang->max_utang == 0 AND $max_utang->status==0 AND $cek_bayar->total ==0) {
				$data = ["status" => 'harus_dp', "id" => $id_invoice, "msg" => 'Belum ada pembayaran'];
				$this->output
				->set_content_type('application/json', 'utf-8')
				->set_output(json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
				->_display();
				exit;
			}
		}
		
	}				
