<?php namespace App\Http\Controllers;

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


class PrognosasisatebuController extends Controller {

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

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


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

	public function getDataFromSP(Request $request)
	{
		$params = [
			$request->input('jawa_luarjawa'),
			$request->input('cluster'),
			$request->input('kode_kebun'),
			$request->input('nama_rayon'),
			$request->input('periode'),
			$request->input('tgl')
		];

		$results = \DB::select('CALL sp_prognosa_sisatebu(?, ?, ?, ?, ?, ?)', $params);

		// Return JSON response
		$jsonResponse = response()->json($results);

		// Generate HTML table
		// Add Bootstrap styling for a more attractive table
		$html = '';
		$html .= '<div class="table-responsive" style="height: 500px;"><table id="tabledata" class="table table-striped table-bordered align-middle">';
		$html .= '<thead class="table-primary" style="position: sticky; top: 0; z-index: 2;"><tr>';
		if (!empty($results)) {
			foreach ($results[0] as $key => $value) {
				$colName = ucwords(str_replace('_', ' ', $key));
				$html .= '<th scope="col">' . htmlspecialchars($colName) . '</th>';
			}
			$html .= '</tr></thead><tbody>';
			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ($row as $cell) {
					$html .= '<td>' . htmlspecialchars($cell) . '</td>';
				}
				$html .= '</tr>';
			}
			$html .= '</tbody></table></div>';
		} else {
			$html .= '<th>No Data</th></tr></thead><tbody></tbody></table></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 'getDataFromSP':
				return $this->getDataFromSP( $request );
		}
	}
}