<?php namespace App\Http\Controllers;

use App\Models\Teburoboh;
use App\Library\DataHelpers;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ; 

class TeburobohController extends Controller {

	protected $layout = "layouts.main";
	protected $data = array();	
	public $module = 'teburoboh';
	static $per_page	= '10';
	
	public function __construct() 
	{
		parent::__construct();
		$this->model = new Teburoboh();
		
		$this->info = $this->model->makeInfo( $this->module);
		$this->access = $this->model->validAccess($this->info['id']);
	
		$this->data = array(
			'pageTitle'			=> 	$this->info['title'],
			'pageNote'			=>  $this->info['note'],
			'pageModule'		=> 'teburoboh',
			'pageUrl'			=>  url('teburoboh'),
			'return' 			=> 	self::returnUrl()	
		);	
			
				
	} 
	public function index()
	{
		if(!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');

		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));
		if($this->access['is_view'] ==0) 
			return redirect('dashboard')->with('message',__('core.note_restric'))->with('status','error');
		
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['tableForm'] 	= $this->info['config']['forms'];
		$this->data['tableGrid'] 	= $this->info['config']['grid'];
		usort($this->data['tableGrid'], "SiteHelpers::_sort");
			$cols = '{"data":"rowId"},';
			if($this->data['setting']['view-method'] =='expand'){
				$cols .= '{"className": "details-control","orderable": false,"data": null,"defaultContent": ""},';
			}		
				
