<?php namespace App\Http\Controllers;

use App\Models\Pipica;
use App\Library\DataHelpers;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ; 
use Config;

class PipicaController extends Controller {

	protected $layout = "layouts.main";
	protected $data = array();	
	public $module = 'pipica';
	static $per_page	= '10';
	
	public function __construct() 
	{
		parent::__construct();
		$this->model = new Pipica();
		
		$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'		=> 'pipica',
			'pageUrl'			=>  url('pipica'),
			'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('pipica.index',$this->data);
	}

	public function indexmodal(Request $request)
	{
config(['app.debug' => true]);

		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'];
		$this->data['lahan_id'] = $request->input('lahan_id', '');
		return view('pipica.indexmodal',$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['lahan_id'] = $request->input('lahan_id', '');
		$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 'indexmodal':
				return $this->indexmodal( $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;		

		}
	}
	public function postData( $request)
	{ 

		config(['app.debug' => true]);

		$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);
		}

		if ($request->has('lahan_id') && $request->input('lahan_id') != '') {
			$lahanId = $request->input('lahan_id');
			$filter .= " AND lahan_id = '{$lahanId}'";
		}
		if ($request->has('afdeling') && $request->input('afdeling') != '') {
			$afdeling = $request->input('afdeling');
			$filter .= " AND master_petak.afd_new = '{$afdeling}'";
		}

		if(session('gid') > 2){
			$filter .= " AND master_petak.plant = '".substr(\Session::get('fid'), 0, 4)."'";
		}

