<?php namespace App\Http\Controllers;

use App\Models\Updatepetaklama;
use App\Library\DataHelpers;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ; 

class UpdatepetaklamaController extends Controller {

	protected $layout = "layouts.main";
	protected $data = array();	
	public $module = 'updatepetaklama';
	static $per_page	= '10';
	
	public function __construct() 
	{
		parent::__construct();
		$this->model = new Updatepetaklama();
		$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'		=> 'updatepetaklama',
			'pageUrl'			=>  url('updatepetaklama'),
			'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('updatepetaklama.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['setting'] 		= $this->info['setting'];
		$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 'cekdatapetak':
				return $this->cekdatapetak( $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->validatePost( $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;		
			case 'ubahdatapetak':
				return $this->ubahdatapetak( $request );
				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);
		}

		$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')
				{
					if($field['field'] == 'entry_by'){
						if($row->petak_lama != $row->petak_baru){
							$values[$field['field']] = '<span class="badge badge-danger">Petak Lama: '.$row->petak_lama.'<br>Petak Baru: '.$row->petak_baru.'</span>';	
						$counttx = \DB::table('TX_TOTAL_KSO')->where('id_lahan',$row->petak_lama)->count();
						$counttx_foto_lkp = \DB::table('tx_foto_kebun')->where('lahan_id',$row->petak_lama)->count();
						$counttx_foto_morfologi = \DB::table('tx_morfologi')->where('lahan_id',$row->petak_lama)->count();
						$counttx_foto_drone = \DB::table('tx_foto_drone')->where('lahan_id',$row->petak_lama)->count();
						$countmaster_petak = \DB::table('master_petak')->where('lahan_id',$row->petak_lama)->count();
						$countpetakpupuk = \DB::table('m_petak_pupuk')->where('lahan_id',$row->petak_lama)->count();
						$counttx_pica_pi = \DB::table('tx_pica_pi')->where('lahan_id',$row->petak_lama)->count();
						$values[$field['field']] = '<div style="display: flex;"><div class="alert-' . ($countmaster_petak > 0 ? 'info' : 'secondary') . ' p-2" style="width:fit-content""><strong>'.$countmaster_petak.' Master Petak </strong> </div>';
						$values[$field['field']] .= '<div style="display: flex;"><div class="alert-' . ($counttx > 0 ? 'info' : 'secondary') . ' p-2" style="width:fit-content"">Ada <strong>'.$counttx.' transaksi LKP </strong> </div>';
						$values[$field['field']] .= '<div class="alert-' . ($counttx_foto_lkp > 0 ? 'info' : 'secondary') . ' p-2" style="width:fit-content">Ada <strong>'.$counttx_foto_lkp.' foto LKP </strong> </div>';
						$values[$field['field']] .= '<div class="alert-' . ($counttx_foto_morfologi > 0 ? 'info' : 'secondary') . ' p-2" style="width:fit-content">Ada <strong>'.$counttx_foto_morfologi.' foto morfologi </strong> </div>';
						$values[$field['field']] .= '<div class="alert-' . ($counttx_foto_drone > 0 ? 'info' : 'secondary') . ' p-2" style="width:fit-content">Ada <strong>'.$counttx_foto_drone.' foto drone </strong> </div>';
						$values[$field['field']] .= '<div class="alert-' . ($countpetakpupuk > 0 ? 'info' : 'secondary') . ' p-2" style="width:fit-content">Ada <strong>'.$countpetakpupuk.' petak pupuk </strong> </div>';
						$values[$field['field']] .= '<div class="alert-' . ($counttx_pica_pi > 0 ? 'info' : 'secondary') . ' p-2" style="width:fit-content">Ada <strong>'.$counttx_pica_pi.' transaksi PICA PI </strong> </div>';
						if($counttx > 0 || $counttx_foto_lkp > 0 || $counttx_foto_morfologi > 0 || $counttx_foto_drone > 0 || $countmaster_petak > 0 || $countpetakpupuk > 0){
							$values[$field['field']] .= ' <button type="button" class="btn btn-success btn-xs btnubah"  onclick="setpetak(`'.$row->petak_lama.'`,`'.$row->petak_baru.'`)"><i class="fa fa-refresh"></i> Ubah Sekarang</button>';
						}
						$values[$field['field']] .= '</div>';
						}else{
							$values[$field['field']] = '<div class="alert-success p-2" style="width:fit-content""> Petak Lama Sama dengan Petak Baru</div>';
						}
					}else{
						$values[$field['field']] = \SiteHelpers::formatRows($row->{$field['field']}, $field , $row);
					}
					
				}	
			}
			$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')
			));

		} 		

	}

	static function makeInfo2( $id )
	{	
		$row =  \DB::table('tb_module')->where('module_name', $id)->get();
		$data = array();
		foreach($row as $r)
		{
			$langs = (json_decode($r->module_lang,true));
			$data['id']		= $r->module_id; 
			$data['title'] 	= \SiteHelpers::infoLang($r->module_title,$langs,'title'); 
			$data['note'] 	= \SiteHelpers::infoLang($r->module_note,$langs,'note'); 
			$data['table'] 	= $r->module_db; 
			$data['key'] 	= $r->module_db_key;
			$data['type'] 	= $r->module_type;
			$data['config'] = \SiteHelpers::CF_decode_json($r->module_config);
			$field = array();	
			foreach($data['config']['grid'] as $fs)
			{
				foreach($fs as $f)
					$field[] = $fs['field']; 	
									
			}
			$data['field'] = $field;	
			$data['setting'] = array(
				'gridtype'		=> (isset($data['config']['setting']['gridtype']) ? $data['config']['setting']['gridtype'] : 'native'  ),
				'orderby'		=> (isset($data['config']['setting']['orderby']) ? $data['config']['setting']['orderby'] : $r->module_db_key),
				'ordertype'		=> (isset($data['config']['setting']['ordertype']) ? $data['config']['setting']['ordertype'] : 'asc'  ),
				'perpage'		=> (isset($data['config']['setting']['perpage']) ? $data['config']['setting']['perpage'] : '10'  ),
				'frozen'		=> (isset($data['config']['setting']['frozen']) ? $data['config']['setting']['frozen'] : 'false'  ),
	            'form-method'   => (isset($data['config']['setting']['form-method'])  ? $data['config']['setting']['form-method'] : 'native'  ),
	            'view-method'   => (isset($data['config']['setting']['view-method'])  ? $data['config']['setting']['view-method'] : 'native'  ),
	            'inline'        => (isset($data['config']['setting']['inline'])  ? $data['config']['setting']['inline'] : 'false'  ),				
				
			);			
					
		}
		return $data;
			
	
	} 

	public function cekdatapetak(Request $request)
	{
		if (!\Auth::check()) {
			return response()->json([
				'status' => 'error',
				'message' => 'You are not logged in'
			]);
		}

		$dataPetak = \DB::table('master_petak')->where('lahan_id', $request->input('petak_lama'))->first();

		if ($dataPetak === null) {
			return response()->json([
				'status' => 'error',
				'message' => 'No data found for the given lahan_id'
			]);
		}

		return response()->json([
			'status' => 'success',
			'data' => $dataPetak
		]);
	}

	public function ubahdatapetak(Request $request)
	{
		if (!\Auth::check()) {
			return response()->json([
				'status' => 'error',
				'message' => 'You are not logged in'
			]);
		}

		$oldIdLahan = $request->input('idlama');
		$newIdLahan = $request->input('idbaru');

		if (empty($oldIdLahan) || empty($newIdLahan)) {
			return response()->json([
				'status' => 'error',
				'message' => 'Both old_id_lahan and new_id_lahan are required'
			]);
		}

		try {
			\DB::table('TX_TOTAL_KSO')
				->where('id_lahan', $oldIdLahan)
				->update(['id_lahan' => $newIdLahan]);
			
			\DB::table('master_petak')
			->where('lahan_id', $oldIdLahan)
			->update(['lahan_id' => $newIdLahan]);	

			\DB::table('tx_foto_kebun')
				->where('lahan_id', $oldIdLahan)
				->update(['lahan_id' => $newIdLahan]);

			\DB::table('tx_morfologi')
				->where('lahan_id', $oldIdLahan)
				->update(['lahan_id' => $newIdLahan]);

			\DB::table('tx_foto_drone')
				->where('lahan_id', $oldIdLahan)
				->update(['lahan_id' => $newIdLahan]);

			\DB::table('t_distribusi_pupuk_herbisida')
				->where('petak', $oldIdLahan)
				->update(['petak' => $newIdLahan]);	

			\DB::table('m_petak_pupuk')
				->where('lahan_id', $oldIdLahan)
				->update(['lahan_id' => $newIdLahan]);		
			
			\DB::table('tx_tebu_berbunga')
				->where('lahan_id', $oldIdLahan)
				->update(['lahan_id' => $newIdLahan]);			

			\DB::table('tx_serangan_hpt')
				->where('lahan_id', $oldIdLahan)
				->update(['lahan_id' => $newIdLahan]);		
			
			\DB::table('tx_tebu_roboh')
				->where('lahan_id', $oldIdLahan)
				->update(['lahan_id' => $newIdLahan]);		
			
			\DB::table('tx_pica_pi')
			->where('lahan_id', $oldIdLahan)
			->update(['lahan_id' => $newIdLahan]);		

			return response()->json([
				'status' => 'success',
				'message' => 'Data successfully updated'
			]);
		} catch (\Exception $e) {
			return response()->json([
				'status' => 'error',
				'message' => 'An error occurred: ' . $e->getMessage()
			]);
		}
	}
}