			foreach($this->data['tableGrid'] as $field)
			{				
				
				if($field['view'] =='1')
				{
					$cols .= '{"data":"'.$field['field'].'"},';
				}						
			}
			$cols .= '{"data":"action"},';
		$this->data['column'] = $cols ;	
		$this->data['access']		= $this->access;	
		$this->data['setting'] 		= $this->info['setting'];
		return view('teburoboh.index',$this->data);
	}
	function create( Request $request ) 
	{
		$this->hook( $request  );
		if($this->access['is_add'] ==0) 
			return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');

		$this->data['row'] = $this->model->getColumnTable( $this->info['table']); 
		$this->data['lahan_id'] = $request->input('id_lahan');
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['tableForm'] 	= $this->info['config']['forms'];
		$this->data['tableGrid'] 	= $this->info['config']['grid'];
		usort($this->data['tableGrid'], "SiteHelpers::_sort");
			$cols = '{"data":"rowId"},';
			if($this->data['setting']['view-method'] =='expand'){
				$cols .= '{"className": "details-control","orderable": false,"data": null,"defaultContent": ""},';
			}		
				
			foreach($this->data['tableGrid'] as $field)
			{				
				
				if($field['view'] =='1')
				{
					$cols .= '{"data":"'.$field['field'].'"},';
				}						
			}
			$cols .= '{"data":"action"},';
		$this->data['column'] = $cols ;	
		$this->data['access']		= $this->access;	
		$this->data['id'] = '';
		return view($this->module.'.form',$this->data);
	}
	function edit( Request $request , $id ) 
	{
		$this->hook( $request , $id );
		if(!isset($this->data['row']))
			return redirect($this->module)->with('message','Record Not Found !')->with('status','error');
		if($this->access['is_edit'] ==0 )
			return redirect('dashboard')->with('message',__('core.note_restric'))->with('status','error');
		$this->data['row'] = (array) $this->data['row'];
		
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['id'] = $id;
		return view($this->module.'.form',$this->data);
	}
	function show( Request $request , $id ) 
	{
		/* Handle import , export and view */
		$task =$id ;
		switch( $task)
		{
			case 'search':
				return $this->getSearch();
				break;
			case 'lookup':
				return $this->getLookup($request );
				break;
			case 'comboselect':
				return $this->getComboselect( $request );
				break;
			case 'import':
				return $this->getImport( $request );
			case 'removefiles':
				return $this->getRemovefiles( $request );	
				break;
			case 'export':
				return $this->getExport( $request );
				break;
			case 'monitoringRobohBungaBanjirPetak':
				return $this->monitoringRobohBungaBanjirPetak();
				break;
			case 'getMonitoringRobohBungaBanjirPetak':
				return $this->getMonitoringRobohBungaBanjirPetak($request);
				break;
			case 'monitoringRobohBungaBanjirRekap':
				return $this->monitoringRobohBungaBanjirRekap();	
				break;
			case 'getMonitoringRobohBungaBanjirRekap':
				return $this->getMonitoringRobohBungaBanjirRekap($request);	
				break;
			default:
				$this->hook( $request , $id );
				if(!isset($this->data['row']))
					return redirect($this->module)->with('message','Record Not Found !')->with('status','error');

				if($this->access['is_detail'] ==0) 
					return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');

				return view($this->module.'.view',$this->data);	
				break;		
		}
	}	
	public function store( Request $request){

		$task = $request->input('action_task');
		switch ($task)
		{
			default:
				return $this->postData( $request);
				break;
			case 'save':
				$rules = $this->validateForm();
				$validator = Validator::make($request->all(), $rules);
				if ($validator->passes()) 
				{
					$data = $this->validateCDNPost( $request );
					$id = $this->model->insertRow($data , $request->input( $this->info['key']));
					
					/* Insert logs */
					$this->model->logs($request , $id);
					return response()->json(array('status'=>'success','message'=> __('core.note_success')));	
					
				} 
				else {
					$message = $this->validateListError(  $validator->getMessageBag()->toArray() );
					return response()->json(array(
						'message'	=> $message,
						'status'	=> 'error'
					));	
				}
				break;
			case 'delete':
				return $result = $this->destroy( $request );
				break;

			case 'import':
				return $this->PostImport( $request );
				break;

			case 'copy':
				$result = $this->copy( $request );
				return response()->json($result);
				break;		

		}
	}
	public function postData( $request)
	{ 
		
		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));

		$tables 	= $this->info['config']['grid'];
		$cols = array();
		foreach($tables as $field)
		{				
			//$cols[$this->info['key']]	= array('db'=> $field['alias'] ,$this->info['key'] );
			if($field['view'] =='1')
			{
				$cols[] = array('db'=> $field['alias'],'dt'=> $field['field'] );
			}					
		}
		$conf = DataHelpers::simple($request->all(),$cols);
		$filter =  '';
		if(!is_null($request->input('search')))
		{
			$filter .= $this->liveSearch( $request);
		}

		$filter .= " AND lahan_id = '".$request->input('lahan_id')."' ";

		$params = array(
			'page'		=> $conf['page'] ,
			'limit'		=> $conf['limit'] ,
			'sort'		=> ($conf['order']['sort'] !='' ? $conf['order']['sort'] : $this->info['setting']['orderby']) ,
			'order'		=> ($conf['order']['by'] !='' ? $conf['order']['by'] : $this->info['setting']['ordertype']),
			'params'	=> $filter,
			'global'	=> (isset($this->access['is_global']) ? $this->access['is_global'] : 0 )
		);


		$results = $this->model->getRows($params);
		
		$array = array();
		foreach($results['rows'] as $row)
		{
			$values = array();
			$values['rowId'] = $row->{$this->info['key']};
			foreach($tables as $field)
			{			
				
				if($field['view'] =='1')
				{
					$values[$field['field']] = \SiteHelpers::formatRows($row->{$field['field']}, $field , $row,true);
				}	
			}
			$values['action'] =  \SiteHelpers::buttonAction($this->module,$this->access ,$row->{$this->info['key']} ,$this->info['setting']) ;
			$array[] = $values; 	
		}
		
		$data = array(
			'draw'			=> (!is_null($request->input('draw')) ? intval($request->input('draw') ) : 0), 
			'recordsTotal'	=> $results['total'] ,
			'recordsFiltered'	=> $results['total'],
			'data'				=> $array

		);
		return response()->json($data);
	}

	public function destroy( Request $request)
	{

		if(!\Auth::check()) 
			return response()->json(array(
				'status'=>'error',
				'message'=> 'You are not login'
			));

		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));
		if($this->access['is_remove'] ==0) 
			return response()->json(array('status'=>'error','message'=> __('core.note_restric')));	


		// delete multipe rows 
		if(count($request->input('ids')) >=1)
		{
			$this->model->destroy($request->input('ids'));
			
			return response()->json(array(
				'status'=>'success',
				'message'=> __('core.note_success_delete')
			));
		} else {
			return response()->json(array(
				'status'=>'error',
				'message'=> __('core.note_error')
			));

		} 		

	}


	public function monitoringRobohBungaBanjirPetak(){
		
		$this->data['pageTitle'] = 'Monitoring Roboh Bunga Banjir Petak';
		$this->data['pageNote'] = 'Menampilkan data monitoring roboh bunga banjir per petak';
		return view('teburoboh.monitoring-roboh-bunga-banjir',$this->data);
	}

	public function getMonitoringRobohBungaBanjirPetak(Request $request)
	{
		$kebun = $request->input('kebun');
		$rayon = $request->input('rayon');
		$afdeling = $request->input('afdeling');
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		try {
			$results = \DB::select('CALL sp_monitoring_roboh_bunga_banjir_petak(?, ?, ?, ?, ?)', 
				[$kebun, $rayon, $afdeling, $dateFrom, $dateTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
					text-align: center;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';

			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array)$row as $value) {
					$html .= '<td>' . htmlspecialchars($value ?? '-') . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}
	
	public function monitoringRobohBungaBanjirRekap(){
		$this->data['pageTitle'] = 'Rekap Roboh Bunga Banjir';
		$this->data['pageNote'] = 'Menampilkan data rekap roboh bunga banjir';
		return view('teburoboh.monitoring-roboh-bunga-banjir-rekap',$this->data);
	}

	public function getMonitoringRobohBungaBanjirRekap(Request $request)
	{
		$level = $request->input('status');
		$kebun = $request->input('kebun');
		$rayon = $request->input('rayon');
		$dateFrom = $request->input('date_from');
		$dateTo = $request->input('date_to');

		try {
			$results = \DB::select('CALL sp_monitoring_roboh_bunga_banjir_rekap(?, ?, ?, ?, ?)', 
				[$level, $kebun, $rayon, $dateFrom, $dateTo]);

			$html = '
			<style>
				.rekap-table-container {
					max-height: 600px;
					overflow-y: auto;
					position: relative;
				}
				.rekap-table {
					width: 100%;
					border-collapse: collapse;
					font-size: 14px;
				}
				.rekap-table th, .rekap-table td {
					border: 1px solid #dee2e6;
					padding: 8px 10px;
				}
				.rekap-table thead {
					background: linear-gradient(90deg, #4e73df 0%, #1cc88a 100%);
					color: #fff;
					position: sticky;
					top: 0;
					z-index: 10;
				}
				.rekap-table tbody tr:nth-child(even) {
					background-color: #f8f9fc;
				}
				.rekap-table tbody tr:hover {
					background-color: #e2eafc;
				}
			</style>
			<div class="rekap-table-container">
				<table id="rekap-table" class="rekap-table">
					<thead>
						<tr>';
			
			if (!empty($results)) {
				foreach (array_keys((array)$results[0]) as $column) {
					$html .= '<th>' . htmlspecialchars(ucwords(str_replace('_', ' ', $column))) . '</th>';
				}
			}
			
			$html .= '</tr></thead><tbody>';
			foreach ($results as $row) {
				$html .= '<tr>';
				foreach ((array)$row as $key => $value) {
					$isNumericColumn = in_array(strtolower($key), ['luas_roboh', 'luas_berbunga', 'luas_banjir']);
					$displayValue = ($isNumericColumn && $value == 0) ? '-' : htmlspecialchars($value ?? '-');
					$alignment = $isNumericColumn ? 'style="text-align: right;"' : '';
					$html .= '<td ' . $alignment . '>' . $displayValue . '</td>';
				}
				$html .= '</tr>';
			}

			$html .= '</tbody></table></div>';
			return response($html);
		} catch (\Exception $e) {
			return response()->json(['status' => 'error', 'message' => 'Gagal mengambil data: ' . $e->getMessage()]);
		}
	}
}