<?php namespace App\Http\Controllers;

use App\Models\Petaktebang;
use App\Library\DataHelpers;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ; 

class PetaktebangController extends Controller {

	protected $layout = "layouts.main";
	protected $data = array();	
	public $module = 'petaktebang';
	static $per_page	= '10';
	
	public function __construct() 
	{
		parent::__construct();
		$this->model = new Petaktebang();
		
		$this->info = $this->model->makeInfo( $this->module);
		$this->access = $this->model->validAccess($this->info['id']);
	
		$this->data = array(
			'pageTitle'			=> 	$this->info['title'],
			'pageNote'			=>  $this->info['note'],
			'pageModule'		=> 'petaktebang',
			'pageUrl'			=>  url('petaktebang'),
			'return' 			=> 	self::returnUrl()	
		);	
			
				
	} 
	public function index()
	{
		if(!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');

		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));
		if($this->access['is_view'] ==0) 
			return redirect('dashboard')->with('message',__('core.note_restric'))->with('status','error');
		
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['tableForm'] 	= $this->info['config']['forms'];
		$this->data['tableGrid'] 	= $this->info['config']['grid'];
		usort($this->data['tableGrid'], "SiteHelpers::_sort");
			$cols = '{"data":"rowId"},';
			if($this->data['setting']['view-method'] =='expand'){
				$cols .= '{"className": "details-control","orderable": false,"data": null,"defaultContent": ""},';
			}		
				
