<?php namespace App\Http\Controllers;

use App\Models\Monitoringbudgetsap;
use App\Library\DataHelpers;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ; 

class MonitoringbudgetsapController extends Controller {

	protected $layout = "layouts.main";
	protected $data = array();	
	public $module = 'monitoringbudgetsap';
	static $per_page	= '10';
	
	public function __construct() 
	{
		parent::__construct();
		$this->model = new Monitoringbudgetsap();
		
		$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'		=> 'monitoringbudgetsap',
			'pageUrl'			=>  url('monitoringbudgetsap'),
			'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('monitoringbudgetsap.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 'getMonitoringDataForm':
				return $this->getMonitoringDataForm( $request );
				break;
			case 'getMonitoringData':
				return $this->getMonitoringData( $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)
	{ 
		
		$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')
				{
					$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')
			));

		} 		

	}

	public function getMonitoringDataForm(Request $request)
	{
		
		$this->data['pageTitle'] = 'Monitoring Budget SAP';
		$this->data['pageNote'] = 'Form untuk melihat monitoring budget SAP berdasarkan kode kebun, tanggal bibit, dan jenjang BMT.';
		$this->data['row'] = $this->model->getColumnTable($this->info['table']);
		$this->data['setting'] = $this->info['setting'];
		$this->data['action'] = 'getMonitoringData';
		
		return view($this->module.'.monitoring-form', $this->data);
	}
		public function getMonitoringData(Request $request)
	{
		$kebun = $request->input('kebun');
		$tg = $request->input('tg');
		$mt = $request->input('mt');

		try {
			$results = \DB::select("CALL sp_monitoring_budget_sap(?, ?, ?)", [$kebun, $tg, $mt]);

			if (empty($results)) {
				$html  = '<div class="alert alert-warning d-flex align-items-center mt-3" role="alert">';
				$html .= '  <i class="fas fa-exclamation-triangle me-2 fs-4"></i>';
				$html .= '  <div><strong>Data Tidak Ditemukan!</strong><br><small>Tidak ada data untuk filter yang dipilih.</small></div>';
				$html .= '</div>';
				return response()->json(['status' => 'empty', 'html' => $html]);
			}

			$total = count($results);
			$selesai = count(array_filter($results, fn($r) => strtoupper(trim((string)$r->status)) === 'SELESAI'));
			$menungguAjuan = count(array_filter($results, fn($r) => strtoupper(trim((string)$r->ajuan_kebun)) !== 'SUDAH'));
			$belum = count(array_filter(
				$results,
				fn($r) => strtoupper(trim((string)$r->status)) !== 'SELESAI'
					&& strtoupper(trim((string)$r->ajuan_kebun)) === 'SUDAH'
			));

			// ── Summary Cards ──────────────────────────────────────────────
			$html  = '<div class="row g-3 mb-4 mt-1">';

			// Total Data
			$html .= '<div class="col-6 col-md-3">';
			$html .= '  <div class="card border-0 shadow-sm h-100" style="background: linear-gradient(135deg,#1e3c72,#2a5298);">';
			$html .= '    <div class="card-body d-flex align-items-center gap-3 text-white">';
			$html .= '      <div class="rounded-circle bg-opacity-25 p-3"><i class="fas fa-database fa-lg"></i></div>';
			$html .= '      <div><div class="fs-3 fw-bold">' . $total . '</div><div class="small opacity-75">Total Kebun</div></div>';
			$html .= '    </div>';
			$html .= '  </div>';
			$html .= '</div>';

			// Selesai
			$html .= '<div class="col-6 col-md-3">';
			$html .= '  <div class="card border-0 shadow-sm h-100" style="background: linear-gradient(135deg,#11998e,#38ef7d);">';
			$html .= '    <div class="card-body d-flex align-items-center gap-3 text-white">';
			$html .= '      <div class="rounded-circle bg-opacity-25 p-3"><i class="fas fa-check-circle fa-lg"></i></div>';
			$html .= '      <div><div class="fs-3 fw-bold">' . $selesai . '</div><div class="small opacity-75">Selesai</div></div>';
			$html .= '    </div>';
			$html .= '  </div>';
			$html .= '</div>';

			// Belum Selesai
			$html .= '<div class="col-6 col-md-3">';
			$html .= '  <div class="card border-0 shadow-sm h-100" style="background: linear-gradient(135deg,#dc3545,#ff6b6b);">';
			$html .= '    <div class="card-body d-flex align-items-center gap-3 text-white">';
			$html .= '      <div class="rounded-circle bg-opacity-25 p-3"><i class="fas fa-times-circle fa-lg"></i></div>';
			$html .= '      <div><div class="fs-3 fw-bold">' . $belum . '</div><div class="small opacity-75">Belum Selesai</div></div>';
			$html .= '    </div>';
			$html .= '  </div>';
			$html .= '</div>';

			// Menunggu Ajuan
			$html .= '<div class="col-6 col-md-3">';
			$html .= '  <div class="card border-0 shadow-sm h-100" style="background: linear-gradient(135deg,#f7971e,#ffd200);">';
			$html .= '    <div class="card-body d-flex align-items-center gap-3 text-white">';
			$html .= '      <div class="rounded-circle bg-opacity-25 p-3"><i class="fas fa-file-signature fa-lg"></i></div>';
			$html .= '      <div><div class="fs-3 fw-bold">' . $menungguAjuan . '</div><div class="small opacity-75">Menunggu Ajuan</div></div>';
			$html .= '    </div>';
			$html .= '  </div>';
			$html .= '</div>';

			$html .= '</div>'; // end row summary

			// ── Table Card ─────────────────────────────────────────────────
			$html .= '<div class="card border-0 shadow">';
			$html .= '  <div class="card-header d-flex justify-content-between align-items-center py-3" style="background: linear-gradient(135deg,#1e3c72,#2a5298);">';
			$html .= '    <span class="text-white fw-semibold fs-6"><i class="fas fa-table me-2"></i> Hasil Monitoring Budget SAP</span>';
			$html .= '    <span class="badge bg-light text-dark px-3 py-2"><i class="fas fa-list me-1"></i> ' . $total . ' Record</span>';
			$html .= '  </div>';
			$html .= '  <div class="card-body p-0">';
			$html .= '    <div class="table-responsive" style="max-height: 500px; overflow-y: auto; position: relative;">';
			$html .= '      <table id="rekap-table" class="table table-hover align-middle mb-0" style="position: relative;">';
			$html .= '        <thead style="position: sticky; top: 0; z-index: 10; background: #2a5298;">';
			$html .= '          <tr>';

			$headers = [
				'fa-hashtag'        => 'No',
				'fa-building'       => 'Kode Kebun',
				'fa-tree'           => 'Kebun',
				'fa-seedling'       => 'Tg Bibit',
				'fa-layer-group'    => 'Jenjang Bibit',
				'fa-calendar'       => 'MT',
				'fa-file-alt'       => 'Ajuan Kebun',
				'fa-calendar-alt'   => 'Tgl Surat Ajuan',
				'fa-cogs'           => 'Status OPS HO',
				'fa-envelope'       => 'Memo Ke BS',
				'fa-calendar-check' => 'Tgl Memo Ke BS',
				'fa-flag'           => 'Status',
			];

			foreach ($headers as $icon => $label) {
				$html .= '<th class="text-white fw-semibold px-3 py-3 text-nowrap" style="background: #2a5298; position: sticky; top: 0;">';
				$html .= '  <i class="fas ' . $icon . ' me-1 opacity-75"></i> ' . $label;
				$html .= '</th>';
			}

			$html .= '          </tr>';
			$html .= '        </thead>';
			$html .= '        <tbody>';

			foreach ($results as $index => $row) {
				$isAjuanSudah = strtoupper(trim((string)$row->ajuan_kebun)) === 'SUDAH';

				if ($row->ajuan_kebun == 'SUDAH') {
					$ajuanClass = 'success text-dark';
					$ajuanIcon  = 'fa-check-circle';
					$ajuanText  = 'SUDAH';
				} else if($row->ajuan_kebun == 'BELUM'){
					$ajuanClass = 'danger';
					$ajuanIcon  = 'fa-times-circle';
					$ajuanText  = 'BELUM';
				} else if($row->ajuan_kebun == 'MENUNGGU AJUAN'){
					$ajuanClass = 'warning text-dark';
					$ajuanIcon  = 'fa-hourglass-start';
					$ajuanText  = 'MENUNGGU AJUAN';
				}else if($row->ajuan_kebun == 'DIPROSES'){
					$ajuanClass = 'info text-dark';
					$ajuanIcon  = 'fa-check-circle';
					$ajuanText  = 'DIPROSES';
				}else if($row->ajuan_kebun == 'SELESAI'){
					$ajuanClass = 'success text-dark';
					$ajuanIcon  = 'fa-check-circle';
					$ajuanText  = 'SELESAI';
				}

				if ($row->status == 'SUDAH') {
					$statusClass = 'success text-dark';
					$statusIcon  = 'fa-check-circle';
					$statusText  = 'SUDAH';
				} else if($row->status == 'BELUM'){
					$statusClass = 'danger';
					$statusIcon  = 'fa-times-circle';
					$statusText  = 'BELUM';
				} else if($row->status == 'MENUNGGU AJUAN'){
					$statusClass = 'warning text-dark';
					$statusIcon  = 'fa-hourglass-start';
					$statusText  = 'MENUNGGU AJUAN';
				}else if($row->status == 'DIPROSES'){
					$statusClass = 'info text-dark';
					$statusIcon  = 'fa-check-circle';
					$statusText  = 'DIPROSES';
				}else if($row->status == 'SELESAI'){
					$statusClass = 'success text-dark';
					$statusIcon  = 'fa-check-circle';
					$statusText  = 'SELESAI';
				}

				if ($row->status_ops_ho == 'SUDAH') {
					$opsClass = 'success text-dark';
					$opsIcon  = 'fa-check-circle';
					$opsText  = 'SUDAH';
				} else if($row->status_ops_ho == 'BELUM'){
					$opsClass = 'danger';
					$opsIcon  = 'fa-times-circle';
					$opsText  = 'BELUM';
				} else if($row->status_ops_ho == 'MENUNGGU AJUAN'){
					$opsClass = 'warning text-dark';
					$opsIcon  = 'fa-hourglass-start';
					$opsText  = 'MENUNGGU AJUAN';
				}else if($row->status_ops_ho == 'DIPROSES'){
					$opsClass = 'info text-dark';
					$opsIcon  = 'fa-check-circle';
					$opsText  = 'DIPROSES';
				}else if($row->status_ops_ho == 'SELESAI'){
					$opsClass = 'success text-dark';
					$opsIcon  = 'fa-check-circle';
					$opsText  = 'SELESAI';
				}

				if ($row->memo_ke_bs == 'SUDAH') {
					$memoClass = 'success text-dark';
					$memoIcon  = 'fa-check-circle';
					$memoText  = 'SUDAH';
				} else if($row->memo_ke_bs == 'BELUM'){
					$memoClass = 'danger';
					$memoIcon  = 'fa-times-circle';
					$memoText  = 'BELUM';
				} else if($row->memo_ke_bs == 'MENUNGGU AJUAN'){
					$memoClass = 'warning text-dark';
					$memoIcon  = 'fa-hourglass-start';
					$memoText  = 'MENUNGGU AJUAN';
				}else if($row->memo_ke_bs == 'DIPROSES'){
					$memoClass = 'info text-dark';
					$memoIcon  = 'fa-check-circle';
					$memoText  = 'DIPROSES';
				}else if($row->memo_ke_bs == 'SELESAI'){
					$memoClass = 'success text-dark';
					$memoIcon  = 'fa-check-circle';
					$memoText  = 'SELESAI';
				}

				
				$rowBg = ($index % 2 === 0) ? 'background:#ffffff;' : 'background:#f8f9ff;';

				$html .= '<tr style="' . $rowBg . '" onmouseover="this.style.background=\'#e8f0fe\'" onmouseout="this.style.background=\'' . ($index % 2 === 0 ? '#ffffff' : '#f8f9ff') . '\'">';
				$html .= '<td class="px-3 py-2 text-center text-muted fw-bold">' . ($index + 1) . '</td>';
				$html .= '<td class="px-3 py-2"><span class="badge text-white px-2 py-1" style="background:#1e3c72;">' . htmlspecialchars((string)$row->kode_kebun) . '</span></td>';
				$html .= '<td class="px-3 py-2 fw-semibold text-dark">' . htmlspecialchars((string)$row->kebun) . '</td>';
				$html .= '<td class="px-3 py-2"><span class="badge bg-secondary text-white">' . htmlspecialchars((string)$row->tg_bibit) . '</span></td>';
				$html .= '<td class="px-3 py-2"><span class="badge bg-primary text-white">' . htmlspecialchars((string)$row->jenjang_bibit) . '</span></td>';
				$html .= '<td class="px-3 py-2 text-center"><span class="badge bg-dark text-white">' . htmlspecialchars((string)$row->mt) . '</span></td>';
				$html .= '<td class="px-3 py-2 text-center"><span class="badge bg-' . $ajuanClass . '"><i class="fas ' . $ajuanIcon . ' me-1"></i> ' . htmlspecialchars($ajuanText) . '</span></td>';
				$html .= '<td class="px-3 py-2 text-nowrap"><i class="fas fa-calendar text-muted me-1"></i> ' . htmlspecialchars((string)$row->tanggal_surat_ajuan) . '</td>';
				$html .= '<td class="px-3 py-2 text-center"><span class="badge bg-' . $opsClass . '"><i class="fas ' . $opsIcon . ' me-1"></i> ' . htmlspecialchars((string)$row->status_ops_ho) . '</span></td>';
				$html .= '<td class="px-3 py-2 text-center"><span class="badge bg-' . $memoClass . '"><i class="fas ' . $memoIcon . ' me-1"></i> ' . htmlspecialchars((string)$row->memo_ke_bs) . '</span></td>';
				$html .= '<td class="px-3 py-2 text-nowrap"><i class="fas fa-calendar-check text-muted me-1"></i> ' . htmlspecialchars((string)$row->tanggal_memo_ke_bs) . '</td>';
				$html .= '<td class="px-3 py-2 text-center"><span class="badge bg-' . $statusClass . ' px-2 py-1"><i class="fas ' . $statusIcon . ' me-1"></i> ' . htmlspecialchars($statusText) . '</span></td>';
				$html .= '</tr>';
			}

			$html .= '        </tbody>';
			$html .= '      </table>';
			$html .= '    </div>';
			$html .= '  </div>';
			$html .= '  <div class="card-footer bg-light d-flex justify-content-between align-items-center py-2 small text-muted">';
			$html .= '    <span><i class="fas fa-database me-1"></i>Sumber: <code>sp_monitoring_budget_sap</code></span>';
			$html .= '    <span><i class="fas fa-sync-alt me-1"></i>Diperbarui: ' . now()->format('d M Y, H:i') . ' WIB</span>';
			$html .= '  </div>';
			$html .= '</div>';

			return response()->json(['status' => 'success', 'html' => $html]);

		} catch (\Exception $e) {
			$html  = '<div class="alert alert-danger d-flex align-items-center mt-3" role="alert">';
			$html .= '  <i class="fas fa-exclamation-circle me-2 fs-4"></i>';
			$html .= '  <div><strong>Terjadi Kesalahan!</strong><br><small>' . htmlspecialchars($e->getMessage()) . '</small></div>';
			$html .= '</div>';
			return response()->json(['status' => 'error', 'html' => $html]);
		}
	}

}