<?php namespace App\Http\Controllers;

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


class RekapbibitkebunController extends Controller {

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

	public function __construct()
	{
		
		parent::__construct();
		$this->model = new Rekapbibitkebun();
		$this->info = $this->model->makeInfo( $this->module);
		$this->access = array();
	
		$this->data = array_merge(array(
			'pageTitle'	=> 	$this->info['title'],
			'pageNote'	=>  $this->info['note'],
			'pageModule'=> 'rekapbibitkebun',
			'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);
	}	

	public function showTable(Request $request)
	{
		$masa_tanam = $request->input('masa_tanam');
		$jenjang_bibitan = $request->input('jenjang_bibitan');



		// Panggil stored procedure
		$results = \DB::select("CALL sp_rekap_bibit_kebun_pc_rc(?, ?)", [$masa_tanam, $jenjang_bibitan]);

		// Ambil kolom dari hasil query
		$columns = array_keys((array)$results[0]);
		$html = '';
		// Bangun HTML table
		// Table with Bootstrap styling and zebra stripes
		$html .= '<div class="table-responsive">';
		$html .= '<table class="table table-bordered table-striped table-hover">';
		$html .= '<thead class="thead-dark"><tr>';
		foreach ($columns as $col) {
			$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $col))) . '</th>';
		}
		$html .= '</tr></thead><tbody>';

		foreach ($results as $row) {
			$html .= '<tr>';
			foreach ($columns as $col) {
			$html .= '<td>' . htmlspecialchars($row->$col) . '</td>';
			}
			$html .= '</tr>';
		}
		$html .= '</tbody></table></div>';

