<?php namespace App\Http\Controllers;

use App\Models\Picapetak;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ; 


class PicapetakController extends Controller {

	protected $layout = "layouts.main";
	protected $data = array();	
	public $module = 'picapetak';
	static $per_page	= '50';

	public function __construct()
	{
		
		parent::__construct();
		$this->model = new Picapetak();
		$this->info = $this->model->makeInfo( $this->module);
		$this->access = array();
	
		$this->data = array_merge(array(
			'pageTitle'	=> 	$this->info['title'],
			'pageNote'	=>  $this->info['note'],
			'pageModule'=> 'picapetak',
			'return'	=> self::returnUrl()
			
		),$this->data);


		
	}

	public function index( Request $request )
	{
		// Make Sure users Logged 
		if(!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');
		// $this->grab( $request) ;
		// if($this->access['is_view'] ==0) 
		// 	return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');				
		// Render into template
		return view( $this->module.'.index',$this->data);
	}	

	public function getAjaxDataPicaPetak(Request $request)
	{
		$draw = (int) $request->get('draw', 1);
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$afdeling = $request->get('afdeling', '');
		$cluster = $request->get('cluster', '');

		// Call stored procedure sp_rekap_pica_kebun with parameters
		$params = [ date('Y-m-d'),$kebun, $rayon, $afdeling,$cluster];
		$results = \DB::select('CALL sp_rekap_pica_kebun(?, ?, ?, ?,?)', $params);

		// Build HTML table instead of JSON
		$includeRayon = ($kebun && empty($rayon) && empty($afdeling));
		$includeAfd   = ($kebun && $rayon && empty($afdeling));
		$includeLahan = ($kebun && $rayon && $afdeling);


		$html = '<table class="table table-bordered table-striped" id="tablepica" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead><tr>';
		$headers = [
			'No','Nama Cluster','Kode Kebun','Nama Kebun'
		];
		if ($includeRayon) {
			$headers[] = 'Nama Rayon';
		}
		if ($includeAfd) {
			$headers[] = 'AFD';
		}
		if ($includeLahan) {
			$headers[] = 'Nama Rayon';
			$headers[] = 'AFD';
			$headers[] = 'Lahan ID';
		}
		$headers = array_merge($headers, [
			'Protas SD',
			'EMAS (Ha)','HIJAU (Ha)','KUNING (Ha)','MERAH (Ha)','HITAM (Ha)','TOTAL LUAS (Ha)',
			'EMAS (Petak)','HIJAU (Petak)','KUNING (Petak)','MERAH (Petak)','HITAM (Petak)','TOTAL PETAK'
		]);

		foreach ($headers as $h) {
			$style = '';
			$txt = strtoupper($h);
			if (strpos($txt, 'EMAS') !== false) {
				$style = 'background-color:#FFD700; color:#000;';
			} elseif (strpos($txt, 'HIJAU') !== false) {
				$style = 'background-color:#008000; color:#FFF;';
			} elseif (strpos($txt, 'KUNING') !== false) {
				$style = 'background-color:#FFFF00; color:#000;';
			} elseif (strpos($txt, 'MERAH') !== false) {
				$style = 'background-color:#FF0000; color:#FFF;';
			} elseif (strpos($txt, 'HITAM') !== false) {
				$style = 'background-color:#000000; color:#FFF;';
			}
			$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
		}
		$html .= '</tr></thead><tbody>';

		$no = 1;
		// totals
		$totals = [
			'protas_sd' => 0.0,
			'emas_luas' => 0.0,
			'hijau_luas' => 0.0,
			'kuning_luas' => 0.0,
			'merah_luas' => 0.0,
			'hitam_luas' => 0.0,
			'total_luas' => 0.0,
			'emas_petak' => 0,
			'hijau_petak' => 0,
			'kuning_petak' => 0,
			'merah_petak' => 0,
			'hitam_petak' => 0,
			'total_petak' => 0,
		];

		foreach ($results as $row) {

			$html .= '<tr>';
			$html .= '<td>' . $no++ . '</td>';
			$html .= '<td>' . htmlspecialchars($row->nama_cluster ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->nama_kebun ?? '') . '</td>';

			if ($includeRayon) {
				$html .= '<td>' . htmlspecialchars($row->nama_rayon ?? $row->kode_rayon ?? '') . '</td>';
			}
			if ($includeAfd) {
				$html .= '<td>' . htmlspecialchars($row->afdeling ?? $row->afdeling ?? '') . '</td>';
			}
			if ($includeLahan) {
				$html .= '<td>' . htmlspecialchars($row->nama_rayon ?? $row->kode_rayon ?? '') . '</td>';
				$html .= '<td>' . htmlspecialchars($row->lahan_id ?? '') . '</td>';
			}

			$protas = isset($row->protas_sd) ? (float)$row->protas_sd : 0.0;
			$emas_l = isset($row->emas_luas) ? (float)$row->emas_luas : 0.0;
			$hijau_l = isset($row->hijau_luas) ? (float)$row->hijau_luas : 0.0;
			$kuning_l = isset($row->kuning_luas) ? (float)$row->kuning_luas : 0.0;
			$merah_l = isset($row->merah_luas) ? (float)$row->merah_luas : 0.0;
			$hitam_l = isset($row->hitam_luas) ? (float)$row->hitam_luas : 0.0;
			$total_l = isset($row->total_luas) ? (float)$row->total_luas : 0.0;

			$emas_p = isset($row->emas_petak) ? (int)$row->emas_petak : 0;
			$hijau_p = isset($row->hijau_petak) ? (int)$row->hijau_petak : 0;
			$kuning_p = isset($row->kuning_petak) ? (int)$row->kuning_petak : 0;
			$merah_p = isset($row->merah_petak) ? (int)$row->merah_petak : 0;
			$hitam_p = isset($row->hitam_petak) ? (int)$row->hitam_petak : 0;
			$total_p = isset($row->total_petak) ? (int)$row->total_petak : 0;

			$html .= '<td>' . ($protas !== 0.0 ? number_format($protas, 2) : '') . '</td>';
			$html .= '<td>' . ($emas_l !== 0.0 ? number_format($emas_l, 3) : '') . '</td>';
			$html .= '<td>' . ($hijau_l !== 0.0 ? number_format($hijau_l, 3) : '') . '</td>';
			$html .= '<td>' . ($kuning_l !== 0.0 ? number_format($kuning_l, 3) : '') . '</td>';
			$html .= '<td>' . ($merah_l !== 0.0 ? number_format($merah_l, 3) : '') . '</td>';
			$html .= '<td>' . ($hitam_l !== 0.0 ? number_format($hitam_l, 3) : '') . '</td>';
			$html .= '<td>' . ($total_l !== 0.0 ? number_format($total_l, 3) : '') . '</td>';

			$html .= '<td>' . ($emas_p !== 0 ? $emas_p : '') . '</td>';
			$html .= '<td>' . ($hijau_p !== 0 ? $hijau_p : '') . '</td>';
			$html .= '<td>' . ($kuning_p !== 0 ? $kuning_p : '') . '</td>';
			$html .= '<td>' . ($merah_p !== 0 ? $merah_p : '') . '</td>';
			$html .= '<td>' . ($hitam_p !== 0 ? $hitam_p : '') . '</td>';
			$html .= '<td>' . ($total_p !== 0 ? $total_p : '') . '</td>';

			$html .= '</tr>';

			
		}

	

		$html .= '</tbody></table>';

	

		return response($html);
	}

	public function chartPieDataPica(Request $request)
	{
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$afdeling = $request->get('afdeling', '');
		$results = \DB::table('pica_petak')
			->selectRaw('count(*) as jml_petak, pica')
			->when($kebun, function ($query) use ($kebun) {
				return $query->where('kode_kebun', $kebun);
			})
			->when($rayon, function ($query) use ($rayon) {
				return $query->where('kode_rayon', $rayon);
			})
			->when($afdeling, function ($query) use ($afdeling) {
				return $query->where('kode_afd', $afdeling);
			})
			->groupBy('pica')
			->get();

		$categories = [];
		$data = [];

		foreach ($results as $row) {
			$categories[] = $row->pica;
			$data[] = (int) $row->jml_petak;
		}

		return response()->json([
			'categories' => $categories,
			'data' => $data
		]);
	}

	public function chartPieDataLuasPica(Request $request)
	{
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$afdeling = $request->get('afdeling', '');
		$results = \DB::table('pica_petak')
			->selectRaw('sum(ha_tebang) as total_luas, pica')
			->when($kebun, function ($query) use ($kebun) {
				return $query->where('kode_kebun', $kebun);
			})
			->when($rayon, function ($query) use ($rayon) {
				return $query->where('kode_rayon', $rayon);
			})
			->when($afdeling, function ($query) use ($afdeling) {
				return $query->where('kode_afd', $afdeling);
			})
			->groupBy('pica')
			->get();

		$categories = [];
		$data = [];

		foreach ($results as $row) {
			$categories[] = $row->pica;
			$data[] = (int) $row->total_luas;
		}

		return response()->json([
			'categories' => $categories,
			'data' => $data
		]);
	}

	public function getTableDataPica( Request $request)
	{
		$pica = $request->get('pica', 'MERAH'); // default to 'MERAH' if not provided
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$afdeling = $request->get('afdeling', '');

		$query = \DB::table('pica_petak')
			->whereRaw("CONVERT(pica USING utf8mb4) COLLATE utf8mb4_unicode_ci = ?", [$pica]);

		// apply filters
		if ($kebun) {
			$query->where('kode_kebun', $kebun);
		}
		if ($rayon) {
			$query->where('kode_rayon', $rayon);
		}
		if ($afdeling) {
			// try both common field names just in case
			$query->where(function($q) use ($afdeling) {
				$q->where('kode_afd', $afdeling)->orWhere('kode_afd', $afdeling);
			});
		}

		// decide grouping & selected columns based on presence of kebun/rayon/afdeling
		$columns = ['nama_cluster', 'nama_kebun'];
		$groupBy = ['kode_kebun'];
		if ($kebun && empty($rayon) && empty($afdeling)) {
			// kebun provided, rayon empty -> show rayon breakdown
			$columns[] = 'nama_rayon';
			$groupBy = ['kode_rayon'];
		} elseif ($kebun && $rayon && empty($afdeling)) {
			// kebun + rayon provided, afdeling empty -> show afdeling breakdown
			$columns[] = 'nama_rayon';
			$columns[] = 'kode_afd';
			$groupBy = ['kode_afd'];
		} elseif ($kebun && $rayon && $afdeling) {
			// kebun + rayon + afdeling provided -> show rayon, afdeling, lahan_id breakdown
			$columns[] = 'nama_rayon';
			$columns[] = 'kode_afd';
			$columns[] = 'lahan_id';
			$groupBy = ['lahan_id'];
		} else {
			// default (no kebun filter) group by kebun
			$groupBy = ['kode_kebun'];
		}

		// build selectRaw
		$selectParts = [];
		foreach ($columns as $c) {
			$selectParts[] = $c;
		}
		$selectParts[] = 'count(*) as jml_petak';
		$selectParts[] = 'SUM(ha_tebang) as ha_tebang';
		$selectParts[] = 'pica';

		$selectRaw = implode(', ', $selectParts);

		$results = $query->selectRaw($selectRaw)
			->groupBy($groupBy)
			->get();

		// Build HTML table with dynamic headers
		$html = '<table class="table table-responsive" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead><tr>';

		// fixed headers from columns
		foreach ($columns as $col) {
			$html .= '<th>' . htmlspecialchars(ucwords(str_replace(['_', 'kode'], [' ', ''], $col))) . '</th>';
		}
		$html .= '<th>Jumlah Petak ' . htmlspecialchars($pica) . '</th>';
		$html .= '<th>Luas Tebang (Ha)</th>';
		$html .= '<th>PICA</th>';
		$html .= '</tr></thead><tbody>';

		$total_jml = 0;
		$total_ha = 0.0;

		foreach ($results as $row) {
			$html .= '<tr>';
			foreach ($columns as $col) {
				$val = isset($row->$col) ? $row->$col : '';
				$html .= '<td>' . htmlspecialchars((string)$val) . '</td>';
			}
			$jml = isset($row->jml_petak) ? (int)$row->jml_petak : 0;
			$ha = isset($row->ha_tebang) ? (float)$row->ha_tebang : 0;
			$html .= '<td>' . $jml . '</td>';
			$html .= '<td>' . number_format($ha, 3) . '</td>';
			$html .= '<td>' . htmlspecialchars($row->pica ?? '') . '</td>';
			$html .= '</tr>';

			$total_jml += $jml;
			$total_ha += $ha;
		}

		// totals row
		$html .= '<tr style="font-weight:bold;">';
		foreach ($columns as $col) {
			$html .= '<td></td>';
		}
		$html .= '<td>' . $total_jml . '</td>';
		$html .= '<td>' . number_format($total_ha, 3) . '</td>';
		$html .= '<td></td>';
		$html .= '</tr>';

		$html .= '</tbody></table>';

		return response($html);
	}

	public function picaMorfologi(Request $request)
	{
		// Make Sure users Logged 
		if(!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');
		
		$this->data = array_merge(array(
			'pageTitle2'	=> 'Pica Morfologi',
			'pageNote2'	=> 'Data Pica Morfologi',
			'pageModule2'=> 'picapetak',
			'return'	=> self::returnUrl()
			
		),$this->data);

		return view( $this->module.'.pica_morfologi',$this->data);

	}

	public function chartPieDataJmlBatangPica(Request $request)
	{
		$cluster = $request->get('cluster', '');
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$afd = $request->get('afd', '');
		$results = \DB::table('q_pica_jml_batang')
			->selectRaw('count(*) as jml_petak, warna')
			->groupBy('warna')
			->whereNotNull('warna')
			->when($kebun, function ($query) use ($kebun) {
				return $query->where('kode_kebun', $kebun);
			})
			->when($rayon, function ($query) use ($rayon) {
				return $query->where('kode_rayon', $rayon);
			})
			->when($afd, function ($query) use ($afd) {
				return $query->where('afd', $afd);
			})
			->when($cluster, function ($query) use ($cluster) {
				return $query->where('nama_cluster', $cluster);
			})
			->get();

		$categories = [];
		$data = [];

		foreach ($results as $row) {
			$categories[] = $row->warna;
			$data[] = (int) $row->jml_petak;
		}

		return response()->json([
			'categories' => $categories,
			'data' => $data
		]);
	}

	public function chartPieDataTinggiBatangPica(Request $request)
	{
		$cluster = $request->get('cluster', '');
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$afd = $request->get('afd', '');
		$results = \DB::table('q_pica_tinggi_batang')
			->selectRaw('count(*) as jml_petak, warna')
			->groupBy('warna')
			->whereNotNull('warna')
						->when($kebun, function ($query) use ($kebun) {
				return $query->where('kode_kebun', $kebun);
			})
			->when($rayon, function ($query) use ($rayon) {
				return $query->where('kode_rayon', $rayon);
			})
			->when($afd, function ($query) use ($afd) {
				return $query->where('afd', $afd);
			})
			->when($cluster, function ($query) use ($cluster) {
				return $query->where('nama_cluster', $cluster);
			})
			->get();

		$categories = [];
		$data = [];

		foreach ($results as $row) {
			$categories[] = $row->warna;
			$data[] = (int) $row->jml_petak;
		}

		return response()->json([
			'categories' => $categories,
			'data' => $data
		]);
	}

	public function chartPieDataDiameterBatangPica(Request $request)
	{
		$cluster = $request->get('cluster', '');
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$afd = $request->get('afd', '');
		$results = \DB::table('q_pica_diameter_batang')
			->selectRaw('count(*) as jml_petak, warna')
			->groupBy('warna')
			// ->whereNotNull('warna')
						->when($kebun, function ($query) use ($kebun) {
				return $query->where('kode_kebun', $kebun);
			})
			->when($rayon, function ($query) use ($rayon) {
				return $query->where('kode_rayon', $rayon);
			})
			->when($afd, function ($query) use ($afd) {
				return $query->where('afd', $afd);
			})
			->when($cluster, function ($query) use ($cluster) {
				return $query->where('nama_cluster', $cluster);
			})
			->get();

		$categories = [];
		$data = [];

		foreach ($results as $row) {
			$categories[] = $row->warna !== null ? $row->warna : 'Abu-abu';
			$data[] = (int) $row->jml_petak;
		}

		return response()->json([
			'categories' => $categories,
			'data' => $data
		]);
	}


	public function chartBarDataPica(Request $request)
	{
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$afd = $request->get('afd', '');
		$tipe = $request->get('tipe', '');
		if($tipe == 1){
			$table = 'q_pica_jml_batang';
		}else if($tipe == 2){
			$table = 'q_pica_tinggi_batang';
		}else if($tipe == 3){
			$table = 'q_pica_diameter_batang';
		}else{
			$table = 'q_pica_jml_batang';
		}
		$results = \DB::table($table)
			->selectRaw('count(*) as jml_petak, warna, bulan_tanam')
			->groupBy('bulan_tanam','warna')
			// ->whereNotNull('warna')
						->when($kebun, function ($query) use ($kebun) {
				return $query->where('kode_kebun', $kebun);
			})
			->when($rayon, function ($query) use ($rayon) {
				return $query->where('kode_rayon', $rayon);
			})
			->when($afd, function ($query) use ($afd) {
				return $query->where('afd', $afd);
			})
			->orderByRaw("FIELD(CONVERT(warna USING utf8mb4), 'EMAS', 'HIJAU', 'KUNING', 'MERAH', 'HITAM')")
			->orderBy('bulan_tanam')
			->get();

		$categories = [];
		$warna = [];
		$data = [];

		foreach ($results as $row) {
			$categories[] = $row->bulan_tanam;
			$warna[] = $row->warna !== null ? $row->warna : 'Abu-abu';
			$data[] = (int) $row->jml_petak;
		}

		return response()->json([
			'categories' => $categories,
			'warna' => $warna,
			'data' => $data
		]);
	}

	public function getTableDataPicaMorfologi( Request $request)
	{
		$pica = $request->get('pica', 'MERAH'); // default to 'MERAH' if not provided
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$afd = $request->get('afd', '');
		$tipe = $request->get('tipe', '');
		if($tipe == 1){
			$table = 'q_pica_jml_batang';
		}else if($tipe == 2){
			$table = 'q_pica_tinggi_batang';
		}else if($tipe == 3){
			$table = 'q_pica_diameter_batang';
		}else{
			$table = 'q_pica_jml_batang';
		}
		$results = \DB::table($table)
			
			->whereRaw("CONVERT(warna USING utf8mb4) COLLATE utf8mb4_unicode_ci = ?", [$pica])
			->whereNotNull('warna')
			->when($kebun, function ($query) use ($kebun) {
				return $query
					->selectRaw('master_kebun.nama_kebun,master_rayon.nama_rayon , count(*) as jml_petak, SUM(luas_ha) as ha_tebang, warna')
					->where('master_kebun.kode_kebun', $kebun)
					->groupBy('master_rayon.kode_rayon');
			})
			->when($rayon, function ($query) use ($rayon) {
				return $query
				->selectRaw('master_kebun.nama_kebun, master_rayon.nama_rayon,afd, count(*) as jml_petak, SUM(luas_ha) as ha_tebang, warna')
				->where('master_rayon.kode_rayon', $rayon)
				->groupBy('afd');
			})
			->when($afd, function ($query) use ($afd) {
				return $query
				->selectRaw('lahan_id, master_kebun.nama_kebun, master_rayon.nama_rayon,afd, count(*) as jml_petak, SUM(luas_ha) as ha_tebang, warna')
				->where('afd', $afd)
				->groupBy('lahan_id');
			})
			->leftJoin('master_kebun', \DB::raw("CONVERT(".$table.".kode_kebun USING utf8mb4) COLLATE utf8mb4_unicode_ci"), '=', \DB::raw("CONVERT(master_kebun.kode_kebun USING utf8mb4) COLLATE utf8mb4_unicode_ci"))
			->leftJoin('master_rayon', \DB::raw("CONVERT(".$table.".kode_rayon USING utf8mb4) COLLATE utf8mb4_unicode_ci"), '=', \DB::raw("CONVERT(master_rayon.kode_rayon USING utf8mb4) COLLATE utf8mb4_unicode_ci"))
			->selectRaw('master_kebun.nama_kebun , count(*) as jml_petak, SUM(luas_ha) as ha_tebang, warna')
			->groupBy($table.'.kode_kebun')
			->get();

		$html = '<table class="table table-responsive" border="1" cellpadding="5" cellspacing="0">';
		// Get column names from the first result
		$columns = [];
		if (count($results) > 0) {
			$columns = array_keys((array)$results[0]);
		}

		$html .= '<thead><tr>';
		foreach ($columns as $col) {
			$html .= '<th style="background: #0265c8;color: #FFF;">' . htmlspecialchars($col) . '</th>';
		}
		$html .= '</tr></thead><tbody>';

		$total_jml_petak = 0;
		$total_ha_tebang = 0;

		foreach ($results as $row) {
			$html .= '<tr>';
			foreach ($columns as $col) {
				if($col == 'warna') {
					// Apply color to the cell based on the 'warna' value
					$color = '';
					switch ($row->$col) {
						case 'Emas':
							$color = 'background-color:#FFD700; color: #000;';
							break;
						case 'Hijau':
							$color = 'background-color:#008000; color: #FFF;';
							break;
						case 'Kuning':
							$color = 'background-color:#FFFF00; color: #000;';
							break;
						case 'Merah':
							$color = 'background-color:#FF0000; color: #FFF;';
							break;
						case 'Hitam':
							$color = 'background-color:#000000; color: #FFF;';
							break;
					}
					$html .= '<td style="' . $color . '">' . htmlspecialchars($row->$col) . '</td>';
				} else if ($col == 'ha_tebang') {
					$html .= '<td>' . number_format($row->$col, 2) . '</td>';
				} else if ($col == 'jml_petak') {
					$html .= '<td>' . (int)$row->$col . '</td>';
				} else if ($col == 'nama_kebun' || $col == 'nama_rayon' || $col == 'afd') {
					$html .= '<td>' . htmlspecialchars($row->$col) . '</td>';
				} else if ($col == 'lahan_id') {
					$button = '';
					if (isset($row->warna) && strtoupper($row->warna) === 'HITAM') {
						$button = ' <button title="Input PICA" class="btn btn-sm btn-outline-primary" type="button" onclick="SximoModal(`' . url("pipica/indexmodal?lahan_id=" . htmlspecialchars($row->lahan_id)) . '`,`Input PICA`)"><i class="fa fa-pencil"></i> </button>';
					}
					$html .= '<td>' . htmlspecialchars($row->$col) .  '</td>';
					$html .= '<td>' . $button . '</td>';
				} else {
					$html .= '<td>' . htmlspecialchars($row->$col) . '</td>';
				}
			}
			$html .= '</tr>';

			if (isset($row->jml_petak)) {
				$total_jml_petak += (int)$row->jml_petak;
			}
			if (isset($row->ha_tebang)) {
				$total_ha_tebang += (float)$row->ha_tebang;
			}
		}

		// Add total row
		if (in_array('jml_petak', $columns) || in_array('ha_tebang', $columns)) {
			$html .= '<tr style="font-weight:bold;">';
			foreach ($columns as $col) {
				if ($col == 'jml_petak') {
					$html .= '<td>' . $total_jml_petak . '</td>';
				} elseif ($col == 'ha_tebang') {
					$html .= '<td>' . $total_ha_tebang . '</td>';
				} else {
					$html .= '<td></td>';
				}
			}
			$html .= '</tr>';
		}

		$html .= '</tbody></table>';

		return response($html);
	}

	public function picaeksekutif(Request $request)
	{
		// Make Sure users Logged 
		if(!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');
		$this->data = array_merge(array(
			'pageTitle2'	=> 'Pica Eksekutif',
			'pageNote2'	=> 'Data Pica Eksekutif',
			'pageModule2'=> 'picapetak',
			'return'	=> self::returnUrl()
		),$this->data);
		// Handle export logic here
		// This is a placeholder for the export functionality
		return view($this->module.'.pica_eksekutif', $this->data);
	}

	public function picaeksekutifmasapemeliharaan(Request $request)
	{
		return view($this->module.'.pica_masa_pemeliharaan', $this->data);
	}

	public function picaeksekutifmasapanen(Request $request)
	{
		return view($this->module.'.pica_masa_panen', $this->data);
	}

	public function chartLineAreaProblem(Request $request)
	{
		config(['app.debug' => true]);
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$afdeling = $request->get('afdeling', '');
		$problem_group = $request->get('problem_group', 'all');
		$results = \DB::table('tx_pica_pi')
			->join('master_petak', 'master_petak.lahan_id', '=', 'tx_pica_pi.lahan_id')
			->join('master_area_pica', 'master_area_pica.id', '=', 'tx_pica_pi.area_problem')
			->join('master_problem_group_pica', 'master_problem_group_pica.id', '=', 'tx_pica_pi.problem_group')
			->leftJoin('tx_pica_pi_problem as a', 'a.id_pica_pi', '=', 'tx_pica_pi.id')
			->leftJoin('tx_pica_pi_corrective as b', 'b.id_pica_pi_problem', '=', 'a.id')
			->leftJoin('tx_pica_pi_corrective_action as c', 'c.id_pica_pi_correction', '=', 'b.id_corrective')
			->leftJoin('master_problem_pica as d', 'd.id', '=', 'a.id_problem')
			->leftJoin('master_corective_pica as e', 'e.id', '=', 'b.id_corrective')
			->select('master_area_pica.area_problem', \DB::raw('count(*) as jumlah_petak'))
			->when($kebun, function ($query) use ($kebun) {
				return $query->where('master_petak.plant', $kebun);
			})
			->when($rayon, function ($query) use ($rayon) {
				return $query->where('master_petak.kode_rayon', $rayon);
			})
			->when($afdeling, function ($query) use ($afdeling) {
				return $query->where('master_petak.afd_new', $afdeling);
			})
			->when($problem_group, function ($query) use ($problem_group) {
				return $query->where('tx_pica_pi.problem_group', $problem_group);
			})
			->groupBy('master_area_pica.area_problem')
			->orderBy('jumlah_petak', 'desc')
			->get();

		$categories = [];
		$data = [];

		foreach ($results as $row) {
			$categories[] = $row->area_problem;
			$data[] = (int) $row->jumlah_petak;
		}

		return response()->json([
			'categories' => $categories,
			'data' => $data
		]);
	}

	public function chartLineAreaProblemDetail(Request $request)
	{
		config(['app.debug' => true]);
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$afdeling = $request->get('afdeling', '');
		$problem_group = $request->get('problem_group', '');
		$area_problem = $request->get('area_problem', '');
		$results = \DB::table('tx_pica_pi')
			->join('master_petak', 'master_petak.lahan_id', '=', 'tx_pica_pi.lahan_id')
			->join('master_area_pica', 'master_area_pica.id', '=', 'tx_pica_pi.area_problem')
			->join('master_problem_group_pica', 'master_problem_group_pica.id', '=', 'tx_pica_pi.problem_group')
			->leftJoin('tx_pica_pi_problem as a', 'a.id_pica_pi', '=', 'tx_pica_pi.id')
			->leftJoin('tx_pica_pi_corrective as b', 'b.id_pica_pi_problem', '=', 'a.id')
			->leftJoin('tx_pica_pi_corrective_action as c', 'c.id_pica_pi_correction', '=', 'b.id_corrective')
			->leftJoin('master_problem_pica as d', 'd.id', '=', 'a.id_problem')
			->leftJoin('master_corective_pica as e', 'e.id', '=', 'b.id_corrective')
			->select('tx_pica_pi.tanggal', 'master_petak.lahan_id', 'master_petak.nama_kebun', 'master_problem_group_pica.problem_group', 'master_area_pica.area_problem', 'd.problem', 'e.corrective', 'b.tanggal_target', 'c.tgl_penyelesaian', 'c.keterangan')
			->when($kebun, function ($query) use ($kebun) {
				return $query->where('master_petak.plant', $kebun);
			})
			->when($rayon, function ($query) use ($rayon) {
				return $query->where('master_petak.kode_rayon', $rayon);
			})
			->when($afdeling, function ($query) use ($afdeling) {
				return $query->where('master_petak.afd_new', $afdeling);
			})
			->when($problem_group, function ($query) use ($problem_group) {
				return $query->where('master_problem_group_pica.id', $problem_group);
			})
			->when($area_problem, function ($query) use ($area_problem) {
				return $query->where('master_area_pica.area_problem', $area_problem);
			})
			->get();

		// Build HTML table view
		$html = '<table class="table table-bordered" border="1" cellpadding="6" cellspacing="0">';
		$html .= '<thead><tr>';
		$headers = ['Tanggal','Lahan ID','Nama Kebun','Problem Group', 'Area Problem','Problem','Corrective Action','Tanggal Target','Status','Keterangan'];
		foreach ($headers as $h) {
			$html .= '<th>' . htmlspecialchars($h) . '</th>';
		}
		$html .= '</tr></thead><tbody>';

		$total = 0;
		$prev_lahan_id = null;
		foreach ($results as $row) {
			$html .= '<tr>';

			// tanggal
			$tgl = $row->tanggal ?? '';
			if (!empty($tgl)) {
				$ts = strtotime($tgl);
				$tgl = $ts ? date('Y-m-d', $ts) : $tgl;
			}
			$html .= '<td>' . htmlspecialchars($tgl) . '</td>';

			// lahan_id - hide if same as previous
			$current_lahan_id = $row->lahan_id ?? '';
			if ($current_lahan_id === $prev_lahan_id && !empty($current_lahan_id)) {
				$html .= '<td></td>';
				$html .= '<td></td>';
			} else {
				$html .= '<td class="font-bold">' . htmlspecialchars($current_lahan_id) . '</td>';
				$html .= '<td class="font-bold">' . htmlspecialchars($row->nama_kebun ?? '') . '</td>';
				$prev_lahan_id = $current_lahan_id;
			}

			// nama_kebun


			// problem_group, area_problem, problem
			$html .= '<td>' . htmlspecialchars($row->problem_group ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->area_problem ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->problem ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->corrective ?? '') . '</td>';
			
			// tanggal_target
			$tgl_target = $row->tanggal_target ?? '';
			if (!empty($tgl_target)) {
				$ts_target = strtotime($tgl_target);
				$tgl_target = $ts_target ? date('Y-m-d', $ts_target) : $tgl_target;
			}
			$html .= '<td>' . htmlspecialchars($tgl_target) . '</td>';
			
			// status
			$tgl_penyelesaian = $row->tgl_penyelesaian ?? '';
			if (!empty($tgl_penyelesaian)) {
				$ts_penyelesaian = strtotime($tgl_penyelesaian);
				$tgl_penyelesaian = $ts_penyelesaian ? date('Y-m-d', $ts_penyelesaian) : $tgl_penyelesaian;
			}
			$status = !empty($tgl_penyelesaian) ? '<i class="fa fa-check text-success"></i> Selesai ('.$tgl_penyelesaian.')' : '<i class="fa fa-cancel text-danger"></i> Belum Selesai';
			$html .= '<td>' . $status . '</td>';
			
			// keterangan
			$html .= '<td>' . htmlspecialchars($row->keterangan ?? '') . '</td>';

			$html .= '</tr>';
			$total++;
		}

		// total row
		$html .= '<tr style="font-weight:bold;background:#f0f0f0;">';
		$html .= '<td colspan="9">Total Baris</td>';
		$html .= '<td>' . $total . '</td>';
		$html .= '</tr>';

		$html .= '</tbody></table>';

		return response($html);
	}
	


		public function kuadranpica(Request $request)
	{
		// Make Sure users Logged 
		if(!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');
		$this->data = array_merge(array(
			'pageTitle2'	=> 'Pica Kuadran',
			'pageNote2'	=> 'Data Pica Kuadran',
			'pageModule2'=> 'picapetak',
			'return'	=> self::returnUrl()
		),$this->data);
		// Handle export logic here
		// This is a placeholder for the export functionality
		return view($this->module.'.pica_kuadran', $this->data);
	}

	public function getKuadranData(Request $request)
	{
		$periode = $request->get('periode', '');
		// if (empty($periode)) {
		// 	$day = (int)date('d');
		// 	$bulan = date('n'); // ambil nomor bulan (1-12)
		// 	$periode = ($day <= 15) ? $bulan . 'A' : $bulan . 'B';
		// }
		$tahun = $request->get('tahun', date('Y'));
		$params = [$periode, $tahun];
		$results = \DB::select('CALL sp_rekap_pica_kebun_cashcost(?, ?)', $params);

		$data = [];
		foreach ($results as $row) {
			$data[] = [
				'nama_kebun' => $row->nama_kebun,
				'nilai_pica' => (float)$row->nilai_pica,
				'cashcostpica_rpkg' => (float)$row->cashcostpica_rpkg,
			];
		}

		return response()->json([
			'data' => $data
		]);
	}

	public function getPicaDashboard(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');

		$params = [$cluster, $kebun, $rayon, $tgl];
		$results = \DB::select('CALL sp_pica_dashboard_1(?, ?, ?, ?)', $params);

		$html = '';
		if (!empty($results)) {
			$row = $results[0];

			// Format numbers
			$formatNum = function($val, $decimals = 2) {
				return number_format((float)$val, $decimals, ',', '.');
			};

			$html .= '<div class="row">';

			// Card 1: Luas Real vs RKAP
			$html .= '<div class="col-md-2-4" style="flex: 0 0 20%; padding: 10px;">';
			$html .= '<div class="card" style="border-top: 4px solid #3498db; box-shadow: 0 4px 8px rgba(0,0,0,0.12); margin-bottom: 20px; border-radius: 6px; height: 100%;">';
			$html .= '<div class="card-body" style="padding: 20px; text-align: center;">';
			$html .= '<h5 class="card-title" style="font-weight: 700; color: #333; margin-bottom: 20px; font-size: 14px;">Luas Areal (Ha)</h5>';
			$html .= '<div style="display: flow; grid-template-columns: 1fr 1fr; gap: 15px;">';
			$html .= '<div style="">';
			$html .= '<p style="margin: 0; font-size: 11px; color: #888; font-weight: 600; text-transform: uppercase; margin-bottom: 8px;">Real</p>';
			$html .= '<p style="margin: 0; font-size: 18px; color: #3498db; font-weight: 700;">' . $formatNum($row->luas_real ?? 0) . '</p>';
			$html .= '</div>';
			$html .= '<div style="">';
			$html .= '<p style="margin: 0; font-size: 11px; color: #888; font-weight: 600; text-transform: uppercase; margin-bottom: 8px;">RKAP</p>';
			$html .= '<p style="margin: 0; font-size: 18px; color: #3498db; font-weight: 700;">' . $formatNum($row->persen_luas_rkap ?? 0) . '%<br> <small>' . $formatNum($row->luas_rkap ?? 0) . '</small></p>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';

			// Card 2: Tebu Real vs RKAP
			$html .= '<div class="col-md-2-4" style="flex: 0 0 20%; padding: 10px;">';
			$html .= '<div class="card" style="border-top: 4px solid #2ecc71; box-shadow: 0 4px 8px rgba(0,0,0,0.12); margin-bottom: 20px; border-radius: 6px; height: 100%;">';
			$html .= '<div class="card-body" style="padding: 20px; text-align: center;">';
			$html .= '<h5 class="card-title" style="font-weight: 700; color: #333; margin-bottom: 20px; font-size: 14px;">Tebu (Ton)</h5>';
			$html .= '<div style="display: flow; grid-template-columns: 1fr 1fr; gap: 15px;">';
			$html .= '<div style="">';
			$html .= '<p style="margin: 0; font-size: 11px; color: #888; font-weight: 600; text-transform: uppercase; margin-bottom: 8px;">Real</p>';
			$html .= '<p style="margin: 0; font-size: 18px; color: #2ecc71; font-weight: 700;">' . $formatNum($row->tebu_real ?? 0) . '</p>';
			$html .= '</div>';
			$html .= '<div style="">';
			$html .= '<p style="margin: 0; font-size: 11px; color: #888; font-weight: 600; text-transform: uppercase; margin-bottom: 8px;">RKAP</p>';
			$html .= '<p style="margin: 0; font-size: 18px; color: #2ecc71; font-weight: 700;">' .$formatNum($row->persen_tebu_rkap ?? 0). '%<br> <small>' . $formatNum($row->tebu_rkap ?? 0) . '</small></p>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';

			// Card 3: Protas Real vs RKAP
			$html .= '<div class="col-md-2-4" style="flex: 0 0 20%; padding: 10px;">';
			$html .= '<div class="card" style="border-top: 4px solid #e74c3c; box-shadow: 0 4px 8px rgba(0,0,0,0.12); margin-bottom: 20px; border-radius: 6px; height: 100%;">';
			$html .= '<div class="card-body" style="padding: 20px; text-align: center;">';
			$html .= '<h5 class="card-title" style="font-weight: 700; color: #333; margin-bottom: 20px; font-size: 14px;">Protas (Ton/Ha)</h5>';
			$html .= '<div style="display: flow; grid-template-columns: 1fr 1fr; gap: 15px;">';
			$html .= '<div style="">';
			$html .= '<p style="margin: 0; font-size: 11px; color: #888; font-weight: 600; text-transform: uppercase; margin-bottom: 8px;">Real</p>';
			$html .= '<p style="margin: 0; font-size: 18px; color: #e74c3c; font-weight: 700;">' . $formatNum($row->protas_real ?? 0) . '</p>';
			$html .= '</div>';
			$html .= '<div style="">';
			$html .= '<p style="margin: 0; font-size: 11px; color: #888; font-weight: 600; text-transform: uppercase; margin-bottom: 8px;">RKAP</p>';
			$html .= '<p style="margin: 0; font-size: 18px; color: #e74c3c; font-weight: 700;">' . $formatNum($row->persen_protas_rkap ?? 0) . '%<br> <small>' . $formatNum($row->protas_rkap ?? 0) . '</small></p>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';

			// Card 4: Mutu A+B
			$html .= '<div class="col-md-2-4" style="flex: 0 0 20%; padding: 10px;">';
			$html .= '<div class="card" style="border-top: 4px solid #f39c12; box-shadow: 0 4px 8px rgba(0,0,0,0.12); margin-bottom: 20px; border-radius: 6px; height: 100%;">';
			$html .= '<div class="card-body" style="padding: 20px; text-align: center;">';
			$html .= '<h5 class="card-title" style="font-weight: 700; color: #333; margin-bottom: 20px; font-size: 14px;">Mutu A+B</h5>';
			$html .= '<div style="border: 1px solid #e0e0e0; padding: 10px; border-radius: 4px; background: linear-gradient(135deg, #fff9e6 0%, #fffbf0 100%); flex: 1; display: flex; align-items: center; justify-content: center; height: 80%;">';
			$html .= '<p style="margin: 0; font-size: 28px; color: #f39c12; font-weight: 700; text-align: center;">' . $formatNum($row->mutu_ab ?? 0) . '</p>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';

			// Card 5: Nilai PICA
			$html .= '<div class="col-md-2-4" style="flex: 0 0 20%; padding: 10px;">';
			$html .= '<div class="card" style="border-top: 4px solid #f312ce; box-shadow: 0 4px 8px rgba(0,0,0,0.12); margin-bottom: 20px; border-radius: 6px; height: 100%;">';
			$html .= '<div class="card-body" style="padding: 20px; text-align: center;">';
			$html .= '<h5 class="card-title" style="font-weight: 700; color: #333; margin-bottom: 20px; font-size: 14px;">Nilai PICA</h5>';
			$html .= '<div style="border: 1px solid #e0e0e0; padding: 10px; border-radius: 4px; background: linear-gradient(135deg, #fff9e6 0%, #fffbf0 100%); flex: 1; display: flex; align-items: center; justify-content: center; height: 80%;">';
			$html .= '<p style="margin: 0; font-size: 28px; color: #ce12f3; font-weight: 700; text-align: center;">' . $formatNum($row->nilai_pica ?? 0) . '</p>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';

			$html .= '</div>';
		} else {
			$html .= '<div class="alert alert-info">Tidak ada data tersedia</div>';
		}

		return response($html);
	}

	public function getDashboardPica2(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tanggal = $request->get('tgl');

		$params = [$cluster, $kebun, $rayon, $tanggal];
		$results = \DB::select('CALL sp_pica_dashboard_2(?, ?, ?, ?)', $params);

		if (!empty($results)) {
			$row = $results[0];

			$formatNum = function($val, $decimals = 2) {
				return number_format((float)$val, $decimals, ',', '.');
			};

			$html = '<div class="row">';

			// Card 1: Luas Tanam Kepras vs RKAP
			$html .= '<div class="col-md-2-4" style="flex: 0 0 19%; padding: 10px;">';
			$html .= '<div class="card" style="border-top: 4px solid #3498db; box-shadow: 0 4px 8px rgba(0,0,0,0.12); margin-bottom: 20px; border-radius: 6px; height: 100%;">';
			$html .= '<div class="card-body" style="padding: 20px; text-align: center;">';
			$html .= '<h5 class="card-title" style="font-weight: 700; color: #333; margin-bottom: 20px; font-size: 14px;">Luas Tanam (Ha)</h5>';
			$html .= '<div style="display: flow; grid-template-columns: 1fr 1fr; gap: 15px;">';
			$html .= '<div style="">';
			$html .= '<p style="margin: 0; font-size: 11px; color: #888; font-weight: 600; text-transform: uppercase; margin-bottom: 8px;">Kepras</p>';
			$html .= '<p style="margin: 0; font-size: 18px; color: #3498db; font-weight: 700;">' . $formatNum($row->luas_tanam_kepras ?? 0) . '</p>';
			$html .= '</div>';
			$html .= '<div style="">';
			$html .= '<p style="margin: 0; font-size: 11px; color: #888; font-weight: 600; text-transform: uppercase; margin-bottom: 8px;">RKAP</p>';
			$html .= '<p style="margin: 0; font-size: 18px; color: #3498db; font-weight: 700;">' . $formatNum($row->persen_luas_rkap ?? 0) . '%<br> <small>' . $formatNum($row->luas_rkap ?? 0) . '</small></p>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';

			// Card 2: Pupuk 1
			$html .= '<div class="col-md-2-4" style="flex: 0 0 19%; padding: 10px;">';
			$html .= '<div class="card" style="border-top: 4px solid #2ecc71; box-shadow: 0 4px 8px rgba(0,0,0,0.12); margin-bottom: 20px; border-radius: 6px; height: 100%;">';
			$html .= '<div class="card-body" style="padding: 20px; text-align: center;">';
			$html .= '<h5 class="card-title" style="font-weight: 700; color: #333; margin-bottom: 20px; font-size: 14px;">Pupuk 1</h5>';
			$html .= '<div style="border: 1px solid #e0e0e0; padding: 10px; border-radius: 4px; background: linear-gradient(135deg, #e8f8f5 0%, #f0fdf4 100%); flex: 1; display: flex; align-items: center; justify-content: center; height: 80%;">';
			$html .= '<div style="text-align: center;">';
			$html .= '<p style="margin: 0; font-size: 28px; color: #2ecc71; font-weight: 700;">' . $formatNum($row->persen_pupuk_1 ?? 0) . '%</p>';
			$html .= '<p style="margin: 5px 0 0 0; font-size: 12px; color: #666;">' . $formatNum($row->luas_pupuk_1 ?? 0) . ' Ha</p>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';

			// Card 3: Pupuk 2
			$html .= '<div class="col-md-2-4" style="flex: 0 0 19%; padding: 10px;">';
			$html .= '<div class="card" style="border-top: 4px solid #e74c3c; box-shadow: 0 4px 8px rgba(0,0,0,0.12); margin-bottom: 20px; border-radius: 6px; height: 100%;">';
			$html .= '<div class="card-body" style="padding: 20px; text-align: center;">';
			$html .= '<h5 class="card-title" style="font-weight: 700; color: #333; margin-bottom: 20px; font-size: 14px;">Pupuk 2</h5>';
			$html .= '<div style="border: 1px solid #e0e0e0; padding: 10px; border-radius: 4px; background: linear-gradient(135deg, #fadbd8 0%, #f5b7b1 100%); flex: 1; display: flex; align-items: center; justify-content: center; height: 80%;">';
			$html .= '<div style="text-align: center;">';
			$html .= '<p style="margin: 0; font-size: 28px; color: #e74c3c; font-weight: 700;">' . $formatNum($row->persen_pupuk_2 ?? 0) . '%</p>';
			$html .= '<p style="margin: 5px 0 0 0; font-size: 12px; color: #666;">' . $formatNum($row->luas_pupuk_2 ?? 0) . ' Ha</p>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';

			// Card 4: Penyerapan Biaya Garap
			$html .= '<div class="col-md-2-4" style="flex: 0 0 19%; padding: 10px;">';
			$html .= '<div class="card" style="border-top: 4px solid #f39c12; box-shadow: 0 4px 8px rgba(0,0,0,0.12); margin-bottom: 20px; border-radius: 6px; height: 100%;">';
			$html .= '<div class="card-body" style="padding: 20px; text-align: center;">';
			$html .= '<h5 class="card-title" style="font-weight: 700; color: #333; margin-bottom: 20px; font-size: 14px;">Penyerapan Biaya Garap</h5>';
			$html .= '<div style="border: 1px solid #e0e0e0; padding: 10px; border-radius: 4px; background: linear-gradient(135deg, #fff9e6 0%, #fffbf0 100%); flex: 1; display: flex; align-items: center; justify-content: center; height: 71%;">';
			$html .= '<p style="margin: 0; font-size: 28px; color: #f39c12; font-weight: 700; text-align: center;">' . $formatNum($row->penyerapan_biaya_garap ?? 0) . '</p>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';

			// Card 5: Nilai PICA
			$html .= '<div class="col-md-2-4" style="flex: 0 0 19%; padding: 10px;">';
			$html .= '<div class="card" style="border-top: 4px solid #9b59b6; box-shadow: 0 4px 8px rgba(0,0,0,0.12); margin-bottom: 20px; border-radius: 6px; height: 100%;">';
			$html .= '<div class="card-body" style="padding: 20px; text-align: center;">';
			$html .= '<h5 class="card-title" style="font-weight: 700; color: #333; margin-bottom: 20px; font-size: 14px;">Nilai PICA</h5>';
			$html .= '<div style="border: 1px solid #e0e0e0; padding: 10px; border-radius: 4px; background: linear-gradient(135deg, #f4ecf7 0%, #faf5ff 100%); flex: 1; display: flex; align-items: center; justify-content: center; height: 80%;">';
			$html .= '<p style="margin: 0; font-size: 28px; color: #9b59b6; font-weight: 700; text-align: center;">' . $formatNum($row->nilai_pica ?? 0) . '</p>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';
			$html .= '</div>';

			$html .= '</div>';
		} else {
			$html = '<div class="alert alert-info">Tidak ada data tersedia</div>';
		}

		return response($html);
	}

	



	public function formKuadranKinerja(Request $request)
	{
		// Make Sure users Logged 
		if(!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');
		$this->data = array_merge(array(
			'pageTitle'	=> 'Kuadran Kinerja Kebun KSO',
			'pageNote'	=> 'Data Kuadran Kinerja Kebun KSO',
			'pageModule'=> 'picapetak',
			'return'	=> self::returnUrl()
		),$this->data);
		return view($this->module.'.kuadran_kinerja_kebun_kso', $this->data);
	}

	public function formKuadranKinerja888(Request $request)
	{
		// Make Sure users Logged 
		if(!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');
		$this->data = array_merge(array(
			'pageTitle'	=> 'Kuadran Kinerja Kebun KSO',
			'pageNote'	=> 'Data Kuadran Kinerja Kebun KSO',
			'pageModule'=> 'picapetak',
			'return'	=> self::returnUrl()
		),$this->data);
		return view($this->module.'.kuadran_kinerja_kebun_kso_888', $this->data);
	}

	public function getKuadranKinerjaTable888(Request $request)
	{
		config(['app.debug' => true]);
		$cluster = $request->get('cluster');
		$bulan = $request->get('bulan');
		$kategori = $request->get('kategori');
		
		$params = [$cluster, $bulan];

		if($kategori == 'hi'){
			$results = \DB::select('CALL kuadran_kinerja_kebun_kso_new_888_hi(?, ?)', $params);
		}else if($kategori == 'sd'){
			$results = \DB::select('CALL kuadran_kinerja_kebun_kso_new_888(?, ?)', $params);
		}
		

		$html = '<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; overflow: hidden; box-shadow: 0 4px 18px rgba(0,0,0,0.13); font-size: 13px; }
			.kuadran-table-wrap-888 .kuadran-table thead tr:first-child { background: linear-gradient(135deg, #1a3b5c 0%, #2c5c8f 60%, #3498db 100%); }
			.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 .= '<div class="table-responsive kuadran-table-wrap-888">';
		$html .= '<table class="kuadran-table" id="tablediv888">';
		$html .= '<thead>';
		
		// First header row with category names
		$html .= '<tr>';
		$html .= '<th>Kebun</th>';
		$html .= '<th colspan="3" class="kuadran-table-group-header">Protas</th>';
		$html .= '<th colspan="3" class="kuadran-table-group-header">Rendemen</th>';
		$html .= '<th colspan="3" class="kuadran-table-group-header">Mutu AB</th>';
		$html .= '<th colspan="3" class="kuadran-table-group-header">Pasok</th>';
		$html .= '<th colspan="3" class="kuadran-table-group-header">Cut to Crush</th>';
		$html .= '</tr>';
		
		// Second header row with sub-categories
		$html .= '<tr style="background: #1a3b5c;">';
		$subHeaders = ['Pertahankan', 'Waspada', 'Bahaya'];
		$html .= '<th></th>';
		// Group separators for sub-headers: indices 1, 4, 7, 10, 13
		$groupSeparators = [1, 4, 7, 10, 13];
		for ($i = 0; $i < 5; $i++) {
			foreach ($subHeaders as $idx => $sh) {
				$headerIdx = $i * 3 + $idx + 1; // +1 because first column is Kebun
				$className = '';
				if ($sh === 'Pertahankan') {
					$className = 'group-green'; // Green
				} elseif ($sh === 'Waspada') {
					$className = 'group-orange'; // Orange
				} else { // Bahaya
					$className = 'group-red'; // Red
				}
				$sep = in_array($headerIdx, $groupSeparators) ? ' kuadran-table-group-header' : '';
				$html .= '<th class="' . $className . $sep . '">' . $sh . '</th>';
			}
		}
		$html .= '</tr>';
		$html .= '</thead><tbody>';
		
		$rowCount = 0;
		foreach ($results as $row) {
			$rowClass = ($rowCount % 2 === 0) ? 'row-even' : 'row-odd';
			$isTotalRow = (stripos($row->Kebun ?? '', 'jumlah') !== false || stripos($row->Kebun ?? '', 'Total') !== false);
			$tdClass = $isTotalRow ? 'td-total' : 'td-num';

			$html .= '<tr class="' . $rowClass . '">';
			
			// Kebun column
			$html .= '<td class="td-kebun">' . htmlspecialchars($row->Kebun ?? '') . '</td>';
			
			// Produktivitas columns
			$html .= '<td class="' . $tdClass . ' group-separator-888">' . ($row->protas_pertahankan ?? '') . '</td>';
			$html .= '<td class="' . $tdClass . ' separator-888">' . ($row->protas_waspada ?? '') . '</td>';
			$html .= '<td class="' . $tdClass . ' separator-888">' . ($row->protas_bahaya ?? '') . '</td>';
			
			// Rendemen columns
			$html .= '<td class="' . $tdClass . ' group-separator-888">' . ($row->rendemen_pertahankan ?? '') . '</td>';
			$html .= '<td class="' . $tdClass . ' separator-888">' . ($row->rendemen_waspada ?? '') . '</td>';
			$html .= '<td class="' . $tdClass . ' separator-888">' . ($row->rendemen_bahaya ?? '') . '</td>';
			
			// Mutu AB columns
			$html .= '<td class="' . $tdClass . ' group-separator-888">' . ($row->mutu_ab_pertahankan ?? '') . '</td>';
			$html .= '<td class="' . $tdClass . ' separator-888">' . ($row->mutu_ab_waspada ?? '') . '</td>';
			$html .= '<td class="' . $tdClass . ' separator-888">' . ($row->mutu_ab_bahaya ?? '') . '</td>';
			
			// Pasok columns
			$html .= '<td class="' . $tdClass . ' group-separator-888">' . ($row->pasok_pertahankan ?? '') . '</td>';
			$html .= '<td class="' . $tdClass . ' separator-888">' . ($row->pasok_waspada ?? '') . '</td>';
			$html .= '<td class="' . $tdClass . ' separator-888">' . ($row->pasok_bahaya ?? '') . '</td>';
			
			// Cut to Crush columns
			$html .= '<td class="' . $tdClass . ' group-separator-888">' . ($row->cut_to_crush_pertahankan ?? '') . '</td>';
			$html .= '<td class="' . $tdClass . ' separator-888">' . ($row->cut_to_crush_waspada ?? '') . '</td>';
			$html .= '<td class="' . $tdClass . ' separator-888">' . ($row->cut_to_crush_bahaya ?? '') . '</td>';
			
			$html .= '</tr>';
			$rowCount++;
		}
		$html .= '</tbody></table>';
		$html .= '</div>';

		// Ranking section from kuadran_kinerja_kebun_kso_new_888_ranking
		if($kategori == 'hi') {
			$ranking = \DB::select('CALL kuadran_kinerja_kebun_kso_new_888_ranking_hi(?, ?)', $params);
		} else if ($kategori == 'sd') {
			$ranking = \DB::select('CALL kuadran_kinerja_kebun_kso_new_888_ranking(?, ?)', $params);
		}
		
		$html .= '<div style="margin-top: 35px; padding: 20px; background-color: #ffffff; border: 1px solid #dee2e6; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.07);">';
		$html .= '<h4 style="font-weight: 700; margin-bottom: 18px; color: #2c3e50; border-left: 4px solid #3498db; padding-left: 10px; font-size: 15px;">🏆 Ranking Kebun KSO</h4>';
		$html .= '<table style="width: 100%; border-collapse: collapse; font-size: 13px; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 4px rgba(0,0,0,0.08);">';
		$html .= '<thead>';
		$html .= '<tr style="background: linear-gradient(135deg, #2c3e50, #3498db); color: #ffffff;">';
		$html .= '<th style="text-align: center; padding: 12px 10px; font-weight: 600; letter-spacing: 0.5px; width: 80px;">Ranking</th>';
		$html .= '<th style="text-align: left; padding: 12px 10px; font-weight: 600; letter-spacing: 0.5px; width: 120px;">Kode Kebun</th>';
		$html .= '<th style="text-align: left; padding: 12px 10px; font-weight: 600; letter-spacing: 0.5px;">Kebun</th>';
		$html .= '<th style="text-align: center; padding: 12px 10px; font-weight: 600; letter-spacing: 0.5px; width: 110px;">Total Poin</th>';
		$html .= '<th style="text-align: center; padding: 12px 10px; font-weight: 600; letter-spacing: 0.5px; width: 180px;">Status Indikator</th>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		
		foreach ($ranking as $row) {
			$rankNum = intval($row->ranking ?? 0);
			$bgColor = $rankNum % 2 === 0 ? '#ffffff' : '#f4f8ff';
			$rankBadge = '';
			$badgeFontSize = '15px';
			if ($rankNum === 1) {
				$rankBadge = '🥇';
				$badgeFontSize = '33px';
			} elseif ($rankNum === 2) {
				$rankBadge = '🥈';
				$badgeFontSize = '33px';
			} elseif ($rankNum === 3) {
				$rankBadge = '🥉';
				$badgeFontSize = '33px';
			} else {
				$rankBadge = '#' . $rankNum;
			}
			$statusIndikatorRaw = $row->status_indikator ?? '';
			$statusParts = array_map('trim', explode(',', $statusIndikatorRaw));
			$statusBadgesHtml = '';
			foreach ($statusParts as $part) {
				if ($part === '') continue;
				$partEscaped = htmlspecialchars($part);
				$sColor = '#6c757d';
				$sBg = '#f8f9fa';
				if (stripos($part, 'pertahankan') !== false) {
					$sColor = '#155724'; $sBg = '#d4edda';
				} elseif (stripos($part, 'waspada') !== false) {
					$sColor = '#856404'; $sBg = '#fff3cd';
				} elseif (stripos($part, 'bahaya') !== false) {
					$sColor = '#721c24'; $sBg = '#f8d7da';
				}
				$statusBadgesHtml .= '<span style="display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 11px; font-weight: 600; background-color: ' . $sBg . '; color: ' . $sColor . '; border: 1px solid ' . $sColor . '; margin: 2px 2px;">' . $partEscaped . '</span>';
			}
			$html .= '<tr style="background-color: ' . $bgColor . '; transition: background 0.2s;" onmouseover="this.style.backgroundColor=\'#eaf3ff\'" onmouseout="this.style.backgroundColor=\'' . $bgColor . '\'">';
			$html .= '<td style="text-align: center; padding: 11px 10px; border-bottom: 1px solid #e9ecef; font-weight: 700; font-size: ' . $badgeFontSize . '; color: #2c3e50;">' . $rankBadge . '</td>';
			$html .= '<td style="text-align: left; padding: 11px 10px; border-bottom: 1px solid #e9ecef; font-weight: 600; color: #3498db; font-family: monospace; font-size: 13px;">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
			$html .= '<td style="text-align: left; padding: 11px 10px; border-bottom: 1px solid #e9ecef; color: #2c3e50;width: 10px">' . htmlspecialchars($row->Kebun ?? '') . '</td>';
			$html .= '<td style="text-align: center; padding: 11px 10px; border-bottom: 1px solid #e9ecef; font-weight: 700; font-size: 14px; color: #2980b9;">' . htmlspecialchars($row->total_poin ?? '') . '</td>';
			$html .= '<td style="text-align: center; padding: 11px 10px; border-bottom: 1px solid #e9ecef;">' . $statusBadgesHtml . '</td>';
			$html .= '</tr>';
		}
		
		$html .= '</tbody>';
		$html .= '</foot>';
		$html .= '<tr style="background: linear-gradient(135deg, #2c3e50, #3498db); color: #ffffff;">';	
		$html .= '<th style="text-align: center; padding: 12px 10px; font-weight: 600; letter-spacing: 0.5px; width: 80px;"></th>';
		$html .= '<th style="text-align: left; padding: 12px 10px; font-weight: 600; letter-spacing: 0.5px; width: 120px;"></th>';
		$html .= '<th style="text-align: left; padding: 12px 10px; font-weight: 600; letter-spacing: 0.5px;"></th	>';
		$html .= '<th style="text-align: center; padding: 12px 10px; font-weight: 600; letter-spacing: 0.5px; width: 110px;"></th>';
		$html .= '<th style="text-align: center; padding: 12px 10px; font-weight: 600; letter-spacing: 0	px; width: 180px;"><button onclick="loadInfoIndikatorModal()" style="background: linear-gradient(135deg, #ff9800, #e67e22); color: #fff; border: none; border-radius: 6px; padding: 9px 20px; font-size: 13px; font-weight: 600; cursor: pointer; box-shadow: 0 2px 6px rgba(0,0,0,0.15); letter-spacing: 0.3px;">🔍 Lihat Info Indikator</button></th>';
		$html .= '</tr>';
		$html .= '</foot>';

		$html .= '</table>';
		$html .= '</div>';

		// Button to open detail indicator modal
		$html .= '<div style="margin-top: 16px; text-align: right;">';
		$html .= '';
		$html .= '</div>';

		// Modal for detail indicator
		$html .= '<div id="modalInfoIndikator" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:9999; overflow:auto;">';
		$html .= '<div style="background:#fff; margin:40px auto; border-radius:10px; max-width:95%; width:1100px; box-shadow:0 8px 32px rgba(0,0,0,0.2); overflow:hidden;">';
		$html .= '<div style="background:linear-gradient(135deg,#2980b9,#1a5276); padding:16px 20px; display:flex; justify-content:space-between; align-items:center;">';
		$html .= '<h5 style="margin:0; color:#fff; font-size:15px; font-weight:700;">🔍 Detail Info Indikator Kinerja Kebun</h5>';
		$html .= '<button onclick="document.getElementById(\'modalInfoIndikator\').style.display=\'none\'" style="background:transparent; border:none; color:#fff; font-size:22px; cursor:pointer; line-height:1;">&times;</button>';
		$html .= '</div>';
		$html .= '<div id="modalInfoIndikatorBody" style="padding:20px; overflow-x:auto; min-height:100px; font-size:13px;">';
		$html .= '<div style="text-align:center; color:#999; padding:30px;">Memuat data...</div>';
		$html .= '</div>';
		$html .= '</div>';
		$html .= '</div>';

		$html .= '<script>';
		$html .= 'function loadInfoIndikatorModal() {';
						//ajax request to fetch the modal content
		$html .= 'var modalBody = document.getElementById("modalInfoIndikatorBody");';
		$html .= 'modalBody.innerHTML = \'<div style="text-align:center; color:#999; padding:30px;">Memuat data...</div>\';';
		$html .= 'document.getElementById("modalInfoIndikator").style.display = "block";';
		$html .= 'fetch("' . url('picapetak/getInfoIndikatorKinerja?cluster=' . $cluster) . '&bulan=' . $bulan . '&kategori=' . $kategori . '")';
		$html .= '.then(response => response.text())';
		$html .= '.then(data => { modalBody.innerHTML = data; })';
		$html .= '.catch(error => { modalBody.innerHTML = \'<div style="text-align:center; color:#e74c3c; padding:30px;">Terjadi kesalahan saat memuat data.</div>\'; console.error("Error fetching info indikator:", error); }); ';

		$html .= '}';
		$html .= '</script>';

		
		// Notes section from master_kriteria_kuadran_kso_888
		$kriteria = \DB::table('master_kriteria_kuadran_kso_888')
			->where('aktif', 1)
			->orderBy('indikator')
			->orderBy('urutan')
			->get();
		
		$kriteriaByIndikator = [];
		foreach ($kriteria as $k) {
			if (!isset($kriteriaByIndikator[$k->indikator])) {
				$kriteriaByIndikator[$k->indikator] = [];
			}
			$kriteriaByIndikator[$k->indikator][] = $k;
		}
		
		$html .= '<div style="margin-top: 24px; padding: 20px; background-color: #ffffff; border: 1px solid #dee2e6; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.06);">';
		$html .= '<h5 style="font-weight: 700; margin-bottom: 14px; color: #343a40; font-size: 14px; letter-spacing: 0.5px; border-left: 4px solid #495057; padding-left: 10px;">📋 Catatan Kriteria Indikator</h5>';
		$html .= '<table style="width: 100%; border-collapse: collapse; font-size: 12px; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 4px rgba(0,0,0,0.08);">';
		$html .= '<thead>';
		$html .= '<tr style="background: linear-gradient(135deg, #495057, #343a40);">';
		$html .= '<th style="text-align: center; padding: 10px 12px; border: 1px solid #555; color: #ffffff; font-weight: 700; font-size: 11px; letter-spacing: 0.5px; text-transform: uppercase;">PROTAS</th>';
		$html .= '<th style="text-align: center; padding: 10px 12px; border: 1px solid #555; color: #ffffff; font-weight: 700; font-size: 11px; letter-spacing: 0.5px; text-transform: uppercase;">RENDEMEN</th>';
		$html .= '<th style="text-align: center; padding: 10px 12px; border: 1px solid #555; color: #ffffff; font-weight: 700; font-size: 11px; letter-spacing: 0.5px; text-transform: uppercase;">MUTU A+B</th>';
		$html .= '<th style="text-align: center; padding: 10px 12px; border: 1px solid #555; color: #ffffff; font-weight: 700; font-size: 11px; letter-spacing: 0.5px; text-transform: uppercase;">PASOK</th>';
		$html .= '<th style="text-align: center; padding: 10px 12px; border: 1px solid #555; color: #ffffff; font-weight: 700; font-size: 11px; letter-spacing: 0.5px; text-transform: uppercase;">CUT TO CRUSH</th>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';

		// Bahaya row
		$html .= '<tr style="background-color: #fff5f5;">';
		foreach (['PRODUKTIVITAS', 'RENDEMEN', 'MUTU_AB', 'PASOK', 'CUT_TO_CRUSH'] as $indikator) {
			$bahaya = collect($kriteriaByIndikator[$indikator] ?? [])->firstWhere('kategori', 'BAHAYA');
			$text = $bahaya ? '<span style="display:inline-block; padding: 2px 7px; border-radius: 10px; background-color: #f8d7da; color: #721c24; font-weight: 700; font-size: 10px; margin-bottom: 3px;">⚠ BAHAYA</span><br><span style="color: #721c24; font-size: 11px;">' . $bahaya->keterangan . '</span>' : '<span style="color: #ccc; font-style: italic; font-size: 11px;">-</span>';
			$html .= '<td style="padding: 10px 12px; border: 1px solid #f5c6cb; vertical-align: top;">' . $text . '</td>';
		}
		$html .= '</tr>';

		// Waspada row
		$html .= '<tr style="background-color: #fffdf0;">';
		foreach (['PRODUKTIVITAS', 'RENDEMEN', 'MUTU_AB', 'PASOK', 'CUT_TO_CRUSH'] as $indikator) {
			$waspada = collect($kriteriaByIndikator[$indikator] ?? [])->firstWhere('kategori', 'WASPADA');
			$text = $waspada ? '<span style="display:inline-block; padding: 2px 7px; border-radius: 10px; background-color: #fff3cd; color: #856404; font-weight: 700; font-size: 10px; margin-bottom: 3px;">🔔 WASPADA</span><br><span style="color: #856404; font-size: 11px;">' . $waspada->keterangan . '</span>' : '<span style="color: #ccc; font-style: italic; font-size: 11px;">-</span>';
			$html .= '<td style="padding: 10px 12px; border: 1px solid #ffeeba; vertical-align: top;">' . $text . '</td>';
		}
		$html .= '</tr>';

		// Pertahankan row
		$html .= '<tr style="background-color: #f4fff7;">';
		foreach (['PRODUKTIVITAS', 'RENDEMEN', 'MUTU_AB', 'PASOK', 'CUT_TO_CRUSH'] as $indikator) {
			$pertahankan = collect($kriteriaByIndikator[$indikator] ?? [])->firstWhere('kategori', 'PERTAHANKAN');
			$text = $pertahankan ? '<span style="display:inline-block; padding: 2px 7px; border-radius: 10px; background-color: #d4edda; color: #155724; font-weight: 700; font-size: 10px; margin-bottom: 3px;">✅ PERTAHANKAN</span><br><span style="color: #155724; font-size: 11px;">' . $pertahankan->keterangan . '</span>' : '<span style="color: #ccc; font-style: italic; font-size: 11px;">-</span>';
			$html .= '<td style="padding: 10px 12px; border: 1px solid #c3e6cb; vertical-align: top;">' . $text . '</td>';
		}
		$html .= '</tr>';

		$html .= '</tbody>';
		$html .= '</table>';
		$html .= '</div>';

		return array('html' => $html, 'tanggal' => $results[0]->tanggal ?? '');
		// return response($html);
	}

	public function getInfoIndikatorKinerja(Request $request)
	{
		config(['app.debug' => true]);
		$nama_kebun = $request->get('cluster');
		$tahun = $request->get('bulan');
		$kategori = $request->get('kategori');

		$params = [$nama_kebun, $tahun];
		if($kategori == 'hi') {
			$results = \DB::select('CALL kuadran_kinerja_kebun_kso_new_888_ranking_detil_hi(?, ?)', $params);
		} else if ($kategori == 'sd') {
			$results = \DB::select('CALL kuadran_kinerja_kebun_kso_new_888_ranking_detil(?, ?)', $params);
		}
		
		$html = '<style>
			.tbl-indikator { width: 100%; border-collapse: separate; border-spacing: 0; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 18px rgba(0,0,0,0.10); font-size: 13px; }
			.tbl-indikator thead tr { background: linear-gradient(135deg, #1a7f4b 0%, #27ae60 100%); color: #fff; }
			.tbl-indikator thead th { padding: 13px 14px; font-weight: 700; text-align: center; vertical-align: middle; letter-spacing: 0.03em; border: none; }
			.tbl-indikator tbody tr:nth-child(even) { background-color: #f4fdf7; }
			.tbl-indikator tbody tr:nth-child(odd) { background-color: #ffffff; }
			.tbl-indikator tbody tr:hover { background-color: #e2f5ea; transition: background 0.2s; }
			.tbl-indikator tbody td { padding: 11px 14px; border-bottom: 1px solid #e0ede6; vertical-align: top; }
			.tbl-indikator tbody tr:last-child td { border-bottom: none; }
			.badge-pertahankan { display: inline-block; padding: 2px 9px; border-radius: 12px; background: #d4edda; color: #155724; font-weight: 700; font-size: 11px; margin-bottom: 4px; }
			.badge-waspada { display: inline-block; padding: 2px 9px; border-radius: 12px; background: #fff3cd; color: #856404; font-weight: 700; font-size: 11px; margin-bottom: 4px; }
			.badge-bahaya { display: inline-block; padding: 2px 9px; border-radius: 12px; background: #f8d7da; color: #721c24; font-weight: 700; font-size: 11px; margin-bottom: 4px; }
			.status-pill { display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; background: #eaf6ee; color: #1a7f4b; border: 1px solid #b2dfca; white-space: nowrap; }
			.kebun-name { font-weight: 700; color: #1a5e35; font-size: 13px; }
			.indikator-item { font-size: 11.5px; color: #444; margin-bottom: 2px; line-height: 1.5; }
			.no-data { color: #bbb; font-style: italic; font-size: 11px; }
		</style>';

		$html .= '<div class="table-responsive" style="border-radius:12px; overflow:hidden;">';
		$html .= '<table class="tbl-indikator">';
		$html .= '<thead><tr>';
		$html .= '<th style="width:14%;">🏭 Kebun</th>';
		$html .= '<th style="width:18%;">📊 Status Indikator</th>';
		$html .= '<th style="width:23%;">✅ Pertahankan</th>';
		$html .= '<th style="width:23%;">🔔 Waspada</th>';
		$html .= '<th style="width:22%;">⚠ Bahaya</th>';
		$html .= '</tr></thead><tbody>';

		foreach ($results as $row) {
			$html .= '<tr>';

			// Kebun
			$html .= '<td><span class="kebun-name">' . htmlspecialchars($row->Kebun ?? $row->nama_kebun ?? '') . '</span></td>';

			// Status
			$status = htmlspecialchars($row->status_indikator ?? '');
			$html .= '<td><span class="status-pill">' . $status . '</span></td>';

			// Pertahankan
			$pertahankan = $row->indikator_pertahankan ?? null;
			if ($pertahankan) {
				$items = explode(';', $pertahankan);
				$html .= '<td>';
				$html .= '<span class="badge-pertahankan">✅ PERTAHANKAN</span><br>';
				foreach ($items as $item) {
					$item = trim($item);
					if ($item) $html .= '<div class="indikator-item">• ' . htmlspecialchars($item) . '</div>';
				}
				$html .= '</td>';
			} else {
				$html .= '<td><span class="no-data">-</span></td>';
			}

			// Waspada
			$waspada = $row->indikator_waspada ?? null;
			if ($waspada) {
				$items = explode(';', $waspada);
				$html .= '<td>';
				$html .= '<span class="badge-waspada">🔔 WASPADA</span><br>';
				foreach ($items as $item) {
					$item = trim($item);
					if ($item) $html .= '<div class="indikator-item">• ' . htmlspecialchars($item) . '</div>';
				}
				$html .= '</td>';
			} else {
				$html .= '<td><span class="no-data">-</span></td>';
			}

			// Bahaya
			$bahaya = $row->indikator_bahaya ?? null;
			if ($bahaya) {
				$items = explode(';', $bahaya);
				$html .= '<td>';
				$html .= '<span class="badge-bahaya">⚠ BAHAYA</span><br>';
				foreach ($items as $item) {
					$item = trim($item);
					if ($item) $html .= '<div class="indikator-item">• ' . htmlspecialchars($item) . '</div>';
				}
				$html .= '</td>';
			} else {
				$html .= '<td><span class="no-data">-</span></td>';
			}

			$html .= '</tr>';
		}

		$html .= '</tbody></table></div>';

		return response($html);
	}

	

	public function getKuadranKinerja(Request $request)
	{
		$nama_kebun = $request->get('cluster');
		$tahun = $request->get('bulan');
		
		$params = [$nama_kebun, $tahun];
		$results = \DB::select('CALL kuadran_kinerja_kebun_kso(?, ?)', $params);

		$data = [];
		foreach ($results as $row) {
			$data[] = [
				'id' => isset($row->id) ? $row->id : null,
				'nama_kebun' => isset($row->nama_kebun) ? $row->nama_kebun : null,
				'nilai_x' => isset($row->x_cashcost) ? (float)$row->x_cashcost : 0.0,
				'nilai_y' => isset($row->y_ipo) ? (float)$row->y_ipo : 0.0,
				'kuadran' => isset($row->nama_kuadran) ? $row->nama_kuadran : null,
			];
		}

		$html = '<div class="table-responsive">';
		$html .= '<table class="table table-hover table-striped" style="box-shadow: 0 2px 4px rgba(0,0,0,0.1); border-radius: 4px; overflow: hidden; border: 1px solid #dee2e6;">';
		$html .= '<thead><tr style="background: #FFF; color: white;">';
		$headers = ['Kebun', 'Real<br>Produktivitas<br>(Bobot 40%)', 'Real<br>Rendemen<br>(Bobot 40%)', 'Real<br>Pasok<br>(Bobot 20%)', 'x_cashcost', 'y_ipo'];
		foreach ($headers as $h) {
			$html .= '<th style="text-align:center; vertical-align: middle; padding: 12px; font-weight: 600; font-size: 13px; color: #333;">' . $h . '</th>';
		}
		$html .= '</tr></thead><tbody>';	
		$rowCount = 0;
		foreach ($results as $row) {
			$bgColor = ($rowCount % 2 === 0) ? '#f8f9fa' : '#ffffff';
			$html .= '<tr style="background-color: ' . $bgColor . '; transition: background-color 0.2s ease;">';
			$html .= '<td style="padding: 10px 12px; font-weight: 500;" onmouseover="this.parentElement.style.backgroundColor=\'#e8f0f7\';" onmouseout="this.parentElement.style.backgroundColor=\'' . $bgColor . '\';">' . htmlspecialchars($row->nama_kebun ?? '') . '</td>';
			$html .= '<td style="text-align:right; padding: 10px 12px;">' . number_format($row->real_protas ?? 0, 2) . '</td>';
			$html .= '<td style="text-align:right; padding: 10px 12px;">' . number_format($row->real_rendemen ?? 0, 2) . '</td>';
			$html .= '<td style="text-align:right; padding: 10px 12px;">' . htmlspecialchars($row->real_pasok_ton ?? '') . '</td>';
			$html .= '<td style="text-align:right; padding: 10px 12px;">' . number_format($row->x_cashcost ?? 0, 0) . '</td>';
			$html .= '<td style="text-align:right; padding: 10px 12px;">' . number_format($row->y_ipo ?? 0, 2) . '</td>';
			$html .= '</tr>';
			$rowCount++;
		}
		$html .= '</tbody></table>';
		$html .= '</div>';

		$setting = \DB::table('setting_kuadran_kinerja')->where('id', 1)->first();

		return response()->json([
			'data' => $data,
			'html' => $html,
			'setting' => [
				'xMin' => isset($setting->xMin) ? (float)$setting->xMin : 0.0,
				'xMax' => isset($setting->xMax) ? (float)$setting->xMax : 0.0,
				'yMin' => isset($setting->yMin) ? (float)$setting->yMin : 0.0,
				'yMax' => isset($setting->yMax) ? (float)$setting->yMax : 0.0,
				'cashCostMid' => isset($setting->cashCostMid) ? (float)$setting->cashCostMid : 0.0,
				'ipoMid' => isset($setting->ipoMid) ? (float)$setting->ipoMid : 0.0
			]
		]);
	}

	public function getBarChartProduktivitas(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');

		$params = [$cluster, $kebun, $rayon, $tgl];
		$results = \DB::select('CALL sp_pica_dashboard_1_protas(?, ?, ?, ?)', $params);

			$chartData = [];
			$total = 0;
			foreach ($results as $row) {
				$emas = isset($row->petak_emas) ? (int)$row->petak_emas : 0;
				$hijau = isset($row->petak_hijau) ? (int)$row->petak_hijau : 0;
				$kuning = isset($row->petak_kuning) ? (int)$row->petak_kuning : 0;
				$merah = isset($row->petak_merah) ? (int)$row->petak_merah : 0;
				$hitam = isset($row->petak_hitam) ? (int)$row->petak_hitam : 0;
				$subtotal = $emas + $hijau + $kuning + $merah + $hitam;
				$total += $subtotal;
				
				$chartData[] = [
					'petak_emas' => $emas,
					'petak_hijau' => $hijau,
					'petak_kuning' => $kuning,
					'petak_merah' => $merah,
					'petak_hitam' => $hitam,
					'total' => $subtotal
				];
			}

			$html = '<div style="padding: 10px; background: #f8f9fa; border-radius: 6px;">';
			$html .= '<h5 style="font-weight: 700; color: #333; margin-bottom: 20px;">Produktivitas (Jml Petak)</h5>';
			
			if (!empty($chartData)) {
				$row = $chartData[0];
				$statusBars = [
					['label' => 'Emas', 'value' => $row['petak_emas'], 'color' => '#d4af37'],
					['label' => 'Hijau', 'value' => $row['petak_hijau'], 'color' => '#27ae60'],
					['label' => 'Kuning', 'value' => $row['petak_kuning'], 'color' => '#f39c12'],
					['label' => 'Merah', 'value' => $row['petak_merah'], 'color' => '#e74c3c'],
					['label' => 'Hitam', 'value' => $row['petak_hitam'], 'color' => '#2c3e50']
				];
				
				$html .= '<div style="width: 100%; height: 50px; background: #e9ecef; border-radius: 6px; overflow: hidden; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); display: flex; margin-bottom: 20px;">';
				
				foreach ($statusBars as $status) {
					$percentage = $total > 0 ? ($status['value'] / $total) * 100 : 0;
					$html .= '<div style="height: 100%; width: ' . $percentage . '%; background: ' . $status['color'] . '; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 700; font-size: 12px; position: relative;">';
					//if ($percentage > 8) {
						$html .= round($percentage, 1) . '%';
					//}
					$html .= '</div>';
				}
				
				$html .= '</div>';
				
				$html .= '<div style="display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 20px;">';
				foreach ($statusBars as $status) {
					$html .= '<div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">';
					$html .= '<div style="width: 16px; height: 16px; background: ' . $status['color'] . '; border-radius: 3px;"></div>';
					$html .= '<span style="color: #333;">' . $status['label'] . ': <strong>' . number_format($status['value'], 0, ',', '.') . '</strong></span>';
					$html .= '</div>';
				}
				$html .= '</div>';
			}
			


			return response()->json([
				'status' => 'success',
				'data' => $chartData,
				'html' => $html
			]);
	}

	function getDiameterChart(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		$umur = $request->get('umur');
		
		$results = \DB::select('CALL sp_pica_dashboard_2_diameter(?, ?, ?, ?, ?)', [$cluster, $kebun, $rayon, $tgl, $umur]);
		
		$chartData = [];
		$total = 0;
		foreach ($results as $row) {
			$emas = isset($row->petak_emas) ? (int)$row->petak_emas : 0;
			$hijau = isset($row->petak_hijau) ? (int)$row->petak_hijau : 0;
			$kuning = isset($row->petak_kuning) ? (int)$row->petak_kuning : 0;
			$merah = isset($row->petak_merah) ? (int)$row->petak_merah : 0;
			$hitam = isset($row->petak_hitam) ? (int)$row->petak_hitam : 0;
			$subtotal = $emas + $hijau + $kuning + $merah + $hitam;
			$total += $subtotal;
			
			$chartData[] = [
				'petak_emas' => $emas,
				'petak_hijau' => $hijau,
				'petak_kuning' => $kuning,
				'petak_merah' => $merah,
				'petak_hitam' => $hitam,
				'total' => $subtotal
			];
		}

		$html = '<div style="padding: 10px; background: #f8f9fa; border-radius: 6px;">';
		$html .= '<h5 style="font-weight: 700; color: #333; margin-bottom: 20px;">Diameter (Jml Petak)</h5>';
		
		if (!empty($chartData)) {
			$row = $chartData[0];
			$statusBars = [
				['label' => 'Emas', 'value' => $row['petak_emas'], 'color' => '#d4af37'],
				['label' => 'Hijau', 'value' => $row['petak_hijau'], 'color' => '#27ae60'],
				['label' => 'Kuning', 'value' => $row['petak_kuning'], 'color' => '#f39c12'],
				['label' => 'Merah', 'value' => $row['petak_merah'], 'color' => '#e74c3c'],
				['label' => 'Hitam', 'value' => $row['petak_hitam'], 'color' => '#2c3e50']
			];
			
			$html .= '<div style="width: 100%; height: 50px; background: #e9ecef; border-radius: 6px; overflow: hidden; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); display: flex; margin-bottom: 20px;">';
			
			foreach ($statusBars as $status) {
				$percentage = $total > 0 ? ($status['value'] / $total) * 100 : 0;
				$html .= '<div style="height: 100%; width: ' . $percentage . '%; background: ' . $status['color'] . '; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 700; font-size: 12px; position: relative;">';
				$html .= round($percentage, 1) . '%';
				$html .= '</div>';
			}
			
			$html .= '</div>';
			
			$html .= '<div style="display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 20px;">';
			foreach ($statusBars as $status) {
				$html .= '<div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">';
				$html .= '<div style="width: 16px; height: 16px; background: ' . $status['color'] . '; border-radius: 3px;"></div>';
				$html .= '<span style="color: #333;">' . $status['label'] . ': <strong>' . number_format($status['value'], 0, ',', '.') . '</strong></span>';
				$html .= '</div>';
			}
			$html .= '</div>';
		}

		return response()->json([
			'status' => 'success',
			'data' => $chartData,
			'html' => $html
		]);
	}

	function getJumlahBatangChart(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		$umur = $request->get('umur');
		
		$results = \DB::select('CALL sp_pica_dashboard_2_jumlahbatang(?, ?, ?, ?, ?)', [$cluster, $kebun, $rayon, $tgl, $umur]);
		
		$chartData = [];
		$total = 0;
		foreach ($results as $row) {
			$emas = isset($row->petak_emas) ? (int)$row->petak_emas : 0;
			$hijau = isset($row->petak_hijau) ? (int)$row->petak_hijau : 0;
			$kuning = isset($row->petak_kuning) ? (int)$row->petak_kuning : 0;
			$merah = isset($row->petak_merah) ? (int)$row->petak_merah : 0;
			$hitam = isset($row->petak_hitam) ? (int)$row->petak_hitam : 0;
			$subtotal = $emas + $hijau + $kuning + $merah + $hitam;
			$total += $subtotal;
			
			$chartData[] = [
				'petak_emas' => $emas,
				'petak_hijau' => $hijau,
				'petak_kuning' => $kuning,
				'petak_merah' => $merah,
				'petak_hitam' => $hitam,
				'total' => $subtotal
			];
		}

		$html = '<div style="padding: 10px; background: #f8f9fa; border-radius: 6px;">';
		$html .= '<h5 style="font-weight: 700; color: #333; margin-bottom: 20px;">Jumlah Batang (Jml Petak)</h5>';
		
		if (!empty($chartData)) {
			$row = $chartData[0];
			$statusBars = [
				['label' => 'Emas', 'value' => $row['petak_emas'], 'color' => '#d4af37'],
				['label' => 'Hijau', 'value' => $row['petak_hijau'], 'color' => '#27ae60'],
				['label' => 'Kuning', 'value' => $row['petak_kuning'], 'color' => '#f39c12'],
				['label' => 'Merah', 'value' => $row['petak_merah'], 'color' => '#e74c3c'],
				['label' => 'Hitam', 'value' => $row['petak_hitam'], 'color' => '#2c3e50']
			];
			
			$html .= '<div style="width: 100%; height: 50px; background: #e9ecef; border-radius: 6px; overflow: hidden; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); display: flex; margin-bottom: 20px;">';
			
			foreach ($statusBars as $status) {
				$percentage = $total > 0 ? ($status['value'] / $total) * 100 : 0;
				$html .= '<div style="height: 100%; width: ' . $percentage . '%; background: ' . $status['color'] . '; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 700; font-size: 12px; position: relative;">';
				$html .= round($percentage, 1) . '%';
				$html .= '</div>';
			}
			
			$html .= '</div>';
			
			$html .= '<div style="display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 20px;">';
			foreach ($statusBars as $status) {
				$html .= '<div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">';
				$html .= '<div style="width: 16px; height: 16px; background: ' . $status['color'] . '; border-radius: 3px;"></div>';
				$html .= '<span style="color: #333;">' . $status['label'] . ': <strong>' . number_format($status['value'], 0, ',', '.') . '</strong></span>';
				$html .= '</div>';
			}
			$html .= '</div>';
		}

		return response()->json([
			'status' => 'success',
			'data' => $chartData,
			'html' => $html
		]);
	}

		function getTinggiBatangChart(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		$umur = $request->get('umur');

		$params = [$cluster, $kebun, $rayon, $tgl, $umur];

		$results = \DB::select('CALL sp_pica_dashboard_2_tinggibatang(?, ?, ?, ?, ?)', $params);
		
		$chartData = [];
		$total = 0;
		
		foreach ($results as $row) {
			$emas = isset($row->petak_emas) ? (int)$row->petak_emas : 0;
			$hijau = isset($row->petak_hijau) ? (int)$row->petak_hijau : 0;
			$kuning = isset($row->petak_kuning) ? (int)$row->petak_kuning : 0;
			$merah = isset($row->petak_merah) ? (int)$row->petak_merah : 0;
			$hitam = isset($row->petak_hitam) ? (int)$row->petak_hitam : 0;
			$subtotal = $emas + $hijau + $kuning + $merah + $hitam;
			$total += $subtotal;
			
			$chartData[] = [
				'petak_emas' => $emas,
				'petak_hijau' => $hijau,
				'petak_kuning' => $kuning,
				'petak_merah' => $merah,
				'petak_hitam' => $hitam,
				'total' => $subtotal
			];
		}

		$html = '<div style="padding: 10px; background: #f8f9fa; border-radius: 6px;">';
		$html .= '<h5 style="font-weight: 700; color: #333; margin-bottom: 20px;">Tinggi Batang (Jml Petak)</h5>';
		
		if (!empty($chartData)) {
			$row = $chartData[0];
			$statusBars = [
				['label' => 'Emas', 'value' => $row['petak_emas'], 'color' => '#d4af37'],
				['label' => 'Hijau', 'value' => $row['petak_hijau'], 'color' => '#27ae60'],
				['label' => 'Kuning', 'value' => $row['petak_kuning'], 'color' => '#f39c12'],
				['label' => 'Merah', 'value' => $row['petak_merah'], 'color' => '#e74c3c'],
				['label' => 'Hitam', 'value' => $row['petak_hitam'], 'color' => '#2c3e50']
			];
			
			$html .= '<div style="width: 100%; height: 50px; background: #e9ecef; border-radius: 6px; overflow: hidden; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); display: flex; margin-bottom: 20px;">';
			
			foreach ($statusBars as $status) {
				$percentage = $total > 0 ? ($status['value'] / $total) * 100 : 0;
				$html .= '<div style="height: 100%; width: ' . $percentage . '%; background: ' . $status['color'] . '; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 700; font-size: 12px; position: relative;">';
				$html .= round($percentage, 1) . '%';
				$html .= '</div>';
			}
			
			$html .= '</div>';
			
			$html .= '<div style="display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 20px;">';
			foreach ($statusBars as $status) {
				$html .= '<div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">';
				$html .= '<div style="width: 16px; height: 16px; background: ' . $status['color'] . '; border-radius: 3px;"></div>';
				$html .= '<span style="color: #333;">' . $status['label'] . ': <strong>' . number_format($status['value'], 0, ',', '.') . '</strong></span>';
				$html .= '</div>';
			}
			$html .= '</div>';
		}

		return response()->json([
			'status' => 'success',
			'data' => $chartData,
			'html' => $html
		]);
	}

	function getPemupukanData(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		$umur = $request->get('umur');
		
		$params = [$cluster, $kebun, $rayon, $tgl, $umur];
		
		$results = \DB::select('CALL sp_pica_dashboard_2_pemupukan(?, ?, ?, ?, ?)', $params);
		
		$chartData = [];
		$total = 0;
		
		foreach ($results as $row) {
			$pupuk_1_tepat_waktu = isset($row->pupuk_1_tepat_waktu) ? (int)$row->pupuk_1_tepat_waktu : 0;
			$pupuk_1_terlambat = isset($row->pupuk_1_terlambat) ? (int)$row->pupuk_1_terlambat : 0;
			$subtotal = $pupuk_1_tepat_waktu + $pupuk_1_terlambat;
			$total += $subtotal;

			$chartData[] = [
				'pupuk_1_tepat_waktu' => $pupuk_1_tepat_waktu,
				'pupuk_1_terlambat' => $pupuk_1_terlambat,
				'total' => $subtotal
			];
		}

		$html = '<div style="padding: 10px; background: #f8f9fa; border-radius: 6px;">';
		$html .= '<h5 style="font-weight: 700; color: #333; margin-bottom: 20px;">Pemupukan 1 (Ha)</h5>';

		if (!empty($chartData)) {
			$row = $chartData[0];
			$statusBars = [
				['label' => 'Tepat Waktu', 'value' => $row['pupuk_1_tepat_waktu'], 'color' => '#27ae60'],
				['label' => 'Terlambat', 'value' => $row['pupuk_1_terlambat'], 'color' => '#e74c3c']
			];
			
			$html .= '<div style="width: 100%; height: 50px; background: #e9ecef; border-radius: 6px; overflow: hidden; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); display: flex; margin-bottom: 20px;">';
			foreach ($statusBars as $status) {
				$percentage = $total > 0 ? ($status['value'] / $total) * 100 : 0;
				$html .= '<div style="height: 100%; width: ' . $percentage . '%; background: ' . $status['color'] . '; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 700; font-size: 12px; position: relative;">';
				$html .= round($percentage, 1) . '%';
				$html .= '</div>';
			}				
			
			$html .= '</div>';

			$html .= '<div style="display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 20px;">';
			foreach ($statusBars as $status) {
				$html .= '<div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">';
				$html .= '<div style="width: 16px; height: 16px; background: ' . $status['color'] . '; border-radius: 3px;"></div>';
				$html .= '<span style="color: #333;">' . $status['label'] . ': <strong>' . number_format($status['value'], 0, ',', '.') . '</strong></span>';
				$html .= '</div>';
			}
			$html .= '</div>';
		}
		
		return response()->json([
			'status' => 'success',
			'data' => $results,
			'html' => $html
		]);
	}




	function getTableParameterPemeliharaan(Request $request)
	{
		$tahun = date('Y');
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$parameter = $request->get('parameter', 'diameter');
		$umur = $request->get('umur', '5');
		
		$params = [$tahun, $cluster, $kebun, $parameter, $umur];
		
		$results = \DB::select('CALL sp_pica_dashboard_2_parameter_pemeliharaan(?, ?, ?, ?, ?)', $params);
		
		$html = '<style>';
		$html .= '.dashboard-table { width: 100%; border-collapse: collapse; font-family: Arial, sans-serif; box-shadow: 0 2px 8px rgba(0,0,0,0.1); border-radius: 8px; }';
		$html .= '.dashboard-table thead { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }';
		$html .= '.dashboard-table th { padding: 16px; text-align: center; font-weight: 600; font-size: 14px; letter-spacing: 0.5px; color: #fff !important; }';
		$html .= '.dashboard-table tbody tr { border-bottom: 1px solid #e0e0e0; transition: background-color 0.3s ease; }';
		$html .= '.dashboard-table tbody tr:hover { background-color: #f8f9ff; }';
		$html .= '.dashboard-table tbody tr:last-child { border-bottom: none; }';
		$html .= '.dashboard-table td { padding: 14px 16px; font-size: 13px; color: #333; text-align: right; }';
		$html .= '.dashboard-table td:first-child { text-align: left; }';
		$html .= '.dashboard-table tbody tr:nth-child(even) { background-color: #f5f5f5; }';
		$html .= '.dashboard-table tbody tr.total-row { background-color: #fff3cd !important; font-weight: bold; }';
		$html .= '</style>';
		
		// Map parameter to display labels
		$parameterLabels = [
			'diameter' => 'Diameter (mm)',
			'tinggi_batang' => 'Tinggi Batang (m)',
			'jumlah_batang' => 'Jumlah Batang (per meter)',
			'pemupukan_tepat_waktu' => 'Pemupukan Tepat Waktu (%)'
		];
		
		$judul = isset($parameterLabels[$parameter]) ? $parameterLabels[$parameter] : ucfirst(str_replace('_', ' ', $parameter));
		$html .= '<h3 class="text-center">' . $judul . ' ' . $tahun . '</h3>';
		$html .= '<table class="table table-responsive dashboard-table">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th>Kebun</th>';
		$html .= '<th>Jan</th>';
		$html .= '<th>Feb</th>';
		$html .= '<th>Mar</th>';
		$html .= '<th>Apr</th>';
		$html .= '<th>Mei</th>';
		$html .= '<th>Jun</th>';
		$html .= '<th>Jul</th>';
		$html .= '<th>Agu</th>';
		$html .= '<th>Sep</th>';
		$html .= '<th>Okt</th>';
		$html .= '<th>Nov</th>';
		$html .= '<th>Des</th>';
		if($parameter === 'pemupukan_tepat_waktu') {
			$html .= '<th>Total</th>';
		}
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		
		foreach($results as $row) {
			$isTotal = stripos($row->nama_rekap, 'total') !== false ? ' class="total-row"' : '';
			$html .= '<tr' . $isTotal . '>';
			$html .= '<td style="text-align:left !important;"><strong>' . $row->nama_rekap . '</strong></td>';
			$html .= '<td>' . ($row->januari ? number_format($row->januari, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->februari ? number_format($row->februari, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->maret ? number_format($row->maret, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->april ? number_format($row->april, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->mei ? number_format($row->mei, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->juni ? number_format($row->juni, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->juli ? number_format($row->juli, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->agustus ? number_format($row->agustus, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->september ? number_format($row->september, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->oktober ? number_format($row->oktober, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->november ? number_format($row->november, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->desember ? number_format($row->desember, 2, ',', '.') : '-') . '</td>';
			if($parameter === 'pemupukan_tepat_waktu') {
				$html .= '<td>' . ($row->total ? number_format($row->total, 2, ',', '.') : '-') . '</td>';
			}
			$html .= '</tr>';
		}
		
		$html .= '</tbody>';
		$html .= '</table>';
		
		return response($html);
	}

	

	public function getKuadranKinerjanew(Request $request)
	{
		$nama_kebun = $request->get('cluster');
		$tahun = $request->get('bulan');
		
		$params = [$nama_kebun, $tahun];
		$results = \DB::select('CALL kuadran_kinerja_kebun_kso_new(?, ?)', $params);

		

		$html = '<style>
			.kuadran-table-wrap { font-family: "Segoe UI", Arial, sans-serif; }
			.kuadran-table-wrap .kuadran-table { width: 100%; border-collapse: separate; border-spacing: 0; border-radius: 10px; overflow: hidden; box-shadow: 0 4px 18px rgba(0,0,0,0.13); font-size: 13px; }
			.kuadran-table-wrap .kuadran-table thead tr { background: linear-gradient(135deg, #1a6b3c 0%, #2e9e5b 60%, #43c97a 100%); }
			.kuadran-table-wrap .kuadran-table thead th { color: #fff; 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 .kuadran-table thead th:first-child { border-radius: 10px 0 0 0; }
			.kuadran-table-wrap .kuadran-table thead th:last-child { border-radius: 0 10px 0 0; }
			.kuadran-table-wrap .kuadran-table tbody tr.row-even { background-color: #f0f9f4; }
			.kuadran-table-wrap .kuadran-table tbody tr.row-odd { background-color: #ffffff; }
			.kuadran-table-wrap .kuadran-table tbody tr { transition: background-color 0.2s, box-shadow 0.2s; }
			.kuadran-table-wrap .kuadran-table tbody tr:hover { background-color: #d4f0e2 !important; box-shadow: inset 0 0 0 1.5px #2e9e5b; }
			.kuadran-table-wrap .kuadran-table tbody td { padding: 10px 12px; border-bottom: 1px solid #e3f1ea; vertical-align: middle; }
			.kuadran-table-wrap .kuadran-table tbody td.td-kebun { font-weight: 600; color: #1a6b3c; white-space: nowrap; }
			.kuadran-table-wrap .kuadran-table tbody td.td-num { text-align: right; color: #333; }
			.kuadran-table-wrap .kuadran-table tbody td.td-delta-pos { text-align: right; color: #1a6b3c; font-weight: 700; }
			.kuadran-table-wrap .kuadran-table tbody td.td-delta-neg { text-align: right; color: #c0392b; font-weight: 700; }
			.kuadran-table-wrap .kuadran-table tbody td.td-delta-zero { text-align: right; color: #888; font-weight: 600; }
			.kuadran-table-wrap .kuadran-table tbody tr:last-child td:first-child { border-radius: 0 0 0 10px; }
			.kuadran-table-wrap .kuadran-table tbody tr:last-child td:last-child { border-radius: 0 0 10px 0; }
			.kuadran-table-wrap .group-separator { border-left: 2.5px solid #b2dfc8; }
		</style>';
		$html .= '<div class="table-responsive kuadran-table-wrap">';
		$html .= '<table class="kuadran-table" id="tablediv3">';
		$html .= '<thead><tr>';
		$headers = ['Kebun', 'Target<br>Produktivitas','Produktivitas<br>sd Minggu Lalu', 'Produktivitas<br>sd Minggu Ini', 'Delta<br>Produktivitas', 'Target<br>Rendemen','Rendemen<br>sd Minggu Lalu', 'Rendemen<br>sd Minggu Ini', 'Delta<br>Rendemen', 'Target<br>Pasok Harian','Rata-rata Pasok Harian<br>sd Minggu Lalu', 'Rata-rata Pasok Harian<br>sd Minggu Ini', 'Delta<br>Pasok Harian', 'X Cashcost', 'IPO Protas','IPO Rendemen','IPO Pasok', 'Y IPO<br>sd Minggu Ini'];
		$groupSeparators = [0, 1, 5, 9, 13, 14, 17]; // indices where a group starts (left border)
		foreach ($headers as $i => $h) {
			$sep = in_array($i, $groupSeparators) && $i > 0 ? ' style="border-left: 2.5px solid rgba(255,255,255,0.35);"' : '';
			$html .= '<th' . $sep . '>' . $h . '</th>';
		}
		$html .= '</tr></thead><tbody>';
		$rowCount = 0;
		foreach ($results as $row) {
			$rowClass = ($rowCount % 2 === 0) ? 'row-even' : 'row-odd';

			$deltaProd = $row->delta_produktivitas ?? 0;
			$deltaRend = $row->delta_rendemen ?? 0;
			$deltaPasok = $row->delta_pasok_harian ?? 0;

			$getDeltaClass = function($val) {
				if ($val > 0) return 'td-delta-pos';
				if ($val < 0) return 'td-delta-neg';
				return 'td-delta-zero';
			};
			$fmtDelta = function($val, $dec = 2) {
				$prefix = $val > 0 ? '▲ ' : ($val < 0 ? '▼ ' : '');
				return $prefix . number_format($val, $dec);
			};

			$html .= '<tr class="' . $rowClass . '">';
			$html .= '<td class="td-kebun" style="text-align:left !important;">' . htmlspecialchars($row->Kebun ?? '') . '</td>';
			$html .= '<td class="td-num group-separator">' . number_format($row->target_produktivitas ?? 0, 2) . '</td>';
			$html .= '<td class="td-num">' . number_format($row->produktivitas_sd_minggu_lalu ?? 0, 2) . '</td>';
			$html .= '<td class="td-num">' . number_format($row->produktivitas_sd_minggu_ini ?? 0, 2) . '</td>';
			$html .= '<td class="' . $getDeltaClass($deltaProd) . '">' . $fmtDelta($deltaProd) . '</td>';
			$html .= '<td class="td-num group-separator">' . number_format($row->target_rendemen ?? 0, 2) . '</td>';
			$html .= '<td class="td-num">' . number_format($row->rendemen_sd_minggu_lalu ?? 0, 2) . '</td>';
			$html .= '<td class="td-num">' . number_format($row->rendemen_sd_minggu_ini ?? 0, 2) . '</td>';
			$html .= '<td class="' . $getDeltaClass($deltaRend) . '">' . $fmtDelta($deltaRend) . '</td>';
			$html .= '<td class="td-num group-separator">' . number_format($row->target_pasok_harian ?? 0, 2) . '</td>';
			$html .= '<td class="td-num">' . number_format($row->rata2_pasok_harian_sd_minggu_lalu ?? 0, 2) . '</td>';
			$html .= '<td class="td-num">' . number_format($row->rata2_pasok_harian_sd_minggu_ini ?? 0, 2) . '</td>';
			$html .= '<td class="' . $getDeltaClass($deltaPasok) . '">' . $fmtDelta($deltaPasok) . '</td>';
			$html .= '<td class="td-num group-separator">' . number_format($row->x_cashcost ?? 0, 0) . '</td>';
			$html .= '<td class="td-num group-separator">' . number_format($row->ipo_protas ?? 0, 2) . '</td>';
			$html .= '<td class="td-num ">' . number_format($row->ipo_rendemen ?? 0, 2) . '</td>';
			$html .= '<td class="td-num ">' . number_format($row->ipo_pasok ?? 0, 2) . '</td>';
			$html .= '<td class="td-num group-separator"><strong>' . number_format($row->y_ipo_sd_minggu_ini ?? 0, 2) . '</strong></td>';
			$html .= '</tr>';
			$rowCount++;
		}
		$html .= '</tbody></table>';
		$html .= '</div>';

				$setting = \DB::table('setting_kuadran_kinerja')->where('id', 1)->first();

		
		return response()->json([
			'html' => $html,
			'setting' => [
				'xMin' => isset($setting->xMin) ? (float)$setting->xMin : 0.0,
				'xMax' => isset($setting->xMax) ? (float)$setting->xMax : 0.0,
				'yMin' => isset($setting->yMin) ? (float)$setting->yMin : 0.0,
				'yMax' => isset($setting->yMax) ? (float)$setting->yMax : 0.0,
				'cashCostMid' => isset($setting->cashCostMid) ? (float)$setting->cashCostMid : 0.0,
				'ipoMid' => isset($setting->ipoMid) ? (float)$setting->ipoMid : 0.0
			]			
		]);
	}

	public function getDashboardMutu(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		
		$params = [$cluster, $kebun, $rayon, $tgl];
		$results = \DB::select('CALL sp_pica_dashboard_1_mutu(?, ?, ?, ?)', $params);
		
		$mutuData = [];
		$totalMutu = 0;
		
		foreach ($results as $row) {
			$mutuA = isset($row->mutu_A) ? (int)$row->mutu_A : 0;
			$mutuB = isset($row->mutu_B) ? (int)$row->mutu_B : 0;
			$mutuC = isset($row->mutu_C) ? (int)$row->mutu_C : 0;
			$mutuD = isset($row->mutu_D) ? (int)$row->mutu_D : 0;
			$mutuE = isset($row->mutu_E) ? (int)$row->mutu_E : 0;
			$mutuF = isset($row->mutu_F) ? (int)$row->mutu_F : 0;
			$mutuG = isset($row->mutu_G) ? (int)$row->mutu_G : 0;
			
			$subtotal = $mutuA + $mutuB + $mutuC + $mutuD + $mutuE + $mutuF + $mutuG;
			$totalMutu += $subtotal;
			
			$mutuData[] = [
				'blok' => $row->blok ?? 'N/A',
				'mutu_A' => $mutuA,
				'mutu_B' => $mutuB,
				'mutu_C' => $mutuC,
				'mutu_D' => $mutuD,
				'mutu_E' => $mutuE,
				'mutu_F' => $mutuF,
				'mutu_G' => $mutuG,
				'total' => $subtotal
			];
		}
		
		$html = '<div style="padding: 10px; background: #f8f9fa; border-radius: 6px;">';
		$html .= '<h5 style="font-weight: 700; color: #333; margin-bottom: 20px;">Mutu Tebu (Ton)</h5>';
		
		if (!empty($mutuData)) {
			$row = $mutuData[0];
			$statusBars = [
				['label' => 'Mutu A', 'value' => $row['mutu_A'], 'color' => '#27ae60'],
				['label' => 'Mutu B', 'value' => $row['mutu_B'], 'color' => '#3498db'],
				['label' => 'Mutu C', 'value' => $row['mutu_C'], 'color' => '#f39c12'],
				['label' => 'Mutu D', 'value' => $row['mutu_D'], 'color' => '#e67e22'],
				['label' => 'Mutu E', 'value' => $row['mutu_E'], 'color' => '#e74c3c'],
				['label' => 'Mutu F', 'value' => $row['mutu_F'], 'color' => '#c0392b'],
				['label' => 'Mutu G', 'value' => $row['mutu_G'], 'color' => '#2c3e50']
			];
			
			$html .= '<div style="width: 100%; height: 50px; background: #e9ecef; border-radius: 6px; overflow: hidden; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); display: flex; margin-bottom: 20px;">';
			
			foreach ($statusBars as $status) {
				$percentage = $totalMutu > 0 ? ($status['value'] / $totalMutu) * 100 : 0;
				$html .= '<div style="height: 100%; width: ' . $percentage . '%; background: ' . $status['color'] . '; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 700; font-size: 12px; position: relative;">';
				// if ($percentage > 5) {
					$html .= round($percentage, 1) . '%';
				// }
				$html .= '</div>';
			}
			
			$html .= '</div>';
			
			$html .= '<div style="display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 20px;">';
			foreach ($statusBars as $status) {
				$html .= '<div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">';
				$html .= '<div style="width: 16px; height: 16px; background: ' . $status['color'] . '; border-radius: 3px;"></div>';
				$html .= '<span style="color: #333;">' . $status['label'] . ': <strong>' . number_format($status['value'], 0, ',', '.') . '</strong></span>';
				$html .= '</div>';
			}
			$html .= '</div>';
		}
		
		$html .= '</div>';
		
		return response()->json([
			'status' => 'success',
			'data' => $mutuData,
			'html' => $html,
			'total' => $totalMutu
		]);
	}
	

	public function getDashboardKlentek(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		
		$params = [$cluster, $kebun, $rayon, $tgl];
		$results = \DB::select('CALL sp_pica_dashboard_1_klentek(?, ?, ?, ?)', $params);
		
		$klentekData = [];
		$totalKlentek = 0;
		$totalBelumKlentek = 0;
		
		foreach ($results as $row) {
			$klentek = isset($row->klentek_1) ? (float)$row->klentek_1 : 0;
			$belumKlentek = isset($row->belum_klentek_1) ? (float)$row->belum_klentek_1 : 0;
			
			$subtotal = $klentek + $belumKlentek;
			$totalKlentek += $klentek;
			$totalBelumKlentek += $belumKlentek;
			
			$klentekData[] = [
				'blok' => $row->blok ?? 'N/A',
				'klentek_1' => $klentek,
				'belum_klentek_1' => $belumKlentek,
				'total' => $subtotal
			];
		}
		
		$html = '<div style="padding: 10px; background: #f8f9fa; border-radius: 6px;">';
		$html .= '<h5 style="font-weight: 700; color: #333; margin-bottom: 20px;">Monitoring Klentek (Ha)</h5>';
		
		$grandTotal = $totalKlentek + $totalBelumKlentek;
		
		if ($grandTotal > 0) {
			$statusBars = [
				['label' => 'Klentek 1', 'value' => $totalKlentek, 'color' => '#27ae60'],
				['label' => 'Belum Klentek 1', 'value' => $totalBelumKlentek, 'color' => '#e74c3c']
			];
			
			$html .= '<div style="width: 100%; height: 50px; background: #e9ecef; border-radius: 6px; overflow: hidden; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); display: flex; margin-bottom: 20px;">';
			
			foreach ($statusBars as $status) {
				$percentage = $grandTotal > 0 ? ($status['value'] / $grandTotal) * 100 : 0;
				$html .= '<div style="height: 100%; width: ' . $percentage . '%; background: ' . $status['color'] . '; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 700; font-size: 12px; position: relative;">';
				// if ($percentage > 5) {
					$html .= round($percentage, 1) . '%';
				// }
				$html .= '</div>';
			}
			
			$html .= '</div>';
			
			$html .= '<div style="display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 20px;">';
			foreach ($statusBars as $status) {
				$html .= '<div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">';
				$html .= '<div style="width: 16px; height: 16px; background: ' . $status['color'] . '; border-radius: 3px;"></div>';
				$html .= '<span style="color: #333;">' . $status['label'] . ': <strong>' . number_format($status['value'], 3, ',', '.') . '</strong></span>';
				$html .= '</div>';
			}
			$html .= '</div>';
		}
		
		$html .= '</div>';
		
		return response()->json([
			'status' => 'success',
			'data' => $klentekData,
			'html' => $html,
			'total_klentek' => $totalKlentek,
			'total_belum_klentek' => $totalBelumKlentek,
			'grand_total' => $grandTotal
		]);
	}



	public function getDashboardKesegaran(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		
		$params = [$cluster, $kebun, $rayon, $tgl];
		$results = \DB::select('CALL sp_pica_dashboard_1_kesegaran(?, ?, ?, ?)', $params);
		
		$ksegaranData = [];
		$total24Jam = 0;
		$total24sd48Jam = 0;
		$totalLebihdari48Jam = 0;
		
		foreach ($results as $row) {
			$jam24 = isset($row->{'<24jam'}) ? (float)$row->{'<24jam'} : 0;
			$jam24sd48 = isset($row->{'24sd48jam'}) ? (float)$row->{'24sd48jam'} : 0;
			$jamLebihdari48 = isset($row->{'>48jam'}) ? (float)$row->{'>48jam'} : 0;
			
			$subtotal = $jam24 + $jam24sd48 + $jamLebihdari48;
			$total24Jam += $jam24;
			$total24sd48Jam += $jam24sd48;
			$totalLebihdari48Jam += $jamLebihdari48;
			
			$ksegaranData[] = [
				'blok' => $row->blok ?? 'N/A',
				'<24jam' => $jam24,
				'24sd48jam' => $jam24sd48,
				'>48jam' => $jamLebihdari48,
				'total' => $subtotal
			];
		}
		
		$html = '<div style="padding: 10px; background: #f8f9fa; border-radius: 6px;">';
		$html .= '<h5 style="font-weight: 700; color: #333; margin-bottom: 20px;">Monitoring Kesegaran Tebu (Ton)</h5>';
		
		$grandTotal = $total24Jam + $total24sd48Jam + $totalLebihdari48Jam;
		
		if ($grandTotal > 0) {
			$statusBars = [
				['label' => '<24 Jam', 'value' => $total24Jam, 'color' => '#27ae60'],
				['label' => '24-48 Jam', 'value' => $total24sd48Jam, 'color' => '#f39c12'],
				['label' => '>48 Jam', 'value' => $totalLebihdari48Jam, 'color' => '#e74c3c']
			];
			
			$html .= '<div style="width: 100%; height: 50px; background: #e9ecef; border-radius: 6px; overflow: hidden; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); display: flex; margin-bottom: 20px;">';
			
			foreach ($statusBars as $status) {
				$percentage = $grandTotal > 0 ? ($status['value'] / $grandTotal) * 100 : 0;
				$html .= '<div style="height: 100%; width: ' . $percentage . '%; background: ' . $status['color'] . '; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 700; font-size: 12px; position: relative;">';
				if ($percentage > 5) {
					$html .= round($percentage, 1) . '%';
				}
				$html .= '</div>';
			}
			
			$html .= '</div>';
			
			$html .= '<div style="display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 20px;">';
			foreach ($statusBars as $status) {
				$html .= '<div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">';
				$html .= '<div style="width: 16px; height: 16px; background: ' . $status['color'] . '; border-radius: 3px;"></div>';
				$html .= '<span style="color: #333;">' . $status['label'] . ': <strong>' . number_format($status['value'], 0, ',', '.') . '</strong></span>';
				$html .= '</div>';
			}
			$html .= '</div>';
		}
		
		$html .= '</div>';
		
		return response()->json([
			'status' => 'success',
			'data' => $ksegaranData,
			'html' => $html,
			'total_24jam' => $total24Jam,
			'total_24sd48jam' => $total24sd48Jam,
			'total_lebih48jam' => $totalLebihdari48Jam,
			'grand_total' => $grandTotal
		]);
	}

	public function getDashboardKlasifikasiProtas(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		
		$params = [$cluster, $kebun, $rayon, $tgl];
		$results = \DB::select('CALL sp_pica_dashboard_1_klasifikasi_protas(?, ?, ?, ?)', $params);
		
		$klasifikasiData = [];
		$totalDiatas12Bulan = 0;
		$total12Bulan = 0;
		$total10sd11Bulan = 0;
		$total9Bulan = 0;
		$totalDibawah9Bulan = 0;
		
		foreach ($results as $row) {
			$diatas12 = isset($row->{'diatas 12 Bulan'}) ? (float)$row->{'diatas 12 Bulan'} : 0;
			$bulan12 = isset($row->{'12 Bulan'}) ? (float)$row->{'12 Bulan'} : 0;
			$bulan10sd11 = isset($row->{'10-11 Bulan'}) ? (float)$row->{'10-11 Bulan'} : 0;
			$bulan9 = isset($row->{'9 Bulan'}) ? (float)$row->{'9 Bulan'} : 0;
			$dibawah9 = isset($row->{'dibawah 9 Bulan'}) ? (float)$row->{'dibawah 9 Bulan'} : 0;
			
			$subtotal = $diatas12 + $bulan12 + $bulan10sd11 + $bulan9 + $dibawah9;
			$totalDiatas12Bulan += $diatas12;
			$total12Bulan += $bulan12;
			$total10sd11Bulan += $bulan10sd11;
			$total9Bulan += $bulan9;
			$totalDibawah9Bulan += $dibawah9;
			
			$klasifikasiData[] = [
				'diatas_12_bulan' => $diatas12,
				'12_bulan' => $bulan12,
				'10sd11_bulan' => $bulan10sd11,
				'9_bulan' => $bulan9,
				'dibawah_9_bulan' => $dibawah9,
				'total' => $subtotal
			];
		}
		
		$html = '<div style="padding: 10px; background: #f8f9fa; border-radius: 6px;">';
		$html .= '<h5 style="font-weight: 700; color: #333; margin-bottom: 20px;">Monitoring Umur Tebu Ditebang (Ha)</h5>';
		
		$grandTotal = $totalDiatas12Bulan + $total12Bulan + $total10sd11Bulan + $total9Bulan + $totalDibawah9Bulan;
		
		if ($grandTotal > 0) {
			$statusBars = [
				['label' => 'Diatas 12 Bulan', 'value' => $totalDiatas12Bulan, 'color' => '#8e44ad'],
				['label' => '12 Bulan', 'value' => $total12Bulan, 'color' => '#3498db'],
				['label' => '10-11 Bulan', 'value' => $total10sd11Bulan, 'color' => '#27ae60'],
				['label' => '9 Bulan', 'value' => $total9Bulan, 'color' => '#f39c12'],
				['label' => 'Dibawah 9 Bulan', 'value' => $totalDibawah9Bulan, 'color' => '#e74c3c']
			];
			
			$html .= '<div style="width: 100%; height: 50px; background: #e9ecef; border-radius: 6px; overflow: hidden; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); display: flex; margin-bottom: 20px;">';
			
			foreach ($statusBars as $status) {
				$percentage = $grandTotal > 0 ? ($status['value'] / $grandTotal) * 100 : 0;
				$html .= '<div style="height: 100%; width: ' . $percentage . '%; background: ' . $status['color'] . '; transition: width 0.3s ease; display: flex; align-items: center; justify-content: center; color: #fff; font-weight: 700; font-size: 12px; position: relative;">';
				// if ($percentage > 5) {
					$html .= round($percentage, 1) . '%';
				// }
				$html .= '</div>';
			}
			
			$html .= '</div>';
			
			$html .= '<div style="display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 20px;">';
			foreach ($statusBars as $status) {
				$html .= '<div style="display: flex; align-items: center; gap: 8px; font-size: 12px;">';
				$html .= '<div style="width: 16px; height: 16px; background: ' . $status['color'] . '; border-radius: 3px;"></div>';
				$html .= '<span style="color: #333;">' . $status['label'] . ': <strong>' . number_format($status['value'], 2, ',', '.') . '</strong></span>';
				$html .= '</div>';
			}
			$html .= '</div>';
		}
		
		$html .= '</div>';
		
		return response()->json([
			'status' => 'success',
			'data' => $klasifikasiData,
			'html' => $html,
			'total_diatas_12_bulan' => $totalDiatas12Bulan,
			'total_12_bulan' => $total12Bulan,
			'total_10sd11_bulan' => $total10sd11Bulan,
			'total_9_bulan' => $total9Bulan,
			'total_dibawah_9_bulan' => $totalDibawah9Bulan,
			'grand_total' => $grandTotal
		]);
	}

	

	

	public function getStatisticsMasterKebun(Request $request)
	{
		$results = \DB::table('master_kebun_kso_pica')
			->selectRaw('COUNT(DISTINCT cluster) AS total_cluster')
			->selectRaw('COUNT(DISTINCT kode_kebun) AS total_kebun')
			->selectRaw('SUM(luas_ha) AS total_luas_ha')
			->where('kode_kebun', 'LIKE', 'SK%')
			->first();

		return response()->json([
			'total_cluster' => (int)($results->total_cluster ?? 0),
			'total_kebun' => (int)($results->total_kebun ?? 0),
			'total_luas_ha' => (float)($results->total_luas_ha ?? 0)
		]);
	}

	public function getStatisticsMasterPG(Request $request)
	{
		$results = \DB::table('master_kebun_kso_pica')
			->selectRaw('COUNT(DISTINCT cluster) AS total_cluster')
			->selectRaw('COUNT(DISTINCT kode_kebun) AS total_kebun')
			->selectRaw('SUM(luas_ha) AS total_luas_ha')
			->where('kode_kebun', 'LIKE', 'SG%')
			->first();

		return response()->json([
			'total_cluster' => (int)($results->total_cluster ?? 0),
			'total_kebun' => (int)($results->total_kebun ?? 0),
			'total_luas_ha' => (float)($results->total_luas_ha ?? 0)
		]);
	}

	public function getTableMasterKebun(Request $request)
	{
		$results = \DB::table('master_kebun_kso_pica')
			->select('id', 'jawa_luarjawa', 'cluster', 'kode_kebun', 'kebun', 'alamat_kebun', 'luas_ha')
			->where('kode_kebun', 'LIKE', 'SK%')
			->orderBy('id')
			->get();

		$html = '<table class="table table-bordered table-striped" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead><tr>';
		$headers = ['No', 'Jawa/Luar Jawa', 'Cluster', 'Kode Kebun', 'Kebun', 'Alamat Kebun', 'Luas (Ha)'];
		
		foreach ($headers as $h) {
			$html .= '<th style="background: #0265c8; color: #FFF;">' . htmlspecialchars($h) . '</th>';
		}
		$html .= '</tr></thead><tbody>';

		$total_luas = 0.0;

		foreach ($results as $row) {
			$html .= '<tr>';
			$html .= '<td>' . htmlspecialchars($row->id ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->jawa_luarjawa ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->cluster ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->kebun ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->alamat_kebun ?? '') . '</td>';
			
			$luas = isset($row->luas_ha) ? (float)$row->luas_ha : 0.0;
			$html .= '<td>' . number_format($luas, 3) . '</td>';
			$html .= '</tr>';

			$total_luas += $luas;
		}

		// Total row
		$html .= '<tr style="font-weight:bold; background:#f0f0f0;">';
		$html .= '<td colspan="6">Total</td>';
		$html .= '<td>' . number_format($total_luas, 3) . '</td>';
		$html .= '</tr>';

		$html .= '</tbody></table>';

		return response($html);
	}


	public function getTableMasterPG(Request $request)
	{
		$results = \DB::table('master_kebun_kso_pica')
			->select('id', 'jawa_luarjawa', 'cluster', 'kode_kebun', 'kebun', 'alamat_kebun', 'luas_ha')
			->where('kode_kebun', 'LIKE', 'SG%')
			->orderBy('id')
			->get();

		$html = '<table class="table table-bordered table-striped" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead><tr>';
		$headers = ['No', 'Jawa/Luar Jawa', 'Cluster', 'Kode PG', 'Pabrik Gula', 'Alamat PG', 'Luas (Ha)'];
		
		foreach ($headers as $h) {
			$html .= '<th style="background: #0265c8; color: #FFF;">' . htmlspecialchars($h) . '</th>';
		}
		$html .= '</tr></thead><tbody>';

		$total_luas = 0.0;

		foreach ($results as $row) {
			$html .= '<tr>';
			$html .= '<td>' . htmlspecialchars($row->id ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->jawa_luarjawa ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->cluster ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->kebun ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->alamat_kebun ?? '') . '</td>';
			
			$luas = isset($row->luas_ha) ? (float)$row->luas_ha : 0.0;
			$html .= '<td>' . number_format($luas, 3) . '</td>';
			$html .= '</tr>';

			$total_luas += $luas;
		}

		// Total row
		$html .= '<tr style="font-weight:bold; background:#f0f0f0;">';
		$html .= '<td colspan="6">Total</td>';
		$html .= '<td>' . number_format($total_luas, 3) . '</td>';
		$html .= '</tr>';

		$html .= '</tbody></table>';

		return response($html);
	}

	public function formtablePicapanenrayonkebun(Request $request)
	{
		$this->data = array_merge(array(
			'pageTitle'	=> 'Pica Panen Rayon Kebun',
			'pageNote'	=> 'Data Pica Panen Rayon Kebun',
		),$this->data);

		return view($this->module.'.pica_panen_rayonkebun', $this->data);
	}

	public function gettablePicapanenrayonkebun(Request $request)
	{
		config(['app.debug' => true]);
		$cluster = $request->get('cluster', '');
		$kebun = $request->get('kebun', '');
		$start_date = $request->get('start_date', '');
		$end_date = $request->get('end_date', '');


		$params = [$cluster, $kebun, $start_date, $end_date];
		$results = \DB::select('CALL sp_pica_panen_rayonkebun(?, ?, ?, ?)', $params);

		$params2 = [$cluster, $kebun, $start_date, $end_date];
		$results2 = \DB::select('CALL sp_nilai_pica_panen_rayonkebun(?, ?, ?, ?)', $params);

				$html = '<table id="rekap-table" class="table table-bordered table-responsive" border="1" cellpadding="5" cellspacing="0">';
				$html .= '<thead>';

				// First row - main headers
				$html .= '<tr>';
				$headers = ['Cluster', 'Kode Kebun', 'Kebun', 'Protas'];

				// Add Rayon columns if kebun is provided
				if (!empty($kebun)) {
					$headers[] = 'Kode Rayon';
					$headers[] = 'Rayon';
				}

				$colspan = !empty($kebun) ? 6 : 4;
				foreach ($headers as $h) {
					$html .= '<th rowspan="3" style="background-color:#0265c8; color:#FFF; vertical-align:middle; text-align:center;">' . htmlspecialchars($h) . '</th>';
				}

				// Add NILAI PICA headers first
				$html .= '<th colspan="6" style="background-color:#4799ea; color:#FFF; text-align:center;">NILAI PICA</th>';
				// Add LUAS (Ha) and JUMLAH PETAK headers
				$html .= '<th colspan="6" style="background-color:#0265c8; color:#FFF; text-align:center;">LUAS (Ha)</th>';
				$html .= '<th colspan="6" style="background-color:#4799ea; color:#FFF; text-align:center;">JUMLAH PETAK</th>';
				$html .= '</tr>';

				// Second row - color headers
				$html .= '<tr>';
				$colorHeaders = ['Emas', 'Hijau', 'Kuning', 'Merah', 'Hitam', 'Total'];

				// For NILAI PICA
				foreach ($colorHeaders as $h) {
					$style = '';
					$txt = strtoupper($h);
					if (strpos($txt, 'EMAS') !== false) {
						$style = 'background-color:#FFD700; color:#000; text-align:center;';
					} elseif (strpos($txt, 'HIJAU') !== false) {
						$style = 'background-color:#008000; color:#FFF; text-align:center;';
					} elseif (strpos($txt, 'KUNING') !== false) {
						$style = 'background-color:#FFFF00; color:#000; text-align:center;';
					} elseif (strpos($txt, 'MERAH') !== false) {
						$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
					} elseif (strpos($txt, 'HITAM') !== false) {
						$style = 'background-color:#000000; color:#FFF; text-align:center;';
					} else {
						$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
					}
					$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
				}

				// For LUAS (Ha)
				foreach ($colorHeaders as $h) {
					$style = '';
					$txt = strtoupper($h);
					if (strpos($txt, 'EMAS') !== false) {
						$style = 'background-color:#FFD700; color:#000; text-align:center;';
					} elseif (strpos($txt, 'HIJAU') !== false) {
						$style = 'background-color:#008000; color:#FFF; text-align:center;';
					} elseif (strpos($txt, 'KUNING') !== false) {
						$style = 'background-color:#FFFF00; color:#000; text-align:center;';
					} elseif (strpos($txt, 'MERAH') !== false) {
						$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
					} elseif (strpos($txt, 'HITAM') !== false) {
						$style = 'background-color:#000000; color:#FFF; text-align:center;';
					} else {
						$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
					}
					$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
				}

				// For JUMLAH PETAK
				foreach ($colorHeaders as $h) {
					$style = '';
					$txt = strtoupper($h);
					if (strpos($txt, 'EMAS') !== false) {
						$style = 'background-color:#FFD700; color:#000; text-align:center;';
					} elseif (strpos($txt, 'HIJAU') !== false) {
						$style = 'background-color:#008000; color:#FFF; text-align:center;';
					} elseif (strpos($txt, 'KUNING') !== false) {
						$style = 'background-color:#FFFF00; color:#000; text-align:center;';
					} elseif (strpos($txt, 'MERAH') !== false) {
						$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
					} elseif (strpos($txt, 'HITAM') !== false) {
						$style = 'background-color:#000000; color:#FFF; text-align:center;';
					} else {
						$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
					}
					$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
				}
				$html .= '</tr>';

				// Third row - description row for color categories
				$html .= '<tr style="font-size:11px; text-align:center;">';
				$html .= '<td style="background-color:#FFD700; color:#000; font-weight:bold;">5</td>';
				$html .= '<td style="background-color:#90EE90; color:#000; font-weight:bold;">4</td>';
				$html .= '<td style="background-color:#FFFF99; color:#000; font-weight:bold;">3</td>';
				$html .= '<td style="background-color:#FFB6C1; color:#000; font-weight:bold;">2</td>';
				$html .= '<td style="background-color:#D3D3D3; color:#000; font-weight:bold;">1</td>';
				$html .= '<td style="background-color:#E0E0E0;"></td>'; // Total Nilai PICA
				$html .= '<td style="background-color:#FFD700; color:#000; font-weight:bold;">≥ 100 ton/ha</td>';
				$html .= '<td style="background-color:#90EE90; color:#000; font-weight:bold;">85 ≤ X < 100 ton/ha</td>';
				$html .= '<td style="background-color:#FFFF99; color:#000; font-weight:bold;">70 ≤ X < 85 ton/ha</td>';
				$html .= '<td style="background-color:#FFB6C1; color:#000; font-weight:bold;">60 ≤ X < 70 ton/ha</td>';
				$html .= '<td style="background-color:#D3D3D3; color:#000; font-weight:bold;">< 60 ton/ha</td>';
				$html .= '<td style="background-color:#E0E0E0;"></td>'; // Total (Ha)
				$html .= '<td style="background-color:#FFD700; color:#000; font-weight:bold;">≥ 100 ton/ha</td>';
				$html .= '<td style="background-color:#90EE90; color:#000; font-weight:bold;">85 ≤ X < 100 ton/ha</td>';
				$html .= '<td style="background-color:#FFFF99; color:#000; font-weight:bold;">70 ≤ X < 85 ton/ha</td>';
				$html .= '<td style="background-color:#FFB6C1; color:#000; font-weight:bold;">60 ≤ X < 70 ton/ha</td>';
				$html .= '<td style="background-color:#D3D3D3; color:#000; font-weight:bold;">< 60 ton/ha</td>';
				$html .= '<td style="background-color:#E0E0E0;"></td>'; // Total Petak
				$html .= '</tr>';

				$html .= '</thead><tbody>';

				// Gabungkan results dan results2 berdasarkan cluster, kode_kebun, kebun, kode_rayon, rayon
				$nilaiPicaMap = [];
				foreach ($results2 as $row2) {
					$key = $row2->cluster . '|' . $row2->kode_kebun . '|' . $row2->kebun;
					if (isset($row2->kode_rayon) && isset($row2->rayon)) {
						$key .= '|' . $row2->kode_rayon . '|' . $row2->rayon;
					}
					$nilaiPicaMap[$key] = [
						'emas_pica' => isset($row2->emas_pica) ? (float)$row2->emas_pica : 0.0,
						'hijau_pica' => isset($row2->hijau_pica) ? (float)$row2->hijau_pica : 0.0,
						'kuning_pica' => isset($row2->kuning_pica) ? (float)$row2->kuning_pica : 0.0,
						'merah_pica' => isset($row2->merah_pica) ? (float)$row2->merah_pica : 0.0,
						'hitam_pica' => isset($row2->hitam_pica) ? (float)$row2->hitam_pica : 0.0,
						'nilai_pica' => isset($row2->nilai_pica) ? (float)$row2->nilai_pica : 0.0,
					];
				}

				$total_emas_ha = 0.0;
				$total_hijau_ha = 0.0;
				$total_kuning_ha = 0.0;
				$total_merah_ha = 0.0;
				$total_hitam_ha = 0.0;
				$total_ha = 0.0;
				$total_emas_petak = 0;
				$total_hijau_petak = 0;
				$total_kuning_petak = 0;
				$total_merah_petak = 0;
				$total_hitam_petak = 0;
				$total_petak = 0;
				$total_emas_pica = 0.0;
				$total_hijau_pica = 0.0;
				$total_kuning_pica = 0.0;
				$total_merah_pica = 0.0;
				$total_hitam_pica = 0.0;
				$total_nilai_pica = 0.0;

				foreach ($results as $row) {
					$emas_ha = isset($row->emas_ha) ? (float)$row->emas_ha : 0.0;
					$hijau_ha = isset($row->hijau_ha) ? (float)$row->hijau_ha : 0.0;
					$kuning_ha = isset($row->kuning_ha) ? (float)$row->kuning_ha : 0.0;
					$merah_ha = isset($row->merah_ha) ? (float)$row->merah_ha : 0.0;
					$hitam_ha = isset($row->hitam_ha) ? (float)$row->hitam_ha : 0.0;
					$total = isset($row->total_ha) ? (float)$row->total_ha : 0.0;

					$emas_petak = isset($row->emas_petak) ? (int)$row->emas_petak : 0;
					$hijau_petak = isset($row->hijau_petak) ? (int)$row->hijau_petak : 0;
					$kuning_petak = isset($row->kuning_petak) ? (int)$row->kuning_petak : 0;
					$merah_petak = isset($row->merah_petak) ? (int)$row->merah_petak : 0;
					$hitam_petak = isset($row->hitam_petak) ? (int)$row->hitam_petak : 0;
					$total_p = isset($row->total_petak) ? (int)$row->total_petak : 0;

					$key = $row->cluster . '|' . $row->kode_kebun . '|' . $row->kebun;
					if (isset($row->kode_rayon) && isset($row->rayon)) {
						$key .= '|' . $row->kode_rayon . '|' . $row->rayon;
					}
					$nilaiPica = isset($nilaiPicaMap[$key]) ? $nilaiPicaMap[$key] : [
						'emas_pica' => 0.0,
						'hijau_pica' => 0.0,
						'kuning_pica' => 0.0,
						'merah_pica' => 0.0,
						'hitam_pica' => 0.0,
						'nilai_pica' => 0.0,
					];

					$html .= '<tr>';
					$html .= '<td style="text-align:center;">' . htmlspecialchars($row->cluster ?? '') . '</td>';
					$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
					$html .= '<td>' . htmlspecialchars($row->kebun ?? '') . '</td>';
					$html .= '<td style="text-align:center;">' . (isset($row->protas) && $row->protas !== 0 ? number_format((float)$row->protas, 2) : '') . '</td>';
					
					// Add Rayon columns if kebun is provided
					if (!empty($kebun)) {
						$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_rayon ?? '') . '</td>';
						$html .= '<td>' . htmlspecialchars($row->rayon ?? '') . '</td>';
					}
					
					// Nilai PICA columns (after Protas)
					$html .= '<td style="text-align:center;">' . ($nilaiPica['emas_pica'] !== 0.0 ? number_format($nilaiPica['emas_pica'], 2) : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($nilaiPica['hijau_pica'] !== 0.0 ? number_format($nilaiPica['hijau_pica'], 2) : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($nilaiPica['kuning_pica'] !== 0.0 ? number_format($nilaiPica['kuning_pica'], 2) : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($nilaiPica['merah_pica'] !== 0.0 ? number_format($nilaiPica['merah_pica'], 2) : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($nilaiPica['hitam_pica'] !== 0.0 ? number_format($nilaiPica['hitam_pica'], 2) : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($nilaiPica['nilai_pica'] !== 0.0 ? number_format($nilaiPica['nilai_pica'], 2) : '') . '</td>';
					
					// LUAS (Ha) columns
					$html .= '<td style="text-align:center;">' . ($emas_ha !== 0.0 ? number_format($emas_ha, 3) : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($hijau_ha !== 0.0 ? number_format($hijau_ha, 3) : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($kuning_ha !== 0.0 ? number_format($kuning_ha, 3) : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($merah_ha !== 0.0 ? number_format($merah_ha, 3) : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($hitam_ha !== 0.0 ? number_format($hitam_ha, 3) : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($total !== 0.0 ? number_format($total, 3) : '') . '</td>';
					
					// JUMLAH PETAK columns
					$html .= '<td style="text-align:center;">' . ($emas_petak !== 0 ? $emas_petak : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($hijau_petak !== 0 ? $hijau_petak : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($kuning_petak !== 0 ? $kuning_petak : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($merah_petak !== 0 ? $merah_petak : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($hitam_petak !== 0 ? $hitam_petak : '') . '</td>';
					$html .= '<td style="text-align:center;">' . ($total_p !== 0 ? $total_p : '') . '</td>';

					$html .= '</tr>';

					$total_emas_ha += $emas_ha;
					$total_hijau_ha += $hijau_ha;
					$total_kuning_ha += $kuning_ha;
					$total_merah_ha += $merah_ha;
					$total_hitam_ha += $hitam_ha;
					$total_ha += $total;
					$total_emas_petak += $emas_petak;
					$total_hijau_petak += $hijau_petak;
					$total_kuning_petak += $kuning_petak;
					$total_merah_petak += $merah_petak;
					$total_hitam_petak += $hitam_petak;
					$total_petak += $total_p;
					$total_emas_pica += $nilaiPica['emas_pica'];
					$total_hijau_pica += $nilaiPica['hijau_pica'];
					$total_kuning_pica += $nilaiPica['kuning_pica'];
					$total_merah_pica += $nilaiPica['merah_pica'];
					$total_hitam_pica += $nilaiPica['hitam_pica'];
					$total_nilai_pica += $nilaiPica['nilai_pica'];
				}

				$html .= '</tbody></table>';

		return response($html);
	}

	public function formtablePicapemeliharaandiameterrayonkebun(Request $request)
	{
		$this->data = array_merge(array(
			'pageTitle'	=> 'Pica Pemeliharaan Diameter Rayon Kebun',
			'pageNote'	=> 'Data Pica Pemeliharaan Diameter Rayon Kebun',
		),$this->data);

		return view($this->module.'.pica_pemeliharaan_diameter_rayonkebun', $this->data);
	}

	public function gettablePicapemeliharaandiameterrayonkebun(Request $request)
	{
		config(['app.debug' => true]);

		$cluster = $request->get('cluster', '');
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$start_date = $request->get('start_date', '');
		$end_date = $request->get('end_date', '');
		$umur = $request->get('umur', '');

		$params = [$cluster, $kebun, $rayon, $start_date, $end_date, $umur];
		$results = \DB::select('CALL sp_pica_pemeliharaan_diameter_rayonkebun(?, ?, ?, ?, ?, ?)', $params);

		$html = '<table id="rekap-table" class="table table-bordered" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead>';

		// First row - main headers
		$html .= '<tr>';
		$headers = ['Cluster', 'Kode Kebun', 'Kebun', 'Nilai PICA'];

		// Add Rayon columns if kebun is provided
		if (!empty($kebun) && empty($rayon)) {
			$headers[] = 'Kode Rayon';
			$headers[] = 'Rayon';
		}

		$colspan = (!empty($kebun) && empty($rayon)) ? 6 : 4;
		foreach ($headers as $h) {
			$html .= '<th rowspan="2" style="background-color:#0265c8; color:#FFF; vertical-align:middle; text-align:center;">' . htmlspecialchars($h) . '</th>';
		}

		// Add LUAS (Ha) and JUMLAH PETAK headers
		$html .= '<th colspan="6" style="background-color:#0265c8; color:#FFF; text-align:center;">LUAS (Ha)</th>';
		$html .= '<th colspan="6" style="background-color:#4799ea; color:#FFF; text-align:center;">JUMLAH PETAK</th>';
		$html .= '</tr>';

		// Second row - color headers
		$html .= '<tr>';
		$colorHeaders = ['Emas', 'Hijau', 'Kuning', 'Merah', 'Hitam', 'Total'];

		// For LUAS (Ha)
		foreach ($colorHeaders as $h) {
			$style = '';
			$txt = strtoupper($h);
			if (strpos($txt, 'EMAS') !== false) {
				$style = 'background-color:#FFD700; color:#000; text-align:center;';
			} elseif (strpos($txt, 'HIJAU') !== false) {
				$style = 'background-color:#008000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'KUNING') !== false) {
				$style = 'background-color:#FFFF00; color:#000; text-align:center;';
			} elseif (strpos($txt, 'MERAH') !== false) {
				$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'HITAM') !== false) {
				$style = 'background-color:#000000; color:#FFF; text-align:center;';
			} else {
				$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
			}
			$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
		}

		// For JUMLAH PETAK
		foreach ($colorHeaders as $h) {
			$style = '';
			$txt = strtoupper($h);
			if (strpos($txt, 'EMAS') !== false) {
				$style = 'background-color:#FFD700; color:#000; text-align:center;';
			} elseif (strpos($txt, 'HIJAU') !== false) {
				$style = 'background-color:#008000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'KUNING') !== false) {
				$style = 'background-color:#FFFF00; color:#000; text-align:center;';
			} elseif (strpos($txt, 'MERAH') !== false) {
				$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'HITAM') !== false) {
				$style = 'background-color:#000000; color:#FFF; text-align:center;';
			} else {
				$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
			}
			$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
		}
		$html .= '</tr>';



		$html .= '</thead><tbody>';

		$total_emas_ha = 0.0;
		$total_hijau_ha = 0.0;
		$total_kuning_ha = 0.0;
		$total_merah_ha = 0.0;
		$total_hitam_ha = 0.0;
		$total_ha = 0.0;
		$total_emas_petak = 0;
		$total_hijau_petak = 0;
		$total_kuning_petak = 0;
		$total_merah_petak = 0;
		$total_hitam_petak = 0;
		$total_petak = 0;

		foreach ($results as $row) {
			$emas_ha = isset($row->emas_ha) ? (float)$row->emas_ha : 0.0;
			$hijau_ha = isset($row->hijau_ha) ? (float)$row->hijau_ha : 0.0;
			$kuning_ha = isset($row->kuning_ha) ? (float)$row->kuning_ha : 0.0;
			$merah_ha = isset($row->merah_ha) ? (float)$row->merah_ha : 0.0;
			$hitam_ha = isset($row->hitam_ha) ? (float)$row->hitam_ha : 0.0;
			$total = isset($row->total_ha) ? (float)$row->total_ha : 0.0;

			$emas_petak = isset($row->emas_petak) ? (int)$row->emas_petak : 0;
			$hijau_petak = isset($row->hijau_petak) ? (int)$row->hijau_petak : 0;
			$kuning_petak = isset($row->kuning_petak) ? (int)$row->kuning_petak : 0;
			$merah_petak = isset($row->merah_petak) ? (int)$row->merah_petak : 0;
			$hitam_petak = isset($row->hitam_petak) ? (int)$row->hitam_petak : 0;
			$total_p = isset($row->total_petak) ? (int)$row->total_petak : 0;

			$nilai_pica_index = isset($row->nilai_pica_index) ? (float)$row->nilai_pica_index : 0.0;

			$html .= '<tr>';
			$html .= '<td style="text-align:center;">' . htmlspecialchars($row->cluster ?? '') . '</td>';
			$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->kebun ?? '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($nilai_pica_index !== 0.0 ? number_format($nilai_pica_index, 2) : '') . '</td>';
			
			// Add Rayon columns if kebun is provided
			if (!empty($kebun) && empty($rayon)) {
				$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_rayon ?? '') . '</td>';
				$html .= '<td>' . htmlspecialchars($row->rayon ?? '') . '</td>';
			}
			
			$html .= '<td style="text-align:center;">' . ($emas_ha !== 0.0 ? number_format($emas_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hijau_ha !== 0.0 ? number_format($hijau_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($kuning_ha !== 0.0 ? number_format($kuning_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($merah_ha !== 0.0 ? number_format($merah_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hitam_ha !== 0.0 ? number_format($hitam_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($total !== 0.0 ? number_format($total, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($emas_petak !== 0 ? $emas_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hijau_petak !== 0 ? $hijau_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($kuning_petak !== 0 ? $kuning_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($merah_petak !== 0 ? $merah_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hitam_petak !== 0 ? $hitam_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($total_p !== 0 ? $total_p : '') . '</td>';
			$html .= '</tr>';

			$total_emas_ha += $emas_ha;
			$total_hijau_ha += $hijau_ha;
			$total_kuning_ha += $kuning_ha;
			$total_merah_ha += $merah_ha;
			$total_hitam_ha += $hitam_ha;
			$total_ha += $total;
			$total_emas_petak += $emas_petak;
			$total_hijau_petak += $hijau_petak;
			$total_kuning_petak += $kuning_petak;
			$total_merah_petak += $merah_petak;
			$total_hitam_petak += $hitam_petak;
			$total_petak += $total_p;
		}


		$html .= '</tbody></table>';

		return response($html);
	}

	public function formtableNilaiPicapanenrayonkebun(Request $request)
	{
		$this->data['pageTitle']	= 'Nilai Pica Panen Rayon Kebun';
		$this->data['pageNote']	= 'Data Nilai Pica Panen Rayon Kebun';

		return view($this->module.'.nilai_pica_panen_rayonkebun', $this->data);
	}

	public function gettableNilaiPicapanenrayonkebun(Request $request)
	{
		$cluster = $request->get('cluster', '');
		$kebun = $request->get('kebun', '');
		$start_date = $request->get('start_date', '');
		$end_date = $request->get('end_date', '');

		$params = [$cluster, $kebun, $start_date, $end_date];
		$results = \DB::select('CALL sp_nilai_pica_panen_rayonkebun(?, ?, ?, ?)', $params);

		$html = '<table id="rekap-table" class="table table-bordered table-responsive" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead>';

		// First row - main headers
		$html .= '<tr>';
		$headers = ['Cluster', 'Kode Kebun', 'Kebun'];

		// Add Rayon columns if kebun is provided
		if (!empty($kebun)) {
			$headers[] = 'Kode Rayon';
			$headers[] = 'Rayon';
		}

		$colspan = !empty($kebun) ? 5 : 3;
		foreach ($headers as $h) {
			$html .= '<th rowspan="2" style="background-color:#0265c8; color:#FFF; vertical-align:middle; text-align:center;">' . htmlspecialchars($h) . '</th>';
		}

		// Add Nilai Pica headers
		$html .= '<th colspan="6" style="background-color:#0265c8; color:#FFF; text-align:center;">NILAI PICA</th>';
		$html .= '</tr>';

		// Second row - color headers
		$html .= '<tr>';
		$colorHeaders = ['Emas', 'Hijau', 'Kuning', 'Merah', 'Hitam', 'Total'];

		foreach ($colorHeaders as $h) {
			$style = '';
			$txt = strtoupper($h);
			if (strpos($txt, 'EMAS') !== false) {
				$style = 'background-color:#FFD700; color:#000; text-align:center;';
			} elseif (strpos($txt, 'HIJAU') !== false) {
				$style = 'background-color:#008000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'KUNING') !== false) {
				$style = 'background-color:#FFFF00; color:#000; text-align:center;';
			} elseif (strpos($txt, 'MERAH') !== false) {
				$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'HITAM') !== false) {
				$style = 'background-color:#000000; color:#FFF; text-align:center;';
			} else {
				$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
			}
			$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
		}
		$html .= '</tr>';

		$html .= '</thead><tbody>';

		$total_emas = 0.0;
		$total_hijau = 0.0;
		$total_kuning = 0.0;
		$total_merah = 0.0;
		$total_hitam = 0.0;
		$total_nilai = 0.0;

		foreach ($results as $row) {
			$emas = isset($row->emas_pica) ? (float)$row->emas_pica : 0.0;
			$hijau = isset($row->hijau_pica) ? (float)$row->hijau_pica : 0.0;
			$kuning = isset($row->kuning_pica) ? (float)$row->kuning_pica : 0.0;
			$merah = isset($row->merah_pica) ? (float)$row->merah_pica : 0.0;
			$hitam = isset($row->hitam_pica) ? (float)$row->hitam_pica : 0.0;
			$total = isset($row->nilai_pica) ? (float)$row->nilai_pica : 0.0;

			$isTotalRow = strtoupper(trim($row->kebun ?? '')) === 'GRAND TOTAL';
			$rowStyle = $isTotalRow ? 'font-weight:bold;' : '';

			$html .= '<tr style="' . $rowStyle . '">';
			$html .= '<td style="text-align:center;">' . htmlspecialchars($row->cluster ?? '') . '</td>';
			$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->kebun ?? '') . '</td>';
			
			// Add Rayon columns if kebun is provided
			if (!empty($kebun)) {
				$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_rayon ?? '') . '</td>';
				$html .= '<td>' . htmlspecialchars($row->rayon ?? '') . '</td>';
			}
			
			$html .= '<td style="text-align:center;">' . ($emas !== 0.0 ? number_format($emas, 2) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hijau !== 0.0 ? number_format($hijau, 2) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($kuning !== 0.0 ? number_format($kuning, 2) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($merah !== 0.0 ? number_format($merah, 2) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hitam !== 0.0 ? number_format($hitam, 2) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($total !== 0.0 ? number_format($total, 2) : '') . '</td>';
			$html .= '</tr>';

			$total_emas += $emas;
			$total_hijau += $hijau;
			$total_kuning += $kuning;
			$total_merah += $merah;
			$total_hitam += $hitam;
			$total_nilai += $total;
		}

	

		$html .= '</tbody></table>';

		return response($html);
	}

	public function formtableCashcostPanen(Request $request)
	{
		$this->data['pageTitle'] = 'Kuadran PICA - Panen';
		$this->data['pageNote'] = '';

		return view($this->module.'.cashcost_panen', $this->data);
	}

	public function gettableCashcostPanen(Request $request)
	{
		$cluster = $request->get('cluster', '');
		$bulan = $request->get('bulan', '');

		$params = [$cluster, $bulan];
		$results = \DB::select('CALL sp_cashcost_panen(?, ?)', $params);

		$html = '<table id="rekap-table" class="table table-bordered table-striped table-hover" border="1" cellpadding="5" cellspacing="0" style="box-shadow: 0 2px 4px rgba(0,0,0,0.1);">';
		$html .= '<thead>';
		$html .= '<tr>';
		$headers = ['Nama Cluster', 'Kode Kebun', 'Nama Kebun', 'Bulan', 'Standar Cash Cost<br>(Exclude Saprodi)', 'Standar Nilai Pica', 'Real Cash Cost<br>(Exclude Saprodi)', 'Nilai Pica'];
		
		foreach ($headers as $h) {
			$html .= '<th style="background: linear-gradient(135deg, #0265c8 0%, #0a4d8f 100%); color:#FFF; text-align:center; padding:12px; font-weight:600; border:none;">' . $h . '</th>';
		}
		$html .= '</tr>';
		$html .= '</thead><tbody>';

		$total_standar_cashcost = 0.0;
		$total_standar_nilai_pica = 0.0;
		$total_real_cashcost = 0.0;
		$total_nilai_pica = 0.0;

		$no = 1;
		foreach ($results as $row) {
			$standar_cashcost = isset($row->standar_cashcost) ? (float)$row->standar_cashcost : 0.0;
			$standar_nilai_pica = isset($row->standar_nilai_pica) ? (float)$row->standar_nilai_pica : 0.0;
			$real_cashcost = isset($row->real_cashcost) ? (float)$row->real_cashcost : 0.0;
			$nilai_pica = isset($row->nilai_pica) ? (float)$row->nilai_pica : 0.0;

			// Alternating row colors
			$rowStyle = ($no % 2 == 0) ? 'background-color:#f8f9fa;' : 'background-color:#ffffff;';
			
			// Highlight based on performance
			$picaStyle = '';
			if ($nilai_pica >= 2.5) {
				$picaStyle = 'background-color:#d4edda; color:#155724; font-weight:600;'; // Green for good
			} elseif ($nilai_pica < 2.0) {
				$picaStyle = 'background-color:#f8d7da; color:#721c24; font-weight:600;'; // Red for poor
			}

			$html .= '<tr style="' . $rowStyle . '">';
			$html .= '<td style="padding:10px;">' . htmlspecialchars($row->nama_cluster ?? '') . '</td>';
			$html .= '<td style="text-align:center; padding:10px; font-weight:500;">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
			$html .= '<td style="padding:10px;">' . htmlspecialchars($row->nama_kebun ?? '') . '</td>';
			
			// Convert month number to name
			$bulan_angka = $row->bulan ?? '';
			$nama_bulan = '';
			if (is_numeric($bulan_angka)) {
				$bulan_int = (int)$bulan_angka;
				$bulan_names = [
					1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
					5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
					9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
				];
				$nama_bulan = isset($bulan_names[$bulan_int]) ? $bulan_names[$bulan_int] : $bulan_angka;
			} else {
				$nama_bulan = $bulan_angka;
			}
			$html .= '<td style="text-align:center; padding:10px; font-weight:500;">' . htmlspecialchars($nama_bulan) . '</td>';
			$html .= '<td style="text-align:right; padding:10px;">' . ($standar_cashcost !== 0.0 ? 'Rp ' . number_format($standar_cashcost, 0, ',', '.') : '-') . '</td>';
			$html .= '<td style="text-align:right; padding:10px;">' . ($standar_nilai_pica !== 0.0 ? number_format($standar_nilai_pica, 2, ',', '.') : '-') . '</td>';
			$html .= '<td style="text-align:right; padding:10px; font-weight:600;">' . ($real_cashcost !== 0.0 ? 'Rp ' . number_format($real_cashcost, 0, ',', '.') : '-') . '</td>';
			$html .= '<td style="text-align:right; padding:10px; ' . $picaStyle . '">' . ($nilai_pica !== 0.0 ? number_format($nilai_pica, 2, ',', '.') : '-') . '</td>';
			$html .= '</tr>';

			$total_standar_cashcost += $standar_cashcost;
			$total_standar_nilai_pica += $standar_nilai_pica;
			$total_real_cashcost += $real_cashcost;
			$total_nilai_pica += $nilai_pica;
			$no++;
		}


		$html .= '</tbody></table>';

		// Prepare data for quadrant chart
				$chartData = [];
				
				// Calculate average cashcost for mid-point
				$count = count($results);
				$avg_cashcost = $count > 0 ? $total_real_cashcost / $count : 0;
				
				foreach ($results as $row) {
					$real_cashcost = isset($row->real_cashcost) ? (float)$row->real_cashcost : 0.0;
					$nilai_pica = isset($row->nilai_pica) ? (float)$row->nilai_pica : 0.0;
					
					// Determine quadrant based on nilai_pica threshold of 2.5 and cashcost average
					$quadrant = '';
					if ($nilai_pica >= 2.5 && $real_cashcost <= $avg_cashcost) {
						$quadrant = 'Q1'; // High Pica, Low Cost (Best)
					} elseif ($nilai_pica >= 2.5 && $real_cashcost > $avg_cashcost) {
						$quadrant = 'Q2'; // High Pica, High Cost
					} elseif ($nilai_pica < 2.5 && $real_cashcost <= $avg_cashcost) {
						$quadrant = 'Q3'; // Low Pica, Low Cost
					} else {
						$quadrant = 'Q4'; // Low Pica, High Cost (Worst)
					}
					
					$chartData[] = [
						'kode_kebun' => $row->kode_kebun ?? '',
						'nama_kebun' => $row->nama_kebun ?? '',
						'real_cashcost' => $real_cashcost,
						'nilai_pica' => $nilai_pica,
						'quadrant' => $quadrant
					];
				}

				$setting = \DB::table('setting_kuadran_pica')->where('id', 1)->first();


		return response()->json([
			'html' => $html,
			'chartData' => $chartData,
			'setting' => [
				'xMin' => isset($setting->xMin) ? (float)$setting->xMin : 0.0,
				'xMax' => isset($setting->xMax) ? (float)$setting->xMax : 0.0,
				'yMin' => isset($setting->yMin) ? (float)$setting->yMin : 0.0,
				'yMax' => isset($setting->yMax) ? (float)$setting->yMax : 0.0,
				'cashCostMid' => isset($setting->cashCostMid) ? (float)$setting->cashCostMid : 0.0,
				'nilaiMid' => isset($setting->nilaiMid) ? (float)$setting->nilaiMid : 0.0
			]
		]);
	}
 
	public function getDataKuadranCashcostPanen(Request $request)
{
    try {
        // ── 1. Parse parameter ─────────────────────────────────────────────
        $dateParam = $request->get('date', date('Y-m-d'));
        $cluster   = $request->get('cluster', '');

        $dt = \DateTime::createFromFormat('Y-m-d', $dateParam);
        if (!$dt) {
            return response()->json([
                'sts'  => 'error',
                'msg'  => "Parameter 'date' harus dalam format YYYY-MM-DD. Contoh: 2026-04-01.",
                'data' => null,
            ]);
        }

        $tahun = (int) $dt->format('Y');
        $bulan = (int) $dt->format('n');

        // ── 2. Konstanta kuadran ───────────────────────────────────────────
        $x_threshold = 2.5;    // Nilai PICA (sumbu x)
        $y_threshold = 8500;   // Cash Cost tengah (sumbu y, polarity negative)
        $x_offset    = 0.5;
        $y_offset    = 500;
        $y_min       = 0;
        $y_max       = 25000;
        $x_min       = 0;
        $x_max       = 5;

        // Definisi kategori
        $cat_hijau  = [
            'id'              => 1,
            'nama_kategori'   => 'Hijau',
            'slug'            => 'hijau',
            'warna'           => '#05ed00',
            'warna_secondary' => '#018a00',
            'warna_text'      => '#ffffff',
            'desc'            => 'PICA baik, Cash Cost rendah (terbaik)',
        ];
        $cat_oranye = [
            'id'              => 2,
            'nama_kategori'   => 'Oranye',
            'slug'            => 'oranye',
            'warna'           => '#ed9d00',
            'warna_secondary' => '#d4a200',
            'warna_text'      => '#1a1a1a',
            'desc'            => 'PICA baik, Cash Cost tinggi',
        ];
        $cat_kuning = [
            'id'              => 3,
            'nama_kategori'   => 'Kuning',
            'slug'            => 'kuning',
            'warna'           => '#eded00',
            'warna_secondary' => '#8a8a00',
            'warna_text'      => '#1a1a1a',
            'desc'            => 'PICA buruk, Cash Cost rendah',
        ];
        $cat_merah  = [
            'id'              => 4,
            'nama_kategori'   => 'Merah',
            'slug'            => 'merah',
            'warna'           => '#ed0000',
            'warna_secondary' => '#8a0000',
            'warna_text'      => '#ffffff',
            'desc'            => 'PICA buruk, Cash Cost tinggi (terburuk)',
        ];

        // Urutan slug untuk historical (best → worst), harus sama setiap bulan
        $slug_order = ['hijau', 'kuning', 'oranye', 'merah'];
        $cat_map    = [
            'hijau'  => $cat_hijau,
            'kuning' => $cat_kuning,
            'oranye' => $cat_oranye,
            'merah'  => $cat_merah,
        ];

        // ── 3. Helper: klasifikasi satu baris ke slug kuadran ─────────────
        $classify = function ($nilai_pica, $real_cashcost)
            use ($x_threshold, $y_threshold) {
            $good_x = ($nilai_pica  >= $x_threshold);
            $good_y = ($real_cashcost <  $y_threshold); // polarity negative: rendah = baik
            if ($good_x && $good_y)  return 'hijau';
            if ($good_x && !$good_y) return 'oranye';
            if (!$good_x && $good_y) return 'kuning';
            return 'merah';
        };

        // ── 4. Helper: format periode ──────────────────────────────────────
        $makePeriod = function (int $y, int $m) {
            $last = cal_days_in_month(CAL_GREGORIAN, $m, $y);
            $pad  = str_pad($m, 2, '0', STR_PAD_LEFT);
            return [
                'start'       => "{$y}-{$pad}-01T00:00:00+07:00",
                'end'         => "{$y}-{$pad}-{$last}T00:00:00+07:00",
                'start_plain' => "{$y}-{$pad}-01",
                'end_plain'   => "{$y}-{$pad}-{$last}",
            ];
        };

        // ── 5. Data bulan ini untuk section ───────────────────────────────
        $results = \DB::select('CALL sp_cashcost_panen(?, ?)', [$cluster, $bulan]);
        $period  = $makePeriod($tahun, $bulan);

        $points = [];

        foreach ($results as $index => $row) {
            $nilai_pica   = isset($row->nilai_pica)   ? (float) $row->nilai_pica   : 0.0;
            $real_cashcost = isset($row->real_cashcost) ? (float) $row->real_cashcost : 0.0;
            $kode_kebun   = $row->kode_kebun ?? ('K' . ($index + 1));
            $nama_kebun   = $row->nama_kebun ?? $row->nama_cluster ?? '';

            $points[] = [
                'x'                  => $nilai_pica,
                'y'                  => $real_cashcost,
                'region'             => $nama_kebun,
                'outputType'         => 'Cash Cost vs. Nilai PICA (Masa Panen)',
                'periode_start'      => $period['start'],
                'periode_end'        => $period['end'],
                'kode_pabrik'        => $kode_kebun,
                'parameter_id'       => $index + 1,
                'parameter_slug'     => 'cashcost_vs_pica',
                'parameter_nickname' => 'Cash Cost',
            ];
        }

        // 4 placeholder sudut domain chart (wajib ada persis 4)
        $ph_corners = [
            ['x' => $x_min,       'y' => $y_min],
            ['x' => $x_min,       'y' => $y_max],
            ['x' => $x_max,       'y' => $y_min],
            ['x' => $x_max,       'y' => $y_max],
        ];
        foreach ($ph_corners as $ph) {
            $points[] = [
                'x'                  => $ph['x'],
                'y'                  => $ph['y'],
                'region'             => '',
                'outputType'         => 'Placeholder',
                'periode_start'      => $period['start_plain'],
                'periode_end'        => $period['end_plain'],
                'kode_pabrik'        => 'placeholder',
                'parameter_id'       => 0,
                'parameter_slug'     => 'cashcost_vs_pica',
                'parameter_nickname' => 'Cash Cost',
            ];
        }

        // ── 6. Bangun sections ─────────────────────────────────────────────
        $sections = [
            [
                'id'    => 'cashcost_vs_pica',
                'label' => 'Cash Cost',
                'icon'  => 'CircleDollarSign',
                'title' => 'Cash Cost vs. Nilai PICA (Masa Panen)',
                'data'  => [
                    'rule' => [
                        'x_threshold' => $x_threshold,
                        'y_threshold' => $y_threshold,
                        'x_offset'    => $x_offset,
                        'y_offset'    => $y_offset,
                        'polarity'    => 'negative',
                        // Q1 top-right setelah flip y = PICA baik + cashcost rendah = hijau
                        'color_q1'    => $cat_hijau,
                        // Q2 top-left = PICA buruk + cashcost rendah = kuning
                        'color_q2'    => $cat_kuning,
                        // Q3 bottom-left = PICA buruk + cashcost tinggi = merah (terburuk)
                        'color_q3'    => $cat_merah,
                        // Q4 bottom-right = PICA baik + cashcost tinggi = oranye
                        'color_q4'    => $cat_oranye,
                        'desc'        => 'Kuadran Cash Cost vs Nilai PICA Masa Panen. '
                                       . 'Sumbu X = Nilai PICA (threshold 2.5), '
                                       . 'Sumbu Y = Real Cash Cost (threshold Rp 8.500, lower is better).',
                    ],
                    'data' => $points,
                ],
            ],
        ];

        // ── 7. Bangun historical (6 bulan terakhir termasuk bulan ini) ─────
        $historical = [];

        for ($i = 5; $i >= 0; $i--) {
            $hist_dt    = clone $dt;
            $hist_dt->modify("-{$i} month");
            $hist_bulan = (int) $hist_dt->format('n');
            $hist_tahun = (int) $hist_dt->format('Y');
            $date_label = $hist_dt->format('M Y'); // "Apr 2026"

            $hist_results = \DB::select('CALL sp_cashcost_panen(?, ?)', [$cluster, $hist_bulan]);

            // Kumpulkan kode_kebun per kategori
            $buckets_raw = ['hijau' => [], 'kuning' => [], 'oranye' => [], 'merah' => []];

            foreach ($hist_results as $row) {
                $np  = isset($row->nilai_pica)    ? (float) $row->nilai_pica    : 0.0;
                $rc  = isset($row->real_cashcost)  ? (float) $row->real_cashcost  : 0.0;
                $kode = trim($row->kode_kebun ?? '');

                // Lewati baris tanpa kode atau tanpa data
                if ($kode === '' || ($np == 0.0 && $rc == 0.0)) {
                    continue;
                }

                $slug = $classify($np, $rc);
                $buckets_raw[$slug][] = $kode;
            }

            // Format bucket sesuai spesifikasi
            $data_buckets = [];
            foreach ($slug_order as $slug) {
                $colors  = $cat_map[$slug];
                $ids_arr = $buckets_raw[$slug];

                if (empty($ids_arr)) {
                    // Zero records → data harus array kosong []
                    $data_buckets[] = [
                        'slug'            => $slug,
                        'warna'           => $colors['warna'],
                        'warna_secondary' => $colors['warna_secondary'],
                        'warna_text'      => $colors['warna_text'],
                        'data'            => [],
                    ];
                } else {
                    // Ada record → data adalah object SectionCountMap
                    $ids_str = implode(',', $ids_arr);
                    $data_buckets[] = [
                        'slug'            => $slug,
                        'warna'           => $colors['warna'],
                        'warna_secondary' => $colors['warna_secondary'],
                        'warna_text'      => $colors['warna_text'],
                        'data'            => [
                            'cashcost_vs_pica' => [
                                'ids'   => $ids_str,
                                'count' => count($ids_arr),
                            ],
                        ],
                    ];
                }
            }

            $historical[] = [
                'date' => $date_label,
                'data' => $data_buckets,
            ];
        }

        // ── 8. Return envelope ─────────────────────────────────────────────
        return response()->json([
            'sts'  => 'success',
            'msg'  => 'OK',
            'data' => [
                'sections'   => $sections,
                'historical' => $historical,
            ],
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'sts'  => 'error',
            'msg'  => $e->getMessage(),
            'data' => null,
        ]);
    }
}


	public function gettableKuadranPemeliharaanPicaGrafik(Request $request)
	{
		config(['app.debug' => true]);
		$kebun    = $request->get('kebun', NULL);
		$kategori = $request->get('kategori', NULL);
		$umur     = $request->get('umur', '5');

		$results = \DB::select('CALL sp_kuadran_pemeliharaan_pica_grafik(?, ?, ?)', [$kebun, $kategori, $umur]);

		$html = '<table id="rekap-table" class="table table-bordered table-striped table-hover" border="1" cellpadding="5" cellspacing="0" style="box-shadow: 0 2px 4px rgba(0,0,0,0.1);">';
		$html .= '<thead>';
		$html .= '<tr>';
		$headers = ['Kode Kebun', 'Kebun', 'Kategori', 'Umur', 'Rencana Biaya Garap/Ha', 'Realisasi Biaya Garap/Ha', 'Persen Biaya Garap', 'Standar Penyerapan Biaya', 'Standar Nilai PICA', 'Nilai PICA'];
		
		foreach ($headers as $h) {
			$html .= '<th style="background: linear-gradient(135deg, #0265c8 0%, #0a4d8f 100%); color:#FFF; text-align:center; padding:12px; font-weight:600; border:none;">' . htmlspecialchars($h) . '</th>';
		}
		$html .= '</tr>';
		$html .= '</thead><tbody>';

		$total_rencana = 0.0;
		$total_realisasi = 0.0;
		$total_persen = 0.0;
		$total_standar_biaya = 0.0;
		$total_standar_pica = 0.0;
		$total_nilai_pica = 0.0;

		$no = 1;
		foreach ($results as $row) {
			$rencana_biaya = isset($row->rencana_biayagarap_perha) ? (float)$row->rencana_biayagarap_perha : 0.0;
			$realisasi_biaya = isset($row->realisasi_biayagarap_perha) ? (float)$row->realisasi_biayagarap_perha : 0.0;
			$persen_biaya = isset($row->persen_biayagarap) ? (float)$row->persen_biayagarap : 0.0;
			$standar_biaya = isset($row->standar_penyerapan_biaya) ? (float)$row->standar_penyerapan_biaya : 0.0;
			$standar_pica = isset($row->standar_nilai_pica) ? (float)$row->standar_nilai_pica : 0.0;
			$nilai_pica = isset($row->nilai_pica) ? (float)$row->nilai_pica : 0.0;

			// Alternating row colors
			$rowStyle = ($no % 2 == 0) ? 'background-color:#f8f9fa;' : 'background-color:#ffffff;';
			
			// Highlight based on performance
			$picaStyle = '';
			if ($nilai_pica >= $standar_pica) {
				$picaStyle = 'background-color:#d4edda; color:#155724; font-weight:600;'; // Green for good
			} elseif ($nilai_pica < ($standar_pica * 0.8)) {
				$picaStyle = 'background-color:#f8d7da; color:#721c24; font-weight:600;'; // Red for poor
			}

			$html .= '<tr style="' . $rowStyle . '">';
			$html .= '<td style="padding:10px; font-weight:500; text-align:center;">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
			$html .= '<td style="padding:10px;">' . htmlspecialchars($row->kebun ?? '') . '</td>';
			$html .= '<td style="text-align:center; padding:10px; font-weight:500;">' . htmlspecialchars($row->kategori ?? '') . '</td>';
			$html .= '<td style="text-align:center; padding:10px;">' . htmlspecialchars($row->umur ?? '') . '</td>';
			$html .= '<td style="text-align:right; padding:10px;">' . ($rencana_biaya !== 0.0 ? 'Rp ' . number_format($rencana_biaya, 0, ',', '.') : '-') . '</td>';
			$html .= '<td style="text-align:right; padding:10px;">' . ($realisasi_biaya !== 0.0 ? 'Rp ' . number_format($realisasi_biaya, 0, ',', '.') : '-') . '</td>';
			$html .= '<td style="text-align:right; padding:10px;">' . ($persen_biaya !== 0.0 ? number_format($persen_biaya, 2, ',', '.') . '%' : '-') . '</td>';
			$html .= '<td style="text-align:right; padding:10px;">' . ($standar_biaya !== 0.0 ? number_format($standar_biaya, 2, ',', '.') : '-') . '</td>';
			$html .= '<td style="text-align:right; padding:10px;">' . ($standar_pica !== 0.0 ? number_format($standar_pica, 2, ',', '.') : '-') . '</td>';
			$html .= '<td style="text-align:right; padding:10px; ' . $picaStyle . '">' . ($nilai_pica !== 0.0 ? number_format($nilai_pica, 2, ',', '.') : '-') . '</td>';
			$html .= '</tr>';

			$total_rencana += $rencana_biaya;
			$total_realisasi += $realisasi_biaya;
			$total_persen += $persen_biaya;
			$total_standar_biaya += $standar_biaya;
			$total_standar_pica += $standar_pica;
			$total_nilai_pica += $nilai_pica;
			$no++;
		}

		// Total row
		$html .= '<tr style="font-weight:bold; background:#f0f0f0;">';
		$html .= '<td colspan="4" style="text-align:right; padding:10px;">TOTAL</td>';
		$html .= '<td style="text-align:right; padding:10px;">Rp ' . number_format($total_rencana, 0, ',', '.') . '</td>';
		$html .= '<td style="text-align:right; padding:10px;">Rp ' . number_format($total_realisasi, 0, ',', '.') . '</td>';
		$html .= '<td style="text-align:right; padding:10px;">' . number_format($total_persen, 2, ',', '.') . '%</td>';
		$html .= '<td style="text-align:right; padding:10px;">' . number_format($total_standar_biaya, 2, ',', '.') . '</td>';
		$html .= '<td style="text-align:right; padding:10px;">' . number_format($total_standar_pica, 2, ',', '.') . '</td>';
		$html .= '<td style="text-align:right; padding:10px;">' . number_format($total_nilai_pica, 2, ',', '.') . '</td>';
		$html .= '</tr>';

		$html .= '</tbody></table>';

		// Prepare data for quadrant chart
		$chartData = [];
		
		foreach ($results as $row) {
			$nilai_pica = isset($row->nilai_pica) ? (float)$row->nilai_pica : 0.0;
			$persen_biaya = isset($row->persen_biayagarap) ? (float)$row->persen_biayagarap : 0.0;
			$standar_pica = isset($row->standar_nilai_pica) ? (float)$row->standar_nilai_pica : 0.0;
			$standar_penyerapan_biaya = isset($row->standar_penyerapan_biaya) ? (float)$row->standar_penyerapan_biaya : 0.0;
			
			// Determine quadrant based on nilai_pica vs standar and persen_biaya
			$quadrant = '';
			if ($nilai_pica >= $standar_pica && $persen_biaya >= 80) {
				$quadrant = 'Q1'; // High Pica, High Efficiency (Best)
			} elseif ($nilai_pica >= $standar_pica && $persen_biaya < 80) {
				$quadrant = 'Q2'; // High Pica, Low Efficiency
			} elseif ($nilai_pica < $standar_pica && $persen_biaya >= 80) {
				$quadrant = 'Q3'; // Low Pica, High Efficiency
			} else {
				$quadrant = 'Q4'; // Low Pica, Low Efficiency (Worst)
			}
			
			$chartData[] = [
				'kode_kebun' => $row->kode_kebun ?? '',
				'kebun' => $row->kebun ?? '',
				'persen_biaya' => $persen_biaya,
				'nilai_pica' => $nilai_pica,
				'standar_pica' => $standar_penyerapan_biaya,
				'quadrant' => $quadrant
			];
		}

		return response()->json([
			'html' => $html,
			'chartData' => $chartData
		]);
	}


	public function formtablePicapemeliharaanjumlahbatangrayonkebun(Request $request)
	{
		$this->data = array_merge(array(
			'pageTitle'	=> 'Pica Pemeliharaan Jumlah Batang Rayon Kebun',
			'pageNote'	=> 'Data Pica Pemeliharaan Jumlah Batang Rayon Kebun',
		),$this->data);

		return view($this->module.'.pica_pemeliharaan_jumlahbatang_rayonkebun', $this->data);
	}

	public function gettablePicapemeliharaanjumlahbatangrayonkebun(Request $request)
	{
		$cluster = $request->get('cluster', '');
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$start_date = $request->get('start_date', '');
		$end_date = $request->get('end_date', '');
		$umur = $request->get('umur', '');

		$params = [$cluster, $kebun, $rayon, $start_date, $end_date, $umur];
		$results = \DB::select('CALL sp_pica_pemeliharaan_jumlahbatang_rayonkebun(?, ?, ?, ?, ?, ?)', $params);
		

		$html = '<table id="rekap-table" class="table table-bordered" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead>';

		// First row - main headers
		$html .= '<tr>';
		$headers = ['Cluster', 'Kode Kebun', 'Kebun', 'Nilai PICA'];

		// Add Rayon columns if kebun is provided
		if (!empty($kebun) && empty($rayon)) {
			$headers[] = 'Kode Rayon';
			$headers[] = 'Rayon';
		}

		$colspan = (!empty($kebun) && empty($rayon)) ? 6 : 4;
		foreach ($headers as $h) {
			$html .= '<th rowspan="2" style="background-color:#0265c8; color:#FFF; vertical-align:middle; text-align:center;">' . htmlspecialchars($h) . '</th>';
		}

		// Add LUAS (Ha) and JUMLAH PETAK headers
		$html .= '<th colspan="6" style="background-color:#0265c8; color:#FFF; text-align:center;">LUAS (Ha)</th>';
		$html .= '<th colspan="6" style="background-color:#4799ea; color:#FFF; text-align:center;">JUMLAH PETAK</th>';
		$html .= '</tr>';

		// Second row - color headers
		$html .= '<tr>';
		$colorHeaders = ['Emas', 'Hijau', 'Kuning', 'Merah', 'Hitam', 'Total'];

		// For LUAS (Ha)
		foreach ($colorHeaders as $h) {
			$style = '';
			$txt = strtoupper($h);
			if (strpos($txt, 'EMAS') !== false) {
				$style = 'background-color:#FFD700; color:#000; text-align:center;';
			} elseif (strpos($txt, 'HIJAU') !== false) {
				$style = 'background-color:#008000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'KUNING') !== false) {
				$style = 'background-color:#FFFF00; color:#000; text-align:center;';
			} elseif (strpos($txt, 'MERAH') !== false) {
				$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'HITAM') !== false) {
				$style = 'background-color:#000000; color:#FFF; text-align:center;';
			} else {
				$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
			}
			$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
		}

		// For JUMLAH PETAK
		foreach ($colorHeaders as $h) {
			$style = '';
			$txt = strtoupper($h);
			if (strpos($txt, 'EMAS') !== false) {
				$style = 'background-color:#FFD700; color:#000; text-align:center;';
			} elseif (strpos($txt, 'HIJAU') !== false) {
				$style = 'background-color:#008000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'KUNING') !== false) {
				$style = 'background-color:#FFFF00; color:#000; text-align:center;';
			} elseif (strpos($txt, 'MERAH') !== false) {
				$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'HITAM') !== false) {
				$style = 'background-color:#000000; color:#FFF; text-align:center;';
			} else {
				$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
			}
			$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
		}
		$html .= '</tr>';

		
		$html .= '</thead><tbody>';

		$total_emas_ha = 0.0;
		$total_hijau_ha = 0.0;
		$total_kuning_ha = 0.0;
		$total_merah_ha = 0.0;
		$total_hitam_ha = 0.0;
		$total_ha = 0.0;
		$total_emas_petak = 0;
		$total_hijau_petak = 0;
		$total_kuning_petak = 0;
		$total_merah_petak = 0;
		$total_hitam_petak = 0;
		$total_petak = 0;

		foreach ($results as $row) {
			$emas_ha = isset($row->emas_ha) ? (float)$row->emas_ha : 0.0;
			$hijau_ha = isset($row->hijau_ha) ? (float)$row->hijau_ha : 0.0;
			$kuning_ha = isset($row->kuning_ha) ? (float)$row->kuning_ha : 0.0;
			$merah_ha = isset($row->merah_ha) ? (float)$row->merah_ha : 0.0;
			$hitam_ha = isset($row->hitam_ha) ? (float)$row->hitam_ha : 0.0;
			$total = isset($row->total_ha) ? (float)$row->total_ha : 0.0;

			$emas_petak = isset($row->emas_petak) ? (int)$row->emas_petak : 0;
			$hijau_petak = isset($row->hijau_petak) ? (int)$row->hijau_petak : 0;
			$kuning_petak = isset($row->kuning_petak) ? (int)$row->kuning_petak : 0;
			$merah_petak = isset($row->merah_petak) ? (int)$row->merah_petak : 0;
			$hitam_petak = isset($row->hitam_petak) ? (int)$row->hitam_petak : 0;
			$total_p = isset($row->total_petak) ? (int)$row->total_petak : 0;

			$nilai_pica_index = isset($row->nilai_pica_index) ? (float)$row->nilai_pica_index : 0.0;

			$html .= '<tr>';
			$html .= '<td style="text-align:center;">' . htmlspecialchars($row->cluster ?? '') . '</td>';
			$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->kebun ?? '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($nilai_pica_index !== 0.0 ? number_format($nilai_pica_index, 2) : '') . '</td>';
			
			// Add Rayon columns if kebun is provided
			if (!empty($kebun) && empty($rayon)) {
				$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_rayon ?? '') . '</td>';
				$html .= '<td>' . htmlspecialchars($row->rayon ?? '') . '</td>';
			}
			
			$html .= '<td style="text-align:center;">' . ($emas_ha !== 0.0 ? number_format($emas_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hijau_ha !== 0.0 ? number_format($hijau_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($kuning_ha !== 0.0 ? number_format($kuning_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($merah_ha !== 0.0 ? number_format($merah_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hitam_ha !== 0.0 ? number_format($hitam_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($total !== 0.0 ? number_format($total, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($emas_petak !== 0 ? $emas_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hijau_petak !== 0 ? $hijau_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($kuning_petak !== 0 ? $kuning_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($merah_petak !== 0 ? $merah_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hitam_petak !== 0 ? $hitam_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($total_p !== 0 ? $total_p : '') . '</td>';
			$html .= '</tr>';

			$total_emas_ha += $emas_ha;
			$total_hijau_ha += $hijau_ha;
			$total_kuning_ha += $kuning_ha;
			$total_merah_ha += $merah_ha;
			$total_hitam_ha += $hitam_ha;
			$total_ha += $total;
			$total_emas_petak += $emas_petak;
			$total_hijau_petak += $hijau_petak;
			$total_kuning_petak += $kuning_petak;
			$total_merah_petak += $merah_petak;
			$total_hitam_petak += $hitam_petak;
			$total_petak += $total_p;
		}


		$html .= '</tbody></table>';

		return response($html);
	}

	public function formtablePicapemeliharaantinggirayonkebun(Request $request)
	{
		$this->data = array_merge(array(
			'pageTitle'	=> 'Pica Pemeliharaan Tinggi Batang Rayon Kebun',
			'pageNote'	=> 'Data Pica Pemeliharaan Tinggi Batang Rayon Kebun',
		),$this->data);

		return view($this->module.'.pica_pemeliharaan_tinggi_rayonkebun', $this->data);
	}

	public function gettablePicapemeliharaantinggirayonkebun(Request $request)
	{
		$cluster = $request->get('cluster', '');
		$kebun = $request->get('kebun', '');
		$rayon = $request->get('rayon', '');
		$start_date = $request->get('start_date', '');
		$end_date = $request->get('end_date', '');
		$umur = $request->get('umur', '');

		$params = [$cluster, $kebun, $rayon, $start_date, $end_date, $umur];
		$results = \DB::select('CALL sp_pica_pemeliharaan_tinggi_rayonkebun(?, ?, ?, ?, ?, ?)', $params);

		$html = '<table id="rekap-table" class="table table-bordered" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead>';

		// First row - main headers
		$html .= '<tr>';
		$headers = ['Cluster', 'Kode Kebun', 'Kebun', 'Nilai PICA'];

		// Add Rayon columns if kebun is provided
		if (!empty($kebun) && empty($rayon)) {
			$headers[] = 'Kode Rayon';
			$headers[] = 'Rayon';
		}

		$colspan = (!empty($kebun) && empty($rayon)) ? 6 : 4;
		foreach ($headers as $h) {
			$html .= '<th rowspan="2" style="background-color:#0265c8; color:#FFF; vertical-align:middle; text-align:center;">' . htmlspecialchars($h) . '</th>';
		}

		// Add LUAS (Ha) and JUMLAH PETAK headers
		$html .= '<th colspan="6" style="background-color:#0265c8; color:#FFF; text-align:center;">LUAS (Ha)</th>';
		$html .= '<th colspan="6" style="background-color:#4799ea; color:#FFF; text-align:center;">JUMLAH PETAK</th>';
		$html .= '</tr>';

		// Second row - color headers
		$html .= '<tr>';
		$colorHeaders = ['Emas', 'Hijau', 'Kuning', 'Merah', 'Hitam', 'Total'];

		// For LUAS (Ha)
		foreach ($colorHeaders as $h) {
			$style = '';
			$txt = strtoupper($h);
			if (strpos($txt, 'EMAS') !== false) {
				$style = 'background-color:#FFD700; color:#000; text-align:center;';
			} elseif (strpos($txt, 'HIJAU') !== false) {
				$style = 'background-color:#008000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'KUNING') !== false) {
				$style = 'background-color:#FFFF00; color:#000; text-align:center;';
			} elseif (strpos($txt, 'MERAH') !== false) {
				$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'HITAM') !== false) {
				$style = 'background-color:#000000; color:#FFF; text-align:center;';
			} else {
				$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
			}
			$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
		}

		// For JUMLAH PETAK
		foreach ($colorHeaders as $h) {
			$style = '';
			$txt = strtoupper($h);
			if (strpos($txt, 'EMAS') !== false) {
				$style = 'background-color:#FFD700; color:#000; text-align:center;';
			} elseif (strpos($txt, 'HIJAU') !== false) {
				$style = 'background-color:#008000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'KUNING') !== false) {
				$style = 'background-color:#FFFF00; color:#000; text-align:center;';
			} elseif (strpos($txt, 'MERAH') !== false) {
				$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'HITAM') !== false) {
				$style = 'background-color:#000000; color:#FFF; text-align:center;';
			} else {
				$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
			}
			$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
		}
		$html .= '</tr>';


		$html .= '</thead><tbody>';

		$total_emas_ha = 0.0;
		$total_hijau_ha = 0.0;
		$total_kuning_ha = 0.0;
		$total_merah_ha = 0.0;
		$total_hitam_ha = 0.0;
		$total_ha = 0.0;
		$total_emas_petak = 0;
		$total_hijau_petak = 0;
		$total_kuning_petak = 0;
		$total_merah_petak = 0;
		$total_hitam_petak = 0;
		$total_petak = 0;

		foreach ($results as $row) {
			$emas_ha = isset($row->emas_ha) ? (float)$row->emas_ha : 0.0;
			$hijau_ha = isset($row->hijau_ha) ? (float)$row->hijau_ha : 0.0;
			$kuning_ha = isset($row->kuning_ha) ? (float)$row->kuning_ha : 0.0;
			$merah_ha = isset($row->merah_ha) ? (float)$row->merah_ha : 0.0;
			$hitam_ha = isset($row->hitam_ha) ? (float)$row->hitam_ha : 0.0;
			$total = isset($row->total_ha) ? (float)$row->total_ha : 0.0;

			$emas_petak = isset($row->emas_petak) ? (int)$row->emas_petak : 0;
			$hijau_petak = isset($row->hijau_petak) ? (int)$row->hijau_petak : 0;
			$kuning_petak = isset($row->kuning_petak) ? (int)$row->kuning_petak : 0;
			$merah_petak = isset($row->merah_petak) ? (int)$row->merah_petak : 0;
			$hitam_petak = isset($row->hitam_petak) ? (int)$row->hitam_petak : 0;
			$total_p = isset($row->total_petak) ? (int)$row->total_petak : 0;

			$nilai_pica_index = isset($row->nilai_pica_index) ? (float)$row->nilai_pica_index : 0.0;

			$html .= '<tr>';
			$html .= '<td style="text-align:center;">' . htmlspecialchars($row->cluster ?? '') . '</td>';
			$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->kebun ?? '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($nilai_pica_index !== 0.0 ? number_format($nilai_pica_index, 2) : '') . '</td>';
			
			// Add Rayon columns if kebun is provided
			if (!empty($kebun) && empty($rayon)) {
				$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_rayon ?? '') . '</td>';
				$html .= '<td>' . htmlspecialchars($row->rayon ?? '') . '</td>';
			}
			
			$html .= '<td style="text-align:center;">' . ($emas_ha !== 0.0 ? number_format($emas_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hijau_ha !== 0.0 ? number_format($hijau_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($kuning_ha !== 0.0 ? number_format($kuning_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($merah_ha !== 0.0 ? number_format($merah_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hitam_ha !== 0.0 ? number_format($hitam_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($total !== 0.0 ? number_format($total, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($emas_petak !== 0 ? $emas_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hijau_petak !== 0 ? $hijau_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($kuning_petak !== 0 ? $kuning_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($merah_petak !== 0 ? $merah_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hitam_petak !== 0 ? $hitam_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($total_p !== 0 ? $total_p : '') . '</td>';
			$html .= '</tr>';

			$total_emas_ha += $emas_ha;
			$total_hijau_ha += $hijau_ha;
			$total_kuning_ha += $kuning_ha;
			$total_merah_ha += $merah_ha;
			$total_hitam_ha += $hitam_ha;
			$total_ha += $total;
			$total_emas_petak += $emas_petak;
			$total_hijau_petak += $hijau_petak;
			$total_kuning_petak += $kuning_petak;
			$total_merah_petak += $merah_petak;
			$total_hitam_petak += $hitam_petak;
			$total_petak += $total_p;
		}


		$html .= '</tbody></table>';

		return response($html);
	}


	public function gettablePicapanenrayonkebun2025(Request $request)
	{
		$cluster = $request->get('cluster', '');
		$kebun = $request->get('kebun', '');
		$start_date = $request->get('start_date', '');
		$end_date = $request->get('end_date', '');

		$params = [$cluster, $kebun, $start_date, $end_date];
		$results = \DB::select('CALL sp_pica_panen_rayonkebun_2025(?, ?, ?, ?)', $params);

		$params2 = [$cluster, $kebun, $start_date, $end_date];
		$results2 = \DB::select('CALL sp_nilai_pica_panen_rayonkebun_2025(?, ?, ?, ?)', $params2);

		// Build a lookup map for results2 by composite key
		$nilaiPicaMap = [];
		foreach ($results2 as $r2) {
			$mapKey = ($r2->kode_kebun ?? '') . '|' . ($r2->kode_rayon ?? '');
			$nilaiPicaMap[$mapKey] = $r2;
		}

		$html = '<table id="rekap-table" class="table table-bordered table-responsive" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead>';
		

		// First row - main headers
		$html .= '<tr>';
		$headers = ['Cluster', 'Kode Kebun', 'Kebun','Protas'];

		// Add Rayon columns if kebun is provided
		if (!empty($kebun)) {
			$headers[] = 'Kode Rayon';
			$headers[] = 'Rayon';
		}

		$colspan = !empty($kebun) ? 5 : 3;
		foreach ($headers as $h) {
			$html .= '<th rowspan="3" style="background-color:#0265c8; color:#FFF; vertical-align:middle; text-align:center;">' . htmlspecialchars($h) . '</th>';
		}

		// Add NILAI PICA headers first
		$html .= '<th colspan="6" style="background-color:#4799ea; color:#FFF; text-align:center;">NILAI PICA</th>';
		// Add LUAS (Ha) and JUMLAH PETAK headers
		$html .= '<th colspan="6" style="background-color:#0265c8; color:#FFF; text-align:center;">LUAS (Ha)</th>';
		$html .= '<th colspan="6" style="background-color:#4799ea; color:#FFF; text-align:center;">JUMLAH PETAK</th>';
		$html .= '</tr>';

		// Second row - color headers
		$html .= '<tr>';
		$colorHeaders = ['Emas', 'Hijau', 'Kuning', 'Merah', 'Hitam', 'Total'];

		// For NILAI PICA
		foreach ($colorHeaders as $h) {
			$style = '';
			$txt = strtoupper($h);
			if (strpos($txt, 'EMAS') !== false) {
				$style = 'background-color:#FFD700; color:#000; text-align:center;';
			} elseif (strpos($txt, 'HIJAU') !== false) {
				$style = 'background-color:#008000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'KUNING') !== false) {
				$style = 'background-color:#FFFF00; color:#000; text-align:center;';
			} elseif (strpos($txt, 'MERAH') !== false) {
				$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'HITAM') !== false) {
				$style = 'background-color:#000000; color:#FFF; text-align:center;';
			} else {
				$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
			}
			$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
		}

		// For LUAS (Ha)
		foreach ($colorHeaders as $h) {
			$style = '';
			$txt = strtoupper($h);
			if (strpos($txt, 'EMAS') !== false) {
				$style = 'background-color:#FFD700; color:#000; text-align:center;';
			} elseif (strpos($txt, 'HIJAU') !== false) {
				$style = 'background-color:#008000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'KUNING') !== false) {
				$style = 'background-color:#FFFF00; color:#000; text-align:center;';
			} elseif (strpos($txt, 'MERAH') !== false) {
				$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'HITAM') !== false) {
				$style = 'background-color:#000000; color:#FFF; text-align:center;';
			} else {
				$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
			}
			$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
		}

		// For JUMLAH PETAK
		foreach ($colorHeaders as $h) {
			$style = '';
			$txt = strtoupper($h);
			if (strpos($txt, 'EMAS') !== false) {
				$style = 'background-color:#FFD700; color:#000; text-align:center;';
			} elseif (strpos($txt, 'HIJAU') !== false) {
				$style = 'background-color:#008000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'KUNING') !== false) {
				$style = 'background-color:#FFFF00; color:#000; text-align:center;';
			} elseif (strpos($txt, 'MERAH') !== false) {
				$style = 'background-color:#FF0000; color:#FFF; text-align:center;';
			} elseif (strpos($txt, 'HITAM') !== false) {
				$style = 'background-color:#000000; color:#FFF; text-align:center;';
			} else {
				$style = 'background-color:#0265c8; color:#FFF; text-align:center;';
			}
			$html .= '<th style="' . $style . '">' . htmlspecialchars($h) . '</th>';
		}
		$html .= '</tr>';

		// Third row - description row for color categories
		$html .= '<tr style="font-size:11px; text-align:center;">';
		// NILAI PICA descriptions (no range labels, just empty)
				$html .= '<td style="background-color:#FFD700; color:#000; font-weight:bold;">5</td>';
				$html .= '<td style="background-color:#90EE90; color:#000; font-weight:bold;">4</td>';
				$html .= '<td style="background-color:#FFFF99; color:#000; font-weight:bold;">3</td>';
				$html .= '<td style="background-color:#FFB6C1; color:#000; font-weight:bold;">2</td>';
				$html .= '<td style="background-color:#D3D3D3; color:#000; font-weight:bold;">1</td>';
				$html .= '<td style="background-color:#E0E0E0;"></td>'; // Total (PICA)
		// LUAS (Ha) descriptions
		$html .= '<td style="background-color:#FFD700; color:#000; font-weight:bold;">≥ 100 ton/ha</td>';
		$html .= '<td style="background-color:#90EE90; color:#000; font-weight:bold;">85 ≤ X < 100 ton/ha</td>';
		$html .= '<td style="background-color:#FFFF99; color:#000; font-weight:bold;">70 ≤ X < 85 ton/ha</td>';
		$html .= '<td style="background-color:#FFB6C1; color:#000; font-weight:bold;">60 ≤ X < 70 ton/ha</td>';
		$html .= '<td style="background-color:#D3D3D3; color:#000; font-weight:bold;">< 60 ton/ha</td>';
		$html .= '<td style="background-color:#E0E0E0;"></td>'; // Total (Ha)
		// JUMLAH PETAK descriptions
		$html .= '<td style="background-color:#FFD700; color:#000; font-weight:bold;">≥ 100 ton/ha</td>';
		$html .= '<td style="background-color:#90EE90; color:#000; font-weight:bold;">85 ≤ X < 100 ton/ha</td>';
		$html .= '<td style="background-color:#FFFF99; color:#000; font-weight:bold;">70 ≤ X < 85 ton/ha</td>';
		$html .= '<td style="background-color:#FFB6C1; color:#000; font-weight:bold;">60 ≤ X < 70 ton/ha</td>';
		$html .= '<td style="background-color:#D3D3D3; color:#000; font-weight:bold;">< 60 ton/ha</td>';
		$html .= '<td style="background-color:#E0E0E0;"></td>'; // Total Petak
		$html .= '</tr>';

		$html .= '</thead><tbody>';

		$total_emas_ha = 0.0;
		$total_hijau_ha = 0.0;
		$total_kuning_ha = 0.0;
		$total_merah_ha = 0.0;
		$total_hitam_ha = 0.0;
		$total_ha = 0.0;
		$total_emas_petak = 0;
		$total_hijau_petak = 0;
		$total_kuning_petak = 0;
		$total_merah_petak = 0;
		$total_hitam_petak = 0;
		$total_petak = 0;
		$total_np_emas = 0.0;
		$total_np_hijau = 0.0;
		$total_np_kuning = 0.0;
		$total_np_merah = 0.0;
		$total_np_hitam = 0.0;
		$total_np_nilai = 0.0;

		foreach ($results as $row) {
			$emas_ha = isset($row->emas_ha) ? (float)$row->emas_ha : 0.0;
			$hijau_ha = isset($row->hijau_ha) ? (float)$row->hijau_ha : 0.0;
			$kuning_ha = isset($row->kuning_ha) ? (float)$row->kuning_ha : 0.0;
			$merah_ha = isset($row->merah_ha) ? (float)$row->merah_ha : 0.0;
			$hitam_ha = isset($row->hitam_ha) ? (float)$row->hitam_ha : 0.0;
			$total = isset($row->total_ha) ? (float)$row->total_ha : 0.0;

			$emas_petak = isset($row->emas_petak) ? (int)$row->emas_petak : 0;
			$hijau_petak = isset($row->hijau_petak) ? (int)$row->hijau_petak : 0;
			$kuning_petak = isset($row->kuning_petak) ? (int)$row->kuning_petak : 0;
			$merah_petak = isset($row->merah_petak) ? (int)$row->merah_petak : 0;
			$hitam_petak = isset($row->hitam_petak) ? (int)$row->hitam_petak : 0;
			$total_p = isset($row->total_petak) ? (int)$row->total_petak : 0;

			// Get nilai pica from results2 map
			$mapKey = ($row->kode_kebun ?? '') . '|' . ($row->kode_rayon ?? '');
			$r2 = isset($nilaiPicaMap[$mapKey]) ? $nilaiPicaMap[$mapKey] : null;
			$np_emas   = $r2 && isset($r2->emas_pica)   ? (float)$r2->emas_pica   : 0.0;
			$np_hijau  = $r2 && isset($r2->hijau_pica)  ? (float)$r2->hijau_pica  : 0.0;
			$np_kuning = $r2 && isset($r2->kuning_pica) ? (float)$r2->kuning_pica : 0.0;
			$np_merah  = $r2 && isset($r2->merah_pica)  ? (float)$r2->merah_pica  : 0.0;
			$np_hitam  = $r2 && isset($r2->hitam_pica)  ? (float)$r2->hitam_pica  : 0.0;
			$np_total  = $r2 && isset($r2->nilai_pica)  ? (float)$r2->nilai_pica  : 0.0;

			$html .= '<tr>';
			$html .= '<td style="text-align:center;">' . htmlspecialchars($row->cluster ?? '') . '</td>';
			$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->kebun ?? '') . '</td>';
			$html .= '<td>' . htmlspecialchars($row->protas ?? '') . '</td>';
			
			// Add Rayon columns if kebun is provided
			if (!empty($kebun)) {
				$html .= '<td style="text-align:center;">' . htmlspecialchars($row->kode_rayon ?? '') . '</td>';
				$html .= '<td>' . htmlspecialchars($row->rayon ?? '') . '</td>';
			}

			// NILAI PICA columns
			$html .= '<td style="text-align:center;">' . ($np_emas   !== 0.0 ? number_format($np_emas,   2) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($np_hijau  !== 0.0 ? number_format($np_hijau,  2) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($np_kuning !== 0.0 ? number_format($np_kuning, 2) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($np_merah  !== 0.0 ? number_format($np_merah,  2) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($np_hitam  !== 0.0 ? number_format($np_hitam,  2) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($np_total  !== 0.0 ? number_format($np_total,  2) : '') . '</td>';

			// LUAS (Ha) columns
			$html .= '<td style="text-align:center;">' . ($emas_ha !== 0.0 ? number_format($emas_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hijau_ha !== 0.0 ? number_format($hijau_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($kuning_ha !== 0.0 ? number_format($kuning_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($merah_ha !== 0.0 ? number_format($merah_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hitam_ha !== 0.0 ? number_format($hitam_ha, 3) : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($total !== 0.0 ? number_format($total, 3) : '') . '</td>';
			// JUMLAH PETAK columns
			$html .= '<td style="text-align:center;">' . ($emas_petak !== 0 ? $emas_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hijau_petak !== 0 ? $hijau_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($kuning_petak !== 0 ? $kuning_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($merah_petak !== 0 ? $merah_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($hitam_petak !== 0 ? $hitam_petak : '') . '</td>';
			$html .= '<td style="text-align:center;">' . ($total_p !== 0 ? $total_p : '') . '</td>';
			$html .= '</tr>';

			$total_np_emas   += $np_emas;
			$total_np_hijau  += $np_hijau;
			$total_np_kuning += $np_kuning;
			$total_np_merah  += $np_merah;
			$total_np_hitam  += $np_hitam;
			$total_np_nilai  += $np_total;
			$total_emas_ha += $emas_ha;
			$total_hijau_ha += $hijau_ha;
			$total_kuning_ha += $kuning_ha;
			$total_merah_ha += $merah_ha;
			$total_hitam_ha += $hitam_ha;
			$total_ha += $total;
			$total_emas_petak += $emas_petak;
			$total_hijau_petak += $hijau_petak;
			$total_kuning_petak += $kuning_petak;
			$total_merah_petak += $merah_petak;
			$total_hitam_petak += $hitam_petak;
			$total_petak += $total_p;
		}

		$html .= '</tbody></table>';

		return response($html);
	}

	public function getTableRkapVsRkoVsTakdesVsTakmarVsReal(Request $request)
	{
		$tgl_awal = $request->get('tgl_awal', date('Y-m-d'));
		$tgl_akhir = $request->get('tgl_akhir', date('Y-m-d'));
		$results = \DB::select('CALL sp_rkapvsrkovstakdesvstakmarvsreal(?, ?)', [$tgl_awal, $tgl_akhir]);

		$html = '<table class="table table-bordered table-striped table-responsive" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead><tr>';

		$columns = [];
		if (!empty($results)) {
			$columns = array_keys((array) $results[0]);
		} else {
			$columns = [
				'kode_kebun','kebun','luas_rkap','tebu_rkap','protas_rkap',
				'luas_rko','tebu_rko','protas_rko',
				'luas_takdes','tebu_takdes','protas_takdes',
				'luas_takmar','tebu_takmar','protas_takmar',
				'luas_real','tebu_real','protas_real','tgl_sd'
			];
		}

		foreach ($columns as $col) {
			$html .= '<th style="background:#0265c8;color:#fff;">' . htmlspecialchars(strtoupper(str_replace('_', ' ', $col))) . '</th>';
		}
		$html .= '</tr></thead><tbody>';

		$totals = array_fill_keys($columns, 0.0);

		foreach ($results as $row) {
			$rowArr = (array) $row;
			$html .= '<tr>';

			foreach ($columns as $col) {
				$val = $rowArr[$col] ?? '';

				if (is_numeric($val)) {
					$num = (float) $val;
					$totals[$col] += $num;

					if (stripos($col, 'luas') !== false) {
						$display = number_format($num, 3);
					} elseif (stripos($col, 'protas') !== false) {
						$display = number_format($num, 2);
					} elseif (stripos($col, 'tebu') !== false) {
						$display = number_format($num, 1);
					} else {
						$display = number_format($num, 2);
					}

					$html .= '<td style="text-align:right;">' . $display . '</td>';
				} else {
					$html .= '<td>' . htmlspecialchars((string) $val) . '</td>';
				}
			}

			$html .= '</tr>';
		}

	

		$html .= '</tbody></table>';

		return response($html);
	}

	private function formatLkpPcrcPicaNumber($value)
	{
		if ($value === null || $value === '') {
			return '';
		}

		$num = (float) $value;

		if ($num == 0.0) {
			return '0';
		}

		if (floor($num) == $num) {
			return number_format($num, 0, '.', '');
		}

		return rtrim(rtrim(number_format($num, 3, '.', ''), '0'), '.');
	}

	public function getTableLkpRekapPcrcPica(Request $request)
	{
		$start_date = $request->get('start_date', '2023-10-01');
		$end_date   = $request->get('end_date', '2026-04-06');
		$kode_kat   = $request->get('kode_kat', 'PC');
		$kebun      = $request->get('kebun', 'SK01');
		$afdeling   = $request->get('afdeling', 'SK01K1');

		$results = \DB::select(
			'CALL sp_lkp_rekap_pcrc_pica(?, ?, ?, ?, ?)',
			[$start_date, $end_date, $kode_kat, $kebun, $afdeling]
		);

		$columns = [];
		if (!empty($results)) {
			$columns = array_keys((array) $results[0]);
		}

		$html = '<table class="table table-bordered table-striped table-responsive" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead><tr>';

		foreach ($columns as $col) {
			$html .= '<th style="background:#0265c8;color:#fff;text-align:center;">' . htmlspecialchars(strtoupper(str_replace('_', ' ', $col))) . '</th>';
		}

		$html .= '</tr></thead><tbody>';

		if (empty($results)) {
			$colspan = count($columns) > 0 ? count($columns) : 1;
			$html .= '<tr><td colspan="' . $colspan . '" style="text-align:center;">Data tidak tersedia</td></tr>';
			$html .= '</tbody></table>';
			return response($html);
		}

		$numericColumns = [];
		$totals = [];

		foreach ($columns as $col) {
			$numericColumns[$col] = false;
			$totals[$col] = 0;
		}

		foreach ($results as $row) {
			$rowArr = (array) $row;

			foreach ($columns as $col) {
				$value = $rowArr[$col] ?? null;
				if (is_numeric($value)) {
					$numericColumns[$col] = true;
					$totals[$col] += (float) $value;
				}
			}
		}

		foreach ($results as $row) {
			$rowArr = (array) $row;
			$html .= '<tr>';

			foreach ($columns as $col) {
				$value = $rowArr[$col] ?? '';

				if ($numericColumns[$col] && is_numeric($value)) {
					$html .= '<td style="text-align:right;">' . $this->formatLkpPcrcPicaNumber($value) . '</td>';
				} else {
					$html .= '<td>' . htmlspecialchars((string) $value) . '</td>';
				}
			}

			$html .= '</tr>';
		}


		$html .= '</tbody></table>';

		return response($html);
	}

	public function getTableLkpMonitoringUmur(Request $request)
	{
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$kode_kat = $request->get('kategori');
		$start_date = $request->get('tgl_awal');
		$end_date = $request->get('tgl_akhir');
//		$umur_min = $request->get('umur');
		$jenis_report = $request->get('jenis_report');

		$results = \DB::select(
			'CALL sp_lkp_monitoring_umur_2(?, ?, ?, ?, ?, ?)',
			[$kebun, $rayon, $kode_kat, $start_date, $end_date, $jenis_report]
		);

		$columns = [];
		if (!empty($results)) {
			$columns = array_keys((array) $results[0]);
		}

		$html = '<table class="table table-bordered table-striped table-responsive" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead><tr>';

		foreach ($columns as $col) {
			$html .= '<th style="background:#0265c8;color:#fff;text-align:center;">' . htmlspecialchars(strtoupper(str_replace('_', ' ', $col))) . '</th>';
		}

		$html .= '</tr></thead><tbody>';

		if (empty($results)) {
			$colspan = count($columns) > 0 ? count($columns) : 1;
			$html .= '<tr><td colspan="' . $colspan . '" style="text-align:center;">Data tidak tersedia</td></tr>';
			$html .= '</tbody></table>';
			return response($html);
		}

		foreach ($results as $row) {
			$rowArr = (array) $row;
			$html .= '<tr>';

			foreach ($columns as $col) {
				$value = $rowArr[$col] ?? '';

				if (is_numeric($value)) {
					$html .= '<td style="text-align:right;">' . htmlspecialchars((string) $value) . '</td>';
				} else {
					$html .= '<td>' . htmlspecialchars((string) $value) . '</td>';
				}
			}

			$html .= '</tr>';
		}

		$html .= '</tbody></table>';

		return response($html);
	}

	public function formtableKuadranPemeliharaanPica(Request $request)
	{
		$this->data = array_merge(array(
			'pageTitle' => 'Kuadran Pemeliharaan PICA',
			'pageNote'  => 'Data Kuadran Pemeliharaan PICA',
		), $this->data);

		return view($this->module.'.kuadran_pemeliharaan_pica', $this->data);
	}

	public function gettableKuadranPemeliharaanPica(Request $request)
	{
		config(['app.debug' => true]);
		$kebun    = $request->get('kebun', '');
		$jenis = $request->get('jenis', 'PC');
		$umur     = $request->get('umur', 'TOTAL');

		$results = \DB::select('CALL sp_kuadran_pemeliharaan_pica(?, ?, ?)', [$kebun, $jenis, $umur]);

		$columns = [];
		if (!empty($results)) {
			$columns = array_keys((array) $results[0]);
		}

		$html = '<table class="table table-bordered table-striped table-hover" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead><tr>';

		$headerLabels = [
			'kode_kebun'   => 'Kode Kebun',
			'kategori'     => 'Kategori',
			'umur'         => 'Umur',
			'rencana_bi'   => 'Rencana BI',
			'realisasi_bi' => 'Realisasi BI',
			'standar_pe'   => 'Standar PE',
		];

		foreach ($columns as $col) {
			$label = isset($headerLabels[$col]) ? $headerLabels[$col] : strtoupper(str_replace('_', ' ', $col));
			$html .= '<th style="background:#0265c8;color:#fff;text-align:center;">' . htmlspecialchars($label) . '</th>';
		}
		$html .= '</tr></thead><tbody>';

		if (empty($results)) {
			$colspan = count($columns) > 0 ? count($columns) : 1;
			$html .= '<tr><td colspan="' . $colspan . '" style="text-align:center;">Data tidak tersedia</td></tr>';
			$html .= '</tbody></table>';
			return response($html);
		}

		$numericTotals = array_fill_keys($columns, 0.0);
		$isNumeric     = array_fill_keys($columns, false);

		foreach ($results as $row) {
			$rowArr = (array) $row;
			foreach ($columns as $col) {
				if (is_numeric($rowArr[$col] ?? null)) {
					$isNumeric[$col] = true;
				}
			}
		}

		foreach ($results as $row) {
			$rowArr = (array) $row;
			$html .= '<tr>';
			foreach ($columns as $col) {
				$value = $rowArr[$col] ?? '';
				if ($isNumeric[$col] && is_numeric($value)) {
					$numericTotals[$col] += (float) $value;
					if (stripos($col, 'rencana') !== false || stripos($col, 'realisasi') !== false) {
						$display = number_format((float)$value, 0, ',', '.');
					} elseif (stripos($col, 'standar') !== false) {
						$display = number_format((float)$value, 2, ',', '.');
					} else {
						$display = htmlspecialchars((string)$value);
					}
					$html .= '<td style="text-align:right;">' . $display . '</td>';
				} else {
					$html .= '<td>' . htmlspecialchars((string)$value) . '</td>';
				}
			}
			$html .= '</tr>';
		}

		// Total row
		

		$html .= '</tbody></table>';

		return response($html);
	}


	public function getTableHighchartColumnMonitoringUmur(Request $request)
	{
		config(['app.debug' => true]);
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$kode_kat = $request->get('kategori');
		$start_date = $request->get('tgl_awal');
		$end_date = $request->get('tgl_akhir');
		$jenis_report = $request->get('jenis_report');
		$kategori_pekerjaan = $request->get('kategori_pekerjaan');

		$results = \DB::select(
			'CALL sp_lkp_monitoring_umur_grafik(?, ?, ?, ?, ?, ?, ?)',
			[$kebun, $rayon, $kode_kat, $start_date, $end_date, $jenis_report, $kategori_pekerjaan]
		);

		// Group data by kebun and pekerjaan
		$groupedData = [];
		$pekerjaanTypes = [];
		
		foreach ($results as $row) {
			$keb = $row->kode_kebun . ' - ' . $row->kebun;
			$pekerjaan = $row->pekerjaan;
			$ha = (float)$row->ha;
			
			if (!isset($groupedData[$keb])) {
				$groupedData[$keb] = [];
			}
			
			$groupedData[$keb][$pekerjaan] = $ha;
			
			if (!in_array($pekerjaan, $pekerjaanTypes)) {
				$pekerjaanTypes[] = $pekerjaan;
			}
		}

		// Prepare categories (kebun names)
		$categories = array_keys($groupedData);
		
		// Prepare series for each pekerjaan type
		$series = [];
		foreach ($pekerjaanTypes as $pekerjaan) {
			$data = [];
			foreach ($categories as $keb) {
				$data[] = isset($groupedData[$keb][$pekerjaan]) ? $groupedData[$keb][$pekerjaan] : 0;
			}
			
			$series[] = [
				'name' => $pekerjaan,
				'data' => $data
			];
		}

		return response()->json([
			'categories' => $categories,
			'series' => $series
		]);
	}


	public function formtableMonitoringPiPemeliharaanPanenPica(Request $request)
	{
		$this->data = array_merge(array(
			'pageTitle'	=> 'Monitoring PI Pemeliharaan Panen PICA',
			'pageNote'	=> 'Data Monitoring PI Pemeliharaan Panen PICA',
		),$this->data);

		return view($this->module.'.monitoring_pi_pemeliharaan_panen_pica', $this->data);
	}
	public function getTableMonitoringPiPemeliharaanPanenPica(Request $request)
	{
		config(['app.debug' => true]);
		$cluster = $request->get('cluster', '');
		$tgl = $request->get('tgl', date('Y-m-d'));

		$results = \DB::select('CALL sp_monitoring_pi_pemeliharaan_panen_pica(?, ?)', [$cluster, $tgl]);

		$html = '<table class="table table-bordered table-striped" border="1" cellpadding="5" cellspacing="0">';
		$html .= '<thead>';
		
		// First row - main group headers
		$html .= '<tr>';
		$html .= '<th rowspan="2" style="background:#0265c8;color:#fff;text-align:center;">Cluster</th>';
		$html .= '<th rowspan="2" style="background:#0265c8;color:#fff;text-align:center;">Kode Kebun</th>';
		$html .= '<th rowspan="2" style="background:#0265c8;color:#fff;text-align:center;">Kebun</th>';
		$html .= '<th rowspan="2" style="background:#0265c8;color:#fff;text-align:center;"></th>';
		$html .= '<th colspan="4" style="background:#4472C4;color:#fff;text-align:center;">Masa Pemeliharaan</th>';
		$html .= '<th colspan="2" style="background:#70AD47;color:#fff;text-align:center;">Masa Panen</th>';
		$html .= '</tr>';
		
		// Second row - sub headers
		$html .= '<tr>';
		$html .= '<th style="background:#4472C4;color:#fff;text-align:center;">Pupuk</th>';
		$html .= '<th style="background:#4472C4;color:#fff;text-align:center;">Jumlah Batang</th>';
		$html .= '<th style="background:#4472C4;color:#fff;text-align:center;">Tinggi Batang</th>';
		$html .= '<th style="background:#4472C4;color:#fff;text-align:center;">Diameter Batang</th>';
		$html .= '<th style="background:#70AD47;color:#fff;text-align:center;">Klentek</th>';
		$html .= '<th style="background:#70AD47;color:#fff;text-align:center;">Protas</th>';
		$html .= '</tr>';
		$html .= '</thead><tbody>';

		// Group data by cluster -> kebun
		$groupedData = [];
		foreach ($results as $row) {
			$clusterKey = $row->cluster;
			$kebunKey   = $row->kode_kebun;

			if (!isset($groupedData[$clusterKey])) {
				$groupedData[$clusterKey] = [];
			}
			if (!isset($groupedData[$clusterKey][$kebunKey])) {
				$groupedData[$clusterKey][$kebunKey] = [
					'cluster'        => $row->cluster,
					'kode_kebun'     => $row->kode_kebun,
					'kebun'          => $row->kebun,
					'ha_pupuk'       => [],
					'jumlah_batang'  => [],
					'tinggi_batang'  => [],
					'diameter_batang'=> [],
					'klentek'        => [],
					'protas'         => [],
				];
			}

			$uraian = $row->uraian;
			$ha     = isset($row->ha)     ? (float)$row->ha     : 0.0;
			$persen = isset($row->persen) ? (float)$row->persen : 0.0;

			if (strpos($uraian, 'pupuk') !== false) {
				$groupedData[$clusterKey][$kebunKey]['ha_pupuk'][] = ['uraian' => $uraian, 'ha' => $ha, 'persen' => $persen];
			} elseif (strpos($uraian, 'jumlah_batang') !== false) {
				$groupedData[$clusterKey][$kebunKey]['jumlah_batang'][] = ['uraian' => $uraian, 'ha' => $ha, 'persen' => $persen];
			} elseif (strpos($uraian, 'tinggi_batang') !== false) {
				$groupedData[$clusterKey][$kebunKey]['tinggi_batang'][] = ['uraian' => $uraian, 'ha' => $ha, 'persen' => $persen];
			} elseif (strpos($uraian, 'diameter_batang') !== false) {
				$groupedData[$clusterKey][$kebunKey]['diameter_batang'][] = ['uraian' => $uraian, 'ha' => $ha, 'persen' => $persen];
			} elseif (strpos($uraian, 'klentek') !== false) {
				$groupedData[$clusterKey][$kebunKey]['klentek'][] = ['uraian' => $uraian, 'ha' => $ha, 'persen' => $persen];
			} elseif (strpos($uraian, 'protas') !== false) {
				$groupedData[$clusterKey][$kebunKey]['protas'][] = ['uraian' => $uraian, 'ha' => $ha, 'persen' => $persen];
			}
		}

		// Render rows
		foreach ($groupedData as $clusterName => $kebunList) {
			$clusterRowspan = count($kebunList);
			$firstKebun     = true;
			foreach ($kebunList as $kebunKey => $kebunData) {
			$html .= '<tr>';

			if ($firstKebun) {
				$html .= '<td rowspan="' . $clusterRowspan . '" style="vertical-align:middle;font-weight:600;text-align:center;">' . htmlspecialchars($clusterName) . '</td>';
				$firstKebun = false;
			}
			
			$html .= '<td style="font-weight:600;color:#1a1a2e;">' . htmlspecialchars($kebunData['kode_kebun']) . '</td>';
			$html .= '<td style="font-weight:500;">' . htmlspecialchars($kebunData['kebun']) . '</td>';
			$html .= '<td style="font-weight:500;"><button class="btn btn-sm btn-primary" onclick="modalfishbond(\'' . htmlspecialchars($kebunData['kode_kebun']) . '\')"><i class="fas fa-fish"></i></button></td>';

			// Helper: render item card
			// Colors per category: pupuk=#4472C4, jumlah_batang=#7030A0, tinggi_batang=#00B0F0, diameter_batang=#ED7D31, klentek=#70AD47, protas=#375623

			// Pupuk
			$html .= '<td style="padding:6px;min-width:160px;">';
			foreach ($kebunData['ha_pupuk'] as $item) {
				$uraian_raw = $item['uraian'];
				$pct   = number_format($item['persen'], 1);
				$ha    = number_format($item['ha'], 2);
				
				if (strpos($uraian_raw, 'tepat_waktu') !== false || strpos($uraian_raw, 'sesuai') !== false || strpos($uraian_raw, 'diatas') !== false) {
					$label  = 'TEPAT WAKTU';
					$bg     = '#E8F5E9';
					$border = '#43A047';
					$badge  = '#43A047';
					$lcolor = '#2e7d32';
					$icon   = '&#10003;';
				} elseif (strpos($uraian_raw, 'terlambat') !== false || strpos($uraian_raw, 'dibawah') !== false) {
					$label  = 'TERLAMBAT';
					$bg     = '#FFF3E0';
					$border = '#E53935';
					$badge  = '#E53935';
					$lcolor = '#c62828';
					$icon   = '&#10007;';
				} else {
					$label  = 'TOTAL';
					$bg     = '#E3F2FD';
					$border = '#1E88E5';
					$badge  = '#1E88E5';
					$lcolor = '#1565c0';
					$icon   = '&#9776;';
				}
				
				$html .= '<div style="margin-bottom:5px;padding:5px 8px;background:' . $bg . ';border-left:3px solid ' . $border . ';border-radius:0 5px 5px 0;">';
				$html .= '<div style="font-size:10px;font-weight:700;color:' . $lcolor . ';letter-spacing:.4px;">' . $icon . ' ' . $label . '</div>';
				$html .= '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:3px;">';
				$html .= '<span style="font-size:12px;font-weight:700;color:#1a1a2e;">' . $ha . ' <small style="font-weight:400;color:#666;">ha</small></span>';
				$html .= '<span style="font-size:10px;background:' . $badge . ';color:#fff;padding:1px 6px;border-radius:10px;">' . $pct . '%</span>';
				$html .= '</div></div>';
			}
			$html .= '</td>';

			// Jumlah Batang
			$html .= '<td style="padding:6px;min-width:160px;">';
			foreach ($kebunData['jumlah_batang'] as $item) {
				$uraian_raw = $item['uraian'];
				$pct   = number_format($item['persen'], 1);
				$ha    = number_format($item['ha'], 2);
				
				if (strpos($uraian_raw, 'sudah') !== false || strpos($uraian_raw, 'sesuai') !== false || strpos($uraian_raw, 'diatas') !== false) {
					$label  = 'DIATAS TARGET';
					$bg     = '#E8F5E9';
					$border = '#43A047';
					$badge  = '#43A047';
					$lcolor = '#2e7d32';
					$icon   = '&#10003;';
				} elseif (strpos($uraian_raw, 'belum') !== false || strpos($uraian_raw, 'dibawah') !== false) {
					$label  = 'DIBAWAH TARGET';
					$bg     = '#FFF3E0';
					$border = '#E53935';
					$badge  = '#E53935';
					$lcolor = '#c62828';
					$icon   = '&#10007;';
				} else {
					$label  = 'TOTAL';
					$bg     = '#E3F2FD';
					$border = '#1E88E5';
					$badge  = '#1E88E5';
					$lcolor = '#1565c0';
					$icon   = '&#9776;';
				}
				
				$html .= '<div style="margin-bottom:5px;padding:5px 8px;background:' . $bg . ';border-left:3px solid ' . $border . ';border-radius:0 5px 5px 0;">';
				$html .= '<div style="font-size:10px;font-weight:700;color:' . $lcolor . ';letter-spacing:.4px;">' . $icon . ' ' . $label . '</div>';
				$html .= '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:3px;">';
				$html .= '<span style="font-size:12px;font-weight:700;color:#1a1a2e;">' . $ha . ' <small style="font-weight:400;color:#666;">ha</small></span>';
				$html .= '<span style="font-size:10px;background:' . $badge . ';color:#fff;padding:1px 6px;border-radius:10px;">' . $pct . '%</span>';
				$html .= '</div></div>';
			}
			$html .= '</td>';

			// Tinggi Batang
			$html .= '<td style="padding:6px;min-width:160px;">';
			foreach ($kebunData['tinggi_batang'] as $item) {
				$uraian_raw = $item['uraian'];
				$pct   = number_format($item['persen'], 1);
				$ha    = number_format($item['ha'], 2);
				
				if (strpos($uraian_raw, 'sudah') !== false || strpos($uraian_raw, 'sesuai') !== false || strpos($uraian_raw, 'diatas') !== false) {
					$label  = 'DIATAS TARGET';
					$bg     = '#E8F5E9';
					$border = '#43A047';
					$badge  = '#43A047';
					$lcolor = '#2e7d32';
					$icon   = '&#10003;';
				} elseif (strpos($uraian_raw, 'belum') !== false || strpos($uraian_raw, 'dibawah') !== false) {
					$label  = 'DIBAWAH TARGET';
					$bg     = '#FFF3E0';
					$border = '#E53935';
					$badge  = '#E53935';
					$lcolor = '#c62828';
					$icon   = '&#10007;';
				} else {
					$label  = 'TOTAL';
					$bg     = '#E3F2FD';
					$border = '#1E88E5';
					$badge  = '#1E88E5';
					$lcolor = '#1565c0';
					$icon   = '&#9776;';
				}
				
				$html .= '<div style="margin-bottom:5px;padding:5px 8px;background:' . $bg . ';border-left:3px solid ' . $border . ';border-radius:0 5px 5px 0;">';
				$html .= '<div style="font-size:10px;font-weight:700;color:' . $lcolor . ';letter-spacing:.4px;">' . $icon . ' ' . $label . '</div>';
				$html .= '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:3px;">';
				$html .= '<span style="font-size:12px;font-weight:700;color:#1a1a2e;">' . $ha . ' <small style="font-weight:400;color:#666;">ha</small></span>';
				$html .= '<span style="font-size:10px;background:' . $badge . ';color:#fff;padding:1px 6px;border-radius:10px;">' . $pct . '%</span>';
				$html .= '</div></div>';
			}
			$html .= '</td>';

			// Diameter Batang
			$html .= '<td style="padding:6px;min-width:160px;">';
			foreach ($kebunData['diameter_batang'] as $item) {
				$uraian_raw = $item['uraian'];
				$pct   = number_format($item['persen'], 1);
				$ha    = number_format($item['ha'], 2);
				
				if (strpos($uraian_raw, 'sudah') !== false || strpos($uraian_raw, 'sesuai') !== false || strpos($uraian_raw, 'diatas') !== false) {
					$label  = 'DIATAS TARGET';
					$bg     = '#E8F5E9';
					$border = '#43A047';
					$badge  = '#43A047';
					$lcolor = '#2e7d32';
					$icon   = '&#10003;';
				} elseif (strpos($uraian_raw, 'belum') !== false || strpos($uraian_raw, 'dibawah') !== false) {
					$label  = 'DIBAWAH TARGET';
					$bg     = '#FFF3E0';
					$border = '#E53935';
					$badge  = '#E53935';
					$lcolor = '#c62828';
					$icon   = '&#10007;';
				} else {
					$label  = 'TOTAL';
					$bg     = '#E3F2FD';
					$border = '#1E88E5';
					$badge  = '#1E88E5';
					$lcolor = '#1565c0';
					$icon   = '&#9776;';
				}
				
				$html .= '<div style="margin-bottom:5px;padding:5px 8px;background:' . $bg . ';border-left:3px solid ' . $border . ';border-radius:0 5px 5px 0;">';
				$html .= '<div style="font-size:10px;font-weight:700;color:' . $lcolor . ';letter-spacing:.4px;">' . $icon . ' ' . $label . '</div>';
				$html .= '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:3px;">';
				$html .= '<span style="font-size:12px;font-weight:700;color:#1a1a2e;">' . $ha . ' <small style="font-weight:400;color:#666;">ha</small></span>';
				$html .= '<span style="font-size:10px;background:' . $badge . ';color:#fff;padding:1px 6px;border-radius:10px;">' . $pct . '%</span>';
				$html .= '</div></div>';
			}
			$html .= '</td>';

			// Klentek
			$html .= '<td style="padding:6px;min-width:160px;">';
			foreach ($kebunData['klentek'] as $item) {
				$uraian_raw = $item['uraian'];
				$pct = number_format($item['persen'], 1);
				$ha  = number_format($item['ha'], 2);

				if (strpos($uraian_raw, 'sudah') !== false || strpos($uraian_raw, 'sesuai') !== false || strpos($uraian_raw, 'diatas') !== false) {
					$label  = 'SUDAH';
					$bg     = '#E8F5E9';
					$border = '#43A047';
					$badge  = '#43A047';
					$lcolor = '#2e7d32';
					$icon   = '&#10003;'; // checkmark
				} elseif (strpos($uraian_raw, 'belum') !== false || strpos($uraian_raw, 'dibawah') !== false) {
					$label  = 'BELUM';
					$bg     = '#FFF3E0';
					$border = '#E53935';
					$badge  = '#E53935';
					$lcolor = '#c62828';
					$icon   = '&#10007;'; // cross
				} else {
					$label  = 'TOTAL';
					$bg     = '#E3F2FD';
					$border = '#1E88E5';
					$badge  = '#1E88E5';
					$lcolor = '#1565c0';
					$icon   = '&#9776;'; // lines
				}

				$html .= '<div style="margin-bottom:5px;padding:5px 8px;background:' . $bg . ';border-left:3px solid ' . $border . ';border-radius:0 5px 5px 0;">';
				$html .= '<div style="font-size:10px;font-weight:700;color:' . $lcolor . ';letter-spacing:.4px;">' . $icon . ' ' . $label . '</div>';
				$html .= '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:3px;">';
				$html .= '<span style="font-size:12px;font-weight:700;color:#1a1a2e;">' . $ha . ' <small style="font-weight:400;color:#666;">ha</small></span>';
				$html .= '<span style="font-size:10px;background:' . $badge . ';color:#fff;padding:1px 6px;border-radius:10px;">' . $pct . '%</span>';
				$html .= '</div></div>';
			}
			$html .= '</td>';

			// Protas
			$html .= '<td style="padding:6px;min-width:160px;">';
			foreach ($kebunData['protas'] as $item) {
				$uraian_raw = $item['uraian'];
				$pct = number_format($item['persen'], 1);
				$ha  = number_format($item['ha'], 2);

				if (strpos($uraian_raw, 'diatas') !== false || strpos($uraian_raw, 'sesuai') !== false || strpos($uraian_raw, 'diatas') !== false) {
					$label  = 'DIATAS RKAP';
					$bg     = '#E8F5E9';
					$border = '#43A047';
					$badge  = '#43A047';
					$lcolor = '#2e7d32';
					$icon   = '&#10003;';
				} elseif (strpos($uraian_raw, 'dibawah') !== false || strpos($uraian_raw, 'dibawah') !== false) {
					$label  = 'DIBAWAH RKAP';
					$bg     = '#FFF3E0';
					$border = '#E53935';
					$badge  = '#E53935';
					$lcolor = '#c62828';
					$icon   = '&#10007;';
				} else {
					$label  = 'TOTAL';
					$bg     = '#E3F2FD';
					$border = '#1E88E5';
					$badge  = '#1E88E5';
					$lcolor = '#1565c0';
					$icon   = '&#9776;';
				}

				$html .= '<div style="margin-bottom:5px;padding:5px 8px;background:' . $bg . ';border-left:3px solid ' . $border . ';border-radius:0 5px 5px 0;">';
				$html .= '<div style="font-size:10px;font-weight:700;color:' . $lcolor . ';letter-spacing:.4px;">' . $icon . ' ' . $label . '</div>';
				$html .= '<div style="display:flex;justify-content:space-between;align-items:center;margin-top:3px;">';
				$html .= '<span style="font-size:12px;font-weight:700;color:#1a1a2e;">' . $ha . ' <small style="font-weight:400;color:#666;">ha</small></span>';
				$html .= '<span style="font-size:10px;background:' . $badge . ';color:#fff;padding:1px 6px;border-radius:10px;">' . $pct . '%</span>';
				$html .= '</div></div>';
			}
			$html .= '</td>';

			$html .= '</tr>';
			} // end foreach kebunList
		} // end foreach groupedData

		$html .= '</tbody></table>';

		$html .= '<style>
			.fishbone-container {
			  display: inline-grid;
			  grid-template-columns: repeat(4, auto);
			  grid-template-rows: auto .2em auto;
			  padding-left: 2em;
			  font-family: Arial;
			  --bone-color: gray;
			  --yellow: #FDBE22;
			  --green: #69E982;
			  --blue: #5CB2FB;
			      position: absolute;
				top: 35px;
				left: 360px;
			}

			.fishbone-container .cause {
			  display: flex;
			  flex-direction: column;
			  transform: skew(20deg);
			  transform-origin: bottom;
			  margin-left: .8em;
			}

			.fishbone-container .rootcause {
			  text-align: center;
			  position: relative;
			  left: 100%;
			  transform: translateX(-50%) skewX(-20deg);
			  font-size: 1.5em;
			  color: #fff;
			  padding: .2em;
			  border-radius: .2em;
			}

			.fishbone-container .rootcause.yellow {
			  background-color: var(--yellow);
			}

			.fishbone-container .rootcause.green {
			  background-color: var(--green);
			}

			.fishbone-container .rootcause.blue {
			  background-color: var(--blue);
			}

			.fishbone-container .subcause {
			  flex-grow: 1;
			  border-right: .2em solid var(--bone-color);
			  padding-bottom: .75em;
			  padding-top: .75em;
			}

			.fishbone-container .stat {
			  text-align: right;
			  padding-right: 3em;
			  position: relative;
			  transform: skewX(-20deg);
			  line-height: 1.5em;
			  font-size: 1em;
			}

			.fishbone-container .stat:before {
			  content: "";
			  display: block;
			  background-color: var(--bone-color);
			  position: absolute;
			  width: 3em;
			  height: .2em;
			  right: 0;
			  top: 50%;
			  transform: translate(.2em, -50%);
			}

			.fishbone-container .line {
			  grid-column-start: 1;
			  grid-column-end: 4;
			  background-color: var(--bone-color);
			}

			.fishbone-container .line ~ .cause {
			  transform: skewX(-20deg);
			  transform-origin: top;
			}

			.fishbone-container .line ~ .cause .rootcause {
			  transform: translateX(-50%) skewX(20deg);
			}

			.fishbone-container .line ~ .cause .stat {
			  transform: skewX(20deg);
			}

			.fishbone-container .defect-spacer-top {
			  grid-column-start: 4;
			  grid-column-end: 4;
			  grid-row-start: 1;
			  grid-row-end: 2;
			}

			.fishbone-container .defect {
			  grid-column-start: 4;
			  grid-column-end: 4;
			  grid-row-start: 2;
			  grid-row-end: 3;
			}

			.fishbone-container .defect-spacer-bottom {
			  grid-column-start: 4;
			  grid-column-end: 4;
			  grid-row-start: 3;
			  grid-row-end: 4;
			}

			.fishbone-container .defect-text {
			  position: relative;
			  top: 50%;
			  transform: translateY(-50%);
			  padding: 1em;
			  margin-left: .5em;
			  border-radius: .5em;
			  color: #fff;
			  text-align: center;
			}
		</style>';

		$html .= '<div class="modal fade" id="modalFishbond" tabindex="-1" role="dialog" aria-labelledby="modalFishbondLabel" aria-hidden="true">';
		$html .= '<div class="modal-dialog modal-lg" role="document" style="max-width: fit-content;">';
		$html .= '<div class="modal-content">';
		$html .= '<div class="modal-header">';
		$html .= '<h5 class="modal-title" id="modalFishbondLabel">Detail Kebun</h5>';
		$html .= '<button type="button" class="close" data-dismiss="modal" aria-label="Close">';
		$html .= '<span aria-hidden="true">&times;</span>';
		$html .= '</button>';
		$html .= '</div>';
		$html .= '<div class="modal-body">';

		
		$html .= '	<div>
					<table style="margin-top: 50px !important;">
						<tr>
							<td>
								<svg width="190" height="250" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">				
									<g transform="translate(-24 -267)">
										<path
											d="M28.0771 274C26.803 274 25.2741 274 24 274 43.6212 290.803 57.8912 308.382 66.3003 331.906 67.3196 335.526 70.3774 337.594 75.4738 338.369 87.1956 338.628 98.6625 340.179 110.639 340.437 112.168 340.696 113.952 340.954 117.01 343.022 104.523 346.383 92.5468 347.934 82.0992 349.744 75.219 350.261 71.6515 351.553 73.9449 358.792 75.9835 367.581 76.4931 376.112 77.2576 383.091 78.022 387.486 79.0413 389.554 82.6088 389.554 83.1185 389.554 83.8829 389.554 84.6474 389.296 108.091 391.364 130.006 391.364 153.449 393.173 154.214 392.656 155.233 392.398 156.252 392.398 157.781 392.398 159.82 392.915 161.858 394.466 148.098 395.759 135.612 398.861 122.106 400.153 109.875 401.704 96.1143 403.255 82.354 404.548 82.0992 404.289 81.5895 404.289 81.3347 404.289 78.7865 404.289 77.2576 406.099 78.022 410.752 78.2769 420.834 76.7479 430.916 71.9063 440.481 71.3967 445.393 72.9256 445.651 77.7672 446.427 86.1763 447.719 94.5854 447.461 102.994 448.753 106.307 449.27 109.62 449.529 114.207 452.114 102.23 453.665 90.2534 455.216 78.022 456.767 71.1419 457.543 65.7906 460.128 62.9876 466.59 56.8719 485.979 44.3857 501.231 29.0964 512.605 27.3127 513.898 27.3127 513.898 27.0579 515.707 26.5482 515.707 26.2934 515.449 26.0386 515.449 25.2741 515.449 25.2741 515.966 25.0193 517 47.1887 517 68.3388 510.02 86.686 500.972 128.731 480.033 165.171 451.338 200.081 420.834 203.394 418.249 209 406.099 208.236 393.173 206.961 374.044 199.317 368.098 196.514 365.513 174.09 346.641 151.156 329.58 126.438 313.811 99.9366 297.783 73.4353 283.306 43.876 277.102 38.7796 275.034 33.4284 274 28.0771 274"
											fill="gray" fill-rule="evenodd" />
									</g>									
								</svg>
							</td>
							<td>
								<svg width="700" height="30" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">        
								<g transform="translate(-195 -379)">
									<path d="M896 409 196 401.552 196 386.552 896 379 896 409Z" fill="gray" fill-rule="evenodd" />
								</g>								
								</svg>								
							</td>
							<td>
								 <g transform="translate(100,230)">
								<rect x="0" y="0" width="700" height="20" fill="gray"/>
							</g>
								<svg width="240" height="250" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">									
								<g transform="translate(-1040 -267)">
									<path
										d="M1154.48 396.775C1151.44 396.775 1148.66 396.516 1145.62 395.74 1128.15 390.827 1117.01 373.761 1121.82 355.66 1126.12 339.628 1139.04 330.577 1153.21 330.577 1156.25 330.577 1159.54 331.094 1162.58 331.87 1180.31 336.783 1190.69 355.66 1186.38 371.951 1182.33 386.948 1168.91 396.775 1154.48 396.775M1089.92 268C1064.6 295.151 1047.38 330.06 1043.08 369.623 1037 422.116 1054.47 472.023 1086.88 509 1091.94 507.966 1095.99 506.931 1097.26 506.673 1153.97 494.261 1206.89 470.471 1255 438.148 1261.07 434.528 1261.58 432.976 1256.01 428.063 1238.79 414.358 1238.79 414.358 1238.79 414.358 1236.01 412.031 1235 409.962 1239.05 407.377 1249.17 401.429 1259.81 393.93 1269.94 387.983 1273.99 385.656 1275 382.294 1270.7 379.45 1248.92 357.729 1224.61 338.593 1199.8 321.268 1177.52 308.08 1155.24 294.893 1131.95 285.067 1118.27 278.861 1104.1 273.172 1089.92 268"
										fill="gray" fill-rule="evenodd" />
									<path
										d="M1127.5 364.5C1127.5 349.036 1139.59 336.5 1154.5 336.5 1169.41 336.5 1181.5 349.036 1181.5 364.5 1181.5 379.964 1169.41 392.5 1154.5 392.5 1139.59 392.5 1127.5 379.964 1127.5 364.5Z"
										stroke="gray" stroke-width="1.33333" stroke-miterlimit="8" fill="gray" fill-rule="evenodd" />
								</g>								
								</svg>
							</td>
						</tr>
					</table>
					<div class="fishbone-container">			
					<div class="cause">
						<div class="rootcause blue">Mensch</div>
						<div class="subcause">
						<div class="stat">
							<div class="stat-text">P1</div>
							<div class="sub-stat">S1</div>
						</div>
						<div class="stat">P1</div>
						<div class="stat">P1</div>
						</div>
					</div>
					<div class="cause">
						<div class="rootcause green">Problem Area</div>
						<div class="subcause">
						<div class="stat">Problem 1</div>
						<div class="stat">Problem 2</div>
						</div>
					</div>
					<div class="cause">
						<div class="rootcause yellow">Milieu</div>
						<div class="subcause">
						<div class="stat">P1</div>
						<div class="stat">P1</div>
						<div class="stat">P1</div>
						<div class="stat">P1</div>
						<div class="stat">P1</div>     
						</div>
					</div>
					<div class="line">
						
					</div>
					<div class="cause">
						<div class="subcause">
						<div class="stat">P1</div>
						<div class="stat">P1</div>
						<div class="stat">P1</div>   
						</div>
						<div class="rootcause blue">Messung</div>   
					</div>
					<div class="cause">
						<div class="subcause">
						<div class="stat">P1</div>
						<div class="stat">P1</div>       
						</div>
						<div class="rootcause green">Material</div>
					</div>
					<div class="cause">
						<div class="subcause">
						<div class="stat">P1</div>
						<div class="stat">P1</div>   
						</div>
						<div class="rootcause yellow">Methoden</div> 
					</div>
					<div class="defect-spacer-top"></div>
					<div class="defect">
						<div class="defect-text">
						
						</div>
					</div>
					<div class="defect-spacer-bottom">
							
					</div>
					</div>
					</div>';

		$html .= '</div>';
		$html .= '<div class="modal-footer">';
		$html .= '<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>';
		$html .= '</div></div></div></div>';

		$html .= '<script>
			function modalfishbond(kode_kebun) {
				$("#modalFishbond").modal("show");
			}
		</script>';

		return response($html);
	}

	function settingKuadranKinerja(Request $request)
	{
		$setting = \DB::table('setting_kuadran_kinerja')->where('id', 1)->first();
		return response()->json($setting);
	}


	function updateSettingKuadranKinerja(Request $request)
	{
		$xMin = $request->input('xMin');
		$xMax = $request->input('xMax');
		$yMin = $request->input('yMin');
		$yMax = $request->input('yMax');
		$cashCostMid = $request->input('cashCostMid');
		$ipoMid = $request->input('ipoMid');
		$data = [
			'xMin' => $xMin,
			'xMax' => $xMax,
			'yMin' => $yMin,
			'yMax' => $yMax,
			'cashCostMid' => $cashCostMid,
			'ipoMid' => $ipoMid
		];
		$update = \DB::table('setting_kuadran_kinerja')->updateOrInsert(['id' => 1], $data);
		
		return response()->json($update);
	}

	function settingKuadranpica(Request $request)
	{
		$setting = \DB::table('setting_kuadran_pica')->where('id', 1)->first();
		return response()->json($setting);
	}


	function updateSettingKuadranpica(Request $request)
	{
		$xMin = $request->input('xMin');
		$xMax = $request->input('xMax');
		$yMin = $request->input('yMin');
		$yMax = $request->input('yMax');
		$nilaiMid = $request->input('nilaiMid');
		$cashCostMid = $request->input('cashCostMid');

		$data = [
			'xMin' => $xMin,
			'xMax' => $xMax,
			'yMin' => $yMin,
			'yMax' => $yMax,
			'nilaiMid' => $nilaiMid,
			'cashCostMid' => $cashCostMid
		];
		$update = \DB::table('setting_kuadran_pica')->updateOrInsert(['id' => 1], $data);
		
		return response()->json($update);
	}

	function settingKuadranpicapemeliharaan(Request $request)
	{
		$setting = \DB::table('setting_kuadran_pica_pemeliharaan')->where('id', 1)->first();
		return response()->json($setting);
	}


	function updateSettingKuadranpicapemeliharaan(Request $request)
	{
		$xMin = $request->input('xMin');
		$xMax = $request->input('xMax');
		$yMin = $request->input('yMin');
		$yMax = $request->input('yMax');
		$nilaiMid = $request->input('nilaiMid');
		$cashCostMid = $request->input('cashCostMid');

		$data = [
			'xMin' => $xMin,
			'xMax' => $xMax,
			'yMin' => $yMin,
			'yMax' => $yMax,
			'nilaiMid' => $nilaiMid,
			'cashCostMid' => $cashCostMid
		];
		$update = \DB::table('setting_kuadran_pica_pemeliharaan')->updateOrInsert(['id' => 1], $data);
		
		return response()->json($update);
	}

	function getKuadranKinerjaKebun(Request $request)
	{
		$nama_kebun = $request->get('cluster');
		$tahun = $request->get('bulan');
		
		$params = [$nama_kebun, $tahun];
		
		$results = \DB::select('CALL kuadran_kinerja_kebun_kso_info(?, ?)', $params);
		
		$html = '<style>';
		$html .= '.kuadran-table { width: 100%; border-collapse: collapse; font-family: Arial, sans-serif; box-shadow: 0 2px 8px rgba(0,0,0,0.1); border-radius: 8px; overflow: hidden;    display: block;overflow: scroll; }';
		$html .= '.kuadran-table thead { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }';
		$html .= '.kuadran-table th { padding: 16px; text-align: left; font-weight: 600; font-size: 14px; letter-spacing: 0.5px; text-align:center; }';
		$html .= '.kuadran-table tbody tr { border-bottom: 1px solid #e0e0e0; transition: background-color 0.3s ease; }';
		$html .= '.kuadran-table tbody tr:hover { background-color: #f8f9ff; }';
		$html .= '.kuadran-table tbody tr:last-child { border-bottom: none; }';
		$html .= '.kuadran-table td { padding: 14px 16px; font-size: 13px; color: #333;white-space: nowrap; text-align: right; }';
		$html .= '.kuadran-table tbody tr:nth-child(even) { background-color: #f5f5f5; }';
		$html .= '.kuadran-table tbody tr.total-row { background-color: #fff3cd !important; font-weight: bold; }';
		$html .= '</style>';
		$html .= '<table class="kuadran-table">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th>Kebun</th>';
		$html .= '<th>Target Produktivitas</th>';
		$html .= '<th>Produktivitas SD Minggu Ini</th>';
		$html .= '<th>Score Produktivitas</th>';
		$html .= '<th>Target Rendemen</th>';
		$html .= '<th>Rendemen SD Minggu Ini</th>';
		$html .= '<th>Score Rendemen</th>';
		$html .= '<th>Target Pasok Harian</th>';
		$html .= '<th>Rata2 Pasok Harian SD Minggu Ini</th>';
		$html .= '<th>Score Pasok</th>';
		$html .= '<th>X Cashcost</th>';
		$html .= '<th>IPO Protas</th>';
		$html .= '<th>IPO Rendemen</th>';
		$html .= '<th>IPO Pasok</th>';
		$html .= '<th>Y IPO SD Minggu Ini</th>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		
		foreach($results as $row) {
			$isTotal = stripos($row->Kebun, 'total') !== false ? ' class="total-row"' : '';
			$html .= '<tr' . $isTotal . '>';
			$html .= '<td style="text-align:left !important;"><strong>' . $row->Kebun . '</strong></td>';
			$html .= '<td>' . number_format($row->target_produktivitas, 2, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->produktivitas_sd_minggu_ini, 2, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->score_produktivitas, 2, ',', '.') . '</td>';		
			$html .= '<td>' . number_format($row->target_rendemen, 2, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->rendemen_sd_minggu_ini, 2, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->score_rendemen, 2, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->target_pasok_harian, 2, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->rata2_pasok_harian_sd_minggu_ini, 2, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->score_pasok, 2, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->x_cashcost, 0, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->ipo_protas, 2, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->ipo_rendemen, 2, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->ipo_pasok, 2, ',', '.') . '</td>';
			$html .= '<td>' . number_format($row->y_ipo_sd_minggu_ini, 2, ',', '.') . '</td>';
			$html .= '</tr>';
		}
		
		$html .= '</tbody>';
		$html .= '</table>';
		
		return response($html);
	}

	function getDashboard1Pica( Request $request )
	{
		$tahun = date('Y');
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		
		$params = [$tahun, $cluster, $kebun];
		
		$results = \DB::select('CALL sp_pica_dashboard_1_pica(?, ?, ?)', $params);
		
		$html = '<style>';
		$html .= '.dashboard-table { width: 100%; border-collapse: collapse; font-family: Arial, sans-serif; box-shadow: 0 2px 8px rgba(0,0,0,0.1); border-radius: 8px; }';
		$html .= '.dashboard-table thead { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }';
		$html .= '.dashboard-table th { padding: 16px; text-align: center; font-weight: 600; font-size: 14px; letter-spacing: 0.5px; color: #fff !important; }';
		$html .= '.dashboard-table tbody tr { border-bottom: 1px solid #e0e0e0; transition: background-color 0.3s ease; }';
		$html .= '.dashboard-table tbody tr:hover { background-color: #f8f9ff; }';
		$html .= '.dashboard-table tbody tr:last-child { border-bottom: none; }';
		$html .= '.dashboard-table td { padding: 14px 16px; font-size: 13px; color: #333; text-align: right; }';
		$html .= '.dashboard-table td:first-child { text-align: left; }';
		$html .= '.dashboard-table tbody tr:nth-child(even) { background-color: #f5f5f5; }';
		$html .= '.dashboard-table tbody tr.total-row { background-color: #fff3cd !important; font-weight: bold; }';
		$html .= '</style>';
		$html .= '<h3 class="text-center">Nilai PICA Panen '.date('Y').'</h3>';
		$html .= '<table class="table table-responsive dashboard-table">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th>Kebun</th>';
		$html .= '<th>Jan</th>';
		$html .= '<th>Feb</th>';
		$html .= '<th>Mar</th>';
		$html .= '<th>Apr</th>';
		$html .= '<th>Mei</th>';
		$html .= '<th>Jun</th>';
		$html .= '<th>Jul</th>';
		$html .= '<th>Agu</th>';
		$html .= '<th>Sep</th>';
		$html .= '<th>Okt</th>';
		$html .= '<th>Nov</th>';
		$html .= '<th>Des</th>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		
		foreach($results as $row) {
			$isTotal = stripos($row->nama_rekap, 'total') !== false ? ' class="total-row"' : '';
			$html .= '<tr' . $isTotal . '>';
			$html .= '<td style="text-align:left !important;"><strong>' . $row->nama_rekap . '</strong></td>';
			$html .= '<td>' . ($row->januari ? number_format($row->januari, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->februari ? number_format($row->februari, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->maret ? number_format($row->maret, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->april ? number_format($row->april, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->mei ? number_format($row->mei, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->juni ? number_format($row->juni, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->juli ? number_format($row->juli, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->agustus ? number_format($row->agustus, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->september ? number_format($row->september, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->oktober ? number_format($row->oktober, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->november ? number_format($row->november, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->desember ? number_format($row->desember, 2, ',', '.') : '-') . '</td>';
			$html .= '</tr>';
		}
		
		$html .= '</tbody>';
		$html .= '</table>';
		
		return response($html);
	}



	function getDashboard2Pica( Request $request )
	{
		$tahun = $request->get('tahun', date('Y'));
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		
		$params = [$tahun, $cluster, $kebun];
		
		$results = \DB::select('CALL sp_pica_dashboard_2_pica(?, ?, ?)', $params);
		
		$html = '<style>';
		$html .= '.dashboard-table { width: 100%; border-collapse: collapse; font-family: Arial, sans-serif; box-shadow: 0 2px 8px rgba(0,0,0,0.1); border-radius: 8px; }';
		$html .= '.dashboard-table thead { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }';
		$html .= '.dashboard-table th { padding: 16px; text-align: center; font-weight: 600; font-size: 14px; letter-spacing: 0.5px; color: #fff !important; }';
		$html .= '.dashboard-table tbody tr { border-bottom: 1px solid #e0e0e0; transition: background-color 0.3s ease; }';
		$html .= '.dashboard-table tbody tr:hover { background-color: #f8f9ff; }';
		$html .= '.dashboard-table tbody tr:last-child { border-bottom: none; }';
		$html .= '.dashboard-table td { padding: 14px 16px; font-size: 13px; color: #333; text-align: right; }';
		$html .= '.dashboard-table td:first-child { text-align: left; }';
		$html .= '.dashboard-table tbody tr:nth-child(even) { background-color: #f5f5f5; }';
		$html .= '.dashboard-table tbody tr.total-row { background-color: #fff3cd !important; font-weight: bold; }';
		$html .= '</style>';
		$html .= '<h3 class="text-center">PICA Tahun '.$tahun.'</h3>';
		$html .= '<table class="table table-responsive dashboard-table">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th>Kebun</th>';
		$html .= '<th>Jan</th>';
		$html .= '<th>Feb</th>';
		$html .= '<th>Mar</th>';
		$html .= '<th>Apr</th>';
		$html .= '<th>Mei</th>';
		$html .= '<th>Jun</th>';
		$html .= '<th>Jul</th>';
		$html .= '<th>Agu</th>';
		$html .= '<th>Sep</th>';
		$html .= '<th>Okt</th>';
		$html .= '<th>Nov</th>';
		$html .= '<th>Des</th>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		
		foreach($results as $row) {
			$isTotal = stripos($row->nama_rekap, 'total') !== false ? ' class="total-row"' : '';
			$html .= '<tr' . $isTotal . '>';
			$html .= '<td style="text-align:left !important;"><strong>' . $row->nama_rekap . '</strong></td>';
			$html .= '<td>' . ($row->januari ? number_format($row->januari, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->februari ? number_format($row->februari, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->maret ? number_format($row->maret, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->april ? number_format($row->april, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->mei ? number_format($row->mei, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->juni ? number_format($row->juni, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->juli ? number_format($row->juli, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->agustus ? number_format($row->agustus, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->september ? number_format($row->september, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->oktober ? number_format($row->oktober, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->november ? number_format($row->november, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->desember ? number_format($row->desember, 2, ',', '.') : '-') . '</td>';
			$html .= '</tr>';
		}
		
		$html .= '</tbody>';
		$html .= '</table>';
		
		return response($html);
	}

	function getDashboard1Produktivitas( Request $request )
	{
		$tahun = $request->get('tahun', date('Y'));
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$parameter = $request->get('parameter', 'produktivitas');
		
		$params = [$tahun, $cluster, $kebun, $parameter];
		
		$results = \DB::select('CALL sp_pica_dashboard_1_parameter_panen(?, ?, ?, ?)', $params);
		
		$html = '<style>';
		$html .= '.dashboard-table { width: 100%; border-collapse: collapse; font-family: Arial, sans-serif; box-shadow: 0 2px 8px rgba(0,0,0,0.1); border-radius: 8px; }';
		$html .= '.dashboard-table thead { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }';
		$html .= '.dashboard-table th { padding: 16px; text-align: center; font-weight: 600; font-size: 14px; letter-spacing: 0.5px; color: #fff !important; }';
		$html .= '.dashboard-table tbody tr { border-bottom: 1px solid #e0e0e0; transition: background-color 0.3s ease; }';
		$html .= '.dashboard-table tbody tr:hover { background-color: #f8f9ff; }';
		$html .= '.dashboard-table tbody tr:last-child { border-bottom: none; }';
		$html .= '.dashboard-table td { padding: 14px 16px; font-size: 13px; color: #333; text-align: right; }';
		$html .= '.dashboard-table td:first-child { text-align: left; }';
		$html .= '.dashboard-table tbody tr:nth-child(even) { background-color: #f5f5f5; }';
		$html .= '.dashboard-table tbody tr.total-row { background-color: #fff3cd !important; font-weight: bold; }';
		$html .= '</style>';
		$judul = ucfirst($parameter);
		if (strtolower($parameter) === 'cashcost') {
			$judul .= ' Sampai Dengan ';
			$tahun = $tahun . ' (Exclude Saprodi)';
		}else if (strtolower($parameter) === 'mutuab') {
			$judul = 'Mutu A+B';
		}
		$html .= '<h3 class="text-center">' . $judul . ' '.$tahun.'</h3>';
		$html .= '<table class="table table-responsive dashboard-table">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th>Kebun</th>';
		$html .= '<th>Jan</th>';
		$html .= '<th>Feb</th>';
		$html .= '<th>Mar</th>';
		$html .= '<th>Apr</th>';
		$html .= '<th>Mei</th>';
		$html .= '<th>Jun</th>';
		$html .= '<th>Jul</th>';
		$html .= '<th>Agu</th>';
		$html .= '<th>Sep</th>';
		$html .= '<th>Okt</th>';
		$html .= '<th>Nov</th>';
		$html .= '<th>Des</th>';
		if(strtolower($parameter) !== 'cashcost') {
			$html .= '<th>Total</th>';
		}
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		
		foreach($results as $row) {
			$isTotal = stripos($row->nama_rekap, 'total') !== false ? ' class="total-row"' : '';
			$html .= '<tr' . $isTotal . '>';
			$html .= '<td style="text-align:left !important;"><strong>' . $row->nama_rekap . '</strong></td>';
			$html .= '<td>' . ($row->januari ? number_format($row->januari, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->februari ? number_format($row->februari, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->maret ? number_format($row->maret, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->april ? number_format($row->april, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->mei ? number_format($row->mei, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->juni ? number_format($row->juni, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->juli ? number_format($row->juli, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->agustus ? number_format($row->agustus, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->september ? number_format($row->september, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->oktober ? number_format($row->oktober, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->november ? number_format($row->november, 2, ',', '.') : '-') . '</td>';
			$html .= '<td>' . ($row->desember ? number_format($row->desember, 2, ',', '.') : '-') . '</td>';
			if(strtolower($parameter) !== 'cashcost') {
				$html .= '<td>' . ($row->total ? number_format($row->total, 2, ',', '.') : '-') . '</td>';
			}
			$html .= '</tr>';
		}
		
		$html .= '</tbody>';
		$html .= '</table>';
		
		return response($html);
	}

	

	

	function getTableAreaProblemCard(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		
		$results = \DB::select("CALL sp_pica_dashboard_1_pi(?, ?, ?, ?)", [$cluster, $kebun, $rayon, $tgl]);
		
		$html = '<div class="card" style="border: none; box-shadow: 0 4px 15px rgba(0,0,0,0.1); border-radius: 12px; overflow: hidden;">';
		$html .= '<div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;">';
		$html .= '<h5 class="card-title" style="color: white; margin: 0; font-weight: 700;">📊 Berdasarkan Kriteria Problem Area</h5>';
		$html .= '</div>';
		$html .= '<div class="card-body" style="padding: 20px; background-color: #f8f9fa;">';
		$html .= '<style>';
		$html .= '.parent-row { cursor: pointer; user-select: none; }';
		$html .= '.parent-row:hover { background-color: #f0f0f0 !important; }';
		$html .= '.child-row { display: none; }';
		$html .= '.child-row.show { display: table-row; }';
		$html .= '</style>';
		$html .= '<table class="table table-borderless" style="margin: 0;">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 8px 0 0 8px; padding: 15px; font-weight: 700; text-transform: uppercase; font-size: 12px; letter-spacing: 1px;">Area Problem</th>';
		$html .= '<th style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; font-weight: 700; text-transform: uppercase; font-size: 12px; letter-spacing: 1px;">Jumlah Petak</th>';
		$html .= '<th style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 0 8px 8px 0; padding: 15px; font-weight: 700; text-transform: uppercase; font-size: 12px; letter-spacing: 1px;">Prosentase</th>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		
		$parents = [];
		$isTotal = false;
		
		foreach($results as $row) {
			if(strtolower($row->area_problem) === 'total') {
				$isTotal = true;
			} elseif($row->parent === '' || $row->parent === null) {
				$parents[$row->area_problem] = $row;
			}
		}
		
		foreach($parents as $parentName => $parentData) {
			$bgColor = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
			$textColor = 'white';
			$parentId = str_replace(' ', '_', $parentName);
			
			$html .= '<tr class="parent-row-1" data-parent="' . htmlspecialchars($parentId) . '" style="transition: all 0.3s ease; border-bottom: 2px solid #667eea; cursor: pointer;">';
			$html .= '<td style="background: ' . $bgColor . '; color: ' . $textColor . '; border-radius: 8px; padding: 15px; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.1);"><span style="margin-right: 10px;">▶</span>' . $parentName . '</td>';
			$html .= '<td style="background-color: #e8f5e9; color: #2e7d32; border-radius: 8px; padding: 15px; text-align: center; font-size: 20px; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.05); cursor: pointer;" class="jumlah-problem-click" data-area="' . htmlspecialchars($parentName) . '" data-cluster="' . htmlspecialchars($cluster) . '" data-kebun="' . htmlspecialchars($kebun) . '" data-rayon="' . htmlspecialchars($rayon) . '" data-tgl="' . htmlspecialchars($tgl) . '">' . number_format($parentData->jumlah_problem, 0, ',', '.') . '</td>';
			$html .= '<td style="background-color: #e8f5e9; color: #2e7d32; border-radius: 8px; padding: 15px; text-align: center; font-size: 18px; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">' . number_format($parentData->persen_terhadap_problemarea, 2, ',', '.') . '%</td>';
			$html .= '</tr>';
			
			foreach($results as $row) {
				if($row->parent === $parentName) {
					$childId = str_replace(' ', '_', $parentId);
					$html .= '<tr class="child-row-1" data-parent="' . htmlspecialchars($parentId) . '" style="transition: all 0.3s ease; border-bottom: 1px solid #e0e0e0; display: none;">';
					$html .= '<td style="background-color: #fff8e1; color: #f57f17; border-radius: 4px; padding: 12px 15px; font-weight: 600; padding-left: 40px; box-shadow: 0 2px 8px rgba(0,0,0,0.05);white-space: normal;">' . $row->area_problem . '</td>';
					$html .= '<td style="background-color: #fff3e0; color: #e65100; border-radius: 4px; padding: 12px 15px; text-align: center; font-size: 16px; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.05); cursor: pointer;" class="jumlah-problem-click" data-area="' . htmlspecialchars($row->area_problem) . '" data-cluster="' . htmlspecialchars($cluster) . '" data-kebun="' . htmlspecialchars($kebun) . '" data-rayon="' . htmlspecialchars($rayon) . '" data-tgl="' . htmlspecialchars($tgl) . '">' . number_format($row->jumlah_problem, 0, ',', '.') . '</td>';
					$html .= '<td style="background-color: #fff3e0; color: #e65100; border-radius: 4px; padding: 12px 15px; text-align: center; font-size: 14px; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">' . number_format($row->persen_terhadap_problemarea, 2, ',', '.') . '%</td>';
					$html .= '</tr>';
				}
			}
		}
		
		if($isTotal) {
			foreach($results as $row) {
				if(strtolower($row->area_problem) === 'total') {
					$html .= '<tr style="transition: all 0.3s ease; border-bottom: 1px solid #e0e0e0;">';
					$html .= '<td style="background: linear-gradient(135deg, #ff6b6b 0%, #ff5252 100%); color: white; border-radius: 8px; padding: 15px; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">' . $row->area_problem . '</td>';
					$html .= '<td style="background-color: #fff3e0; color: #e65100; border-radius: 8px; padding: 15px; text-align: center; font-size: 20px; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">' . number_format($row->jumlah_problem, 0, ',', '.') . '</td>';
					$html .= '<td style="background-color: #fff3e0; color: #e65100; border-radius: 8px; padding: 15px; text-align: center; font-size: 18px; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">' . number_format($row->persen_terhadap_problemarea, 2, ',', '.') . '%</td>';
					$html .= '</tr>';
				}
			}
		}
		
		
		$html .= '</tbody>';
		$html .= '</table>';

		//modal detail jumlah problem
		$html .= '<div class="modal fade" id="detailJumlahProblemModal" tabindex="-1" role="dialog" aria-labelledby="detailJumlahProblemModalLabel" aria-hidden="true">';
		$html .= '<div class="modal-dialog modal-lg" role="document">';
		$html .= '<div class="modal-content">';
		$html .= '<div class="modal-header">';
		$html .= '<h5 class="modal-title" id="detailJumlahProblemModalLabel">Detail Jumlah Problem</h5>';
		$html .= '<button type="button" class="close" data-dismiss="modal" aria-label="Close">';
		$html .= '<span aria-hidden="true">&times;</span>';
		$html .= '</button>';
		$html .= '</div>';
		$html .= '<div class="modal-body">';
		$html .= '<div id="detailJumlahProblemContent">Loading...</div>';
		$html .= '</div>';
		$html .= '<div class="modal-footer">';
		$html .= '<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>';
		$html .= '</div>';	
		$html .= '<script>';
		//klik jumlah-problem-click muncul modal
		$html .= 'document.querySelectorAll(".jumlah-problem-click").forEach(cell => {';
		$html .= '  cell.addEventListener("click", function() {';
		$html .= '    const area = this.getAttribute("data-area");';
		$html .= '    const cluster = this.getAttribute("data-cluster");';
		$html .= '    const kebun = this.getAttribute("data-kebun");';
		$html .= '    const rayon = this.getAttribute("data-rayon");';
		$html .= '    const tgl = this.getAttribute("data-tgl");';
		$html .= '    const modalContent = document.getElementById("detailJumlahProblemContent");';
		$html .= '    modalContent.innerHTML = "Loading...";';
		$html .= '    $("#detailJumlahProblemModal").modal("show");';
		$html .= '    fetch("/picapetak/getTablePiDetil?problem=" + encodeURIComponent(area) + "&cluster=" + encodeURIComponent(cluster) + "&kebun=" + encodeURIComponent(kebun) + "&rayon=" + encodeURIComponent(rayon) + "&tgl=" + encodeURIComponent(tgl))';
		$html .= '      .then(response => response.text())';
		$html .= '      .then(data => {';
		$html .= '        modalContent.innerHTML = data;';
		$html .= '      })';
		$html .= '      .catch(error => {';
		$html .= '        modalContent.innerHTML = "Error loading data.";';
		$html .= '      });';
		$html .= '  });';
		$html .= '});';



		$html .= 'document.querySelectorAll(".parent-row-1").forEach(row => {';
		$html .= '  row.addEventListener("click", function() {';
		$html .= '    const parentId = this.getAttribute("data-parent");';
		$html .= '    const children = document.querySelectorAll(".child-row-1[data-parent=\"" + parentId + "\"]");';
		$html .= '    const arrow = this.querySelector("span");';
		$html .= '    children.forEach(child => {';
		$html .= '      if (child.style.display === "none" || child.style.display === "") {';
		$html .= '        child.style.display = "table-row";';
		$html .= '      } else {';
		$html .= '        child.style.display = "none";';
		$html .= '      }';
		$html .= '    });';
		$html .= '    arrow.textContent = arrow.textContent === "▶" ? "▼" : "▶";';
		$html .= '  });';
		$html .= '});';
		$html .= '</script>';
		$html .= '</div>';
		$html .= '</div>';
		
		return response($html);
	}



	function getTableCorrectiveCard(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		
		$params = [$cluster, $kebun, $rayon, $tgl];
		$results = \DB::select('CALL sp_pica_dashboard_1_ca(?, ?, ?, ?)', $params);
		
		// Group results by parent
		$grouped = [];
		$totals = null;
		foreach($results as $row) {
			if (strtolower($row->corrective) === 'total') {
				$totals = $row;
			} else {
				$parent = $row->parent ?? 'Uncategorized';
				if (!isset($grouped[$parent])) {
					$grouped[$parent] = [];
				}
				$grouped[$parent][] = $row;
			}
		}
		
		$html = '<div class="card" style="border: none; box-shadow: 0 4px 15px rgba(0,0,0,0.1); border-radius: 12px; overflow: hidden;">';
		$html .= '<div class="card-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;">';
		$html .= '<h5 class="card-title" style="color: white; margin: 0; font-weight: 700;">✅ Corrective Action</h5>';
		$html .= '</div>';
		$html .= '<div class="card-body" style="padding: 20px; background-color: #f8f9fa;">';
		$html .= '<table class="table table-borderless table-responsive" style="margin: 0; font-size: 12px;">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 8px 0 0 0; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Corrective</th>';
		$html .= '<th style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Mulai</th>';
		$html .= '<th style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Target Selesai</th>';
		$html .= '<th style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Progress</th>';
		$html .= '<th style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Status</th>';
		$html .= '<th style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Selesai</th>';
		$html .= '<th style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 0 8px 0 0; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Total</th>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		
		$parentIndex = 0;
		foreach($grouped as $parent => $rows) {
			$parentId = 'parent-' . ($parentIndex++);
			
			// Parent row
			$html .= '<tr class="parent-row" data-parent="' . $parentId . '" style="cursor: pointer; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-bottom: 1px solid #e0e0e0;">';
			$html .= '<td style="color: white; padding: 12px; font-weight: 700;"><span style="margin-right: 8px;">▶</span>' . htmlspecialchars($parent) . '</td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center; font-weight: 700;">' . count($rows) . '</td>';
			$html .= '</tr>';
			
			// Child rows
			foreach($rows as $row) {
				$statusColor = strtolower($row->status) === 'close' ? '#4CAF50' : '#ff9800';
				$statusBg = strtolower($row->status) === 'close' ? '#e8f5e9' : '#fff3e0';
				$dataColor = '#e8f5e9';
				$dataTextColor = '#2e7d32';
				
				$html .= '<tr class="child-row" data-parent="' . $parentId . '" style="transition: all 0.3s ease; border-bottom: 1px solid #e0e0e0; background-color: #f5f5f5;">';
				$html .= '<td style="padding: 12px 12px 12px 36px; font-weight: 500; white-space: normal;">' . htmlspecialchars($row->corrective) . '</td>';
				$html .= '<td style="background-color: ' . $dataColor . '; color: ' . $dataTextColor . '; border-radius: 8px; padding: 12px; text-align: center; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">' . ($row->bulan_target_mulai ?? '-') . '</td>';
				$html .= '<td style="background-color: ' . $dataColor . '; color: ' . $dataTextColor . '; border-radius: 8px; padding: 12px; text-align: center; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">' . ($row->bulan_target_selesai ?? '-') . '</td>';
				$html .= '<td style="background-color: ' . $dataColor . '; color: ' . $dataTextColor . '; border-radius: 8px; padding: 12px; text-align: center; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">' . $row->progress . '</td>';
				$html .= '<td style="background-color: ' . $statusBg . '; color: ' . $statusColor . '; border-radius: 8px; padding: 12px; text-align: center; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">' . $row->status . '</td>';
				$html .= '<td style="background-color: ' . $dataColor . '; color: ' . $dataTextColor . '; border-radius: 8px; padding: 12px; text-align: center; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">' . ($row->bulan_selesai ?? '-') . '</td>';
				$html .= '<td style="background-color: ' . $dataColor . '; color: ' . $dataTextColor . '; border-radius: 8px; padding: 12px; text-align: center; font-size: 14px; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.05);" class="jumlah-corrective-click" >' . $row->jumlah_corrective . '</td>';
				$html .= '</tr>';
			}
		}
		
		// Total row
		if ($totals) {
			$html .= '<tr style="background: linear-gradient(135deg, #ff6b6b 0%, #ff5252 100%); border-bottom: 1px solid #e0e0e0; font-weight: 700;">';
			$html .= '<td style="color: white; padding: 12px; font-weight: 700;">' . htmlspecialchars($totals->corrective) . '</td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center; font-weight: 700;">' . $totals->progress . '</td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center; font-weight: 700;">' . $totals->status . '</td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
			$html .= '<td style="color: white; padding: 12px; text-align: center; font-weight: 700;">' . $totals->jumlah_corrective . '</td>';
			$html .= '</tr>';
		}
		
		$html .= '</tbody>';
		$html .= '</table>';

		//modal detail jumlah corrective
		$html .= '<div class="modal fade" id="detailJumlahCorrectiveModal" tabindex="-1" role="dialog" aria-labelledby="detailJumlahCorrectiveModalLabel" aria-hidden="true">';
		$html .= '<div class="modal-dialog modal-lg" role="document">';
		$html .= '<div class="modal-content">';
		$html .= '<div class="modal-header">';
		$html .= '<h5 class="modal-title" id="detailJumlahCorrectiveModalLabel">Detail Jumlah Corrective</h5>';
		$html .= '<button type="button" class="close" data-dismiss="modal" aria-label="Close">';
		$html .= '<span aria-hidden="true">&times;</span>';
		$html .= '</button>';
		$html .= '</div>';
		$html .= '<div class="modal-body">';
		$html .= '<div id="detailJumlahCorrectiveContent">Loading...</div>';
		$html .= '</div>';
		$html .= '<div class="modal-footer">';
		$html .= '<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>';
		$html .= '</div>';
		$html .= '</div>'; // Close modal-content
		$html .= '</div>'; // Close modal-dialog
		$html .= '</div>'; // Close modal
		$html .= '<script>';

		//klik jumlah-corrective-click muncul modal
		$html .= 'document.querySelectorAll(".jumlah-corrective-click").forEach(cell => {';
		$html .= '  cell.addEventListener("click", function() {';
		$html .= '    const corrective = this.closest("tr").querySelector("td").textContent.trim();';
		$html .= '    const modalContent = document.getElementById("detailJumlahCorrectiveContent");';
		$html .= '    modalContent.innerHTML = "Loading...";';
		$html .= '    $("#detailJumlahCorrectiveModal").modal("show");';
		$html .= '    fetch("/picapetak/getTableCaDetil?problem=" + encodeURIComponent(corrective) + "&cluster=" + encodeURIComponent("' . htmlspecialchars($cluster) . '") + "&kebun=" + encodeURIComponent("' . htmlspecialchars($kebun) . '") + "&rayon=" + encodeURIComponent("' . htmlspecialchars($rayon) . '") + "&tgl=" + encodeURIComponent("' . htmlspecialchars($tgl) . '"))';
		$html .= '      .then(response => response.text())';
		$html .= '      .then(data => {';
		$html .= '        modalContent.innerHTML = data;';
		$html .= '      })';
		$html .= '      .catch(error => {';
		$html .= '        modalContent.innerHTML = "Error loading data.";';
		$html .= '      });';
		$html .= '  });';
		$html .= '});';

		$html .= 'document.querySelectorAll(".parent-row").forEach(row => {';
		$html .= '  row.addEventListener("click", function(e) {';
		$html .= '    if(e.target.closest("td")) {';
		$html .= '      const parentId = this.getAttribute("data-parent");';
		$html .= '      const children = document.querySelectorAll(".child-row[data-parent=\"" + parentId + "\"]");';
		$html .= '      const arrow = this.querySelector("span");';
		$html .= '      children.forEach(child => {';
		$html .= '        child.style.display = child.style.display === "table-row" ? "none" : "table-row";';
		$html .= '      });';
		$html .= '      arrow.textContent = arrow.textContent === "▶" ? "▼" : "▶";';
		$html .= '    }';
		$html .= '  });';
		$html .= '});';
		$html .= '</script>';
		$html .= '</div>';
		$html .= '</div>';
		
		return response($html);
	}

	function getTablePiDetil(Request $request)
	{
		config(['app.debug' => true]);
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		$problem = $request->get('problem');
		
		$params = [$cluster, $kebun, $rayon, $tgl, $problem];
		$results = \DB::select('CALL sp_pica_dashboard_1_pi_detil(?, ?, ?, ?, ?)', $params);
		
		$html = '<div class="card" style="border: none; box-shadow: 0 4px 15px rgba(0,0,0,0.1); border-radius: 12px; overflow: hidden;">';
		$html .= '<div class="card-header" style="background: linear-gradient(135deg, #34a853 0%, #2d8a5b 100%); border: none;">';
		$html .= '<h5 class="card-title" style="color: white; margin: 0; font-weight: 700;">🔍 Problem Identification Detail</h5>';
		$html .= '</div>';
		$html .= '<div class="card-body" style="padding: 20px; background-color: #f8f9fa;">';
		$html .= '<table class="table table-borderless" style="margin: 0; font-size: 12px;">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th style="background: linear-gradient(135deg, #34a853 0%, #2d8a5b 100%); color: white; border-radius: 8px 0 0 0; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Problem</th>';
		$html .= '<th style="background: linear-gradient(135deg, #34a853 0%, #2d8a5b 100%); color: white; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Lahan ID</th>';
		$html .= '<th style="background: linear-gradient(135deg, #34a853 0%, #2d8a5b 100%); color: white; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Afdeling</th>';
		$html .= '<th style="background: linear-gradient(135deg, #34a853 0%, #2d8a5b 100%); color: white; border-radius: 0 8px 0 0; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Total</th>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		
		$grandTotal = 0;
		
		foreach($results as $row) {
			$grandTotal++;
			$html .= '<tr style="transition: all 0.3s ease; border-bottom: 1px solid #e0e0e0; background-color: #f5f5f5;">';
			$html .= '<td style="padding: 12px 12px 12px 12px; font-weight: 500; white-space: normal;">' . htmlspecialchars($row->problem) . '</td>';
			$html .= '<td style="background-color: #e8f5e9; color: #2e7d32; border-radius: 8px; padding: 12px; text-align: center; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.05); font-family: monospace;">' . htmlspecialchars($row->lahan_id) . '</td>';
			$html .= '<td style="background-color: #e8f5e9; color: #2e7d32; border-radius: 8px; padding: 12px; text-align: center; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">' . htmlspecialchars($row->afdeling) . '</td>';
			$html .= '<td style="background-color: #e8f5e9; color: #2e7d32; border-radius: 8px; padding: 12px; text-align: center; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">1</td>';
			$html .= '</tr>';
		}
		
		// Total row
		$html .= '<tr style="background: linear-gradient(135deg, #ff6b6b 0%, #ff5252 100%); border-bottom: 1px solid #e0e0e0; font-weight: 700;">';
		$html .= '<td style="color: white; padding: 12px; font-weight: 700;">TOTAL</td>';
		$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
		$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
		$html .= '<td style="color: white; padding: 12px; text-align: center; font-weight: 700;">' . $grandTotal . '</td>';
		$html .= '</tr>';
		
		$html .= '</tbody>';
		$html .= '</table>';
		$html .= '</div>';
		$html .= '</div>';
		
		return response($html);
	}

	function getTableCaDetil(Request $request)
	{
		$cluster = $request->get('cluster');
		$kebun = $request->get('kebun');
		$rayon = $request->get('rayon');
		$tgl = $request->get('tgl');
		$problem = $request->get('problem');

		$params = [$cluster, $kebun, $rayon, $tgl, $problem];
		
		$results = \DB::select('CALL sp_pica_dashboard_1_ca_detil(?, ?, ?, ?, ?)', $params);
		
		$html = '<div class="card" style="border: none; box-shadow: 0 4px 15px rgba(0,0,0,0.1); border-radius: 12px; overflow: hidden;">';
		$html .= '<div class="card-header" style="background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%); border: none;">';
		$html .= '<h5 class="card-title" style="color: white; margin: 0; font-weight: 700;">✅ Corrective Action Detail</h5>';
		$html .= '</div>';
		$html .= '<div class="card-body" style="padding: 20px; background-color: #f8f9fa;">';
		$html .= '<table class="table table-borderless" style="margin: 0; font-size: 12px;">';
		$html .= '<thead>';
		$html .= '<tr>';
		$html .= '<th style="background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%); color: white; border-radius: 8px 0 0 0; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Corrective</th>';
		$html .= '<th style="background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%); color: white; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Lahan ID</th>';
		$html .= '<th style="background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%); color: white; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Afdeling</th>';
		$html .= '<th style="background: linear-gradient(135deg, #2196F3 0%, #1976D2 100%); color: white; border-radius: 0 8px 0 0; padding: 12px; font-weight: 700; text-transform: uppercase; font-size: 11px; letter-spacing: 1px;">Total</th>';
		$html .= '</tr>';
		$html .= '</thead>';
		$html .= '<tbody>';
		
		$grandTotal = 0;
		
		foreach($results as $row) {
			$grandTotal++;
			$html .= '<tr style="transition: all 0.3s ease; border-bottom: 1px solid #e0e0e0; background-color: #f5f5f5;">';
			$html .= '<td style="padding: 12px 12px 12px 12px; font-weight: 500; white-space: normal;">' . htmlspecialchars($row->corrective) . '</td>';
			$html .= '<td style="background-color: #E3F2FD; color: #1565C0; border-radius: 8px; padding: 12px; text-align: center; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.05); font-family: monospace;">' . htmlspecialchars($row->lahan_id) . '</td>';
			$html .= '<td style="background-color: #E3F2FD; color: #1565C0; border-radius: 8px; padding: 12px; text-align: center; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">' . htmlspecialchars($row->afdeling) . '</td>';
			$html .= '<td style="background-color: #E3F2FD; color: #1565C0; border-radius: 8px; padding: 12px; text-align: center; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">1</td>';
			$html .= '</tr>';
		}
		
		// Total row
		$html .= '<tr style="background: linear-gradient(135deg, #ff6b6b 0%, #ff5252 100%); border-bottom: 1px solid #e0e0e0; font-weight: 700;">';
		$html .= '<td style="color: white; padding: 12px; font-weight: 700;">TOTAL</td>';
		$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
		$html .= '<td style="color: white; padding: 12px; text-align: center;"></td>';
		$html .= '<td style="color: white; padding: 12px; text-align: center; font-weight: 700;">' . $grandTotal . '</td>';
		$html .= '</tr>';
		
		$html .= '</tbody>';
		$html .= '</table>';
		$html .= '</div>';
		$html .= '</div>';
		
		return response($html);
	}

	

	

function formtablePicapanenrayonkebunMutu(Request $request)
	{
			if(!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');
		$this->data = array_merge(array(
			'pageTitle'	=> 'PICA Panen Rayon Kebun Mutu',
			'pageNote'	=> 'Data PICA Panen Rayon Kebun Mutu',
			'pageModule'=> 'picapetak',
			'return'	=> self::returnUrl()
		),$this->data);
		return view($this->module.'.pica_panen_rayon_kebun_mutu', $this->data);
	}

	function gettablePicapanenrayonkebunMutu(Request $request)
	{
		config(['app.debug' => true]);
		$cluster    = $request->input('cluster')    ?? null;
		$kebun	  = $request->input('kebun')      ?? null;
		$start_date  = $request->input('start_date')  ?? null;
		$end_date= $request->input('end_date')??null;

		$clusterParam    = $cluster     ? "'" . addslashes($cluster)     . "'" : 'NULL';
		$startDateParam   = $start_date   ? "'" . addslashes($start_date)   . "'" : 'NULL';
		$endDateParam = $end_date ? "'" . addslashes($end_date) . "'" : 'NULL';
		$kebunParam    = $kebun     ? "'" . addslashes($kebun)     . "'" : 'NULL';

		$params = [$cluster, $kebun, $start_date, $end_date];
		$results = \DB::select('CALL sp_pica_panen_rayonkebun_mutu(?, ?, ?, ?)', $params);

		$thStyle    = "background: #0265c8; color: #FFF; padding: 10px; font-weight: 600; text-transform: uppercase; font-size: 12px; text-align: center; border: 1px solid #ddd;";

		// Color mapping for columns
		$colorMap = [
			'emas'  => ['bg' => '#FFD700', 'color' => '#000'],
			'hijau' => ['bg' => '#008000', 'color' => '#FFF'],
			'kuning'=> ['bg' => '#FFFF00', 'color' => '#000'],
			'merah' => ['bg' => '#FF0000', 'color' => '#FFF'],
			'hitam' => ['bg' => '#000000', 'color' => '#FFF']
		
		];

		$html  = '<div style="overflow-x: auto;">';
		$html .= '<table id="rekap-table" style="width: 100%; border-collapse: collapse; font-family: Arial, sans-serif; font-size: 12px;">';
		$html .= '<thead><tr>';
		$html .= '<th style="' . $thStyle . ' white-space: nowrap;">Cluster</th>';
		$html .= '<th style="' . $thStyle . ' white-space: nowrap;">Kode</th>';
		$html .= '<th style="' . $thStyle . ' white-space: nowrap;">Kebun</th>';
		$html .= '<th style="' . $thStyle . ' white-space: nowrap;">Protas</th>';
		// Ha columns
		foreach (['emas','hijau','kuning','merah','hitam','total'] as $m) {
			$bgColor = ($m === 'total') ? '#FFF' : $colorMap[$m]['bg'];
			$textColor = ($m === 'total') ? '#333' : $colorMap[$m]['color'];
			$haStyle = 'background: ' . $bgColor . '; color: ' . $textColor . '; padding: 10px; font-weight: 600; text-transform: uppercase; font-size: 12px; text-align: center; border: 1px solid #999; white-space: nowrap;';
			$html .= '<th style="' . $haStyle . '">' . strtoupper($m) . ' Ha</th>';
		}
		$html .= '<th style="border-left: 3px solid #333;"></th>';
		// Petak columns
		foreach (['emas','hijau','kuning','merah','hitam','total'] as $m) {
			$bgColor = ($m === 'total') ? '#FFF' : $colorMap[$m]['bg'];
			$textColor = ($m === 'total') ? '#333' : $colorMap[$m]['color'];
			$petakStyle = 'background: ' . $bgColor . '; color: ' . $textColor . '; padding: 10px; font-weight: 600; text-transform: uppercase; font-size: 12px; text-align: center; border: 1px solid #999; white-space: nowrap;';
			$label = ($m === 'total') ? 'TOTAL Petak' : strtoupper($m) . ' Petak';
			$html .= '<th style="' . $petakStyle . '">' . $label . '</th>';
		}
		$html .= '</tr></thead>';
		$html .= '<tbody>';

		$prevCluster = null;
		foreach ($results as $i => $row) {
			$isGrandTotal = (stripos($row->kebun ?? '', 'GRAND TOTAL') !== false || stripos($row->cluster ?? '', 'GRAND TOTAL') !== false);
			$isNewCluster = ($row->cluster !== $prevCluster);
			$prevCluster  = $row->cluster;

			$rowBg = $isGrandTotal ? '#0265c8' : ($i % 2 === 0 ? '#ffffff' : '#f9f9f9');
			$rowStyle = 'background: ' . $rowBg . '; border-bottom: 1px solid #ddd;color: ' . ($isGrandTotal ? '#fff' : '#333') . '; font-weight: ' . ($isGrandTotal ? '700' : '400') . ';';

			$tdBase = 'padding: 10px; border: 1px solid #ddd; white-space: nowrap;';
			$tdNum  = $tdBase . ' text-align: right;';
			$tdCtr  = $tdBase . ' text-align: center;';

			$html .= '<tr style="' . $rowStyle . '">';

			// Cluster cell with badge
			$clusterDisplay = htmlspecialchars($row->cluster ?? '');
			if ($isGrandTotal) {
				$html .= '<td colspan="3" style="' . $tdBase . ' font-weight: 700;">' . $clusterDisplay . '</td>';
			} else {
				$html .= '<td style="' . $tdBase . '">' . $clusterDisplay . '</td>';
				$html .= '<td style="' . $tdCtr . '">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
				$html .= '<td style="' . $tdBase . '">' . htmlspecialchars($row->kebun ?? '') . '</td>';
			}

			// Protas
			$html .= '<td style="' . $tdNum . '">' . number_format((float)($row->protas ?? 0), 2) . '</td>';

			// Ha columns
			foreach (['emas_ha','hijau_ha','kuning_ha','merah_ha','hitam_ha','total_ha'] as $col) {
				$html .= '<td style="' . $tdNum . '">' . number_format((float)($row->$col ?? 0), 3) . '</td>';
			}

			// Separator
			$html .= '<td style="border-left: 3px solid #333;"></td>';

			// Petak columns
			foreach (['emas_petak','hijau_petak','kuning_petak','merah_petak','hitam_petak','total_petak'] as $col) {
				$html .= '<td style="' . $tdNum . '">' . (int)($row->$col ?? 0) . '</td>';
			}

			$html .= '</tr>';
		}

		$html .= '</tbody></table></div>';

		return response($html);
	}

	

	function show( Request $request , $id ) 
	{
		/* Handle import , export and view */
		$task =$id ;
		switch( $task)
		{

			case 'export':
				return $this->getExport( $request );
				break;
			case 'chartPieDataPica':
				return $this->chartPieDataPica($request);	
				break;
			case 'chartPieDataLuasPica':
				return $this->chartPieDataLuasPica($request);
				break;
			case 'getTableDataPica':
				return $this->getTableDataPica($request);
				break;
			case 'picaMorfologi':
				return $this->picaMorfologi($request);
				break;
			case 'chartPieDataJmlBatangPica':
				return $this->chartPieDataJmlBatangPica($request);
				break;
			case 'chartPieDataTinggiBatangPica':
				return $this->chartPieDataTinggiBatangPica($request);
				break;	
			case 'chartPieDataDiameterBatangPica':
				return $this->chartPieDataDiameterBatangPica($request);
				break;
			case 'chartBarDataPica':
				return $this->chartBarDataPica($request);
				break;
			case 'getTableDataPicaMorfologi':
				return $this->getTableDataPicaMorfologi($request);
				break;
			case 'getAjaxDataPicaPetak':
				return $this->getAjaxDataPicaPetak($request);
				break;	
			case 'chartLineAreaProblem':
				return $this->chartLineAreaProblem($request);
				break;	
			case 'picaeksekutif':
				return $this->picaeksekutif($request);
				break;	
			case 'chartLineAreaProblemDetail':
				return $this->chartLineAreaProblemDetail($request);	
				break;
			case 'getKuadranData':
				return $this->getKuadranData($request);
				break;
			case 'kuadranpica':
				return $this->kuadranpica($request);
				break;
			case 'getStatisticsMasterKebun':
				return $this->getStatisticsMasterKebun($request);
				break;
			case 'getStatisticsMasterPG':
				return $this->getStatisticsMasterPG($request);	
				break;	
			case 'getTableMasterKebun':
				return $this->getTableMasterKebun($request);
				break;	
			case 'getTableMasterPG':
				return $this->getTableMasterPG($request);
				break;
			case 'formtablePicapanenrayonkebun':
				return $this->formtablePicapanenrayonkebun($request);
				break;
			case 'gettablePicapanenrayonkebun':
				return $this->gettablePicapanenrayonkebun($request);
				break;		
			case 'formtableNilaiPicapanenrayonkebun':
				return $this->formtableNilaiPicapanenrayonkebun($request);
				break;
			case 'gettableNilaiPicapanenrayonkebun':
				return $this->gettableNilaiPicapanenrayonkebun($request);	
				break;	
			case 'formtablePicapemeliharaandiameterrayonkebun':
				return $this->formtablePicapemeliharaandiameterrayonkebun($request);
				break;
			case 'gettablePicapemeliharaandiameterrayonkebun':
				return $this->gettablePicapemeliharaandiameterrayonkebun($request);	
				break;	
			case 'formtableCashcostPanen':
				return $this->formtableCashcostPanen($request);
				break;
			case 'gettableCashcostPanen':
				return $this->gettableCashcostPanen($request);	
				break;
			case 'formtablePicapemeliharaanjumlahbatangrayonkebun':
				return $this->formtablePicapemeliharaanjumlahbatangrayonkebun($request);
				break;
			case 'gettablePicapemeliharaanjumlahbatangrayonkebun':
				return $this->gettablePicapemeliharaanjumlahbatangrayonkebun($request);	
				break;
			case 'formtablePicapemeliharaantinggirayonkebun':
				return $this->formtablePicapemeliharaantinggirayonkebun($request);
				break;
			case 'gettablePicapemeliharaantinggirayonkebun':
				return $this->gettablePicapemeliharaantinggirayonkebun($request);	
				break;
			case 'gettablePicapanenrayonkebun2025':
				return $this->gettablePicapanenrayonkebun2025($request);	
				break;
			case 'getTableRkapVsRkoVsTakdesVsTakmarVsReal':
				return $this->getTableRkapVsRkoVsTakdesVsTakmarVsReal($request);	
				break;
			case 'getTableLkpRekapPcrcPica':
				return $this->getTableLkpRekapPcrcPica($request);	
				break;	
			case 'getTableLkpMonitoringUmur':
				return $this->getTableLkpMonitoringUmur($request);	
				break;	
			case 'formtableKuadranPemeliharaanPica':
				return $this->formtableKuadranPemeliharaanPica($request);
				break;
			case 'gettableKuadranPemeliharaanPica':
				return $this->gettableKuadranPemeliharaanPica($request);	
				break;	
			case 'getTableHighchartColumnMonitoringUmur':
				return $this->getTableHighchartColumnMonitoringUmur($request);	
				break;
			case 'gettableKuadranPemeliharaanPicaGrafik':
				return $this->gettableKuadranPemeliharaanPicaGrafik($request);	
				break;
			case 'formtableMonitoringPiPemeliharaanPanenPica':
				return $this->formtableMonitoringPiPemeliharaanPanenPica($request);	
				break;
			case 'getTableMonitoringPiPemeliharaanPanenPica':
				return $this->getTableMonitoringPiPemeliharaanPanenPica($request);	
				break;
			case 'picaeksekutifmasapemeliharaan':
				return $this->picaeksekutifmasapemeliharaan($request);	
				break;
			case 'picaeksekutifmasapanen':
				return $this->picaeksekutifmasapanen($request);	
				break;
			case 'formKuadranKinerja':
				return $this->formKuadranKinerja($request);	
				break;
			case 'getKuadranKinerja':
				return $this->getKuadranKinerja($request);	
				break;
			case 'getDataKuadranCashcostPanen':
				return $this->getDataKuadranCashcostPanen($request);	
				break;
			case 'settingKuadranKinerja':
				return $this->settingKuadranKinerja($request);	
				break;
			case 'updateSettingKuadranKinerja':
				return $this->updateSettingKuadranKinerja($request);	
				break;
			case 'settingKuadranpica':
				return $this->settingKuadranpica($request);	
				break;
			case 'updateSettingKuadranpica':
				return $this->updateSettingKuadranpica($request);	
				break;	
			case 'settingKuadranpicapemeliharaan':
				return $this->settingKuadranpicapemeliharaan($request);	
				break;
			case 'updateSettingKuadranpicapemeliharaan':
				return $this->updateSettingKuadranpicapemeliharaan($request);	
				break;		
			case 'getKuadranKinerjanew':
				return $this->getKuadranKinerjanew($request);	
				break;
			case 'getKuadranKinerjaKebun':
				return $this->getKuadranKinerjaKebun($request);	
				break;
			case 'getPicaDashboard':
				return $this->getPicaDashboard($request);	
				break;
			case 'getBarChartProduktivitas':
				return $this->getBarChartProduktivitas($request);	
				break;
			case 'getDashboardMutu':
				return $this->getDashboardMutu($request);	
				break;
			case 'getDashboardKlentek':
				return $this->getDashboardKlentek($request);	
				break;	
			case 'getDashboard1Pica':
				return $this->getDashboard1Pica($request);	
				break;
			case 'getDashboardKesegaran':
				return $this->getDashboardKesegaran($request);	
				break;
			case 'getDashboard1Produktivitas':
				return $this->getDashboard1Produktivitas($request);	
				break;
			case 'getDashboardKlasifikasiProtas':
				return $this->getDashboardKlasifikasiProtas($request);	
				break;	
			case 'getTableAreaProblemCard':
				return $this->getTableAreaProblemCard($request);	
				break;
			case 'getTableCorrectiveCard':
				return $this->getTableCorrectiveCard($request);
				break;	
			case 'formtablePicapanenrayonkebunMutu':
				return $this->formtablePicapanenrayonkebunMutu($request);
				break;
			case 'gettablePicapanenrayonkebunMutu':
				return $this->gettablePicapanenrayonkebunMutu($request);
				break;
			case 'getDashboardPica2':
				return $this->getDashboardPica2($request);
				break;
			case 'getTableParameterPemeliharaan':
				return $this->getTableParameterPemeliharaan($request);
				break;
			case 'getDashboard2Pica':
				return $this->getDashboard2Pica($request);
				break;
			case 'getDiameterChart':
				return $this->getDiameterChart($request);
				break;
			case 'getJumlahBatangChart':
				return $this->getJumlahBatangChart($request);
				break;
			case 'getTinggiBatangChart':
				return $this->getTinggiBatangChart($request);
				break;
			case 'getPemupukanData':
				return $this->getPemupukanData($request);
				break;
			case 'formKuadranKinerja888':
				return $this->formKuadranKinerja888($request);
				break;
			case 'getKuadranKinerjaTable888':
				return $this->getKuadranKinerjaTable888($request);
				break;	
			case 'getTablePiDetil':
				return $this->getTablePiDetil($request);
				break;
			case 'getTableCaDetil':
				return $this->getTableCaDetil($request);
				break;
			case 'getInfoIndikatorKinerja':
				return $this->getInfoIndikatorKinerja($request);
				break;
			default:
				// Handle other tasks or show a 404 error
				return redirect()->back()->with('status', 'error')->with('message', 'Invalid task specified.');
				break;
	
		}
	}
}