<?php namespace App\Http\Controllers;

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


class ConsolelhpmksoController extends Controller {

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

	public function __construct()
	{
		
		parent::__construct();
		$this->model = new Consolelhpmkso();
		$this->info = $this->model->makeInfo( $this->module);
		$this->access = array();
	
		$this->data = array_merge(array(
			'pageTitle'	=> 	$this->info['title'],
			'pageNote'	=>  $this->info['note'],
			'pageModule'=> 'consolelhpmkso',
			'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');
	
	    			
		// 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 'getConsoleProdis':
				return $this->getConsoleProdis( $request );
				break;
			case 'formConsoleProdis':
				return $this->formConsoleProdis( $request );
				break;
			case 'getConsoleProdispg':
				return $this->getConsoleProdispg( $request );
				break;
			case 'formConsoleProdispg':
				return $this->formConsoleProdispg( $request );
				break;
	
		}
	}

	public function formConsoleProdis( Request $request )
	{
			$html = '
			<div class="card">
				<div class="card-body">
					<form id="filterForm" class="form-horizontal">
						<div class="row">
							<div class="col-md-3">
								<div class="form-group">
									<label for="start_date">Start Date</label>
									<input type="date" class="form-control" id="start_date" name="start_date" value="" required>
								</div>
							</div>
							<div class="col-md-3">
								<div class="form-group">
									<label for="end_date">End Date</label>
									<input type="date" class="form-control" id="end_date" name="end_date" value="" required>
								</div>
							</div>
							<div class="col-md-3">
								<div class="form-group">
									<label for="kode_kebun">Cluster</label>
								<select class="form-control" id="kode_kebun" name="kode_kebun">
								<option value="">Semua Cluster</option>
								<option value="SUMATERA 1">SUMATERA 1</option>
								<option value="SUMATERA 2">SUMATERA 2</option>
								<option value="JATENG">JATENG</option>
								<option value="JATIM 1">JATIM 1</option>
								<option value="JATIM 2">JATIM 2</option>
								<option value="SULAWESI">SULAWESI</option>
								<option value="PUSLIT">PUSLIT</option>
									</select>

								</div>
							</div>
							<div class="col-md-3">
								<div class="form-group">
									<button type="submit" class="btn btn-xs btn-primary mt-4">Filter</button>
									<button type="button" id="downloadExcel" class="btn btn-xs btn-success mt-4">Download Excel</button>
								</div>
							</div>

						</div>

					</form>
				</div>
			</div>
			<div id="results" class="mt-3"></div>
			';

			$html .= '
			<script>


			// Set date range to last 7 days
			var today = new Date();
			var sevenDaysAgo = new Date();
			sevenDaysAgo.setDate(today.getDate() - 7);

			var formatDate = function(date) {
				var year = date.getFullYear();
				var month = String(date.getMonth() + 1).padStart(2, "0");
				var day = String(date.getDate()).padStart(2, "0");
				return year + "-" + month + "-" + day;
			};

			$("#start_date").val(formatDate(sevenDaysAgo));
			$("#end_date").val(formatDate(today));

			fetchConsoleProdis(); // Fetch initial data on page load
			$(document).ready(function() {
				$("#filterForm").on("submit", function(e) {
					e.preventDefault();
					fetchConsoleProdis();

				});
			});

			function fetchConsoleProdis() {
					var formData = {
						start_date: $("#start_date").val(),
						end_date: $("#end_date").val(),
						kode_kebun: $("#kode_kebun").val()
					};
					
					$.ajax({
						url: "' . url($this->module . '/getConsoleProdis') . '",
						type: "GET",
						data: formData,
						beforeSend: function() {
							$("#results").html("<div class=\"text-center\"><i class=\"fa fa-spinner fa-spin\"></i> Loading...</div>");
						},
						success: function(response) {
							$("#results").html(response);
						},
						error: function(xhr, status, error) {
							$("#results").html("<div class=\"alert alert-danger\">Error: " + error + "</div>");
						}
					});
			}

			$("#downloadExcel").on("click", function() {
				   var table = document.getElementById("rekap-table");
        
					if (!table) {
						alert("Table tidak ditemukan!");
						return;
					}
					
					var wb = XLSX.utils.table_to_book(table, {sheet: "Rekap Pengadaan"});

					var filename = "Rekap_Produksi" + ".xlsx";
					
					XLSX.writeFile(wb, filename);
			});
			</script>
			';

			return $html;
	}

