<?php namespace App\Http\Controllers;

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


class PrognosaproduksitebukabagController extends Controller {

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

	public function __construct()
	{
		
		parent::__construct();
		$this->model = new Prognosaproduksitebukabag();
		$this->info = $this->model->makeInfo( $this->module);
		$this->access = array();
	
		$this->data = array_merge(array(
			'pageTitle'	=> 	$this->info['title'],
			'pageNote'	=>  $this->info['note'],
			'pageModule'=> 'prognosaproduksitebukabag',
			'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);
	}	
	function show( Request $request , $id ) 
	{
		/* Handle import , export and view */
		$task =$id ;
		switch( $task)
		{

			case 'export':
				return $this->getExport( $request );
				break;
	
			case 'htmlTable':
				return $this->htmlTable( $request );
				break;
			case 'htmlTablepPg':
				return $this->htmlTablepPg( $request );
				break;
		}
	}

	public function htmlTable(Request $request)
	{
		// require login and view access
		if(!\Auth::check()) {
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');
		}
		$this->grab($request);
		if(isset($this->access['is_view']) && $this->access['is_view'] == 0) {
			return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');
		}

		// fetch rows from the database view
		$rows = \DB::table('q_prod_prognosa_produksi_tebu_kabag')->get();

		// build html table
		$headers = [
			'nama_cluster','kode_kebun','nama_kebun','tanggal','luas_takmar','ton_takmar','protas_takmar',
			'hi_ha_tebang','hi_netto_ton','hi_protas','ha_tebang','netto_ton','protas',
			'sisa_ha','sisa_tebu','sisa_protas','prognosa_luas','prognosa_tebu','prognosa_protas',
			'persen_luas','persen_tebu','persen_protas'
		];

		// styled, colorful and responsive table
		$html = '<style>
			.table-wrap{font-family: Arial, Helvetica, sans-serif; margin:10px 0; overflow:auto;}
			.styled-table{border-collapse:collapse; width:100%; min-width:900px; box-shadow:0 2px 6px rgba(0,0,0,0.08);}
			.styled-table thead th{
				background: linear-gradient(90deg,#1e3c72, #2a5298);
				color:#fff; font-weight:600; padding:10px 8px; text-align:left; position:sticky; top:0;
				border-bottom:2px solid rgba(255,255,255,0.06);
				font-size: 12px;
			}
			.styled-table tbody td{padding:8px 8px; border-bottom:1px solid #eef2f7; vertical-align:middle; color:#333;font-size: 12px;}
			.styled-table tbody tr:nth-child(even){background:#fbfdff;}
			.styled-table tbody tr:hover{background:#f1f8ff;}
			.total-row{background:linear-gradient(90deg,#ffefba,#ffffff); font-weight:700;}
			.cell-number{ text-align:right; font-feature-settings: "tnum"; -moz-font-feature-settings: "tnum"; }
			.small{font-size:0.85em; color:#666;}
			.table-caption{margin:6px 0 10px; font-weight:900; color:#2a3f6b;}
			@media (max-width:720px){
				.styled-table thead th{font-size:12px; padding:8px 6px;}
				.styled-table tbody td{font-size:13px; padding:6px;}
			}
		</style>';




		$html .= '<div class="table-wrap">';
		if (!$rows->isEmpty() && isset($rows[0]->periode)) {
			$periode = htmlspecialchars($rows[0]->periode, ENT_QUOTES, 'UTF-8');
			$html .= '
			<div class="table-caption" style="
				font-size:1.18em;
				font-weight:900;
				background: linear-gradient(90deg,#1e3c72 0%, #2a5298 100%);
				color:#fff;
				padding:12px 18px;
				border-radius:8px 8px 0 0;
				box-shadow:0 2px 8px rgba(30,60,114,0.08);
				letter-spacing:0.5px;
				margin-bottom:0px;
				display:inline-block;
			">
				<span style="font-size:1.25em;vertical-align:middle;">&#127942;</span>
				<span style="vertical-align:middle;">Data <span style="color:#ffe066;">Prognosa Produksi Tebu</span> <span style="font-size:0.95em;font-weight:600;">Periode</span> <span style="background:#ffe066;color:#1e3c72;padding:2px 10px;border-radius:5px;margin-left:4px;">' . $periode . '</span></span>
			</div>';

			$html .= '
				<button id="download-excel-btn" style="
					margin: 12px 0 18px 0;
					padding: 8px 18px;
					background: linear-gradient(90deg,#1e3c72 0%, #2a5298 100%);
					color: #fff;
					border: none;
					border-radius: 5px;
					font-weight: 600;
					font-size: 1em;
					cursor: pointer;
					box-shadow: 0 2px 6px rgba(30,60,114,0.08);
					transition: background 0.2s;
					float: right;
				">
					&#128190; Download Excel
				</button>
				
			';
		}
		// add extra CSS to make first 3 columns sticky when scrolling horizontally
		$html .= '<style>
			/* sticky left columns */
			.sticky-col { position: sticky; left: 0; z-index: 4; background: #fff; }
			.sticky-col-2 { position: sticky; left: 111px; z-index: 4; background: #fff; }
			.sticky-col-3 { position: sticky; left: 208px; z-index: 4; background: #fff; }
			/* header sticky should sit above body cells */
			.styled-table thead th.sticky-col,
			.styled-table thead th.sticky-col-2,
			.styled-table thead th.sticky-col-3 { z-index: 6; background: linear-gradient(90deg,#1e3c72, #2a5298); color:#fff; }
			/* ensure no wrapping for nicer sticky behaviour */
			.styled-table th, .styled-table td { white-space: nowrap; }
		</style>';

		$html .= '<table class="styled-table" cellspacing="0" cellpadding="0" border="0">';
		// header row
		$html .= '<thead><tr>';
		$html .= '<style>
		/* override header colors for specific column ranges (1-based nth-child) */
		.styled-table thead th:nth-child(6),
		.styled-table thead th:nth-child(7),
		.styled-table thead th:nth-child(8) {
			background: #cc5500 !important; /* orange tua */
			color: #ffffff !important;
		}
		.styled-table thead th:nth-child(9),
		.styled-table thead th:nth-child(10),
		.styled-table thead th:nth-child(11) {
			background: #b3d9ff !important; /* biru muda */
			color: #013047 !important;
		}
		.styled-table thead th:nth-child(12),
		.styled-table thead th:nth-child(13),
		.styled-table thead th:nth-child(14) {
			background: #2e8b57 !important; /* hijau tua */
			color: #ffffff !important;
		}
		.styled-table thead th:nth-child(15),
		.styled-table thead th:nth-child(16),
		.styled-table thead th:nth-child(17) {
			background: #9fe5a6 !important; /* hijau muda */
			color: #013047 !important;
		}
		.styled-table thead th:nth-child(18),
		.styled-table thead th:nth-child(19),
		.styled-table thead th:nth-child(20) {
			background: #cc5500 !important; /* orange tua */
			color: #ffffff !important;
		}
		</style>';
		foreach ($headers as $index => $h) {
			$label = strtoupper(str_replace('_', ' ', $h));
			$thClass = '';
			$thStyle = '';
			// first three columns fixed
			if ($index === 0) {
				$thClass = 'sticky-col';
				$thStyle = 'width:160px;';
			} elseif ($index === 1) {
				$thClass = 'sticky-col-2';
				$thStyle = 'width:120px;';
			} elseif ($index === 2) {
				$thClass = 'sticky-col-3';
				$thStyle = 'width:140px;';
			}
			$html .= '<th class="'. $thClass .'" style="'. $thStyle .'">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</th>';
		}
		$html .= '</tr></thead><tbody>';

		if ($rows->isEmpty()) {
			$html .= '<tr><td colspan="'.count($headers).'" class="small">No data found</td></tr>';
		} else {
			$rowIndex = 0;
			$numericCols = [
				'luas_takmar','ton_takmar','protas_takmar','hi_ha_tebang','hi_netto_ton','hi_protas',
				'ha_tebang','netto_ton','protas','sisa_ha','sisa_tebu','sisa_protas',
				'prognosa_luas','prognosa_tebu','prognosa_protas','persen_luas','persen_tebu','persen_protas'
			];

			foreach ($rows as $r) {
				$rowClass =  '';
				$isTotalKso = (isset($r->nama_cluster) && strtoupper(trim($r->nama_cluster)) === 'TOTAL KSO');
				$html .= '<tr class="'. $rowClass .'">';

				$colIndex = 0;
				foreach ($headers as $h) {
					$val = isset($r->{$h}) ? $r->{$h} : null;

					// apply sticky class for first 3 columns on body cells too
					$tdClass = '';
					$tdStyle = '';
					if ($colIndex === 0) {
						$tdClass = 'sticky-col';
						$tdStyle = 'width:160px;';
					} elseif ($colIndex === 1) {
						$tdClass = 'sticky-col-2';
						$tdStyle = 'width:120px;';
					} elseif ($colIndex === 2) {
						$tdClass = 'sticky-col-3';
						$tdStyle = 'width:140px;';
					}

					// format date
					if ($h === 'tanggal' && !empty($val)) {
						$ts = strtotime($val);
						$val = $ts ? date('d/m/Y', $ts) : $val;
					}

					// Kolom persen_luas, persen_tebu, persen_protas (index 19,20,21)
					if (in_array($colIndex, [19, 20, 21])) {
						$percent = is_numeric($val) ? (float)$val : null;
						if ($percent === null || $val === '') {
							$cellContent = '';
						} elseif ($percent == 100.00) {
							$cellContent = '-';
						} elseif ($percent > 100.00) {
							// panah naik hijau
							$cellContent = '<span style="color:#1bb934;font-weight:bold;">&#9650; '.htmlspecialchars(number_format($percent,2)).' %</span>';
						} elseif ($percent < 100.00) {
							// panah turun merah
							$cellContent = '<span style="color:#e74c3c;font-weight:bold;">&#9660; '.htmlspecialchars(number_format($percent,2)).' %</span>';
						}
						if ($isTotalKso) $cellContent = '<b>' . $cellContent . '</b>';
						$cell = '<td class="cell-number '. $tdClass .'" style="'. $tdStyle .'">' . $cellContent . '</td>';
					}
					// numeric formatting untuk kolom 5..18
					elseif ($colIndex >= 4 && $colIndex <= 17 && $val !== null && $val !== '') {
						$val = number_format((float)$val, 2); // e.g. 1.234,56
						$cellContent = htmlspecialchars((string)$val, ENT_QUOTES, 'UTF-8');
						if ($isTotalKso) $cellContent = '<b>' . $cellContent . '</b>';
						$cell = '<td class="cell-number '. $tdClass .'" style="'. $tdStyle .'">' . $cellContent . '</td>';
					} elseif (in_array($h, $numericCols) && $val !== null && $val !== '') {
						// fallback numeric formatting for other numeric columns (no thousands separator, dot decimal)
						$val = number_format((float)$val, 2, '.', '');
						// add percent sign for persen_* columns
						if (strpos($h, 'persen') !== false) {
							$val = $val . ' %';
						}
						$cellContent = htmlspecialchars((string)$val, ENT_QUOTES, 'UTF-8');
						if ($isTotalKso) $cellContent = '<b>' . $cellContent . '</b>';
						$cell = '<td class="cell-number '. $tdClass .'" style="'. $tdStyle .'">' . $cellContent . '</td>';
					} else {
						// boolean/int flag formatting
						if ($h === 'is_total') {
							$val = (int)$val;
						}
						$cellContent = htmlspecialchars((string)$val, ENT_QUOTES, 'UTF-8');
						// Bold only for nama_cluster column if TOTAL KSO
						if ($isTotalKso && $h === 'nama_cluster') {
							$cellContent = '<b>' . $cellContent . '</b>';
						} elseif ($isTotalKso && $h !== 'nama_cluster') {
							$cellContent = '<b>' . $cellContent . '</b>';
						}
						$cell = '<td class="'. $tdClass .'" style="'. $tdStyle .'">' . $cellContent . '</td>';
					}

					$html .= $cell;
					$colIndex++;
				}

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

		$html .= '</tbody></table></div>';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
				<script>
				document.getElementById("download-excel-btn").addEventListener("click", function() {
					var table = document.querySelector(".styled-table");
					if (!table) return;
					var wb = XLSX.utils.table_to_book(table, {sheet:"Sheet1"});
					XLSX.writeFile(wb, "prognosa_produksi_tebu.xlsx");
				});
				</script>';

		return response($html, 200)->header('Content-Type', 'text/html; charset=utf-8');
	}

	public function htmlTablepPg(Request $request)
	{
		// Ambil parameter tanggal dari request, default ke hari ini jika tidak ada
		$tanggal = $request->input('tanggal', date('Y-m-d'));

		// Eksekusi stored procedure
		$rows = \DB::select("CALL sp_rekap_mejatebu_sd_kebun_pg_prognosa(?, ?)", [$tanggal, null]);

		// Definisikan header kolom
		$headers = [
			'nama_cluster','kode_kebun','nama_kebun','pg_penggiling','nama_pg','periode',
			'prognosa_luas','prognosa_tebu','prognosa_protas',
			'ha_tebang','netto_ton','protas',
			'sisa_ha','sisa_tebu','sisa_protas',
			'jumlah_spta','jumlah_spta_uniq','tanggal_giling_sd'
		];

		// Kolom numerik untuk subtotal/total
		$numericCols = [
			'prognosa_luas','prognosa_tebu','prognosa_protas',
			'ha_tebang','netto_ton','protas',
			'sisa_ha','sisa_tebu','sisa_protas',
			'jumlah_spta','jumlah_spta_uniq'
		];

		// Siapkan subtotal dan total
		$subtotals = [];
		$totals = [];
		foreach ($numericCols as $col) $totals[$col] = 0;

		$html = '<div class="table-wrap">';
		// Tambahkan CSS untuk tampilan menarik dan berwarna
		$html .= '<style>
		.table-wrap{font-family: Arial, Helvetica, sans-serif; margin:10px 0; overflow:auto;}
		.styled-table{border-collapse:collapse; width:100%; min-width:900px; box-shadow:0 2px 6px rgba(0,0,0,0.08);}
		.styled-table thead th{
			background: linear-gradient(90deg,#1e3c72, #2a5298);
			color:#fff; font-weight:600; padding:10px 8px; text-align:left; position:sticky; top:0;
			border-bottom:2px solid rgba(255,255,255,0.06);
			font-size: 12px;
		}
		.styled-table tbody td{padding:8px 8px; border-bottom:1px solid #eef2f7; vertical-align:middle; color:#333;font-size: 12px;}
		.styled-table tbody tr:nth-child(even){background:#fbfdff;}
		.styled-table tbody tr:hover{background:#f1f8ff;}
		.total-row{background:linear-gradient(90deg,#ffefba,#ffffff); font-weight:700;}
		.cell-number{ text-align:right; font-feature-settings: "tnum"; -moz-font-feature-settings: "tnum"; }
		.small{font-size:0.85em; color:#666;}
		.table-caption{margin:6px 0 10px; font-weight:900; color:#2a3f6b;}
		@media (max-width:720px){
			.styled-table thead th{font-size:12px; padding:8px 6px;}
			.styled-table tbody td{font-size:13px; padding:6px;}
		}
		.styled-table thead th:nth-child(7),
		.styled-table thead th:nth-child(8),
		.styled-table thead th:nth-child(9) {
			background: #cc5500 !important; /* orange tua */
			color: #ffffff !important;
		}
		.styled-table thead th:nth-child(10),
		.styled-table thead th:nth-child(11),
		.styled-table thead th:nth-child(12) {
			background: #b3d9ff !important; /* biru muda */
			color: #013047 !important;
		}
		.styled-table thead th:nth-child(13),
		.styled-table thead th:nth-child(14),
		.styled-table thead th:nth-child(15) {
			background: #2e8b57 !important; /* hijau tua */
			color: #ffffff !important;
		}
		.styled-table thead th:nth-child(16),
		.styled-table thead th:nth-child(17) {
			background: #9fe5a6 !important; /* hijau muda */
			color: #013047 !important;
		}
		/* Freeze kolom 1-6 */
		.sticky-col { position: sticky; left: 0; z-index: 4; background: #fff; }
		.sticky-col-2 { position: sticky; left: 144px; z-index: 4; background: #fff; }
		.sticky-col-3 { position: sticky; left: 240px; z-index: 4; background: #fff; }
		.sticky-col-4 { position: sticky; left: 353px; z-index: 4; background: #fff; }
		.sticky-col-5 { position: sticky; left: 465px; z-index: 4; background: #fff; }
		.sticky-col-6 { position: sticky; left: 600px; z-index: 4; background: #fff; }
		.styled-table thead th.sticky-col,
		.styled-table thead th.sticky-col-2,
		.styled-table thead th.sticky-col-3,
		.styled-table thead th.sticky-col-4,
		.styled-table thead th.sticky-col-5,
		.styled-table thead th.sticky-col-6 { z-index: 6; background: linear-gradient(90deg,#1e3c72, #2a5298); color:#fff; }
		.styled-table th, .styled-table td { white-space: nowrap; }
		</style>';

		// Caption judul tabel
		$html .= '<div class="table-caption" style="
			font-size:1.18em;
			font-weight:900;
			background: linear-gradient(90deg,#1e3c72 0%, #2a5298 100%);
			color:#fff;
			padding:12px 18px;
			border-radius:8px 8px 0 0;
			box-shadow:0 2px 8px rgba(30,60,114,0.08);
			letter-spacing:0.5px;
			margin-bottom:0px;
			display:inline-block;
		">
			<span style="font-size:1.25em;vertical-align:middle;">&#127942;</span>
			<span style="vertical-align:middle;">Data <span style="color:#ffe066;">Rekap Prognosa Tebu PG</span></span>
		</div>
		<button id="download-excel-btn" style="
			margin: 12px 0 18px 0;
			padding: 8px 18px;
			background: linear-gradient(90deg,#1e3c72 0%, #2a5298 100%);
			color: #fff;
			border: none;
			border-radius: 5px;
			font-weight: 600;
			font-size: 1em;
			cursor: pointer;
			box-shadow: 0 2px 6px rgba(30,60,114,0.08);
			transition: background 0.2s;
			float: right;
		">
			&#128190; Download Excel
		</button>
		';

		$html .= '<div style="clear:both"></div>';

		$html .= '<table class="styled-table table-responsive" cellspacing="0" cellpadding="0" border="0" style="height: 600px !important;display: block;">';
		$html .= '<thead><tr>';
		foreach ($headers as $i => $h) {
			$label = strtoupper(str_replace('_',' ',$h));
			$thClass = '';
			$thStyle = '    position: sticky;top: 0;';
			// Freeze kolom 1-6
			if ($i === 0) { $thClass = 'sticky-col'; $thStyle = 'width:120px;'; }
			elseif ($i === 1) { $thClass = 'sticky-col-2'; $thStyle = 'width:120px;'; }
			elseif ($i === 2) { $thClass = 'sticky-col-3'; $thStyle = 'width:120px;'; }
			elseif ($i === 3) { $thClass = 'sticky-col-4'; $thStyle = 'width:120px;'; }
			elseif ($i === 4) { $thClass = 'sticky-col-5'; $thStyle = 'width:120px;'; }
			elseif ($i === 5) { $thClass = 'sticky-col-6'; $thStyle = 'width:120px;'; }
			$html .= '<th class="'. $thClass .'" style="'. $thStyle .'">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</th>';
		}
		$html .= '</tr></thead><tbody>';

		$lastKodeKebun = null;
		$namakebun = null;
		foreach ($rows as $i => $r) {
			// Hitung subtotal per kode_kebun
			if ($lastKodeKebun !== null && $lastKodeKebun !== $r->kode_kebun) {
				// Hitung subtotal khusus untuk prognosa_protas, protas dan sisa_protas
				$sub_prognosa_protas = ($subtotals['prognosa_luas'] ?? 0) != 0 ? ($subtotals['prognosa_tebu'] ?? 0) / ($subtotals['prognosa_luas'] ?? 1) : 0;
				$sub_protas = ($subtotals['ha_tebang'] ?? 0) != 0 ? ($subtotals['netto_ton'] ?? 0) / ($subtotals['ha_tebang'] ?? 1) : 0;
				$sub_sisa_protas = ($subtotals['sisa_ha'] ?? 0) != 0 ? ($subtotals['sisa_tebu'] ?? 0) / ($subtotals['sisa_ha'] ?? 1) : 0;

				$html .= '<tr class="total-row">';
				foreach ($headers as $j => $h) {
					$tdClass = '';
					$tdStyle = '';
					if ($j === 0) { $tdClass = 'sticky-col'; $tdStyle = 'width:120px;'; }
					elseif ($j === 1) { $tdClass = 'sticky-col-2'; $tdStyle = 'width:120px;'; }
					elseif ($j === 2) { $tdClass = 'sticky-col-3'; $tdStyle = 'width:120px;'; }
					elseif ($j === 3) { $tdClass = 'sticky-col-4'; $tdStyle = 'width:120px;'; }
					elseif ($j === 4) { $tdClass = 'sticky-col-5'; $tdStyle = 'width:120px;'; }
					elseif ($j === 5) { $tdClass = 'sticky-col-6'; $tdStyle = 'width:120px;'; }
					if ($h == 'nama_cluster') {
						$html .= '<td class="'. $tdClass .'" style="font-weight:bold;background:#ffe066;color:#1e3c72;'. $tdStyle .'">Subtotal ' . htmlspecialchars($namakebun) . '</td>';
					} elseif ($h == 'prognosa_protas') {
						$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;background:#ffe066;color:#1e3c72;'. $tdStyle .'">' . number_format($sub_prognosa_protas, 2) . '</td>';
					} elseif ($h == 'protas') {
						$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;background:#ffe066;color:#1e3c72;'. $tdStyle .'">' . number_format($sub_protas, 2) . '</td>';
					} elseif ($h == 'sisa_protas') {
						$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;background:#ffe066;color:#1e3c72;'. $tdStyle .'">' . number_format($sub_sisa_protas, 2) . '</td>';
					} elseif (in_array($h, $numericCols)) {
						$val = isset($subtotals[$h]) ? number_format($subtotals[$h], 2) : '';
						$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;background:#ffe066;color:#1e3c72;'. $tdStyle .'">' . $val . '</td>';
					} else {
						$html .= '<td class="'. $tdClass .'" style="background:#ffe066;'. $tdStyle .'"></td>';
					}
				}
				$html .= '</tr>';
				$subtotals = [];
			}
			$lastKodeKebun = $r->kode_kebun;
			$namakebun = $r->nama_kebun;

			// Akumulasi subtotal dan total
			foreach ($numericCols as $col) {
				$val = isset($r->$col) ? (float)$r->$col : 0;
				$subtotals[$col] = isset($subtotals[$col]) ? $subtotals[$col] + $val : $val;
				$totals[$col] += $val;
			}

			$html .= '<tr>';
			foreach ($headers as $j => $h) {
				$tdClass = '';
				$tdStyle = '';
				if ($j === 0) { $tdClass = 'sticky-col'; $tdStyle = 'width:120px;'; }
				elseif ($j === 1) { $tdClass = 'sticky-col-2'; $tdStyle = 'width:120px;'; }
				elseif ($j === 2) { $tdClass = 'sticky-col-3'; $tdStyle = 'width:120px;'; }
				elseif ($j === 3) { $tdClass = 'sticky-col-4'; $tdStyle = 'width:120px;'; }
				elseif ($j === 4) { $tdClass = 'sticky-col-5'; $tdStyle = 'width:120px;'; }
				elseif ($j === 5) { $tdClass = 'sticky-col-6'; $tdStyle = 'width:120px;'; }
				$val = isset($r->$h) ? $r->$h : '';
				if (in_array($h, $numericCols) && $val !== '') {
					$html .= '<td class="cell-number '. $tdClass .'" style="color:#1e3c72;font-weight:600;'. $tdStyle .'">' . number_format((float)$val, 2) . '</td>';
				} elseif ($h == 'tanggal_giling_sd' && $val) {
					$html .= '<td class="'. $tdClass .'" style="'. $tdStyle .'">' . date('d/m/Y', strtotime($val)) . '</td>';
				} else {
					$html .= '<td class="'. $tdClass .'" style="'. $tdStyle .'">' . htmlspecialchars((string)$val, ENT_QUOTES, 'UTF-8') . '</td>';
				}
			}
			$html .= '</tr>';

			// Jika baris terakhir, tampilkan subtotal
			if ($i === count($rows) - 1) {
				$sub_prognosa_protas = ($subtotals['prognosa_luas'] ?? 0) != 0 ? ($subtotals['prognosa_tebu'] ?? 0) / ($subtotals['prognosa_luas'] ?? 1) : 0;
				$sub_protas = ($subtotals['ha_tebang'] ?? 0) != 0 ? ($subtotals['netto_ton'] ?? 0) / ($subtotals['ha_tebang'] ?? 1) : 0;
				$sub_sisa_protas = ($subtotals['sisa_ha'] ?? 0) != 0 ? ($subtotals['sisa_tebu'] ?? 0) / ($subtotals['sisa_ha'] ?? 1) : 0;

				$html .= '<tr class="total-row">';
				foreach ($headers as $j => $h) {
					$tdClass = '';
					$tdStyle = '';
					if ($j === 0) { $tdClass = 'sticky-col'; $tdStyle = 'width:120px;'; }
					elseif ($j === 1) { $tdClass = 'sticky-col-2'; $tdStyle = 'width:120px;'; }
					elseif ($j === 2) { $tdClass = 'sticky-col-3'; $tdStyle = 'width:120px;'; }
					elseif ($j === 3) { $tdClass = 'sticky-col-4'; $tdStyle = 'width:120px;'; }
					elseif ($j === 4) { $tdClass = 'sticky-col-5'; $tdStyle = 'width:120px;'; }
					elseif ($j === 5) { $tdClass = 'sticky-col-6'; $tdStyle = 'width:120px;'; }
					if ($h == 'nama_cluster') {
						$html .= '<td class="'. $tdClass .'" style="font-weight:bold;background:#ffe066;color:#1e3c72;'. $tdStyle .'">Subtotal ' . htmlspecialchars($namakebun) . '</td>';
					} elseif ($h == 'prognosa_protas') {
						$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;background:#ffe066;color:#1e3c72;'. $tdStyle .'">' . number_format($sub_prognosa_protas, 2) . '</td>';
					} elseif ($h == 'protas') {
						$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;background:#ffe066;color:#1e3c72;'. $tdStyle .'">' . number_format($sub_protas, 2) . '</td>';
					} elseif ($h == 'sisa_protas') {
						$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;background:#ffe066;color:#1e3c72;'. $tdStyle .'">' . number_format($sub_sisa_protas, 2) . '</td>';
					} elseif (in_array($h, $numericCols)) {
						$val = isset($subtotals[$h]) ? number_format($subtotals[$h], 2) : '';
						$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;background:#ffe066;color:#1e3c72;'. $tdStyle .'">' . $val . '</td>';
					} else {
						$html .= '<td class="'. $tdClass .'" style="background:#ffe066;'. $tdStyle .'"></td>';
					}
				}
				$html .= '</tr>';
			}
		}

		// Tampilkan total keseluruhan
		$html .= '<tr class="total-row" style="background:linear-gradient(90deg,#ffe066,#fffbe6);">';
		// Hitung total khusus untuk prognosa_protas, protas dan sisa_protas
		$total_prognosa_protas = ($totals['prognosa_luas'] ?? 0) != 0 ? ($totals['prognosa_tebu'] ?? 0) / ($totals['prognosa_luas'] ?? 1) : 0;
		$total_protas = ($totals['ha_tebang'] ?? 0) != 0 ? ($totals['netto_ton'] ?? 0) / ($totals['ha_tebang'] ?? 1) : 0;
		$total_sisa_protas = ($totals['sisa_ha'] ?? 0) != 0 ? ($totals['sisa_tebu'] ?? 0) / ($totals['sisa_ha'] ?? 1) : 0;

		foreach ($headers as $j => $h) {
			$tdClass = '';
			$tdStyle = '';
			if ($j === 0) { $tdClass = 'sticky-col'; $tdStyle = 'width:120px;'; }
			elseif ($j === 1) { $tdClass = 'sticky-col-2'; $tdStyle = 'width:120px;'; }
			elseif ($j === 2) { $tdClass = 'sticky-col-3'; $tdStyle = 'width:120px;'; }
			elseif ($j === 3) { $tdClass = 'sticky-col-4'; $tdStyle = 'width:120px;'; }
			elseif ($j === 4) { $tdClass = 'sticky-col-5'; $tdStyle = 'width:120px;'; }
			elseif ($j === 5) { $tdClass = 'sticky-col-6'; $tdStyle = 'width:120px;'; }
			if ($h == 'nama_cluster') {
				$html .= '<td class="'. $tdClass .'" style="font-weight:bold;    background: #545454;color: #FFF;'. $tdStyle .'">TOTAL</td>';
			} elseif ($h == 'prognosa_protas') {
				$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;    background: #545454;color: #FFF;'. $tdStyle .'">' . number_format($total_prognosa_protas, 2) . '</td>';
			} elseif ($h == 'protas') {
				$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;    background: #545454;color: #FFF;'. $tdStyle .'">' . number_format($total_protas, 2) . '</td>';
			} elseif ($h == 'sisa_protas') {
				$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;    background: #545454;color: #FFF;'. $tdStyle .'">' . number_format($total_sisa_protas, 2) . '</td>';
			} elseif (in_array($h, $numericCols)) {
				$val = isset($totals[$h]) ? number_format($totals[$h], 2) : '';
				$html .= '<td class="cell-number '. $tdClass .'" style="font-weight:bold;    background: #545454;color: #FFF;'. $tdStyle .'">' . $val . '</td>';
			} else {
				$html .= '<td class="'. $tdClass .'" style="background: #545454;'. $tdStyle .'"></td>';
			}
		}
		$html .= '</tr>';

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

		// Tombol download Excel
		$html .= '<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
		<script>
		document.getElementById("download-excel-btn").addEventListener("click", function() {
			var table = document.querySelector(".styled-table");
			if (!table) return;
			var wb = XLSX.utils.table_to_book(table, {sheet:"Sheet1"});
			XLSX.writeFile(wb, "rekap_prognosa_tebu_pg.xlsx");
		});
		</script>';

		return response($html, 200)->header('Content-Type', 'text/html; charset=utf-8');
	}


}	