		$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')
					{
						$problemCount = \DB::table('tx_pica_pi_problem')->where('id_pica_pi', $row->{$this->info['key']})->count();
						//list problem join master_problem_pica
						$listProblem = \DB::table('tx_pica_pi_problem as a')
							->select('a.*', 'b.problem')
							->join('master_problem_pica as b', 'b.id', '=', 'a.id_problem')
							->where('a.id_pica_pi', $row->{$this->info['key']})
							->get();
						
						

						if ($problemCount > 0) {
							//list problem berupa table dengan badge dan button
							$problemList = '<table class="" style="margin-bottom: 0;">';
							$problemList .= '<tbody>';
							foreach ($listProblem as $problem) {
								$correctiveCount = \DB::table('tx_pica_pi_corrective as a')
									->select('a.*', 'd.corrective')
									->join('tx_pica_pi_problem as b', 'b.id', '=', 'a.id_pica_pi_problem')
									->join('tx_pica_pi as c', 'c.id', '=', 'b.id_pica_pi')
									->join('master_corective_pica as d', 'd.id', '=', 'a.id_corrective')
									->where('c.id', $row->{$this->info['key']})
									->where('b.id', $problem->id)
									->groupBy('a.id')
									->get();
								$problemList .= '<tr style="    border-left: 3px solid #0255a9;">';
								$problemList .= '<td style="">';
								$problemList .= '<span class="badge badge-danger" style="font-size:12px; padding: 6px 10px; font-weight: 500; display: inline-block; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; max-width: 200px;"><i class="fa fa-exclamation-triangle"></i> ' . $problem->problem . '</span>';
								$problemList .= '</td>';
								$problemList .= '<td style="">';
								$problemList .= '<button class="btn btn-sm btn-success" style="font-size:11px; padding: 4px 10px;" onclick="SximoModal2(\'corretiveaction/create?id=' . $problem->id . '\', \'Tambah Corrective\')"><i class="fa fa-plus-circle"></i> Tambah Corrective</button>';
								$problemList .= '</td>';
								$problemList .= '</tr>';
								//list corrective berupa table row dengan badge dan button
								foreach ($correctiveCount as $corrective) {
									$selesaicount = \DB::table('tx_pica_pi_corrective_action as d')
									->join('tx_pica_pi_corrective as a', 'a.id', '=', 'd.id_pica_pi_correction')
									->join('tx_pica_pi_problem as b', 'b.id', '=', 'a.id_pica_pi_problem')
									->join('tx_pica_pi as c', 'c.id', '=', 'b.id_pica_pi')
									->where('c.id', $row->{$this->info['key']})
									->where('d.id_pica_pi_correction', $corrective->id)
									->groupBy('d.id')
									->get();

									if (count($selesaicount) > 0) {
										$countselesai = '<span class="badge badge-secondary" style="font-size:11px; padding: 4px 8px; margin-left: 6px;"><i class="fa fa-check-circle"></i> ' . count($selesaicount) . ' Selesai</span>';
									} else {
										$countselesai = '';
									}
									$problemList .= '<tr>';
									$problemList .= '<td style=" ">';
									$problemList .= '<span class="badge badge-warning" style="font-size:11px; padding: 5px 9px; font-weight: 500;"><i class="fa fa-arrow-right"></i> ' . $corrective->corrective . '</span>';
									$problemList .= '</td>';
									$problemList .= '<td style="">';
									$problemList .= '<button class="btn btn-sm btn-info" style="font-size:11px; " onclick="SximoModal(\'correctiveactiondone/create?id=' . $corrective->id . '\', \'Tambah Penyelesaian CA\')"><i class="fa fa-edit"></i> Selesaikan CA</button> '.$countselesai;
									$problemList .= '</td>';
									$problemList .= '</tr>';

								}

							}
							$problemList .= '</tbody>';
							$problemList .= '</table>';
							$values[$field['field']] = $problemList;

							
							// $values[$field['field']] =
							// 	'<button class="btn btn-sm btn-danger input-problem-btn" onclick="SximoModal(\'problemidentification/create?id=' . $row->{$this->info['key']} . '\', \'Tambah Problem\')">
							// 		<span class="badge badge-light">' . $problemCount . '</span> Problem <i class="fa fa-plus-circle "></i>
							// 	</button> <i class="fa fa-arrow-right"></i>
							// 		<button class="btn btn-sm btn-warning input-problem-btn" onclick="SximoModal(\'problemidentification/create?id=' . $row->{$this->info['key']} . '\', \'Tambah Problem\')"><span class="badge badge-warning" style="font-size:12px;"><span class="badge badge-light">' . $correctiveCount . '</span> Corrective</span>
							// 		</button>
							// 		<i class="fa fa-arrow-right"></i>
							// 		<button class="btn btn-sm btn-success input-problem-btn" onclick="SximoModal(\'picaselesai?id=' . $row->{$this->info['key']} . '\', \'Tambah Penyelesaian CA\')"><span class="badge badge-light">' . $selesaicount . '</span> Terselesaikan <i class="fa fa-plus-circle "></i></button>';
						} else {
							$values[$field['field']] =
								'<button class="btn btn-sm btn-default input-problem-btn" onclick="SximoModal(\'problemidentification/create?id=' . $row->{$this->info['key']} . '\', \'Tambah Problem\')">
									<i class="fa fa-exclamation-circle"></i> Problem
								</button>';
						}
					
					}else if($field['field'] == 'Deskripsi')
					{
						// Truncate description with tooltip for full text and nicer styling
						$desc = strip_tags($row->deskripsi);
						$short = (strlen($desc) > 120) ? substr($desc,0,120) . '...' : $desc;
						$escapedFull = htmlentities($desc, ENT_QUOTES, 'UTF-8');
						$escapedShort = htmlentities($short, ENT_QUOTES, 'UTF-8');
						$values[$field['field']] = '<div><div style="max-width:400px; white-space:normal;">'
							. '<span title="' . $escapedFull . '" style="display:block; color:#333;">' . $escapedShort . '</span>'
							. '</div></div>';
					}
					else if($field['field'] == 'Afdeling')
					{
						// Show afdeling as a colored badge for better visibility
						$afdeling = htmlentities($row->afdeling, ENT_QUOTES, 'UTF-8');
						$values[$field['field']] = '<div><span class="badge badge-pill" style="background:#17a2b8; color:#fff; padding:6px 10px; font-size:12px;">' . $afdeling . '</span></div>';
					}
					else if($field['field'] == 'tanggal')
					{
						// Show tanggal in a formatted way
						// $tanggal = \SiteHelpers::formatRows($row->tanggal, $field, $row);
						//format date to indonesian format example: 2023-08-15 to 15-08-2023
						$tanggal = date('d-m-Y', strtotime($row->tanggal));
						// tambah style div date yang menarik dan tambah icon kalender
						$values[$field['field']] = '<div><div style="max-width:400px; white-space:nowrap;"><i class="fa fa-calendar"></i> ' . $tanggal . '</div></div>';
					}
					else if($field['field'] == 'lahan_id')
					{
						$content = \SiteHelpers::formatRows($row->lahan_id, $field , $row);
						$values[$field['field']] = '<div><div style=" padding:8px 12px; border-radius:6px; border-left:3px solid #0066cc; font-weight:500;">' . $content . '</div></div>';
					}
					else if($field['field'] == 'deskripsi')
					{
						// Limit deskripsi text to a reasonable length
						$content = $row->deskripsi;
						$text = strip_tags($content);
						$maxLen = 50; // characters
						if(mb_strlen($text) > $maxLen) {
							$text = mb_substr($text, 0, $maxLen) . '...';
						}
						$values[$field['field']] = '<div><div style="max-width:400px; white-space:normal;">' . htmlentities($text, ENT_QUOTES, 'UTF-8') . '</div></div>';
					}
					else if($field['field'] == 'problem_group')
					{
						$content = \SiteHelpers::formatRows($row->problem_group, $field , $row);
						$content = preg_replace('/<\/?p\b[^>]*>/i', ' ', $content);
						$content = trim(strip_tags($content));
						$values[$field['field']] = '<div><span style="background:#e8f4f8; color:#0066cc; padding:6px 12px; border-radius:20px; font-size:12px; font-weight:600; display:inline-block;">' . $content . '</span></div>';
					}
					else if($field['field'] == 'area_problem')
					{
						$content = \SiteHelpers::formatRows($row->area_problem, $field , $row);
						$content = preg_replace('/<\/?p\b[^>]*>/i', ' ', $content);
						$content = trim(strip_tags($content));
						$values[$field['field']] = '<div><span style="background:#fff3cd; color:#856404; padding:6px 12px; border-radius:20px; font-size:12px; font-weight:600; display:inline-block;">' . $content . '</span></div>';
					}
					else{
						//tambah style div
						$values[$field['field']] = '<div><div style="max-width:400px; white-space:normal;">' . \SiteHelpers::formatRows($row->{$field['field']}, $field , $row) . '</div></div>';
					}

				}	
			}
			
			$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')
			));

		} 		

	}
}