	public function getConsoleProdis(Request $request)
	{
		$startDate = $request->input('start_date', '2026-02-15');
		$endDate = $request->input('end_date', '2026-02-22');
		$kode_kebun = $request->input('kode_kebun', 'sk01');
		
		$results = \DB::select('CALL sp_console_prodis_kebun(?, ?, ?)', [
			$startDate,
			$endDate,
			$kode_kebun
		]);
		
		$html = '<style>
		.table-responsive {
			overflow-x: auto;
		}
		.sticky-col {
			position: sticky;
			left: 0;
			background-color: white;
			z-index: 10;
		}
		</style>';
		$html .= '<div class="table-responsive">';
		$html .= '<table id="rekap-table" class="table table-bordered table-striped table-hover">';
		$html .= '<thead class="thead-dark">';
		$html .= '<tr>';
		
		if (!empty($results)) {
			foreach (array_keys((array)$results[0]) as $header) {
				$displayHeader = strtoupper(str_replace('_', ' ', $header));
				$html .= '<th class="text-center">' . htmlspecialchars($displayHeader) . '</th>';
			}
		}
		
		$html .= '</tr></thead><tbody>';
		
		foreach ($results as $index => $row) {
			$html .= '<tr>';
			$colIndex = 0;
			foreach ((array)$row as $cell) {
				$stickyClass = ($colIndex < 3) ? 'sticky-col' : '';
				
				if ($colIndex >= 3) {
					// Numeric columns - right aligned with number formatting
					$formattedValue = is_numeric($cell) ? number_format($cell, 2, ',', '.') : htmlspecialchars($cell);
					$html .= '<td class="text-right">' . $formattedValue . '</td>';
				}else if($colIndex == 2){
					$icons = [
					'luas digiling' => '<i class="fa fa-map text-primary"></i>',
					'tebu digiling' => '<i class="fa fa-pagelines text-success"></i>',
					'protas' => '<i class="fa fa-chart-line text-info"></i>',
					'hablur' => '<i class="fa fa-cube text-warning"></i>',
					'rendemen' => '<i class="fa fa-percent text-danger"></i>',
					'gula' => '<i class="fas fa-boxes text-purple"></i>',
					'tetes' => '<i class="fa fa-tint text-secondary"></i>'
				];
					$icon = $icons[$cell] ?? '';
					$html .= '<td class="' . $stickyClass . '">' . $icon . ' ' . htmlspecialchars($cell) . '</td>';

				} else {
					// Text columns - left aligned
					$html .= '<td class="' . $stickyClass . '">' . htmlspecialchars($cell) . '</td>';
				}
				$colIndex++;
			}
			$html .= '</tr>';
		}
		
		$html .= '</tbody></table>';
		$html .= '</div>';
				
				return $html;
	}