			foreach($this->data['tableGrid'] as $field)
			{				
				
				if($field['view'] =='1')
				{
					$cols .= '{"data":"'.$field['field'].'"},';
				}						
			}
			$cols .= '{"data":"action"},';
		$this->data['column'] = $cols ;	
		$this->data['access']		= $this->access;	
		$this->data['setting'] 		= $this->info['setting'];
		return view('petaktebang.index',$this->data);
	}
	function create( Request $request ) 
	{
		$this->hook( $request  );
		if($this->access['is_add'] ==0) 
			return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');

		$this->data['row'] = $this->model->getColumnTable( $this->info['table']); 
		
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['id'] = '';
		return view($this->module.'.form',$this->data);
	}
	function edit( Request $request , $id ) 
	{
		$this->hook( $request , $id );
		if(!isset($this->data['row']))
			return redirect($this->module)->with('message','Record Not Found !')->with('status','error');
		if($this->access['is_edit'] ==0 )
			return redirect('dashboard')->with('message',__('core.note_restric'))->with('status','error');
		$this->data['row'] = (array) $this->data['row'];
		
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['id'] = $id;
		return view($this->module.'.form',$this->data);
	}
	function show( Request $request , $id ) 
	{
		/* Handle import , export and view */
		$task =$id ;
		switch( $task)
		{
			case 'search':
				return $this->getSearch();
				break;
			case 'lookup':
				return $this->getLookup($request );
				break;
			case 'comboselect':
				return $this->getComboselect( $request );
				break;
			case 'import':
				return $this->getImport( $request );
			case 'removefiles':
				return $this->getRemovefiles( $request );	
				break;
			case 'export':
				return $this->getExport( $request );
				break;
			case 'download':
				return $this->getDownload( $request );
				break;	
			case 'getLuasTertebangByKebun':
				return $this->getLuasTertebangByKebun( $request );
				break;
			case 'monitoringluasan':
				return $this->monitoringluasan( $request );
				break;
			case 'insertAffTebang':
				return $this->insertAffTebang( $request );
				break;
			case 'rekaptimbangan':
				return $this->rekaptimbangan($request );
				break;
			case 'rekaptimbanganspta':
				return $this->rekaptimbanganspta($request );
				break;	
			case 'getRekapTimbanganSpta':
				return $this->getRekapTimbanganSpta( $request );
				break;
			case 'rekaptimbanganmandor':
				return $this->rekaptimbanganmandor($request );
				break;
			case 'getRekapTimbanganMandor':
				return $this->getRekapTimbanganMandor( $request );
				break;		
			case 'getRekapTimbangan':
				return $this->getRekapTimbangan($request );
				break;
			case 'rekaptimbangankebunsd':
				return $this->rekaptimbangankebunsd($request );
				break;
			case 'getRekapTimbanganKebun':
				return $this->getRekapTimbanganKebun( $request );
				break;
			case 'rekaptimbanganpetaksd':
				return $this->rekaptimbanganpetaksd($request );
				break;
			case 'getRekapTimbanganPetak':
				return $this->getRekapTimbanganPetak( $request );
				break;
			case 'consolespta':
				return $this->consolespta( $request );
				break;
			case 'getConsoleSpta':
				return $this->getConsoleSpta( $request );
				break;	
			case 'rekaptimbangannopg':
				return $this->rekaptimbangannopg($request );
				break;
			case 'getRekapTimbangannopg':
				return $this->getRekapTimbangannopg( $request );
				break;
			case 'rekaptimbanganmejamutu':
				return $this->rekaptimbanganmejamutu($request );
				break;
			case 'getRekapmejatebumutuAfdeling':
				return $this->getRekapmejatebumutuAfdeling( $request );
				break;
			case 'rekaptimbanganmejamutuqadirops':
				return $this->rekaptimbanganmejamutuqadirops($request );
				break;	
			case 'getRekapmejatebumutuAfdelingQadirops':
				return $this->getRekapmejatebumutuAfdelingQadirops( $request );
				break;
			case 'rekapposperjenistebang':
				return $this->rekapposperjenistebang($request );
				break;
			case 'getRekapPosperJenisTebang':
				return $this->getRekapPosperJenisTebang( $request );
				break;		
			case 'rekaptimbanganpetaksdaff':
				return $this->rekaptimbanganpetaksdaff($request );
				break;
			case 'getRekapTimbanganPetakSdAff':
				return $this->getRekapTimbanganPetakSdAff( $request );
				break;
			case 'rekaptimbanganmejamutuKlentek':
				return $this->rekaptimbanganmejamutuKlentek($request );
				break;
			case 'getRekapmejatebumutuAfdelingKlentek':
				return $this->getRekapmejatebumutuAfdelingKlentek( $request );
				break;
			case 'realthninivsthnlaluhgsama':
				return $this->realthninivsthnlaluhgsama($request );
				break;
			case 'getRealtahuninivstahunlaluhgsama':
				return $this->getRealtahuninivstahunlaluhgsama($request );
				break;
			case 'rekaptimbanganrayonsdnonpg':
				return $this->rekaptimbanganrayonsdnonpg($request );
				break;
			case 'getRekapTimbanganRayonSdNonpg':
				return $this->getRekapTimbanganRayonSdNonpg( $request );
				break;
			case 'rekaptimbangankebunsdnonpg':
				return $this->rekaptimbangankebunsdnonpg($request );
				break;
			case 'getRekapTimbanganKebunSdNonpg':
				return $this->getRekapTimbanganKebunSdNonpg( $request );
				break;
			case 'consoleprodiskebun':
				return $this->consoleprodiskebun( $request );
				break;
			case 'getconsoledata':
				return $this->getconsoledata( $request );
				break;
			case 'consoleprodiskebunall':
				return $this->consoleprodiskebunall( $request );
				break;
			case 'getconsoledataall':
				return $this->getconsoledataall( $request );
				break;
			case 'rekaptimbanganmejamutu2':
				return $this->rekaptimbanganmejamutu2($request );
				break;
			case 'getRekapmejatebumutu2':
				return $this->getRekapmejatebumutu2( $request );
				break;
			case 'monitoringcuttocrush':
				return $this->monitoringcuttocrush( $request );
				break;
			case 'getMonitoringCuttocrush':
				return $this->getMonitoringCuttocrush( $request );
				break;
			case 'formMonitoringPos2VsPos1':
				return $this->formMonitoringPos2VsPos1( $request );
				break;
			case 'getMonitoringPos2VsPos1':
				return $this->getMonitoringPos2VsPos1( $request );
				break;
			case 'rekaptakmarpetak':
				return $this->rekaptakmarpetak($request );
				break;
			case 'getRekaptakmarpetak':
				return $this->getRekaptakmarpetak($request );
				break;
			case 'cashcostksoPeriodikPetak':
				return $this->cashcostksoPeriodikPetak($request );
				break;
			case 'getCashcostksoPeriodikPetak':
				return $this->getCashcostksoPeriodikPetak($request );
				break;
			case 'formSasaranPasokHarianPivot':
				return $this->formSasaranPasokHarianPivot($request );
				break;
			case 'getSasaranpasokharian':
				return $this->getSasaranpasokharian($request );
				break;
			case 'cashcostksoPeriodikRekap':
				return $this->cashcostksoPeriodikRekap($request );
				break;
			case 'getCashcostksoPeriodikRekap':
				return $this->getCashcostksoPeriodikRekap($request );
				break;
			case 'cashcostksoPeriodikDashboard':
				return $this->cashcostksoPeriodikDashboard($request );
				break;
			case 'getCashcostksoPeriodikDashboard':
				return $this->getCashcostksoPeriodikDashboard($request );
				break;
			case 'cashcostksoPeriodikRekapDashboard':
				return $this->cashcostksoPeriodikRekapDashboard($request );
				break;
			case 'formConsoleSptaRayonPg':
				return $this->formConsoleSptaRayonPg($request );
				break;
			case 'getConsoleSptaRayonPg':
				return $this->getConsoleSptaRayonPg($request );
				break;
			case 'formRealnowvsoldTglSama':
				return $this->formRealnowvsoldTglSama($request );
				break;
			case 'getRealnowvsoldTglSama':
				return $this->getRealnowvsoldTglSama($request );
				break;
			case 'formRealnowvsoldTglSamaSpta':
				return $this->formRealnowvsoldTglSamaSpta($request );
				break;
			case 'getRealnowvsoldTglSamaSpta':
				return $this->getRealnowvsoldTglSamaSpta($request );
				break;
			default:
				$this->hook( $request , $id );
				if(!isset($this->data['row']))
					return redirect($this->module)->with('message','Record Not Found !')->with('status','error');

				if($this->access['is_detail'] ==0) 
					return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');

				return view($this->module.'.view',$this->data);	
				break;		
		}
	}	
	public function store( Request $request){

		$task = $request->input('action_task');
		switch ($task)
		{
			default:
				return $this->postData( $request);
				break;
			case 'save':
				$rules = $this->validateForm();
				$validator = Validator::make($request->all(), $rules);
				if ($validator->passes()) 
				{
					$data = $this->validatePost( $request );
					$data['vendor_gl'] = $request->input('vendor_gl', '');
					$id = $this->model->insertRow($data , $request->input( $this->info['key']));
					
					/* Insert logs */
					$this->model->logs($request , $id);
					return response()->json(array('status'=>'success','message'=> __('core.note_success')));	
					
				} 
				else {
					$message = $this->validateListError(  $validator->getMessageBag()->toArray() );
					return response()->json(array(
						'message'	=> $message,
						'status'	=> 'error'
					));	
				}
				break;
			case 'delete':
				return $result = $this->destroy( $request );
				break;

			case 'import':
				return $this->PostImport( $request );
				break;

			case 'copy':
				$result = $this->copy( $request );
				return response()->json($result);
				break;		

		}
	}
	public function postData( $request)
	{ 
		config(['app.debug' => true]);
		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));

		$tables 	= $this->info['config']['grid'];
		$cols = array();
		foreach($tables as $field)
		{				
			//$cols[$this->info['key']]	= array('db'=> $field['alias'] ,$this->info['key'] );
			if($field['view'] =='1')
			{
				$cols[] = array('db'=> $field['alias'],'dt'=> $field['field'] );
			}					
		}
		$conf = DataHelpers::simple($request->all(),$cols);
		$filter =  '';
		if(!is_null($request->input('search')))
		{
			$filter .= $this->liveSearch( $request);
		}

		if(!is_null($request->input('date_from')) && !is_null($request->input('date_to')))
		{
			$from = date('Y-m-d', strtotime($request->input('date_from')));
			$to = date('Y-m-d', strtotime($request->input('date_to')));
			$filter .= " AND DATE(tanggal) BETWEEN '".$from."' AND '".$to."' ";
		}
		if(!is_null($request->input('filter_kebun')))
		{
			$kebun = $request->input('filter_kebun');
			$filter .= " AND left(tx_ajuan_tebang.rayon, 4) = '".$kebun."' ";
		}

		if(!is_null($request->input('filter_rayon')))
		{
			$rayon = $request->input('filter_rayon');
			$filter .= " AND tx_ajuan_tebang.rayon = '".$rayon."' ";
		}

		if(session('gid') != 1 && session('gid') != 2){
			$filter .= " AND left(tx_ajuan_tebang.rayon, 4) = '".session('fid')."' ";
		}

		$conf['order']['sort'] = ' id ';
		$conf['order']['by'] =  ' desc';


		$params = array(
			'page'		=> $conf['page'] ,
			'limit'		=> $conf['limit'] ,
			'sort'		=> ($conf['order']['sort'] !='' ? $conf['order']['sort'] : $this->info['setting']['orderby']) ,
			'order'		=> ($conf['order']['by'] !='' ? $conf['order']['by'] : $this->info['setting']['ordertype']),
			'params'	=> $filter,
			'global'	=> (isset($this->access['is_global']) ? $this->access['is_global'] : 0 )
		);


		$results = $this->model->getRows($params);
		
		$array = array();
		foreach($results['rows'] as $row)
		{
			$values = array();
			$values['rowId'] = $row->{$this->info['key']};
			foreach($tables as $field)
			{			
				
				if($field['view'] =='1')
				{
					config(['app.debug' => true]);
					$getbooking = \DB::table('tx_pos_keluar')->where('kode_booking', $row->nomor_booking)->select('kode_booking','spta')->first();
					if(!empty($getbooking->spta)) {
						$nodok = \DB::table('tx_upah_tebang_tma_detail')->where('no_spta', $getbooking->spta)->select('no_dokumen')->first();
						$nodok2 = \DB::table('tx_upah_angkutan_tma_detail')->where('no_spta', $getbooking->spta)->select('no_dokumen')->first();
						$nodok3 = \DB::table('tx_upah_angkutan_gl_tma_detail')->where('no_spta', $getbooking->spta)->select('no_dokumen')->first();
					}
					if($field['field'] == 'nomor_booking')
					{
							$values[$field['field']] = '<span class="text-success font-bold"><i class="fa fa-qrcode"></i> '.$row->nomor_booking . '</span>';
					}else if($field['field'] == 'thntnm')
					{						
						if(!empty($getbooking->kode_booking)) {
							$getselektor = \DB::table('data_selektor')->where('no_spta', $getbooking->spta)->select('no_spta')->first();
							$selektor = '';
							if(!empty($getselektor->no_spta)) {
								$selektor = '<br><span class="text-info font-bold"><i class="fa fa-check"></i> Pos Selektor</span>';
							} 
							$values[$field['field']] = '<span class="text-success font-bold"><i class="fa fa-check"></i> Pos Keluar</span>'.$selektor;
						} else {
							$values[$field['field']] = '<span class="text-danger font-bold"><i class="fa fa-times"></i> Belum Pos Keluar</span>';
						}
					}else if($field['field'] == 'foto_kendaraan'){
						$values[$field['field']] = '<a href="#" class="previewImage"><img src="https://difa.ksotebu.com/' . $row->foto_kendaraan . '" border="0" width="50" class="img-circle avatar" style="margin-right:2px;" /></a>';
					}else if($field['field'] == 'updatedOn'){
						//menampilkan status sudah di upah dengan no dokumen
						$values[$field['field']] = '';
						if(!empty($nodok->no_dokumen) || !empty($nodok2->no_dokumen)) {
							if(!empty($nodok->no_dokumen)) {
								$values[$field['field']] .= '<span class="text-success font-bold"><i class="fa fa-check"></i> Upah Tebang (' . $nodok->no_dokumen . ')</span>';
							}
							if(!empty($nodok2->no_dokumen)) {
								$values[$field['field']] .= '<br><span class="text-success font-bold"><i class="fa fa-check"></i> Upah Angkut (' . $nodok2->no_dokumen . ')</span>';
							}
							if(!empty($nodok3->no_dokumen)) {
								$values[$field['field']] .= '<br><span class="text-success font-bold"><i class="fa fa-check"></i> Upah Angkut GL (' . $nodok3->no_dokumen . ')</span>';
							}
						} else {
							$values[$field['field']] = '<span class="text-danger font-bold"><i class="fa fa-times"></i> Belum di Upah</span>';
						}
					}else{
						$values[$field['field']] = \SiteHelpers::formatRows($row->{$field['field']}, $field , $row);
					}
					
				}	
			}
			$values['action'] =  \SiteHelpers::buttonAction($this->module,$this->access ,$row->{$this->info['key']} ,$this->info['setting']) ;
			$array[] = $values; 	
		}
		
		$data = array(
			'draw'			=> (!is_null($request->input('draw')) ? intval($request->input('draw') ) : 0), 
			'recordsTotal'	=> $results['total'] ,
			'recordsFiltered'	=> $results['total'],
			'data'				=> $array

		);
		return response()->json($data);
	}

	public function getDownload( Request $request)
	{
		if($request->has('filter'))
			return $this->getExpotion();

		$t = $request->input('do');
		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));

		if(isset($this->access['is_'.$t]) ){
			if($this->access['is_'.$t] == 0 )
				return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');
		} else {
			return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');
		}

		$info 		= $this->model->makeInfo( $this->module);
		$filter = ' ';	

		if($request->input('date_from') !='' && $request->input('date_to') !='')
		{
			$from = date('Y-m-d', strtotime($request->input('date_from')));
			$to = date('Y-m-d', strtotime($request->input('date_to')));
			$filter .= " AND DATE(tanggal) BETWEEN '".$from."' AND '".$to."' ";
		}

		if($request->input('kebun') !='')
		{
			$kebun = $request->input('kebun');
			$filter .= " AND left(tx_ajuan_tebang.rayon, 4) = '".$kebun."' ";
		}

		if($request->input('rayon') !='')
		{
			$rayon = $request->input('rayon');
			$filter .= " AND tx_ajuan_tebang.rayon = '".$rayon."' ";
		}
		
		$params 	= array(
					'params'	=> $filter ,
					'limit'	=> 1000,

					'fstart'  => $request->input('fstart'),
    				'flimit'  => $request->input('flimit') 
		);		


		$results 	= $this->model->getRows( $params );
		$fields		= $info['config']['grid'];		
		$rows		= $results['rows'];

		$content 	= array(
						'fields' => $fields,
						'rows' => $rows,
						'title' => $this->data['pageTitle'],
					);
		
		
			 return view('sximo.module.utility.excel',$content);
			
	}		

	public function destroy( Request $request)
	{

		if(!\Auth::check()) 
			return response()->json(array(
				'status'=>'error',
				'message'=> 'You are not login'
			));

		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));
		if($this->access['is_remove'] ==0) 
			return response()->json(array('status'=>'error','message'=> __('core.note_restric')));	


		// delete multipe rows 
		if(count($request->input('ids')) >=1)
		{
			$this->model->destroy($request->input('ids'));
			
			return response()->json(array(
				'status'=>'success',
				'message'=> __('core.note_success_delete')
			));
		} else {
			return response()->json(array(
				'status'=>'error',
				'message'=> __('core.note_error')
			));

		} 		

	}

	public function monitoringluasan(){
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Monitoring Luas Tertebang Per Kebun';
		$this->data['pageNote'] = 'Menampilkan data luas tertebang berdasarkan kebun dari tabel TAKDES dan PETAK TEBANG';
		return view('petaktebang.monitoringluas',$this->data);
	}
	public function getLuasTertebangByKebun(Request $request)
	{
		config(['app.debug' => true]);
		if(session('gid') != 1){
			$kodeKebun = session('fid');
		}else{
			$kodeKebun = $request->input('kode_kebun',null);
		}
		
		$page = $request->input('page', 1);
		$perPage = $request->input('per_page', 10);
		$offset = ($page - 1) * $perPage;
		$searchLahanId = $request->input('search_lahan_id', null);

		$query = \DB::table('q_takdes_petak as a')
			->join('tx_petak_tebang as b', 'a.lahan_id', '=', 'b.id_petak')
			->select(
				'a.cluster',
				'a.nama_kebun',
				'a.nama_rayon',
				'a.lahan_id',
				'a.afdeling',
				'a.luas_poligon',
				\DB::raw('ROUND(SUM(b.luas_tebang),3) as luas_tertebang')
			)
			->when($kodeKebun, function ($query, $kodeKebun) {
				return $query->where('a.kode_kebun', $kodeKebun);
			})
			->when($searchLahanId, function ($query, $searchLahanId) {
				return $query->where('a.lahan_id', 'LIKE', '%' . $searchLahanId . '%');
			})
			->groupBy('a.lahan_id');

		$total = $query->get()->count();
		$results = $query->offset($offset)->limit($perPage)->get();
		
		$totalPages = ceil($total / $perPage);

		// Tambahkan CSS inline untuk membuat tabel lebih menarik dan berwarna
		$html = '
		<div id="monitoring-result">
		<style>
			.monitoring-table-container {
				max-height: 600px;
				overflow-y: auto;
				position: relative;
			}
			.monitoring-table {
			width: 100%;
			border-collapse: collapse;
			font-size: 14px;
			}
			.monitoring-table th, .monitoring-table td {
			border: 1px solid #dee2e6;
			padding: 8px 10px;
			text-align: center;
			}
			.monitoring-table thead {
			background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
			color: #fff;
			position: sticky;
			top: 0;
			z-index: 10;
			}
			.monitoring-table tbody tr:nth-child(even) {
			background-color: #f8f9fc;
			}
			.monitoring-table tbody tr:hover {
			background-color: #e2eafc;
			}
			.luas-tertebang {
			color: #1cc88a;
			font-weight: bold;
			}
			.prosentase {
			font-weight: bold;
			}
			.sisa-luas {
			color: #e74a3b;
			font-weight: bold;
			}
			.progress-bar-container {
				background: #e9ecef;
				border-radius: 8px;
				overflow: hidden;
				height: 18px;
				width: 100px;
				margin: 0 auto;
			}
			.progress-bar {
				height: 100%;
				transition: width 0.5s, background 0.5s;
				color: #fff;
				font-size: 12px;
				line-height: 18px;
				text-align: center;
				font-weight: bold;
			}
			.btn-aff-tebang {
				background: #4e73df;
				color: #fff;
				border: none;
				border-radius: 4px;
				padding: 5px 12px;
				cursor: pointer;
				font-size: 13px;
				transition: background 0.2s;
			}
			.btn-aff-tebang:hover {
				background: #224abe;
			}
			.pagination-container {
				display: flex;
				justify-content: center;
				align-items: center;
				margin-top: 15px;
				gap: 5px;
			}
			.pagination-btn {
				background: #4e73df;
				color: #fff;
				border: none;
				border-radius: 4px;
				padding: 8px 12px;
				cursor: pointer;
				font-size: 13px;
				transition: background 0.2s;
			}
			.pagination-btn:hover {
				background: #224abe;
			}
			.pagination-btn:disabled {
				background: #ccc;
				cursor: not-allowed;
			}
			.pagination-btn.active {
				background: #1cc88a;
			}
			.pagination-info {
				margin: 0 10px;
				font-size: 14px;
			}
			.per-page-select {
				padding: 5px 10px;
				border-radius: 4px;
				border: 1px solid #dee2e6;
				margin-left: 10px;
			}
			.search-container {
				display: flex;
				justify-content: flex-end;
				margin-bottom: 15px;
				gap: 10px;
			}
			.search-input {
				padding: 8px 12px;
				border-radius: 4px;
				border: 1px solid #dee2e6;
				font-size: 14px;
				width: 250px;
			}
			.search-btn {
				background: #4e73df;
				color: #fff;
				border: none;
				border-radius: 4px;
				padding: 8px 16px;
				cursor: pointer;
				font-size: 14px;
				transition: background 0.2s;
			}
			.search-btn:hover {
				background: #224abe;
			}
		</style>
		<div class="search-container">
			<input type="text" class="search-input" id="search_lahan_id" placeholder="Cari Lahan ID..." value="'.htmlspecialchars($searchLahanId ?? '').'">
			<button class="search-btn" onclick="searchLahanId()"><i class="fa fa-search"></i> Cari</button>
		</div>
		<div class="monitoring-table-container" >
		<table class="monitoring-table">
			<thead>
			<tr>
				<th>Cluster</th>
				<th>Nama Kebun</th>
				<th>Nama Rayon</th>
				<th>Lahan ID</th>
				<th>Afdeling</th>
				<th>Luas Poligon</th>
				<th>Luas Tertebang</th>
				<th>Prosentase Tertebang (%)</th>
				<th>Sisa Luas</th>
				<th>AFF Tebang</th>
			</tr>
			</thead>
			<tbody>
		';

		// Fungsi untuk mendapatkan warna gradient dari hijau (0%) ke kuning (50%) ke merah (100%)
		function getGradientColor($percent) {
			// Clamp percent
			$percent = max(0, min(100, $percent));
			if ($percent <= 50) {
				// Hijau ke Kuning
				$r = intval(28 + (246 - 28) * ($percent / 50)); // 28->246
				$g = intval(200 + (194 - 200) * ($percent / 50)); // 200->194
				$b = intval(138 + (62 - 138) * ($percent / 50)); // 138->62
			} else {
				// Kuning ke Merah
				$r = intval(246 + (231 - 246) * (($percent - 50) / 50)); // 246->231
				$g = intval(194 + (74 - 194) * (($percent - 50) / 50)); // 194->74
				$b = intval(62 + (59 - 62) * (($percent - 50) / 50)); // 62->59
			}
			return sprintf("rgb(%d,%d,%d)", $r, $g, $b);
		}

		foreach ($results as $row) {
			$luas_poligon = floatval($row->luas_poligon);
			$luas_tertebang = floatval($row->luas_tertebang);
			$prosentase = $luas_poligon > 0 ? round(($luas_tertebang / $luas_poligon) * 100, 2) : 0;
			$sisa_luas = round($luas_poligon - $luas_tertebang, 3);

			$barColor = getGradientColor($prosentase);

			$progressBar = '
				<div class="progress-bar-container">
					<div class="progress-bar" style="width: '.$prosentase.'%; background: '.$barColor.';">'.$prosentase.'%</div>
				</div>
			';

			// Tombol AFF Tebang
			$btnAffTebang = '<button class="btn-aff-tebang" data-lahanid="'.htmlspecialchars($row->lahan_id).'" onclick="insertAffTebang(\''.htmlspecialchars($row->lahan_id).'\')">AFF Tebang</button>';
			$affStatus = \DB::table('tx_afftebang_tma')->where('lahan_id', $row->lahan_id)->first();
			if ($affStatus && $affStatus->aff == 1) {
				$btnAffTebang= '<br><span class="badge" style="background:#1cc88a;color:#fff;padding:4px 8px;border-radius:4px;">Sudah AFF</span><br><span class="text-info font-bold"><i class="fa fa-check"></i> Tanggal AFF: '.date('d M Y', strtotime($affStatus->tgl_aff)).'</span>';
			}

			$html .= '<tr>
			<td>' . htmlspecialchars($row->cluster) . '</td>
			<td>' . htmlspecialchars($row->nama_kebun) . '</td>
			<td>' . htmlspecialchars($row->nama_rayon) . '</td>
			<td>' . htmlspecialchars($row->lahan_id) . '</td>
			<td>' . htmlspecialchars($row->afdeling) . '</td>
			<td>' . htmlspecialchars(number_format($row->luas_poligon, 3)) . '</td>
			<td class="luas-tertebang">' . htmlspecialchars(number_format($row->luas_tertebang, 3)) . '</td>
			<td class="prosentase">' . $progressBar . '</td>
			<td class="sisa-luas">' . number_format($sisa_luas, 3) . '</td>
			<td>' . $btnAffTebang . '</td>
			</tr>';
		}

		$html .= '</tbody></table></div>';

		// Pagination
		$html .= '<div class="pagination-container">';
		$html .= '<button class="pagination-btn" onclick="goToPage(1)" '.($page == 1 ? 'disabled' : '').'>«</button>';
		$html .= '<button class="pagination-btn" onclick="goToPage('.($page - 1).')" '.($page == 1 ? 'disabled' : '').'>&lt;</button>';
		
		// Show page numbers
		$startPage = max(1, $page - 2);
		$endPage = min($totalPages, $page + 2);
		
		for ($i = $startPage; $i <= $endPage; $i++) {
			$html .= '<button class="pagination-btn '.($i == $page ? 'active' : '').'" onclick="goToPage('.$i.')">'.$i.'</button>';
		}
		
		$html .= '<button class="pagination-btn" onclick="goToPage('.($page + 1).')" '.($page >= $totalPages ? 'disabled' : '').'>&gt;</button>';
		$html .= '<button class="pagination-btn" onclick="goToPage('.$totalPages.')" '.($page >= $totalPages ? 'disabled' : '').'">»</button>';
		$html .= '<span class="pagination-info">Halaman '.$page.' dari '.$totalPages.' | Total: '.$total.' data</span>';
		$html .= '<select class="per-page-select" onchange="changePerPage(this.value)">';
		$html .= '<option value="10" '.($perPage == 10 ? 'selected' : '').'>10 per halaman</option>';
		$html .= '<option value="25" '.($perPage == 25 ? 'selected' : '').'>25 per halaman</option>';
		$html .= '<option value="50" '.($perPage == 50 ? 'selected' : '').'>50 per halaman</option>';
		$html .= '<option value="100" '.($perPage == 100 ? 'selected' : '').'>100 per halaman</option>';
		$html .= '</select>';
		$html .= '</div>';

		// Script JS untuk pagination dan search
		$html .= '
		<script>
			var currentPage = '.$page.';
			var currentPerPage = '.$perPage.';
			var currentSearchLahanId = "'.addslashes($searchLahanId ?? '').'";
			
			function goToPage(page) {
				if (page < 1 || page > '.$totalPages.') return;
				loadLuasTertebang(page, currentPerPage, currentSearchLahanId);
			}
			
			function changePerPage(perPage) {
				currentPerPage = perPage;
				loadLuasTertebang(1, perPage, currentSearchLahanId);
			}
			
			function searchLahanId() {
				var searchValue = $("#search_lahan_id").val() || "";
				currentSearchLahanId = searchValue;
				loadLuasTertebang(1, currentPerPage, searchValue);
			}
			
			// Enter key untuk search
			$(document).off("keypress", "#search_lahan_id").on("keypress", "#search_lahan_id", function(e) {
				if (e.which == 13) {
					searchLahanId();
				}
			});
			
			function loadLuasTertebang(page, perPage, searchLahanId) {
				$("#monitoring-result").html(`
					<div style="text-align:center;padding:60px 20px;background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);border-radius:12px;box-shadow:0 10px 30px rgba(0,0,0,0.2);">
						<div style="position:relative;width:80px;height:80px;margin:0 auto 20px;">
							<div style="position:absolute;width:80px;height:80px;border:8px solid rgba(255,255,255,0.2);border-radius:50%;"></div>
							<div style="position:absolute;width:80px;height:80px;border:8px solid transparent;border-top-color:#fff;border-radius:50%;animation:spin 1s linear infinite;"></div>
						</div>
						<h3 style="color:#fff;font-size:20px;font-weight:600;margin:0 0 10px 0;text-shadow:0 2px 4px rgba(0,0,0,0.2);">Memuat Data</h3>
						<p style="color:rgba(255,255,255,0.9);font-size:14px;margin:0;">Mohon tunggu sebentar...</p>
					</div>
					<style>
						@keyframes spin {
							0% { transform: rotate(0deg); }
							100% { transform: rotate(360deg); }
						}
					</style>
				`);
				var kodeKebun = $("#kode_kebun").val() || "";
				$.ajax({
					url: "'.url('petaktebang/getLuasTertebangByKebun').'",
					type: "GET",
					data: {
						kode_kebun: kodeKebun,
						page: page,
						per_page: perPage,
						search_lahan_id: searchLahanId
					},
					success: function(response) {
						$("#monitoring-result").html(response);
					}
				});
			}
		</script></div>
		';

		return response($html);
	}

	public function insertAffTebang(Request $request)
	{
		$lahanId = $request->input('lahan_id');
		$tanggal_aff = $request->input('tanggal_aff');
		if (!$lahanId) {
			return response()->json(['status' => 'error', 'message' => 'Lahan ID tidak ditemukan.']);
		}

		try {
			\DB::table('tx_afftebang_tma')->insert([
				'lahan_id' => $lahanId,
				'tgl_aff' => $tanggal_aff,
				'aff' => 1
			]);
			return response()->json(['status' => 'success', 'message' => 'Data berhasil disimpan.']);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal menyimpan data.']);
		}
	}

	public function rekaptimbanganspta(){
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Rekap Timbangan SPTA';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi timbangan SPTA berdasarkan kebun dan rentang tanggal';
		return view('petaktebang.rekaptimbanganspta',$this->data);
	}
	public function getRekapTimbanganSpta(Request $request)
	{
		$jenis = $request->input('jenis', null);
		$kebun = $request->input('kebun', null);
		$rayon = $request->input('rayon', null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');
		$pg = $request->input('pg', null);

		if (!$dateFrom || !$dateTo) {
			return response()->json(['status' => 'error', 'message' => 'Parameter kebun, rayon, date_from, dan date_to wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_rekap_timbangan_spta(?, ?, ?, ?, ?, ?)', [$kebun, $rayon, $pg,$dateFrom, $dateTo, $jenis]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
					white-space: nowrap;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';

			if (!empty($results)) {
				$columns = array_keys((array)$results[0]);
				foreach ($columns as $index => $column) {
					// Starting from column 36 (index 35), map to master_upah_potongan descriptions
					if ($index >= 35) {
						$mappedName = \DB::table('master_upah_potongan')
							->where('tebang', $jenis)
							->where('kode_kebun', $kebun)
							->where('kode', $column)
							->value('deskripsi');
						
						$displayName = strtoupper($mappedName ?? ucwords(str_replace('_', ' ', $column)));
					} else {
						$displayName = ucwords(str_replace('_', ' ', $column));
					}
					
					$html .= '<th>' . htmlspecialchars($displayName) . '</th>';
				}
			}

			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array)$row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekaptimbanganmandor(){
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Rekap Timbangan Mandor Tebang';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi timbangan Mandor Tebang berdasarkan kebun dan rentang tanggal';
		return view('petaktebang.rekaptimbanganmandor',$this->data);
	}
	public function getRekapTimbanganMandor(Request $request)
	{
		$kebun = $request->input('kebun', null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		if (!$dateFrom || !$dateTo) {
			return response()->json(['status' => 'error', 'message' => 'Parameter kebun, date_from, dan date_to wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_rekap_timbangan_mandor_tebang(?, ?, ?)', [$kebun, $dateFrom, $dateTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
					white-space: nowrap;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array)$row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekaptimbangan(Request $request){
		$this->data['pageTitle'] = 'Rekap Timbangan';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi timbangan berdasarkan kebun dan rentang tanggal';
		return view('petaktebang.rekaptimbangan',$this->data);
	}

	public function getRekapTimbangan(Request $request){
		$kebun = $request->input('kebun', null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');
		$report_type = $request->input('report_type', 'petak');

		if (!$dateFrom || !$dateTo) {
			return response()->json(['status' => 'error', 'message' => 'Parameter kebun, date_from, dan date_to wajib diisi.']);
		}		

		try {
			if($report_type === 'petak') {
				$results = \DB::select('CALL sp_rekap_timbangan_petak(?, ?, ?)', [$kebun, $dateFrom, $dateTo]);
			} else if($report_type === 'afdeling') {
				$results = \DB::select('CALL sp_rekap_timbangan_afdeling(?, ?, ?)', [$kebun, $dateFrom, $dateTo]);
			} else if($report_type === 'rayon') {
				$results = \DB::select('CALL sp_rekap_timbangan_rayon(?, ?, ?)', [$kebun, $dateFrom, $dateTo]);
			} else if($report_type === 'kebun') {
				$results = \DB::select('CALL sp_rekap_timbangan_kebun(?, ?, ?)', [$kebun, $dateFrom, $dateTo]);
			} else {
				return response()->json(['status' => 'error', 'message' => 'Tipe laporan tidak valid.']);
			}

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
					white-space: nowrap;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array)$row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekaptimbangankebunsd(Request $request){
		$this->data['pageTitle'] = 'Rekap Timbangan';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi timbangan berdasarkan kebun dan rentang tanggal';
		return view('petaktebang.rekaptimbangankebunsd',$this->data);
	}

	public function getRekapTimbanganKebun(Request $request)
	{
		$kebun = $request->input('kebun');
		$tanggal = $request->input('date_from');
		$tanggalTo = $request->input('date_to');
		$rayon = $request->input('rayon', null);

		try {
			$results = \DB::select('CALL sp_rekap_timbangan_kebun_sd(?, ?, ?, ?)', [$kebun, $rayon, $tanggal, $tanggalTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';

			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}

			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array)$row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekaptimbanganpetaksd(Request $request){
		$this->data['pageTitle'] = 'Rekap Timbangan';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi timbangan berdasarkan Petak dan rentang tanggal';
		return view('petaktebang.rekaptimbanganpetaksd',$this->data);
	}

	public function getRekapTimbanganPetak(Request $request)
	{
		$kebun = $request->input('kebun');
		$tanggal = $request->input('date_from');
		$tanggalTo = $request->input('date_to');
		$rayon = $request->input('rayon', null);

		try {
			$results = \DB::select('CALL sp_rekap_timbangan_petak_sd(?, ?, ?, ?)', [$kebun, $rayon, $tanggal, $tanggalTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
					white-space: nowrap;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}

				.grand-total-row {
					background: #9badff !important;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
				.progress-bar-container {
					background: #e9ecef;
					border-radius: 8px;
					overflow: hidden;
					height: 20px;
					width: 100%;
					margin: 0 auto;
				}
				.progress-bar {
					height: 100%;
					transition: width 0.5s, background 0.5s;
					color: #fff;
					font-size: 12px;
					line-height: 20px;
					text-align: center;
					font-weight: bold;
				}
				.grand-total-row {
					background-color: #4c9e5f;
					font-weight: bold;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';

			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}

			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$isGrandTotal = isset($row->nama_kebun) && strtoupper($row->nama_kebun) === 'GRAND TOTAL';
				$html .= '<tr' . ($isGrandTotal ? ' class="grand-total-row"' : '') . '>';
				foreach ((array)$row as $key => $value) {
					if ($key === 'persen_takdes' || $key === 'persen_pratebang' || $key === 'persen_luas' || $key === 'persen_takmar') {
						if (empty($value) || $value === null || $value === '') {
							$barColor = '#ffffff';
							$html .= '<td><div class="progress-bar-container"><div class="progress-bar" style="width: 100%; background: ' . $barColor . ';">-</div></div></td>';
						} else {
							$percent = floatval($value);
							$color = $percent >= 90 ? '#28a745' : ($percent >= 70 ? '#ffc107' : '#dc3545');
							$backgroundColor = $percent >= 90 ? '#c3e6cb' : ($percent >= 70 ? '#ffeeba' : '#f5c6cb');
							$html .= '<td><div class="progress-bar-container"><div class="progress-bar" style="width: ' . ($percent > 100 ? 100 : $percent) . '%; background-color: ' . $color . '; ">' . htmlspecialchars($value) . '%</div></div></td>';
						}
					}else if($key === 'cek_luas'){
							if (!empty($value)) {
							$html .= '<td><span style="display: inline-block; animation: blink 0.7s infinite; color: #dc3545; font-weight: bold;">'.htmlspecialchars($value).'</span></td>';
							} else {
								$html .= '<td>-</td>';
							}						
					}else if($key === 'aff_tebang'){
							if (!empty($value)) {
							$html .= '<td><span class="badge badge-success">'.htmlspecialchars($value).'</span></td>';
							} else {
								$html .= '<td>-</td>';
							}						
					} else {
						$html .= '<td>' . ($isGrandTotal ? '<strong>' . htmlspecialchars($value ?? '-') . '</strong>' : htmlspecialchars($value ?? '-')) . '</td>';
					}
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function consolespta(){
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Rekap Console SPTA';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi console SPTA berdasarkan kebun dan rentang tanggal';
		return view('petaktebang.rekapconsolespta',$this->data);
	}
	public function getConsoleSpta(Request $request)
	{
		$kebun = $request->input('kebun', null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		if (!$dateFrom || !$dateTo) {
			return response()->json(['status' => 'error', 'message' => 'Parameter kebun, date_from, dan date_to wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_console_spta_lempar_spreadsheet(?, ?, ?)', [$kebun, $dateFrom, $dateTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array)$row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekaptimbangannopg(Request $request){
		$this->data['pageTitle'] = 'Rekap Timbangan No PG';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi timbangan Non PG dan rentang tanggal';
		return view('petaktebang.rekaptimbangannopg',$this->data);
	}

	public function getRekapTimbangannopg(Request $request)
	{
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');
		$kebun = $request->input('kebun', null);
		$rayon = $request->input('rayon', null);

		if (!$dateFrom || !$dateTo) {
			return response()->json(['status' => 'error', 'message' => 'Parameter date_from dan date_to wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_rekap_timbangan_kebun_sd_nonpg(?, ?, ?, ?)', [$kebun, $rayon,$dateFrom, $dateTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
					white-space: nowrap;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array)$row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';

			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekaptimbanganmejamutu(){
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Rekap Meja Tebu Mutu Afdeling';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi meja tebu mutu berdasarkan afdeling dan rentang tanggal';
		return view('petaktebang.rekaptimbanganmejamutu',$this->data);
	}

	public function getRekapmejatebumutuAfdeling(Request $request)
	{
		$kebun = $request->input('kebun');
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');


		try {
			$results = \DB::select('CALL sp_rekap_mejatebu_mutu_afdeling(?, ?, ?)', [$kebun, $dateFrom, $dateTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				$colIndex = 0;
				foreach ((array)$row as $value) {
					$colIndex++;
					$isTotalOrDash = (strtoupper($row->nama_afd ?? '') === 'TOTAL' || $row->nama_afd === '-' || $row->nama_afd === null || $row->nama_afd === '');
					if ($colIndex === 8) {
						// Format kolom ke-7 dengan 3 digit desimal
						$formattedValue = is_numeric($value) ? number_format((float)$value, 3, '.', '') : ($value ?? '-');
						$html .= '<td>' . htmlspecialchars($formattedValue) . '</td>';
					} elseif ($colIndex === 9) {
						// Format kolom ke-8 dengan ribuan dan 2 digit desimal
						$formattedValue = is_numeric($value) ? number_format((float)$value, 2, '.', ',') : ($value ?? '-');
						$html .= '<td>' . htmlspecialchars($formattedValue) . '</td>';
					} elseif ($colIndex === 14) {
						// Format kolom ke-13 dengan ribuan dan 2 digit desimal
						$formattedValue = is_numeric($value) ? number_format((float)$value, 2, '.', ',') : ($value ?? '-');
						
						// Cek apakah nilai adalah TOTAL atau -
						
						
						if (!$isTotalOrDash) {
							// Hitung warna gradient dari merah (atas) ke hijau (bawah)
							static $rowNumber = 0;
							$rowNumber++;
							
							$totalRows = count($results);
							$percent = ($rowNumber / $totalRows) * 100;
							
							// Gradient merah ke hijau
							if ($percent <= 50) {
								// Merah ke Kuning
								$r = 220;
								$g = intval(53 + (190 * ($percent / 50)));
								$b = 48;
							} else {
								// Kuning ke Hijau
								$r = intval(220 - (180 * (($percent - 50) / 50)));
								$g = 180 + intval(20 * (($percent - 50) / 50));
								$b = 48;
							}
							
							$bgColor = sprintf("rgb(%d,%d,%d)", $r, $g, $b);
							$html .= '<td style="background-color: '.$bgColor.'; color: #fff; font-weight: bold;">' . htmlspecialchars($formattedValue) . '</td>';
						} else {
							$html .= '<td style="background-color: #eee; color: #000; font-weight: bold;">' . htmlspecialchars($formattedValue) . '</td>';
						}
					} else {
						if (!$isTotalOrDash) {
							$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
						} else {
							$html .= '<td style="background-color: #eee; color: #000; font-weight: bold;">' . htmlspecialchars($value ?? '-') . '</td>';
						}
					}
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekaptimbanganmejamutuqadirops(){
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Rekap Meja Tebu Mutu Afdeling QA dirops';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi meja tebu mutu QA dirops berdasarkan afdeling dan rentang tanggal';
		return view('petaktebang.rekaptimbanganmejamutuqadirops',$this->data);
	}

	public function getRekapmejatebumutuAfdelingQadirops(Request $request)
	{
		$kebun = $request->input('kebun', null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		if (!$dateFrom || !$dateTo) {
			return response()->json(['status' => 'error', 'message' => 'Parameter date_from dan date_to wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_rekap_mejatebu_mutu_afdeling_qadirops(?, ?, ?)', [$kebun, $dateFrom, $dateTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array)$row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekapposperjenistebang(){
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Rekap Pos per Jenis Tebang';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi pos per jenis tebang berdasarkan cluster, kebun, rayon dan rentang tanggal';
		return view('petaktebang.rekapposperjenistebang',$this->data);
	}

	public function getRekapPosperJenisTebang(Request $request)
	{
		$cluster = $request->input('cluster', null);
		$kebun = $request->input('kebun', null);
		$rayon = $request->input('rayon', null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		if (!$dateFrom || !$dateTo) {
			return response()->json(['status' => 'error', 'message' => 'Parameter date_from dan date_to wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_cek_pos12_jenistebang_rekap_pg(?, ?, ?, ?, ?)', [$cluster, $kebun, $rayon, $dateFrom, $dateTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
				.sg-header {
					background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
					color: #fff;
					font-weight: bold;
					text-align: center;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>';
			
			if (!empty($results)) {
				// Get first row to determine structure
				$firstRow = (array)$results[0];
				$nonSgColumns = [];
				$sgColumns = [];
				
				// Separate SG and non-SG columns
				foreach (array_keys($firstRow) as $column) {
					if (preg_match('/^(sg\d+)_(.+)$/i', $column, $matches)) {
						$sgNumber = strtoupper($matches[1]);
						$columnType = $matches[2];
						if (!isset($sgColumns[$sgNumber])) {
							$sgColumns[$sgNumber] = [];
						}
						$sgColumns[$sgNumber][] = $columnType;
					} else {
						$nonSgColumns[] = $column;
					}
				}
				
				// First header row - SG groups
				$html .= '<tr>';
				foreach ($nonSgColumns as $col) {
					$html .= '<th rowspan="2">' . htmlspecialchars(ucwords(str_replace('_', ' ', $col))) . '</th>';
				}
				foreach ($sgColumns as $sgName => $types) {
					$colspan = count($types);
					$namaSg = \DB::table('master_pg')->where('kode_pg', $sgName)->value('nama_pg') ?? $sgName;
					$html .= '<th colspan="' . $colspan . '" class="sg-header">PG ' . htmlspecialchars($namaSg) . '</th>';
				}
				$html .= '</tr>';
				
				// Second header row - Column types under each SG
				$html .= '<tr>';
				foreach ($sgColumns as $sgName => $types) {
					foreach ($types as $type) {
						$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $type))) . '</th>';
					}
				}
				$html .= '</tr>';
			}
			
			$html .= '</thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				$rowArray = (array)$row;
				
				// Display non-SG columns
				foreach ($nonSgColumns as $col) {
					$value = $rowArray[$col] ?? '-';
					$html .= '<td>' . htmlspecialchars($value) . '</td>';
				}
				
				// Display SG columns in order
				foreach ($sgColumns as $sgName => $types) {
					foreach ($types as $type) {
						$key = strtolower($sgName) . '_' . $type;
						$value = $rowArray[$key] ?? '-';
						$html .= '<td>' . htmlspecialchars($value) . '</td>';
					}
				}
				
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekaptimbanganpetaksdaff(){
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Rekap Timbangan Petak SD AFF';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi timbangan petak SD dengan status AFF berdasarkan kebun, rayon dan rentang tanggal';
		return view('petaktebang.rekaptimbanganpetaksdaff',$this->data);
	}

	public function getRekapTimbanganPetakSdAff(Request $request)
	{
		$jenis_report = $request->input('jenis', 'petak');
		$kebun = $request->input('kebun');
		$rayon = $request->input('rayon', null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		if (!$dateFrom || !$dateTo) {
			return response()->json(['status' => 'error', 'message' => 'Parameter date_from dan date_to wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_rekap_timbangan_petak_sd_aff(?, ?, ?, ?, ?)', [$jenis_report, $kebun, $rayon, $dateFrom, $dateTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
					white-space: nowrap;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			$rowCount = count($results);
			$currentRow = 0;
			$kebunGroups = [];
			
			// Group results by kebun
			foreach ($results as $row) {
				$kebunName = $row->nama_kebun ?? 'Unknown';
				if (!isset($kebunGroups[$kebunName])) {
					$kebunGroups[$kebunName] = [];
				}
				$kebunGroups[$kebunName][] = $row;
			}
			
			foreach ($kebunGroups as $kebunName => $kebunRows) {
				$kebunRowCount = count($kebunRows);
				$kebunCurrentRow = 0;
				
				foreach ($kebunRows as $row) {
					$kebunCurrentRow++;
					$currentRow++;
					$html .= '<tr>';
					$isTotal = strtoupper($kebunName) === 'TOTAL' || strpos(strtoupper($kebunName), 'TOTAL') !== false;
					
					foreach ((array)$row as $key => $value) {
						if ($key === 'aff_tebang' && !empty($value)) {
							$html .= '<td style="background-color: #28a745; color: #fff; font-weight: bold;">' . htmlspecialchars($value) . '</td>';
						} else if ($key === 'protas' && is_numeric($value)) {
							if ($isTotal) {
								// Tidak ada gradien untuk baris TOTAL
								$html .= '<td style="background-color: #eee; color: #000; font-weight: bold;">' . htmlspecialchars($value) . '</td>';
							} else if ($jenis_report === 'rayon') {
								// Gradient warna per kebun dari hijau (atas) ke merah (bawah) untuk rayon
								$percent = ($kebunCurrentRow / $kebunRowCount) * 100;
								
								if ($percent <= 50) {
									// Hijau ke Kuning
									$r = intval(28 + (246 - 28) * ($percent / 50));
									$g = intval(200 + (194 - 200) * ($percent / 50));
									$b = intval(138 + (62 - 138) * ($percent / 50));
								} else {
									// Kuning ke Merah
									$r = intval(246 + (231 - 246) * (($percent - 50) / 50));
									$g = intval(194 + (74 - 194) * (($percent - 50) / 50));
									$b = intval(62 + (59 - 62) * (($percent - 50) / 50));
								}
								
								$bgColor = sprintf("rgb(%d,%d,%d)", $r, $g, $b);
								$html .= '<td style="background-color: ' . $bgColor . '; color: #fff; font-weight: bold;">' . htmlspecialchars($value) . '</td>';
							} else {
								// Gradient warna dari hijau ke merah untuk keseluruhan data
								$percent = ($currentRow / $rowCount) * 100;
								
								if ($percent <= 50) {
									// Hijau ke Kuning
									$r = intval(28 + (246 - 28) * ($percent / 50));
									$g = intval(200 + (194 - 200) * ($percent / 50));
									$b = intval(138 + (62 - 138) * ($percent / 50));
								} else {
									// Kuning ke Merah
									$r = intval(246 + (231 - 246) * (($percent - 50) / 50));
									$g = intval(194 + (74 - 194) * (($percent - 50) / 50));
									$b = intval(62 + (59 - 62) * (($percent - 50) / 50));
								}
								
								$bgColor = sprintf("rgb(%d,%d,%d)", $r, $g, $b);
								$html .= '<td style="background-color: ' . $bgColor . '; color: #fff; font-weight: bold;">' . htmlspecialchars($value) . '</td>';
							}
						} else if (in_array($key, ['takdes_ton', 'ton_pratebang', 'netto_ton']) && is_numeric($value)) {
							$html .= '<td>' . number_format((float)$value, 2, '.', ',') . '</td>';
						} else {
							$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
						}
					}
					$html .= '</tr>';
				}
			
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekaptimbanganmejamutuKlentek(){
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Rekap Meja Tebu Mutu Afdeling Klentek';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi meja tebu mutu klentek berdasarkan jenis, kebun, rayon dan rentang tanggal';
		return view('petaktebang.rekaptimbanganmejamutuKlentek',$this->data);
	}

	public function getRekapmejatebumutuAfdelingKlentek(Request $request)
	{
		$jenis_report = $request->input('jenis', 'petak');
		$kebun = $request->input('kebun', null);
		$rayon = $request->input('rayon', null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		if (!$dateFrom || !$dateTo) {
			return response()->json(['status' => 'error', 'message' => 'Parameter date_from dan date_to wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_rekap_mejatebu_mutu_afdeling_klentek(?, ?, ?, ?, ?)', [$jenis_report, $kebun, $rayon, $dateFrom, $dateTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
					white-space: nowrap;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				$colIndex = 0;
				foreach ((array)$row as $key => $value) {
					$displayValue = ($value === 0.0 || $value === '0.0' || $value == '0.000') ? '-' : ($value ?? '-');
					$colIndex++;
					
					// Determine background color based on column name
					$bgColor = '#ffffff';
					$keyLower = strtolower($key);
					
					if (strpos($keyLower, 'klentek') !== false) {
						$bgColor = '#e3f2fd'; // Light blue for Klentek
					} elseif (strpos($keyLower, 'luas') !== false) {
						$bgColor = '#f3e5f5'; // Light purple for Luas
					} elseif (strpos($keyLower, 'mutu') !== false) {
						$bgColor = '#e8f5e9'; // Light green for Mutu
					}
					
					$html .= '<td style="background-color: ' . $bgColor . ';">' . htmlspecialchars($displayValue) . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function realthninivsthnlaluhgsama(){
		
		$this->data['pageTitle'] = 'Real '.date('Y').' vs '.(date('Y') - 1).' HG Sama LHP';
		$this->data['pageNote'] = 'Menampilkan perbandingan data real '.date('Y').' vs '.(date('Y') - 1).' untuk HG sama berdasarkan tanggal dan kebun';
		return view('petaktebang.realtahuninivstahunlaluhgsama',$this->data);
	}

	public function getRealtahuninivstahunlaluhgsama(Request $request)
	{
		$dateFrom = $request->input('date_from');
		$kebun = $request->input('kebun', null);

		if (!$dateFrom) {
			return response()->json(['status' => 'error', 'message' => 'Parameter date_from dan kebun wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_real_2026vs2025_hgsama_lhp(?, ?)', [$dateFrom, $kebun]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array)$row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekaptimbanganrayonsdnonpg()
	{
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Rekap Timbangan Rayon SD Non PG';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi timbangan rayon SD Non PG berdasarkan rentang tanggal';
		return view('petaktebang.rekaptimbanganrayonsdnonpg', $this->data);
	}

	public function getRekapTimbanganRayonSdNonpg(Request $request)
	{
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		if (!$dateFrom || !$dateTo) {
			return response()->json([
				'status' => 'error',
				'message' => 'Parameter date_from dan date_to wajib diisi.'
			]);
		}

		try {
			$results = \DB::select('CALL sp_rekap_timbangan_rayon_sd_nonpg(?, ?)', [$dateFrom, $dateTo]);
			return response($this->renderSimpleRekapTable($results));
		} catch (\Exception $e) {
			return response()->json([
				'status' => 'error',
				'message' => 'Gagal mengambil data: ' . $e->getMessage()
			]);
		}
	}

	public function rekaptimbangankebunsdnonpg()
	{
		$this->data['pageTitle'] = 'Rekap Timbangan Kebun SD Non PG';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi timbangan kebun SD Non PG berdasarkan kebun, rayon, dan rentang tanggal';
		return view('petaktebang.rekaptimbangankebunsdnonpg', $this->data);
	}

	public function getRekapTimbanganKebunSdNonpg(Request $request)
	{
		$kebun = $request->input('kebun',null);
		$rayon = $request->input('rayon',null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');


		try {
			$results = \DB::select(
				'CALL sp_rekap_timbangan_kebun_sd_nonpg(?, ?, ?, ?)',
				[$kebun, $rayon, $dateFrom, $dateTo]
			);
			return response($this->renderSimpleRekapTable($results));
		} catch (\Exception $e) {
			return response()->json([
				'status' => 'error',
				'message' => 'Gagal mengambil data: ' . $e->getMessage()
			]);
		}
	}

	public function consoleprodiskebun(){
		$this->data['pageTitle'] = 'Console Prodis Kebun';
		$this->data['pageNote'] = 'Menampilkan data console prodis berdasarkan kebun dan rentang tanggal';
		return view('petaktebang.consoleprodiskebun',$this->data);
	}

	

	public function getconsoledata(Request $request)
	{
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');
		$kebun = $request->input('kebun', null);

		if (!$dateFrom || !$dateTo) {
			return response()->json(['status' => 'error', 'message' => 'Parameter date_from, date_to dan kebun wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_console_prodis_kebun(?, ?, ?)', [$dateFrom, $dateTo, $kebun]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #4e73df 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #4e73df 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
				/* Freeze columns 1-3 */
				.rekap-table td:nth-child(1),
				.rekap-table th:nth-child(1) {
					position: sticky;
					left: 0px;
					background-color: #f8f9fc;
					z-index: 5;
				}
				.rekap-table td:nth-child(2),
				.rekap-table th:nth-child(2) {
					position: sticky;
					left: 67px;
					background-color: #f8f9fc;
					z-index: 5;
				}
				.rekap-table td:nth-child(3),
				.rekap-table th:nth-child(3) {
					position: sticky;
					left: 193px;
					background-color: #f8f9fc;
					z-index: 5;
				}
				.rekap-table thead th:nth-child(1),
				.rekap-table thead th:nth-child(2),
				.rekap-table thead th:nth-child(3) {
					background: linear-gradient(90deg, #4e73df 0%, #4e73df 100%);
					z-index: 11;
				}
				.rekap-table tbody tr:nth-child(even) td:nth-child(1),
				.rekap-table tbody tr:nth-child(even) td:nth-child(2),
				.rekap-table tbody tr:nth-child(even) td:nth-child(3) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:nth-child(odd) td:nth-child(1),
				.rekap-table tbody tr:nth-child(odd) td:nth-child(2),
				.rekap-table tbody tr:nth-child(odd) td:nth-child(3) {
					background-color: #ffffff;
				}
				.total-row {
					font-weight: bold;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				// Check if any column contains "TOTAL"
				$isTotalRow = false;
				foreach ((array)$row as $value) {
					if (stripos($value, 'total') !== false) {
						$isTotalRow = true;
						break;
					}
				}
				
				$html .= '<tr' . ($isTotalRow ? ' class="total-row"' : '') . '>';
				$columnIndex = 0;
				foreach ((array)$row as $value) {
					$columnIndex++;
					$displayValue = $value;
					
					// From column 4 onwards, convert 0.0000 to -
					if ($columnIndex >= 4 && ($value === 0.0 || $value === '0.0000' || $value === 0 || floatval($value) === 0.0)) {
						$displayValue = '-';
					}
					
					// From column 4 onwards, format as decimal 3 places and right align
					if ($columnIndex >= 4 && is_numeric($value) && $value !== '' && $displayValue !== '-') {
						$displayValue = number_format((float)$value, 3, '.', ',');
						$html .= '<td style="text-align: right;">' . htmlspecialchars($displayValue) . '</td>';
					} else {
						$html .= '<td>' . htmlspecialchars($displayValue ?? '-') . '</td>';
					}
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function consoleprodiskebunall(){
		$this->data['pageTitle'] = 'Console Prodis Kebun All';
		$this->data['pageNote'] = 'Menampilkan data console prodis semua kebun berdasarkan rentang tanggal';
		return view('petaktebang.consoleprodiskebunall',$this->data);
	}

	public function getconsoledataall(Request $request)
	{
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');
		$kebun = $request->input('kebun', null);

		if (!$dateFrom || !$dateTo) {
			return response()->json(['status' => 'error', 'message' => 'Parameter date_from, date_to dan kebun wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_console_prodis_kebun_all(?, ?, ?)', [$dateFrom, $dateTo, $kebun]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #4e73df 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
				/* Freeze columns 1-3 */
				.rekap-table td:nth-child(1),
				.rekap-table th:nth-child(1) {
					position: sticky;
					left: 0px;
					background-color: #f8f9fc;
					z-index: 5;
				}
				.rekap-table td:nth-child(2),
				.rekap-table th:nth-child(2) {
					position: sticky;
					left: 67px;
					background-color: #f8f9fc;
					z-index: 5;
				}
				.rekap-table td:nth-child(3),
				.rekap-table th:nth-child(3) {
					position: sticky;
					left: 193px;
					background-color: #f8f9fc;
					z-index: 5;
				}
				.rekap-table thead th:nth-child(1),
				.rekap-table thead th:nth-child(2),
				.rekap-table thead th:nth-child(3) {
					background: linear-gradient(90deg, #4e73df 0%, #4e73df 100%);
					z-index: 11;
				}
				.rekap-table tbody tr:nth-child(even) td:nth-child(1),
				.rekap-table tbody tr:nth-child(even) td:nth-child(2),
				.rekap-table tbody tr:nth-child(even) td:nth-child(3) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:nth-child(odd) td:nth-child(1),
				.rekap-table tbody tr:nth-child(odd) td:nth-child(2),
				.rekap-table tbody tr:nth-child(odd) td:nth-child(3) {
					background-color: #ffffff;
				}
				.total-row {
					font-weight: bold;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				// Check if any column contains "TOTAL"
				$isTotalRow = false;
				foreach ((array)$row as $value) {
					if (stripos($value, 'total') !== false) {
						$isTotalRow = true;
						break;
					}
				}
				
				$html .= '<tr' . ($isTotalRow ? ' class="total-row"' : '') . '>';
				$columnIndex = 0;
				foreach ((array)$row as $value) {
					$columnIndex++;
					$displayValue = $value;
					
					// From column 4 onwards, convert 0.0000 to -
					if ($columnIndex >= 4 && ($value === 0.0 || $value === '0.0000' || $value === 0 || floatval($value) === 0.0)) {
						$displayValue = '-';
					}
					
					// From column 4 onwards, format as decimal 3 places and right align
					if ($columnIndex >= 4 && is_numeric($value) && $value !== '' && $displayValue !== '-') {
						$displayValue = number_format((float)$value, 3, '.', ',');
						$html .= '<td style="text-align: right;">' . htmlspecialchars($displayValue) . '</td>';
					} else {
						$html .= '<td>' . htmlspecialchars($displayValue ?? '-') . '</td>';
					}
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

		public function rekaptimbanganmejamutu2(){
			config(['app.debug' => true]);
			$this->data['pageTitle'] = 'Rekap Meja Tebu Mutu';
			$this->data['pageNote'] = 'Menampilkan rekapitulasi meja tebu mutu berdasarkan cluster, kebun, rayon dan rentang tanggal';
			return view('petaktebang.rekaptimbanganmejamutu2',$this->data);
		}

		public function getRekapmejatebumutu2(Request $request)
		{

			$kebun = $request->input('kebun');
			$rayon = $request->input('rayon');
			$dateFrom = $request->input('date_from');
			$dateTo = $request->input('date_to');

			try {
				$results = \DB::select('CALL sp_rekap_mejatebu_mutu(?, ?, ?, ?)', [$kebun,$rayon, $dateFrom, $dateTo]);

				$html = '
				<style>
					.rekap-table-container {
						max-height: 600px;
						overflow-y: auto;
						position: relative;
					}
					.rekap-table {
						width: 100%;
						border-collapse: collapse;
						font-size: 14px;
					}
					.rekap-table th, .rekap-table td {
						border: 1px solid #dee2e6;
						padding: 8px 10px;
						text-align: center;
					}
					.rekap-table thead {
						background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
						color: #fff;
						position: sticky;
						top: 0;
						z-index: 10;
					}
					.rekap-table tbody tr:nth-child(even) {
						background-color: #f8f9fc;
					}
					.rekap-table tbody tr:hover {
						background-color: #e2eafc;
					}
				</style>
				<div class="rekap-table-container">
					<table id="rekap-table" class="rekap-table">
						<thead>
							<tr>';
				
				if (!empty($results)) {
					foreach (array_keys((array)$results[0]) as $column) {
						$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
					}
				}
				
				$html .= '</tr></thead><tbody>';

				foreach ($results as $row) {
					$html .= '<tr>';
					foreach ((array)$row as $value) {
						$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
					}
					$html .= '</tr>';
				}

				$html .= '</tbody></table></div>';
				return response($html);
			} catch (\Exception $e) {
				return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
			}
		}

		public function monitoringcuttocrush(){
			config(['app.debug' => true]);
			$this->data['pageTitle'] = 'Monitoring Cut to Crush';
			$this->data['pageNote'] = 'Menampilkan data monitoring cut to crush berdasarkan kebun, rayon, PG dan rentang tanggal';
			return view('petaktebang.monitoringcuttocrush',$this->data);
		}

		public function getMonitoringCuttocrush(Request $request)
		{
			$rayon = $request->input('rayon', null);
			$kebun = $request->input('kebun', null);
			$pg = $request->input('pg', null);
			$dateFrom = $request->input('date_from');
			$dateTo = $request->input('date_to');

			if (!$dateFrom || !$dateTo) {
				return response()->json(['status' => 'error', 'message' => 'Parameter date_from dan date_to wajib diisi.']);
			}

			try {
				$results = \DB::select('CALL sp_monitoring_cuttocrush(?, ?, ?, ?, ?)', [$kebun, $rayon, $pg, $dateFrom, $dateTo]);

				$html = '
				<style>
					.rekap-table-container {
						max-height: 600px;
						overflow-y: auto;
						position: relative;
					}
					.rekap-table {
						width: 100%;
						border-collapse: collapse;
						font-size: 14px;
					}
					.rekap-table th, .rekap-table td {
						border: 1px solid #dee2e6;
						padding: 8px 10px;
						text-align: center;
						white-space: nowrap;
					}
					.rekap-table thead {
						background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
						color: #fff;
						position: sticky;
						top: 0;
						z-index: 10;
					}
					.rekap-table tbody tr:nth-child(even) {
						background-color: #f8f9fc;
					}
					.rekap-table tbody tr:hover {
						background-color: #e2eafc;
					}
				</style>
				<div class="rekap-table-container">
					<table id="rekap-table" class="rekap-table">
						<thead>
							<tr>';
				
				if (!empty($results)) {
					foreach (array_keys((array)$results[0]) as $column) {
						$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
					}
				}
				
				$html .= '</tr></thead><tbody>';

				foreach ($results as $row) {
					$html .= '<tr>';
					foreach ((array)$row as $key => $value) {
						if ($key === 'ajuan_sat') {
							$bgColor = strtoupper($value) === 'ADA' ? '#28a745' : '#dc3545';
							$textColor = '#fff';
							$html .= '<td style="background-color: ' . $bgColor . '; color: ' . $textColor . '; font-weight: bold;">' . htmlspecialchars($value ?? '-') . '</td>';
						} else {
							$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
						}
					}
					$html .= '</tr>';
				}

				$html .= '</tbody></table></div>';
				return response($html);
			} catch (\Exception $e) {
				return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
			}
		}

		

	public function formMonitoringPos2VsPos1(Request $request)
	{
		if (!\Auth::check())
			return redirect('user/login')->with('status', 'error')->with('message', 'You are not login');

		$this->data['pageTitle'] = 'Monitoring POS2 vs POS1';
		$this->data['pageNote'] = 'Menampilkan monitoring perbandingan POS2 vs POS1 berdasarkan kebun, rayon, afdeling dan rentang tanggal';


		return view('petaktebang.monitoring_pos2_vs_pos1', $this->data);
	}

	public function getMonitoringPos2VsPos1(Request $request)
	{
		if (!\Auth::check())
			return redirect('user/login')->with('status', 'error')->with('message', 'You are not login');

		$dateFrom  = $request->input('date_from');
		$dateTo    = $request->input('date_to');
		$kodeKebun = $request->input('kebun');
		$kodeRayon = $request->input('rayon','');
		$afdeling  = $request->input('afdeling','');

		if (!$dateFrom || !$dateTo || !$kodeKebun) {
			return response()->json(['status' => 'error', 'message' => 'Semua parameter wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_monitoring_pos2_vs_pos1(?, ?, ?, ?, ?)', [
				$dateFrom,
				$dateTo,
				$kodeKebun,
				$kodeRayon,
				$afdeling,
			]);

			if (empty($results)) {
				return response('<p class="text-center text-muted mt-3">Tidak ada data ditemukan.</p>');
			}

			$html = '
			<style>
				.rekap-table-container { max-height: 600px; overflow-y: auto; position: relative; }
				.rekap-table { width: 100%; border-collapse: collapse; font-size: 14px; }
				.rekap-table th, .rekap-table td { border: 1px solid #dee2e6; padding: 8px 10px; text-align: center; white-space: nowrap; }
				.rekap-table thead { background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%); color: #fff; position: sticky; top: 0; z-index: 10; }
				.rekap-table tbody tr:nth-child(even) { background-color: #f8f9fc; }
				.rekap-table tbody tr:hover { background-color: #e2eafc; }
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table-pos2" class="rekap-table">
					<thead><tr>';

			foreach (array_keys((array) $results[0]) as $column) {
				$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
			}

			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array) $row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';

			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function rekaptakmarpetak(Request $request)
	{
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Rekap Takmar Petak';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi takmar berdasarkan petak, afdeling, rayon, kebun atau cluster';
		return view('petaktebang.rekaptakmarpetak', $this->data);
	}

	public function getRekaptakmarpetak(Request $request)
	{
		$tipeReport = $request->input('jenis', 'PETAK');
		$cluster = $request->input('cluster', null);
		$kebun = $request->input('kebun', null);
		$rayon = $request->input('rayon', null);
		$afdeling = $request->input('afdeling', null);

		if (!$tipeReport) {
			return response()->json(['status' => 'error', 'message' => 'Parameter tipe_report wajib diisi.']);
		}

		try {
			$results = \DB::select('CALL sp_takmar_petak_rkap(?, ?, ?, ?)', [
				strtoupper($tipeReport),
				$kebun,
				$rayon,
				$afdeling
			]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
					white-space: nowrap;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead><tr>';

			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}

			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array)$row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}


	//sp_cashcost_kso_periodik_petak(regional, kode_kebun, kode_rayon, afdeling)
	public function cashcostksoPeriodikPetak(Request $request)
	{
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Cash Cost KSO Periodik Petak';
		$this->data['pageNote'] = 'Menampilkan data cash cost KSO periodik berdasarkan petak, afdeling, rayon, kebun atau cluster';
		return view('petaktebang.cashcostkso_periodik_petak', $this->data);
	}

	public function getCashcostksoPeriodikPetak(Request $request)
	{
		$regional = $request->input('regional', null);
		$kebun = $request->input('kebun', null);
		$rayon = $request->input('rayon', null);
		$afdeling = $request->input('afdeling', null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		try {
			$results = \DB::select('CALL sp_cashcost_kso_periodik_petak(?, ?, ?, ?, ?, ?)', [
				$regional,
				$kebun,
				$rayon,
				$afdeling,
				$dateFrom,
				$dateTo
			]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
					white-space: nowrap;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>	
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
					<tr>';
			if (!empty($results)) {
				$columns = array_keys((array)$results[0]);
				$totalCols = count($columns);

				// Group header definitions (1-indexed)
				$groups = [
					['label' => 'Taksasi Maret / Sasaran', 'from' => 27, 'to' => 35],
					['label' => 'NKM',                      'from' => 36, 'to' => 37],
					['label' => 'Biaya Garap s.d (Rp)',     'from' => 38, 'to' => 41],
					['label' => 'Biaya Bahan s.d (Rp)',     'from' => 42, 'to' => 45],
					['label' => 'Biaya Pekerjaan s.d Lain (Bahan + Jasa) (Rp)', 'from' => 46, 'to' => 48],
					['label' => 'Biaya TMA (Rp)',           'from' => 49, 'to' => 51],
					['label' => 'Biaya Lain (Rp)',          'from' => 52, 'to' => 54],
					['label' => 'HPP',                      'from' => 55, 'to' => 62],
					['label' => 'Pendapatan (Rp)',          'from' => 63, 'to' => 65],
					['label' => 'Profit/Loss (Rp)',         'from' => 66, 'to' => 68],
					['label' => 'Realisasi Produksi',       'from' => 69, 'to' => 77],
					['label' => 'Persen (%)',               'from' => 79, 'to' => 80],
				];

				// Build a set of column indices (1-indexed) that belong to a group
				$groupedIndices = [];
				foreach ($groups as $g) {
					for ($i = $g['from']; $i <= $g['to']; $i++) {
						$groupedIndices[$i] = true;
					}
				}

				// Row 1: rowspan=2 for cols 1-26, group headers for grouped cols, rowspan=2 for col 78
				// Columns 1-26: rowspan 2
				for ($i = 1; $i <= min(26, $totalCols); $i++) {
					$col = $columns[$i - 1];
					$html .= '<th rowspan="2">' . htmlspecialchars(ucwords(str_replace('_', ' ', $col))) . '</th>';
				}

				// Group headers
				foreach ($groups as $g) {
					$span = 0;
					for ($i = $g['from']; $i <= $g['to']; $i++) {
						if ($i <= $totalCols) $span++;
					}
					if ($span > 0) {
						$html .= '<th colspan="' . $span . '">' . htmlspecialchars($g['label']) . '</th>';
					}
				}

				// Column 78: rowspan=2
				if ($totalCols >= 78) {
					$col = $columns[77];
					$html .= '<th rowspan="2">' . htmlspecialchars(ucwords(str_replace('_', ' ', $col))) . '</th>';
				}

				$html .= '</tr><tr>';

				// Row 2: sub-headers for grouped columns only
				foreach ($groups as $g) {
					for ($i = $g['from']; $i <= $g['to']; $i++) {
						if ($i <= $totalCols) {
							$col = $columns[$i - 1];
							$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $col))) . '</th>';
						}
					}
				}
			}
			$html .= '</tr>
			</thead><tbody>';
			foreach ($results as $row) {
				$html .= '<tr>';
				$colIdx = 1;
				foreach ((array)$row as $value) {
					$formattedValue = $value ?? '-';
					if (
						(($colIdx >= 38 && $colIdx <= 58) || ($colIdx >= 62 && $colIdx <= 68))
						&& $value !== null && $value !== ''
						&& is_numeric($value)
					) {
						$formattedValue = number_format((float)$value, 0, ',', '.');
					}
					$html .= '<td>' . htmlspecialchars($formattedValue) . '</td>';
					$colIdx++;
				}
				$html .= '</tr>';
			}
			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function formSasaranPasokHarianPivot(Request $request)
	{
		config(['app.debug' => true]);

		$this->data['pageTitle'] = 'Sasaran Pasok Harian ';
		$this->data['pageNote'] = 'Menampilkan sasaran pasok harian dalam format pivot berdasarkan rayon atau kebun dan rentang tanggal';

		return view('petaktebang.sasaran_pasok_harian_pivot', $this->data);
	}

	public function getSasaranpasokharian(Request $request)
	{
		try {
			$filter    = $request->input('filter', 'rayon'); // rayon or kebun
			$tgl_awal  = $request->input('tgl_awal', date('Y-m-01'));
			$tgl_akhir = $request->input('tgl_akhir', date('Y-m-d'));

			if (!in_array($filter, ['rayon', 'kebun'])) {
				return response()->json(['status' => 'error', 'message' => 'Filter tidak valid. Pilih rayon atau kebun.']);
			}

			$results = \DB::select("CALL sp_sasaran_pasok_harian_pivot(?, ?, ?)", [
				$filter,
				$tgl_awal,
				$tgl_akhir,
			]);

			if (empty($results)) {
				return response('<div class="alert alert-warning">Tidak ada data untuk filter yang dipilih.</div>');
			}

			$html = '
			<style>
				.sphp-table-container { max-height: 600px; overflow: auto; position: relative; }
				.sphp-table { width: 100%; border-collapse: collapse; font-size: 13px; }
				.sphp-table th, .sphp-table td { border: 1px solid #dee2e6; padding: 6px 10px; text-align: center; white-space: nowrap; }
				.sphp-table thead { background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%); color: #fff; position: sticky; top: 0; z-index: 10; }
				.sphp-table tbody tr:nth-child(even) { background-color: #f8f9fc; }
				.sphp-table tbody tr:hover { background-color: #e2eafc; }
			</style>
			<div class="sphp-table-container">
				<table class="sphp-table">
					<thead><tr>';

			foreach (array_keys((array) $results[0]) as $col) {
				$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $col))) . '</th>';
			}

			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array) $row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';

			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function cashcostksoPeriodikRekap(Request $request)
	{
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Cash Cost KSO Periodik Rekap';
		$this->data['pageNote'] = 'Menampilkan rekapitulasi cash cost KSO periodik berdasarkan afdeling, kebun, rayon dan rentang tanggal';
		return view('petaktebang.cashcostkso_periodik_rekap', $this->data);
	}

	public function getCashcostksoPeriodikRekap(Request $request)
	{
		$tipeReport = $request->input('jenis', 'afdeling');
		$kebun = $request->input('kebun', null);
		$rayon = $request->input('rayon', null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		try {
			$results = \DB::select('CALL sp_cashcost_kso_periodik_rekap(?, ?, ?, ?, ?)', [
				$tipeReport,
				$kebun,
				$rayon,
				$dateFrom,
				$dateTo
			]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
					white-space: nowrap;
				}
				.rekap-table th:nth-child(-n+5),
				.rekap-table td:nth-child(-n+5) {
					position: sticky;
					left: 0;
					z-index: 5;
					background-color: #f8f9fc;
				}
				.rekap-table th:nth-child(-n+5) {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					z-index: 11;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:nth-child(even) td:nth-child(-n+5) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
				.rekap-table tbody tr:hover td:nth-child(-n+5) {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead><tr>';

			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}

			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				$colIndex = 0;
				$isTotalRow = false;
				
				// Check if first column contains "TOTAL"
				$rowArray = (array)$row;
				if (!empty($rowArray)) {
					$firstValue = reset($rowArray);
					if (stripos($firstValue, 'total') !== false) {
						$isTotalRow = true;
					}
				}
				
				foreach ((array)$row as $value) {
					$colIndex++;
					$alignment = 'text-align: left;';
					$formattedValue = $value ?? '-';
					$bgColor = '';
					
					// Kolom 3-6: rata kiri
					if ($colIndex >= 3 && $colIndex <= 6) {
						$alignment = 'text-align: left;';
					}
					// Kolom 7: decimal 3 angka, rata kanan
					else if ($colIndex === 7 && is_numeric($value) && $value !== '') {
						$formattedValue = number_format((float)$value, 3, '.', ',');
						$alignment = 'text-align: right;';
						if ((float)$value < 0) {
							$bgColor = 'background-color: #f8d7da;';
						}
					}
					// Kolom 8-16: decimal 2 angka, rata kanan
					else if ($colIndex >= 8 && $colIndex <= 16 && is_numeric($value) && $value !== '') {
						$formattedValue = number_format((float)$value, 2, '.', ',');
						$alignment = 'text-align: right;';
						if ((float)$value < 0) {
							$bgColor = 'background-color: #f8d7da;';
						}
					}
					// Kolom 17-39: decimal 0 angka, rata kanan
					else if ($colIndex >= 17 && $colIndex <= 39 && is_numeric($value) && $value !== '') {
						$formattedValue = number_format((float)$value, 0, '.', ',');
						$alignment = 'text-align: right;';
						if ((float)$value < 0) {
							$bgColor = 'background-color: #f8d7da;';
						}
					}
					// Kolom 40: decimal 3 angka, rata kanan
					else if ($colIndex === 40 && is_numeric($value) && $value !== '') {
						$formattedValue = number_format((float)$value, 3, '.', ',');
						$alignment = 'text-align: right;';
						if ((float)$value < 0) {
							$bgColor = 'background-color: #f8d7da;';
						}
					}
					// Kolom 41-48: decimal 2 angka, rata kanan
					else if ($colIndex >= 41 && $colIndex <= 48 && is_numeric($value) && $value !== '') {
						$formattedValue = number_format((float)$value, 2, '.', ',');
						$alignment = 'text-align: right;';
						if ((float)$value < 0) {
							$bgColor = 'background-color: #f8d7da;';
						}
					}
					// Kolom 49: decimal 0 angka, rata kanan
					else if ($colIndex === 49 && is_numeric($value) && $value !== '') {
						$formattedValue = number_format((float)$value, 0, '.', ',');
						$alignment = 'text-align: right;';
						if ((float)$value < 0) {
							$bgColor = 'background-color: #f8d7da;';
						}
					}
					// Kolom 50-52: decimal 2 angka, rata kanan
					else if ($colIndex >= 50 && $colIndex <= 52 && is_numeric($value) && $value !== '') {
						$formattedValue = number_format((float)$value, 2, '.', ',');
						$alignment = 'text-align: right;';
						if ((float)$value < 0) {
							$bgColor = 'background-color: #f8d7da;';
						}
					}
					// Kolom 53-59: decimal 0 angka, rata kanan
					else if ($colIndex >= 53 && $colIndex <= 59 && is_numeric($value) && $value !== '') {
						$formattedValue = number_format((float)$value, 0, '.', ',');
						$alignment = 'text-align: right;';
						if ((float)$value < 0) {
							$bgColor = 'background-color: #f8d7da;';
						}
					}
					// Kolom 60-61: decimal 2 angka, rata kanan
					else if ($colIndex >= 60 && $colIndex <= 61 && is_numeric($value) && $value !== '') {
						$formattedValue = number_format((float)$value, 2, '.', ',');
						$alignment = 'text-align: right;';
						if ((float)$value < 0) {
							$bgColor = 'background-color: #f8d7da;';
						}
					}
					
					$boldStyle = $isTotalRow ? 'font-weight: bold;' : '';
					$html .= '<td style="' . $alignment . $bgColor . $boldStyle . '">' . htmlspecialchars($formattedValue) . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}

	public function cashcostksoPeriodikDashboard(Request $request)
	{
		config(['app.debug' => true]);
		$this->data['pageTitle'] = 'Cash Cost KSO Periodik Dashboard';
		$this->data['pageNote'] = 'Menampilkan data cash cost KSO periodik dashboard berdasarkan afdeling, kebun, rayon dan rentang tanggal';
		return view('petaktebang.cashcostkso_periodik_dashboard', $this->data);
	}

	public function getCashcostksoPeriodikDashboard(Request $request)
	{
		$tipeReport = $request->input('jenis', 'afdeling');
		$kebun = $request->input('kebun', null);
		$rayon = $request->input('rayon', null);
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		try {
			$results = \DB::select('CALL sp_cashcost_kso_periodik_dashboard(?, ?, ?, ?, ?)', [
				$tipeReport,
				$kebun,
				$rayon,
				$dateFrom,
				$dateTo
			]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
					white-space: nowrap;
				}
					.rekap-table th{
						white-space: normal;
						font-weight: 600;
					}
				.rekap-table thead {
					position: sticky;
					top: 0;
					z-index: 10;
				}
					
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
				.hide-kode-kebun {
					display: none;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';

			if (!empty($results)) {
				$columnAliases = [
					'regional' => 'Regional',
					'cluster' => 'Cluster',
					'jawa_luarjawa' => 'Jawa Luarjawa',
					'kode_kebun' => 'Kode Kebun',
					'nama_kebun' => 'Nama Kebun',
					'nama_general_manager' => 'Nama General Manager',
					'produktivitas_takmar' => 'Produktivitas<br>Takmar (ton/ha)',
					'taksasi_pratebang' => 'Taksasi<br>Pratebang (ton/ha)',
					'rendemen_takmar' => 'Rendemen<br>Takmar (%)',
					'hpp_kebunperton' => 'Hpp<br>Kebun (rp/ton)',
					'rendemen_bep' => 'Rendemen<br>Bep(%)',
					'produktivitas_bep' => 'Produktivitas<br>BEP (ton/ha)',
					'hpp_gulaperkg' => 'Hpp<br>Gula (Rp/kg)',
					'realisasi_produktivitas' => 'Realisasi<br>Produktivitas<br>(ton/ha)',
					'realisasi_rendemen' => 'Realisasi<br>Rendemen<br>(%)',
					'real_protas_thd_takmar' => 'Takmar',
					'real_rend_thd_bep' => 'Real Rend<br>Thd BEP',
					'realisasi_produktivitas_sd' => 'Realisasi<br>Produktivitas<br>SD (ton/ha)',
					'realisasi_rendemen_sd' => 'Realisasi<br>Rendemen<br>SD (%)',
					'protas_takmar' => 'Protas<br>Takmar',
					'rendemen_takmar_persen' => 'Rendemen<br>Takmar (%)',
					'real_rendemen_thd_bep' => 'Bep',
					'real_protas_thd_bep' => 'Bep',
					'real_rendemen_thd_takmar' => 'Takmar',	

					'real_protas_sd_thd_takmar' => 'Takmar',
					'real_protas_sd_thd_bep' => 'Bep',
					'real_rendemen_sd_thd_takmar' => 'Takmar',
					'real_rendemen_sd_thd_bep' => 'Bep'
				];
				
				// Define grouped columns with their headers
				$groupedColumns = [
					'Real Produktivitas Thd' => ['real_protas_thd_takmar', 'real_protas_thd_bep'],
					'Real Rendemen Thd' => ['real_rendemen_thd_takmar', 'real_rendemen_thd_bep'],
					'Real Produktivitas SD Thd' => ['real_protas_sd_thd_takmar', 'real_protas_sd_thd_bep'],
					'Real Rendemen SD Thd' => ['real_rendemen_sd_thd_takmar', 'real_rendemen_sd_thd_bep']
				];
				
				$allColumns = array_keys((array)$results[0]);
				$groupedSet = [];
				$groupsAdded = [];
				
				// Build set of grouped column names
				foreach ($groupedColumns as $group => $cols) {
					foreach ($cols as $col) {
						$groupedSet[$col] = $group;
					}
				}
				
				// First header row - Add group headers for grouped columns
				foreach ($allColumns as $column) {
					$isHidden = ($column === 'kode_kebun') ? ' class="hide-kode-kebun"' : '';
					
					if (isset($groupedSet[$column])) {
						$groupName = $groupedSet[$column];
						if (!isset($groupsAdded[$groupName])) {
							$html .= '<th colspan="2" style=""' . $isHidden . '>' . $groupName . '</th>';
							$groupsAdded[$groupName] = true;
						}
					} else {
						$html .= '<th rowspan="2"' . $isHidden . '>' . ($columnAliases[$column] ?? ucwords(str_replace('_', ' ', $column))) . '</th>';
					}
				}
				
				$html .= '</tr><tr style="border-bottom: 3px solid #333 !important;">';
				
				// Second header row - Add sub-headers for grouped columns only
				foreach ($allColumns as $column) {
					$isHidden = ($column === 'kode_kebun') ? ' class="hide-kode-kebun"' : '';
					
					if (isset($groupedSet[$column])) {
						$displayName = $columnAliases[$column] ?? ucwords(str_replace('_', ' ', $column));
						$html .= '<th' . $isHidden . '>' . $displayName . '</th>';
					}
				}
				
				$html .= '</tr>
					</thead><tbody>';
			}

						foreach ($results as $row) {
							$rowArray = (array)$row;
							
							// Check if any column contains "TOTAL"
							$isTotalRow = false;
							foreach ($rowArray as $value) {
								if (stripos($value, 'TOTAL') !== false) {
									$isTotalRow = true;
									break;
								}
							}
							
							$html .= '<tr' . ($isTotalRow ? ' style="font-weight: bold; background-color: #ececec;"' : '') . '>';
							$colIndex = 0;
							$totalCols = count((array)$row);
							$lastThreeCols = array_slice(array_keys((array)$row), -3);
							foreach ((array)$row as $key => $value) {
								$colIndex++;
								$isHidden = ($key === 'kode_kebun') ? ' class="hide-kode-kebun"' : '';
								
								// Define column formatting rules
								$formattedValue = $value ?? '-';
								$alignment = 'text-align: left;';
								
								// Columns with 2 decimal places, right aligned
								$decimalTwoColumns = ['protas_takmar', 'rendemen_takmar','rendemen_bep', 'protas', 'rendemen', 'real_protas_thd_sasaran', 'real_rend_thd_sasaran'];
								
								// Columns with no decimal, right aligned
								$noDecimalColumns = ['hpp_kebunperton', 'protas_bep', 'hpp_gulaperkg'];
								
								// Percentage columns that need status bar
								$percentageColumns = ['real_protas_thd_takmar', 'real_protas_thd_bep', 'real_rendemen_thd_takmar', 'real_rendemen_thd_bep', 'real_protas_sd_thd_takmar', 'real_protas_sd_thd_bep', 'real_rendemen_sd_thd_takmar', 'real_rendemen_sd_thd_bep'];
								
								// Columns with blue transparent background
								$blueTransparentColumns = ['realisasi_produktivitas', 'realisasi_rendemen'];
								
								// Columns with light green transparent background
								$greenTransparentColumns = ['realisasi_produktivitas_sd', 'realisasi_rendemen_sd'];
								
								$keyLower = strtolower($key);
								
								if (in_array($key, $lastThreeCols) && is_numeric($value) && $value !== '') {
									// Format last 3 columns as currency with negative in red with parentheses
									$numValue = (float)$value;
									$isNegative = $numValue < 0;
									$absValue = abs($numValue);
									$formattedValue = number_format($absValue, 0, '.', ',');
									$displayValue = $isNegative ? '(' . $formattedValue . ')' : $formattedValue;
									$textColor = $isNegative ? 'color: #dc3545;' : '';
									$alignment = 'text-align: right;';
									$html .= '<td style="' . $alignment . '; ' . $textColor . '; font-weight: ' . ($isNegative ? 'bold' : 'normal') . ';"' . $isHidden . '>' . htmlspecialchars($displayValue) . '</td>';
								} elseif (in_array($keyLower, $percentageColumns) && is_numeric($value) && $value !== '') {
									// Create status bar based on value: Green >=100, Yellow 90-99.99, Red <90
									$percent = (float)$value;
									
									if ($percent >= 100) {
										// Green
										$bgColor = 'rgb(40, 167, 69)';
									} elseif ($percent >= 90 && $percent < 100) {
										// Yellow
										$bgColor = 'rgb(255, 193, 7)';
									} else {
										// Red
										$bgColor = 'rgb(220, 53, 48)';
									}
									
									$html .= '<td style="text-align: center; background-color: ' . $bgColor . '; color: white; font-weight: bold; padding: 8px 10px;"' . $isHidden . '>
										<div style="display: flex; align-items: center; justify-content: center;">
											<span>' . htmlspecialchars(number_format((float)$value, 2, '.', ',')) . '%</span>
										</div>
									</td>';
								} elseif (in_array($keyLower, $greenTransparentColumns) && is_numeric($value) && $value !== '') {
									$formattedValue = number_format((float)$value, 2, '.', ',');
									$alignment = 'text-align: right;';
									$html .= '<td style="' . $alignment . '; background-color: rgba(40, 167, 69, 0.2);"' . $isHidden . '>' . htmlspecialchars($formattedValue) . '</td>';
								} elseif (in_array($keyLower, $blueTransparentColumns) && is_numeric($value) && $value !== '') {
									$formattedValue = number_format((float)$value, 2, '.', ',');
									$alignment = 'text-align: right;';
									$html .= '<td style="' . $alignment . '; background-color: rgba(78, 115, 223, 0.2);"' . $isHidden . '>' . htmlspecialchars($formattedValue) . '</td>';
								} elseif (in_array($keyLower, $decimalTwoColumns) && is_numeric($value) && $value !== '') {
									$formattedValue = number_format((float)$value, 2, '.', ',');
									$alignment = 'text-align: right;';
									$html .= '<td style="' . $alignment . '"' . $isHidden . '>' . htmlspecialchars($formattedValue) . '</td>';
								} elseif (in_array($keyLower, $noDecimalColumns) && is_numeric($value) && $value !== '') {
									$formattedValue = number_format((float)$value, 0, '.', ',');
									$alignment = 'text-align: right;';
									$html .= '<td style="' . $alignment . '"' . $isHidden . '>' . htmlspecialchars($formattedValue) . '</td>';
								} else {					
									if ($colIndex >= 1 && $colIndex <= 6) {
										$alignment = 'text-align: left;';
									} else {
										$alignment = 'text-align: right;';
									}
									$html .= '<td style="' . $alignment . '"' . $isHidden . '>' . htmlspecialchars($formattedValue) . '</td>';
								}
							}
							$html .= '</tr>';
						}

						$html .= '</tbody></table></div>';

						// Add charts section
						$html .= '
						<div style="margin-top: 20px; display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
							<div style="background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"><canvas id="chart-produktivitas"></canvas></div>
							<div style="background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"><canvas id="chart-rendemen"></canvas></div>
						</div>

						<div style="margin-top: 20px; display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
							<div style="background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"><canvas id="chart-realisasi-produksi"></canvas></div>
							<div style="background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"><canvas id="chart-rendemen-sd"></canvas></div>
						</div>

						<div style="margin-top: 20px; padding: 15px; background-color: #f8f9fc; border-left: 4px solid #4e73df; border-radius: 4px;">
							<h5 style="margin-top: 0; color: #4e73df; font-weight: 600;">Catatan:</h5>
							<ul style="margin: 10px 0; padding-left: 20px; font-size: 13px; color: #666;">
								<li>Asumsi Harga Gula menggunakan angka RKAP Rp 14.500/kg</li>
								<li>Asumsi Harga Tetes menggunakan angka RKAP Rp 1.005/kg</li>
							</ul>
						</div>

						<script>
							function initCharts() {
								try {
									var rows = document.querySelectorAll("#rekap-table tbody tr");
									var chartLabels = [];
									var produktivitasTakmar = [];
									var produktivitasBep = [];
									var realisasiProduktivitas = [];
									var rendemenTakmar = [];
									var rendemenBep = [];
									var realisasiRendemen = [];
									var produktivitasSd = [];
									var rendemenSd = [];
									
									var tipeReport = "' . htmlspecialchars($tipeReport) . '";
									var kolom = (tipeReport === "regional") ? 1 : ((tipeReport === "kebun") ? 5 : -1);
									
									if (kolom === -1) return;
									
									rows.forEach(function(row) {
										var cells = row.querySelectorAll("td");
										if (cells.length === 0) return;
										
										var labelCell = cells[kolom - 1];
										var label = labelCell ? labelCell.textContent.trim() : "";
										
										// Skip TOTAL rows
										if (label.toUpperCase().includes("TOTAL")) return;

										if (label.toUpperCase().includes("-")) return;
										
										// Find column indices for data
										var headerCells = document.querySelectorAll("#rekap-table thead th");
										var colIndices = {};
										
										headerCells.forEach(function(th, index) {
											// Mapping berdasarkan posisi kolom (0-based)
											var offset = (tipeReport === "regional") ? 4 : ((tipeReport === "rayon") ? 7 : ((tipeReport === "afdeling") ? 9 : 0));
											
											if (index === 5 - offset) colIndices.prodTakmar = index;
											if (index === 10 - offset) colIndices.prodBep = index;
											if (index === 12 - offset) colIndices.realProd = index;
											if (index === 7 - offset) colIndices.rendTakmar = index;
											if (index === 9 - offset) colIndices.rendBep = index;
											if (index === 14 - offset) colIndices.realRend = index;
											if (index === 13 - offset) colIndices.prodSd = index;
											if (index === 15 - offset) colIndices.rendSd = index;
										});
										
										if (Object.keys(colIndices).length === 0) return;
										
										chartLabels.push(label);
										produktivitasTakmar.push(parseFloat(cells[colIndices.prodTakmar]?.textContent) || 0);
										produktivitasBep.push(parseFloat(cells[colIndices.prodBep]?.textContent) || 0);
										realisasiProduktivitas.push(parseFloat(cells[colIndices.realProd]?.textContent) || 0);
										rendemenTakmar.push(parseFloat(cells[colIndices.rendTakmar]?.textContent) || 0);
										rendemenBep.push(parseFloat(cells[colIndices.rendBep]?.textContent) || 0);
										realisasiRendemen.push(parseFloat(cells[colIndices.realRend]?.textContent) || 0);
										produktivitasSd.push(parseFloat(cells[colIndices.prodSd]?.textContent) || 0);
										rendemenSd.push(parseFloat(cells[colIndices.rendSd]?.textContent) || 0);
									});
									
									// Chart Produktivitas
									var ctx1 = document.getElementById("chart-produktivitas").getContext("2d");
									new Chart(ctx1, {
										type: "bar",
										data: {
											labels: chartLabels,
											datasets: [
												{
													label: "Produktivitas Takmar",
													data: produktivitasTakmar,
													backgroundColor: "rgba(78, 115, 223, 0.8)",
													borderColor: "rgba(78, 115, 223, 1)",
													borderWidth: 1
												},
												{
													label: "Produktivitas BEP",
													data: produktivitasBep,
													backgroundColor: "rgba(28, 200, 138, 0.8)",
													borderColor: "rgba(28, 200, 138, 1)",
													borderWidth: 1
												},
												{
													label: "Realisasi Produktivitas",
													data: realisasiProduktivitas,
													backgroundColor: "rgba(255, 193, 7, 0.8)",
													borderColor: "rgba(255, 193, 7, 1)",
													borderWidth: 1
												}
											]
										},
										options: {
											responsive: true,
											maintainAspectRatio: true,
											plugins: {
												title: { display: true, text: "Perbandingan Produktivitas" },
												legend: { position: "top" }
											},
											scales: {
												y: { beginAtZero: true, title: { display: true, text: "Ton/Ha" } }
											}
										}
									});
									
									// Chart Rendemen
									var ctx2 = document.getElementById("chart-rendemen").getContext("2d");
									new Chart(ctx2, {
										type: "bar",
										data: {
											labels: chartLabels,
											datasets: [
												{
													label: "Rendemen Takmar",
													data: rendemenTakmar,
													backgroundColor: "rgba(78, 115, 223, 0.8)",
													borderColor: "rgba(78, 115, 223, 1)",
													borderWidth: 1
												},
												{
													label: "Rendemen BEP",
													data: rendemenBep,
													backgroundColor: "rgba(28, 200, 138, 0.8)",
													borderColor: "rgba(28, 200, 138, 1)",
													borderWidth: 1
												},
												{
													label: "Realisasi Rendemen",
													data: realisasiRendemen,
													backgroundColor: "rgba(255, 193, 7, 0.8)",
													borderColor: "rgba(255, 193, 7, 1)",
													borderWidth: 1
												}
											]
										},
										options: {
											responsive: true,
											maintainAspectRatio: true,
											plugins: {
												title: { display: true, text: "Perbandingan Rendemen" },
												legend: { position: "top" }
											},
											scales: {
												y: { beginAtZero: true, title: { display: true, text: "%" } }
											}
										}
									});
									
									// Chart Realisasi Produksi SD
									var ctx3 = document.getElementById("chart-realisasi-produksi").getContext("2d");
									new Chart(ctx3, {
										type: "bar",
										data: {
											labels: chartLabels,
											datasets: [
												{
													label: "Produktivitas Takmar",
													data: produktivitasTakmar,
													backgroundColor: "rgba(78, 115, 223, 0.8)",
													borderColor: "rgba(78, 115, 223, 1)",
													borderWidth: 1
												},
												{
													label: "Produktivitas BEP",
													data: produktivitasBep,
													backgroundColor: "rgba(28, 200, 138, 0.8)",
													borderColor: "rgba(28, 200, 138, 1)",
													borderWidth: 1
												},
												{
													label: "Realisasi Produktivitas",
													data: produktivitasSd,
													backgroundColor: "rgba(255, 193, 7, 0.8)",
													borderColor: "rgba(255, 193, 7, 1)",
													borderWidth: 1
												}
											]
										},
										options: {
											responsive: true,
											maintainAspectRatio: true,
											plugins: {
												title: { display: true, text: "Perbandingan Produktivitas SD" },
												legend: { position: "top" }
											},
											scales: {
												y: { beginAtZero: true, title: { display: true, text: "Ton/Ha" } }
											}
										}
									});
									
									// Chart Rendemen SD
									var ctx4 = document.getElementById("chart-rendemen-sd").getContext("2d");
									new Chart(ctx4, {
										type: "bar",
										data: {
											labels: chartLabels,
											datasets: [
												{
													label: "Rendemen Takmar SD",
													data: rendemenTakmar,
													backgroundColor: "rgba(78, 115, 223, 0.8)",
													borderColor: "rgba(78, 115, 223, 1)",
													borderWidth: 1
												},
												{
													label: "Rendemen BEP SD",
													data: rendemenBep,
													backgroundColor: "rgba(28, 200, 138, 0.8)",
													borderColor: "rgba(28, 200, 138, 1)",
													borderWidth: 1
												},
												{
													label: "Realisasi Rendemen SD",
													data: rendemenSd,
													backgroundColor: "rgba(255, 193, 7, 0.8)",
													borderColor: "rgba(255, 193, 7, 1)",
													borderWidth: 1
												}
											]
										},
										options: {
											responsive: true,
											maintainAspectRatio: true,
											plugins: {
												title: { display: true, text: "Perbandingan Rendemen SD" },
												legend: { position: "top" }
											},
											scales: {
												y: { beginAtZero: true, title: { display: true, text: "%" } }
											}
										}
									});
								} catch (error) {
									console.error("Error initializing charts:", error);
								}
							}
							
							initCharts();
						</script>
						';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}





	private function renderSimpleRekapTable(array $results)
	{
		$html = '
		<style>
			.rekap-table-container { max-height: 600px; overflow-y: auto; position: relative; }
			.rekap-table { width: 100%; border-collapse: collapse; font-size: 14px; }
			.rekap-table th, .rekap-table td { border: 1px solid #dee2e6; padding: 8px 10px; text-align: center; white-space: nowrap; }
			.rekap-table thead { background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%); color: #fff; position: sticky; top: 0; z-index: 10; }
			.rekap-table tbody tr:nth-child(even) { background-color: #f8f9fc; }
			.rekap-table tbody tr:hover { background-color: #e2eafc; }
		</style>
		<div class="rekap-table-container">
			<table id="rekap-table" class="rekap-table">
				<thead><tr>';

		if (!empty($results)) {
			foreach (array_keys((array) $results[0]) as $column) {
				$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
			}
		}

		$html .= '</tr></thead><tbody>';

		foreach ($results as $row) {
			$html .= '<tr>';
			foreach ((array) $row as $value) {
				$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
			}
			$html .= '</tr>';
		}

		$html .= '</tbody></table></div>';

		return $html;
	}


	//CALL sp_console_spta_rayon_pg(?, ?)
	function formConsoleSptaRayonPg(Request $request)
	{
		$this->data['pageTitle'] = 'Console SPTA Rayon PG';
		$this->data['pageNote'] = 'Menampilkan data spta rayon pg berdasarkan rayon dan rentang tanggal';
		return view('petaktebang.console_spta_rayon_pg', $this->data);
	}

	function getConsoleSptaRayonPg(Request $request)
	{
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

			$results = \DB::select('CALL sp_console_spta_rayon_pg(?, ?)', [
				$dateFrom,
				$dateTo
			]);

			$html = $this->renderSimpleRekapTable($results);
			return response($html);

	}

	function formRealnowvsoldTglSama(Request $request)
	{
		$this->data['pageTitle'] = 'Real ' . date('Y') . ' vs ' . (date('Y') - 1) . ' Tgl Sama';
		$this->data['pageNote'] = 'Menampilkan data real ' . date('Y') . ' vs ' . (date('Y') - 1) . ' tgl sama berdasarkan tanggal';
		return view('petaktebang.real_now_vs_old_tglsama', $this->data);
	}

	function getRealnowvsoldTglSama(Request $request)
	{
		$date = $request->input('date', date('Y-m-d'));

		$results = \DB::select('CALL sp_real_' . date('Y') . 'vs' . (date('Y') - 1) . '_tglsama(?)', [
			$date
		]);

		// Build custom HTML table grouped by kebun and listing uraian rows
		$yearnow = date('Y');
		$yearold = $yearnow - 1;
		// Enhanced table with Bootstrap styling, number formatting and grouped kebun rows
		$styles = '<style>
            .kuadran-table-wrap-888 { font-family: "Segoe UI", Arial, sans-serif; }
            .kuadran-table-wrap-888 .kuadran-table { width: 100%; border-collapse: separate; border-spacing: 0; border-radius: 10px;  box-shadow: 0 4px 18px rgba(0,0,0,0.13); font-size: 13px; height: 600px;overflow: scroll; }
			/* Make header sticky when scrolling */
			.kuadran-table-wrap-888 { max-height: 600px; overflow: auto; }
			.kuadran-table-wrap-888 .kuadran-table thead th { position: sticky; top: 0; z-index: 5; }
            .kuadran-table-wrap-888 .kuadran-table thead tr:first-child { background: linear-gradient(135deg, #1a3b5c 0%, #2c5c8f 60%, #3498db 100%); position: sticky; top: 0; }
            .kuadran-table-wrap-888 .kuadran-table thead th { color: #fff !important; text-align: center; vertical-align: middle; padding: 13px 10px; font-weight: 700; font-size: 12.5px; letter-spacing: 0.3px; border: none; white-space: nowrap; text-shadow: 0 1px 2px rgba(0,0,0,0.18); }
            .kuadran-table-wrap-888 .kuadran-table thead tr:first-child th:first-child { border-radius: 10px 0 0 0; }
            .kuadran-table-wrap-888 .kuadran-table thead tr:first-child th:last-child { border-radius: 0 10px 0 0; }
            .kuadran-table-wrap-888 .kuadran-table-group-header { border-left: 2.5px solid rgba(255,255,255,0.35) !important; }
            .kuadran-table-wrap-888 .kuadran-table tbody tr.row-even { background-color: #eef6fb; }
            .kuadran-table-wrap-888 .kuadran-table tbody tr.row-odd { background-color: #ffffff; }
            .kuadran-table-wrap-888 .kuadran-table tbody tr { transition: background-color 0.2s, box-shadow 0.2s; }
            .kuadran-table-wrap-888 .kuadran-table tbody tr:hover { background-color: #d6e9f8 !important; box-shadow: inset 0 0 0 1.5px #3498db; }
            .kuadran-table-wrap-888 .kuadran-table tbody td { padding: 10px 12px; border-bottom: 1px solid #e3edf5; vertical-align: middle; }
            .kuadran-table-wrap-888 .kuadran-table tbody td.td-kebun { font-weight: 600; color: #1a3b5c; white-space: nowrap; text-align:left !important; }
            .kuadran-table-wrap-888 .kuadran-table tbody td.td-num { text-align: right; color: #333; }
            .kuadran-table-wrap-888 .kuadran-table tbody td.td-total { text-align: right; font-weight: 700; font-size: 14px; }
            .kuadran-table-wrap-888 .kuadran-table tbody tr:last-child td:first-child { border-radius: 0 0 0 10px; }
            .kuadran-table-wrap-888 .kuadran-table tbody tr:last-child td:last-child { border-radius: 0 0 10px 0; }
            .group-separator-888 { border-left: 2.5px solid #b9d7ee; }
            .separator-888 { border-left: 1px solid #b9d7ee; }
            .group-green { background-color: #27ae60; }
            .group-orange { background-color: #f39c12; }
            .group-red { background-color: #c0392b; }
        </style>';
		$html = $styles . '<div class="kuadran-table-wrap-888">'
			. '<table class="kuadran-table" id="rekap-table">'
			. '<thead><tr><th style="width:20%">Kebun</th><th>Uraian</th><th style="text-align:right">' . $yearnow . '</th><th style="text-align:right">' . $yearold . '</th></tr></thead><tbody>';

		$currentKebun = null;
		foreach ($results as $row) {
			$kebun = isset($row->kebun) ? $row->kebun : '';
			$uraian = isset($row->uraian) ? $row->uraian : '';

			$valnow = isset($row->{$yearnow}) ? $row->{$yearnow} : (isset($row->{'y' . $yearnow}) ? $row->{'y' . $yearnow} : '');
			$valold = isset($row->{$yearold}) ? $row->{$yearold} : (isset($row->{'y' . $yearold}) ? $row->{'y' . $yearold} : '');

			// When kebun changes, insert a highlighted header row
			if ($currentKebun !== $kebun) {
				$currentKebun = $kebun;
				$html .= '<tr class="bg-light"><td colspan="4"><strong>' . htmlspecialchars($kebun) . '</strong></td></tr>';
			}

			// Format numbers if numeric
			$displayNow = is_numeric($valnow) ? number_format($valnow, 0, '.', ',') : $valnow;
			$displayOld = is_numeric($valold) ? number_format($valold, 0, '.', ',') : $valold;

			$html .= '<tr>';
			// Only show kebun name on the first row of the group to reduce repetition
			$html .= '<td>' . htmlspecialchars($kebun) . '</td>';
			$html .= '<td>' . htmlspecialchars(strtoupper(str_replace('_', ' ', $uraian))) . '</td>';
			$html .= '<td style="text-align:right;" class="separator-888">' . htmlspecialchars((string)$displayNow) . '</td>';
			$html .= '<td style="text-align:right;" class="separator-888">' . htmlspecialchars((string)$displayOld) . '</td>';
			$html .= '</tr>';
		}

		$html .= '</tbody></table></div>';
		return response($html);
	}


	//sp_real_2026vs2025_tglsama_spta
	public function formRealnowvsoldTglSamaSpta(Request $request)
	{
		$this->data['pageTitle'] = 'Real ' . date('Y') . ' vs ' . (date('Y') - 1) . ' Tgl Sama SPTA';
		$this->data['pageNote'] = 'Menampilkan data real ' . date('Y') . ' vs ' . (date('Y') - 1) . ' tgl sama berdasarkan tanggal';
		return view('petaktebang.real_now_vs_old_tglsama_spta', $this->data);
	}

	public function getRealnowvsoldTglSamaSpta(Request $request)
	{
		$date = $request->input('date', date('Y-m-d'));

		$results = \DB::select('CALL sp_real_' . date('Y') . 'vs' . (date('Y') - 1) . '_tglsama_spta(?)', [
			$date
		]);

		// Build custom HTML table grouped by kebun and listing uraian rows
		$yearnow = date('Y');
		$yearold = $yearnow - 1;
		// Enhanced table with Bootstrap styling, number formatting and grouped kebun rows
		$styles = '<style> 
			.kuadran-table-wrap-888 { font-family: "Segoe UI", Arial, sans-serif; }
			.kuadran-table-wrap-888 .kuadran-table { width: 100%; border-collapse: separate; border-spacing: 0; border-radius: 10px;  box-shadow: 0 4px 18px rgba(0,0,0,0.13); font-size: 13px; height: 600px;overflow: scroll; }
			/* Make header sticky when scrolling */
			.kuadran-table-wrap-888 { max-height: 600px; overflow: auto; }
			.kuadran-table-wrap-888 .kuadran-table thead th { position: sticky; top: 0; z-index: 5; }
			.kuadran-table-wrap-888 .kuadran-table thead tr:first-child { background: linear-gradient(135deg, #1a3b5c 0%, #2c5c8f 60%, #3498db 100%); position: sticky; top: 0; }
			.kuadran-table-wrap-888 .kuadran-table thead th { color: #fff !important; text-align: center; vertical-align: middle; padding: 13px 10px; font-weight: 700; font-size: 12.5px; letter-spacing: 0.3px; border: none; white-space: nowrap; text-shadow: 0 1px 2px rgba(0,0,0,0.18); }
			.kuadran-table-wrap-888 .kuadran-table thead tr:first-child th:first-child { border-radius: 10px 0 0 0; }
			.kuadran-table-wrap-888 .kuadran-table thead tr:first-child th:last-child { border-radius: 0 10px 0 0; }
			.kuadran-table-wrap-888 .kuadran-table-group-header { border-left: 2.5px solid rgba(255,255,255,0.35) !important; }
			.kuadran-table-wrap-888 .kuadran-table tbody tr.row-even { background-color: #eef6fb; }
			.kuadran-table-wrap-888 .kuadran-table tbody tr.row-odd { background-color: #ffffff; }
			.kuadran-table-wrap-888 .kuadran-table tbody tr { transition: background-color 0.2s, box-shadow 0.2s; }
			.kuadran-table-wrap-888 .kuadran-table tbody tr:hover { background-color: #d6e9f8 !important; box-shadow: inset 0 0 0 1.5px #3498db; }
			.kuadran-table-wrap-888 .kuadran-table tbody td { padding: 10px 12px; border-bottom: 1px solid #e3edf5; vertical-align: middle; }
			.kuadran-table-wrap-888 .kuadran-table tbody td.td-kebun { font-weight: 600; color: #1a3b5c; white-space: nowrap; text-align:left !important; }
			.kuadran-table-wrap-888 .kuadran-table tbody td.td-num { text-align: right; color: #333; }
			.kuadran-table-wrap-888 .kuadran-table tbody td.td-total { text-align: right; font-weight: 700; font-size: 14px; }
			.kuadran-table-wrap-888 .kuadran-table tbody tr:last-child td:first-child { border-radius: 0 0 0 10px; }
			.kuadran-table-wrap-888 .kuadran-table tbody tr:last-child td:last-child { border-radius: 0 0 10px 0; }
			.group-separator-888 { border-left: 2.5px solid #b9d7ee; }
			.separator-888 { border-left: 1px solid #b9d7ee	; }
			.group-green { background-color: #27ae60; }
			.group-orange { background-color: #f39c12; }
			.group-red { background-color: #c0392b; }
		</style>';
		$html = $styles . '<div class="kuadran-table-wrap-888">'
			. '<table class="kuadran-table" id="rekap-table">'
			. '<thead><tr><th style="width:20%">Kebun</th><th>Uraian</th><th style="text-align:right">' . $yearnow . '</th><th style="text-align:right">' . $yearold . '</th></tr></thead><tbody>';
		
		$currentKebun = null;
		foreach ($results as $row) {
			if ($currentKebun !== $row->kebun) {
				$currentKebun = $row->kebun;
				$html .= '<tr class="bg-light"><td colspan="4"><strong>' . htmlspecialchars($currentKebun) . '</strong></td></tr>';
			}

			$html .= '<tr>';
			$html .= '<td>' . htmlspecialchars($row->kebun) . '</td>';
			$html .= '<td>' . htmlspecialchars(strtoupper(str_replace('_', ' ', $row->uraian))) . '</td>';
			$html .= '<td style="text-align:right;" class="separator-888">' . htmlspecialchars($row->{$yearnow}) . '</td>';
			$html .= '<td style="text-align:right;" class="separator-888">' . htmlspecialchars($row->{$yearold}) . '</td>';
			$html .= '</tr>';
		}

		$html .= '</tbody></table></div>';
		return response($html);
	}
		


}