		return $html;
	}

	public function formrekapbibit(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'	=> 'Rekap Bibit Kebun',
			'pageNote'	=> 'Data Rekap Bibit Kebun',
			'pageModule'=> 'rekapbibitkebun',
			'return'	=> self::returnUrl()
			
		),$this->data);
		return view($this->module.'.rekapbibit', $this->data);
	}

	public function rekapBibit(Request $request)
	{
		$jenjang = $request->input('jenjang');
		$sistem = $request->input('sistem');
		$tahun = $request->input('tahun');
		$kemasakan = $request->input('kemasakan');
		$kategori = $request->input('kategori');
		$tingkat = $request->input('tingkat');

		// Panggil stored procedure
		$results = \DB::select("CALL sp_rekap_bibit_new(?, ?, ?, ?, ?, ?)", [$jenjang, $sistem, $tahun, $kemasakan, $kategori, $tingkat]);

		// Ambil kolom dari hasil query
		if (empty($results)) {
			return '<div class="alert alert-warning">No data found</div>';
		}

		$columns = array_keys((array)$results[0]);
		$html = '';
		// Bangun HTML table
		// Table with Bootstrap styling and zebra stripes
		$html .= '<style>
			#rekap-table { border-collapse: separate; border-spacing: 0; font-size: 13px; font-family: "Segoe UI", Arial, sans-serif; }
			#rekap-table thead tr th { position: sticky; top: 0; z-index: 20; font-weight: 700; letter-spacing: 0.04em; border-bottom: 3px solid #4a90d9 !important; text-align: center; vertical-align: middle; padding: 10px 10px; white-space: nowrap; box-shadow: 0 2px 4px rgba(0,0,0,0.08); }
			#rekap-table tbody tr td { padding: 7px 10px; vertical-align: middle; white-space: nowrap; border-top: 1px solid #e3eaf3; transition: background 0.15s; }
			#rekap-table tbody tr:hover td { filter: brightness(0.93); }
			#rekap-table tbody tr:nth-child(even) td { filter: brightness(0.97); }
			.rekap-badge { display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 11px; font-weight: 600; }
			.rekap-wrap { border-radius: 12px; overflow: hidden; box-shadow: 0 4px 24px rgba(74,144,217,0.13), 0 1.5px 6px rgba(0,0,0,0.07); border: 1.5px solid #d0e4f7; background: #fff; }
		</style>';
		$html .= '<div class="rekap-wrap"><div class="table-responsive" style="position: relative; border-radius: 12px; max-height: 75vh; overflow-y: auto;">';
		$html .= '<table id="rekap-table" class="table table-bordered table-hover mb-0">';
		$html .= '<thead><tr>';
		
		// Generate color map based on filter tahun
		$filterYear = intval(substr(str_replace('/', '', $tahun), 0, 2))+2000;
		$colorMap = array(
			($filterYear - 2) => array('header' => '#F28B82', 'row' => '#FDE8E6'),
			($filterYear - 1) => array('header' => '#7BB3F0', 'row' => '#E3EFFD'),
			$filterYear       => array('header' => '#57BB8A', 'row' => '#E2F4EC'),
			($filterYear + 1) => array('header' => '#F6C549', 'row' => '#FEF9E7'),
			($filterYear + 2) => array('header' => '#B39DDB', 'row' => '#F3EFFE'),
		);
		
		foreach ($columns as $col) {
			$colIndex = array_search($col, $columns);
			
			// Determine header background color based on year
			$headerBgColor = '#4a90d9';
			$headerTextColor = '#fff';
			if ($colIndex >= 5) {
				$yearStr = substr($col, 0, 4);
				if (isset($colorMap[$yearStr])) {
					$headerBgColor = $colorMap[$yearStr]['header'];
					$headerTextColor = '#fff';
				} else {
					$headerBgColor = '#7f8c8d';
					$headerTextColor = '#fff';
				}
			}
			
			if ($colIndex < 5) {
				$leftOffset = array(0 => 0, 1 => 90, 2 => 170, 3 => 250, 4 => 330);
				$left = isset($leftOffset[$colIndex]) ? $leftOffset[$colIndex] : ($colIndex * 80);
				$stickyStyle = ' style="position: sticky; left: ' . $left . 'px; z-index: 10; background: linear-gradient(135deg, #2c3e50 0%, #4a6fa5 100%); color: #fff; border-right: 2px solid #1a2636;"';
			} else {
				$stickyStyle = ' style="background-color: ' . $headerBgColor . '; color: ' . $headerTextColor . '; border-right: 1px solid rgba(255,255,255,0.25);"';
			}
			$html .= '<th' . $stickyStyle  . '>' . htmlspecialchars(ucwords(str_replace('_', ' ', $col))) . '</th>';
		}
		$html .= '</tr></thead><tbody>';

		$rowNum = 0;
		foreach ($results as $row) {
			$rowNum++;
			$html .= '<tr>';
			foreach ($columns as $col) {
				$colIndex = array_search($col, $columns);

				if ($colIndex < 5) {
					$leftOffset = array(0 => 0, 1 => 90, 2 => 170, 3 => 250, 4 => 330);
					$left = isset($leftOffset[$colIndex]) ? $leftOffset[$colIndex] : ($colIndex * 80);
					$stickyBg = ($rowNum % 2 === 0) ? '#eaf2fb' : '#ffffff';
					$stickyStyle = ' style="position: sticky; left: ' . $left . 'px; z-index: 9; background-color: ' . $stickyBg . '; border-right: 2px solid #d0e4f7; font-weight: ' . ($colIndex === 0 ? '600' : 'normal') . ';"';
					$html .= '<td' . $stickyStyle . '>' . htmlspecialchars($row->$col) . '</td>';
				} else {
					$yearStr = substr($col, 0, 4);
					$bgColor = isset($colorMap[$yearStr]) ? $colorMap[$yearStr]['row'] : '#fff';
					$val = $row->$col;
					$numericStyle = '';
					$displayVal = ($val == '0' || $val === 0) ? '-' : htmlspecialchars($val);
					if (is_numeric(str_replace(',', '', $val)) && $val !== '' && $val != '0' && $val !== 0) {
						$numericStyle = ' font-weight: 500;';
					}
					$html .= '<td style="text-align: right; background-color: ' . $bgColor . ';' . $numericStyle . ' border-right: 1px solid rgba(0,0,0,0.05);">' . $displayVal . '</td>';
				}
			}
			$html .= '</tr>';
		}
		$html .= '</tbody></table></div></div>';

		return $html;
	}


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

			case 'export':
				return $this->getExport( $request );
				break;
			case 'showTable':
				return $this->showTable( $request );
				break;
			case 'rekapBibit':
				return $this->rekapBibit( $request );
				break;
			case 'formrekapbibit':
				return $this->formrekapbibit( $request );
				break;		

		}
	}
}