	public function formConsoleProdispg( Request $request )
	{
		$html = '
		<div class="card">
			<div class="card-body">
				<form id="filterFormPg" class="form-horizontal">
					<div class="row">
						<div class="col-md-3">
							<div class="form-group">
								<label for="start_date_pg">Start Date</label>
								<input type="date" class="form-control" id="start_date_pg" name="start_date" value="" required>
							</div>
						</div>
						<div class="col-md-3">
							<div class="form-group">
								<label for="end_date_pg">End Date</label>
								<input type="date" class="form-control" id="end_date_pg" name="end_date" value="" required>
							</div>
						</div>
						<div class="col-md-3">
							<div class="form-group">
								<label for="kode_kebun_pg">Kode Kebun</label>
								<select class="form-control" id="kode_kebun_pg" name="kode_kebun">
								</select>
							</div>
						</div>
						<div class="col-md-3">
							<div class="form-group">
								<button type="submit" class="btn btn-xs btn-primary mt-4">Filter</button>
								<button type="button" id="downloadExcelPg" class="btn btn-xs btn-success mt-4">Download Excel</button>
							</div>
						</div>
					</div>
				</form>
			</div>
		</div>
		<div id="results-pg" class="mt-3"></div>
		';

		$html .= '
		<script>
		$(document).ready(function() {
			$("#kode_kebun_pg").jCombo("' . url('dataprodisconsole/comboselect?filter=master_kebun:kode_kebun:nama_kebun') . '",
				{ initial_text: "Semua Kebun" });

			var today = new Date();
			var sevenDaysAgo = new Date();
			sevenDaysAgo.setDate(today.getDate() - 7);

			var formatDate = function(date) {
				var year = date.getFullYear();
				var month = String(date.getMonth() + 1).padStart(2, "0");
				var day = String(date.getDate()).padStart(2, "0");
				return year + "-" + month + "-" + day;
			};

			$("#start_date_pg").val(formatDate(sevenDaysAgo));
			$("#end_date_pg").val(formatDate(today));

			fetchConsoleProdispg();

			$("#filterFormPg").on("submit", function(e) {
				e.preventDefault();
				fetchConsoleProdispg();
			});

			$("#downloadExcelPg").on("click", function() {
				var table = document.getElementById("rekap-table-pg");
				if (!table) {
					alert("Table tidak ditemukan!");
					return;
				}
				var wb = XLSX.utils.table_to_book(table, { sheet: "Rekap Produksi PG" });
				var filename = "Rekap_Produksi_PG.xlsx";
				XLSX.writeFile(wb, filename);
			});
		});

		function fetchConsoleProdispg() {
			var formData = {
				start_date: $("#start_date_pg").val(),
				end_date: $("#end_date_pg").val(),
				kode_kebun: $("#kode_kebun_pg").val()
			};
			$.ajax({
				url: "' . url($this->module . '/getConsoleProdispg') . '",
				type: "GET",
				data: formData,
				beforeSend: function() {
					$("#results-pg").html("<div class=\\"text-center\\"><i class=\\"fa fa-spinner fa-spin\\"></i> Loading...</div>");
				},
				success: function(response) {
					$("#results-pg").html(response);
				},
				error: function(xhr, status, error) {
					$("#results-pg").html("<div class=\\"alert alert-danger\\">Error: " + error + "</div>");
				}
			});
		}
		</script>
		';

		return $html;
	}

	public function getConsoleProdispg(Request $request)
	{
		$startDate = $request->input('start_date');
		$endDate = $request->input('end_date');
		$kode_kebun = $request->input('kode_kebun');

		$results = \DB::select('CALL sp_console_prodis_pg(?, ?, ?)', [
			$startDate,
			$endDate,
			$kode_kebun
		]);

		$html = '<style>
		.table-responsive {
			overflow-x: auto;
		}
		.sticky-col {
			position: sticky;
			left: 0;
			background-color: white;
			z-index: 10;
		}
		</style>';
		$html .= '<div class="table-responsive">';
		$html .= '<table id="rekap-table-pg" class="table table-bordered table-striped table-hover">';
		$html .= '<thead class="thead-dark">';
		$html .= '<tr>';

		if (!empty($results)) {
			foreach (array_keys((array)$results[0]) as $header) {
				$displayHeader = strtoupper(str_replace('_', ' ', $header));
				$html .= '<th class="text-center">' . htmlspecialchars($displayHeader) . '</th>';
			}
		}

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

		foreach ($results as $index => $row) {
			$html .= '<tr>';
			$colIndex = 0;
			foreach ((array)$row as $cell) {
				$stickyClass = ($colIndex < 5) ? 'sticky-col' : '';

				if ($colIndex >= 5) {
					$formattedValue = is_numeric($cell) ? number_format($cell, 2, ',', '.') : htmlspecialchars($cell);
					$html .= '<td class="text-right">' . $formattedValue . '</td>';
				} else if ($colIndex == 3) {
					$icons = [
						'luas digiling' => '<i class="fa fa-map text-primary"></i>',
						'tebu digiling' => '<i class="fa fa-pagelines text-success"></i>',
						'protas' => '<i class="fa fa-chart-line text-info"></i>',
						'hablur' => '<i class="fa fa-cube text-warning"></i>',
						'rendemen' => '<i class="fa fa-percent text-danger"></i>',
						'gula' => '<i class="fas fa-boxes text-purple"></i>',
						'tetes' => '<i class="fa fa-tint text-secondary"></i>'
					];
					$icon = $icons[$cell] ?? '';
					$html .= '<td class="' . $stickyClass . '">' . $icon . ' ' . htmlspecialchars($cell) . '</td>';
				} else {
					$html .= '<td class="' . $stickyClass . '">' . htmlspecialchars($cell) . '</td>';
				}
				$colIndex++;
			}
			$html .= '</tr>';
		}

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

		return $html;
	}

	
}