<?php namespace App\Http\Controllers;

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


class MonitoringpicaController extends Controller {

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

	public function __construct()
	{
		
		parent::__construct();
		$this->model = new Monitoringpica();
		$this->info = $this->model->makeInfo( $this->module);
		$this->access = array();
	
		$this->data = array_merge(array(
			'pageTitle'	=> 	$this->info['title'],
			'pageNote'	=>  $this->info['note'],
			'pageModule'=> 'monitoringpica',
			'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');
		// Render into template
		$this->data['total_petak'] = \DB::table('master_petak')->count();

		$this->data['total_pica'] = \DB::table('tx_pica_pi as a')
			->join('tx_pica_pi_problem as b', 'b.id_pica_pi', '=', 'a.id')
			->select('a.lahan_id')
			->distinct()
			->groupBy('a.lahan_id')
			->get()
			->count();

		$this->data['total_pica_corrective'] = \DB::table('tx_pica_pi as a')
			->join('tx_pica_pi_problem as b', 'b.id_pica_pi', '=', 'a.id')
			->join('tx_pica_pi_corrective as c', 'c.id_pica_pi_problem', '=', 'b.id_problem')
			->select('a.lahan_id')
			->distinct()
			->groupBy('a.lahan_id')
			->get()
			->count();

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

	public function getDataByParams(Request $request)
	{
		$kode_afd = $request->input('kode_afd', '');
		$problem_group = $request->input('problem_group', '');
		$area_problem = $request->input('area', '');

		$results = \DB::table('tx_pica_pi as a')
			->join('tx_pica_pi_problem as b', 'b.id_pica_pi', '=', 'a.id')
			->join('master_problem_pica as c', 'c.id', '=', 'b.id_problem')
			->join('master_petak as d', 'd.lahan_id', '=', 'a.lahan_id')
			->join('master_kebun as e', function($join) {
				$join->on('e.kode_kebun', '=', \DB::raw('d.plant COLLATE utf8mb4_unicode_ci'));
			})
			->join('master_rayon as f', function($join) {
				$join->on('f.kode_rayon', '=', \DB::raw('d.kode_rayon COLLATE utf8mb4_unicode_ci'));
			})
			->join('master_afd as g', 'g.kode_afd', '=', 'd.afd_new')
			->select(
				'e.kode_kebun',
				'f.kode_rayon',
				'g.kode_afd',
				'a.lahan_id',
				'c.problem',
				'a.problem_group',
				'a.area_problem',
				'b.id_problem'
			)
			->where('g.kode_afd', $kode_afd)
			->where('a.problem_group', $problem_group)
			->where('a.area_problem', $area_problem)
			->groupBy('c.problem')
			->distinct()
			->get();

		if ($results->isEmpty()) {
			$html = '<div style="background:linear-gradient(90deg,#6dd5ed,#2193b0);border-radius:12px;padding:32px;box-shadow:0 4px 16px rgba(33,147,176,0.12);width:100%;margin:32px auto;color:#fff;">';
			$html .= '<p style="color:#f1f1f1;font-size:18px;display:flex;align-items:center;"><span style="margin-right:10px;"><svg width="24" height="24" fill="#fff" viewBox="0 0 24 24"><path d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm1 15h-2v-2h2zm0-4h-2V7h2z"/></svg></span>Tidak ada data problem yang ditemukan berdasarkan filter yang dipilih.</p>';
			$html .= '</div>';
		} else {
			$html = '<div style="background:linear-gradient(90deg,#6dd5ed,#2193b0);border-radius:12px;padding:32px;box-shadow:0 4px 16px rgba(33,147,176,0.12);width:100%;margin:32px auto;color:#fff;">';
			$html .= '<p style="color:#f1f1f1;font-size:18px;display:flex;align-items:center;"><span style="margin-right:10px;"><svg width="24" height="24" fill="#fff" viewBox="0 0 24 24"><path d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm1 15h-2v-2h2zm0-4h-2V7h2z"/></svg></span>Berikut adalah problem yang terjadi berdasarkan filter yang dipilih:</p>';
			$html .= '<ul style="padding-left:24px;margin-top:18px;">';
			foreach ($results as $row) {
				$html .= '<li onclick="SximoModal(\'monitoringpica/getTableDataByParams?' . http_build_query(['kode_afd' => $kode_afd, 'problem_group' => $problem_group, 'area' => $area_problem,'id_problem' => $row->id_problem]) . '\',\'' . htmlspecialchars($row->problem) . '\')" style="margin-bottom:12px;font-size: 19px;cursor: pointer;display:flex;align-items:center;"><span style="margin-right:8px;"><svg width="18" height="18" fill="#e74c3c" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><text x="12" y="16" text-anchor="middle" font-size="12" fill="#fff">!</text></svg></span><span style="font-weight:500;">' . htmlspecialchars($row->problem) . '</span></li>';
			}
			$html .= '</ul>';
			$html .= '</div>';
		}
		return response($html, 200)->header('Content-Type', 'text/html');
	}

	public function getColumnChartData(Request $request)
	{
		$kode_kebun = $request->input('kode_kebun', '');
		$problem_group = $request->input('problem_group', '');
		$area_problem = $request->input('area', '');

		$results = \DB::table('tx_pica_pi as a')
			->join('tx_pica_pi_problem as b', 'b.id_pica_pi', '=', 'a.id')
			->join('master_problem_pica as c', 'c.id', '=', 'b.id_problem')
			->join('master_petak as d', 'd.lahan_id', '=', 'a.lahan_id')
			->join('master_kebun as e', function($join) {
				$join->on('e.kode_kebun', '=', \DB::raw('d.plant COLLATE utf8mb4_unicode_ci'));
			})
			->join('master_rayon as f', function($join) {
				$join->on('f.kode_rayon', '=', \DB::raw('d.kode_rayon COLLATE utf8mb4_unicode_ci'));
			})
			->join('master_afd as g', 'g.kode_afd', '=', 'd.afd_new')
			->select('c.problem', \DB::raw('COUNT(DISTINCT a.lahan_id) as jumlah_petak'))
			->where('e.kode_kebun', $kode_kebun)
			->where('a.problem_group', $problem_group)
			->where('a.area_problem', $area_problem)
			->groupBy('c.problem')
			->get();

		$categories = [];
		$data = [];

		foreach ($results as $row) {
			$categories[] = $row->problem;
			$data[] = (int) $row->jumlah_petak;
		}

		return response()->json([
			'categories' => $categories,
			'data' => $data
		]);
	}

	public function getStackedColumnChartData(Request $request)
	{
		$kode_kebun = $request->input('kode_kebun', '');
		$problem_group = $request->input('problem_group', '');
		$area_problem = $request->input('area', '');

		$results = \DB::table('tx_pica_pi as a')
			->join('tx_pica_pi_problem as b', 'b.id_pica_pi', '=', 'a.id')
			->join('master_problem_pica as c', 'c.id', '=', 'b.id_problem')
			->join('master_petak as d', 'd.lahan_id', '=', 'a.lahan_id')
			->join('master_kebun as e', function($join) {
				$join->on('e.kode_kebun', '=', \DB::raw('d.plant COLLATE utf8mb4_unicode_ci'));
			})
			->join('master_rayon as f', function($join) {
				$join->on('f.kode_rayon', '=', \DB::raw('d.kode_rayon COLLATE utf8mb4_unicode_ci'));
			})
			->join('master_afd as g', 'g.kode_afd', '=', 'd.afd_new')
			->select(
				'f.nama_rayon',
				'c.problem',
				\DB::raw('COUNT(DISTINCT a.lahan_id) as jumlah_petak')
			)
			->where('e.kode_kebun', $kode_kebun)
			->where('a.problem_group', $problem_group)
			->where('a.area_problem', $area_problem)
			->groupBy('f.nama_rayon', 'c.problem')
			->get();

		$rayons = [];
		$problems = [];
		$dataMap = [];

		foreach ($results as $row) {
			$rayons[$row->nama_rayon] = true;
			$problems[$row->problem] = true;
			$dataMap[$row->problem][$row->nama_rayon] = (int) $row->jumlah_petak;
		}

		$categories = array_keys($rayons);
		$series = [];
		foreach (array_keys($problems) as $problem) {
			$data = [];
			foreach ($categories as $rayon) {
				$data[] = isset($dataMap[$problem][$rayon]) ? $dataMap[$problem][$rayon] : 0;
			}
			$series[] = [
				'name' => $problem,
				'data' => $data
			];
		}

		return response()->json([
			'categories' => $categories,
			'series' => $series
		]);
	}

	public function getTableDataByParams(Request $request)
	{
		$kode_afd = $request->input('kode_afd', '');
		$problem_group = $request->input('problem_group', '');
		$area_problem = $request->input('area', '');
		$id_problem = $request->input('id_problem', '');

		$results = \DB::table('tx_pica_pi as a')
			->join('tx_pica_pi_problem as b', 'b.id_pica_pi', '=', 'a.id')
			->join('master_problem_pica as c', 'c.id', '=', 'b.id_problem')
			->join('master_petak as d', 'd.lahan_id', '=', 'a.lahan_id')
			->join('master_kebun as e', function($join) {
				$join->on('e.kode_kebun', '=', \DB::raw('d.plant COLLATE utf8mb4_unicode_ci'));
			})
			->join('master_rayon as f', function($join) {
				$join->on('f.kode_rayon', '=', \DB::raw('d.kode_rayon COLLATE utf8mb4_unicode_ci'));
			})
			->join('master_afd as g', 'g.kode_afd', '=', 'd.afd_new')
			->select(
				'a.lahan_id',
				'd.nama_kebun',
				'd.luas_polig as luas_ha',
				'c.problem'
			)
			->where('g.kode_afd', $kode_afd)
			->where('a.problem_group', $problem_group)
			->where('a.area_problem', $area_problem)
			->where('b.id_problem', $id_problem)
			->distinct()
			->get();

		$html = '<table border="0" cellpadding="0"  cellspacing="0" style="width:100%;border-collapse:collapse;margin:24px 0;background:#fff;border-radius:12px;box-shadow:0 4px 16px rgba(33,147,176,0.12);" class="table table-responsive">';
		$html .= '<thead style="background:linear-gradient(90deg,#6dd5ed,#2193b0);color:#fff;">';
		$html .= '<tr>';
		$html .= '<th style="padding:14px;">Lahan ID</th>';
		$html .= '<th style="padding:14px;">Nama Kebun</th>';
		$html .= '<th style="padding:14px;">Luas (Ha)</th>';
		$html .= '<th style="padding:14px;">Problem</th>';
		$html .= '<th style="padding:14px;">Action</th>';
		$html .= '</tr></thead><tbody>';

		if ($results->isEmpty()) {
			$html .= '<tr><td colspan="5" style="text-align:center;color:#e74c3c;padding:32px;">';
			$html .= '<span style="display:inline-flex;align-items:center;"><svg width="28" height="28" fill="#e74c3c" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><text x="12" y="16" text-anchor="middle" font-size="12" fill="#fff">!</text></svg> <span style="margin-left:10px;">Tidak ada data ditemukan.</span></span>';
			$html .= '</td></tr>';
		} else {
			foreach ($results as $row) {
				$html .= '<tr style="border-bottom:1px solid #f1f1f1;">';
				$html .= '<td style="padding:12px;">' . htmlspecialchars($row->lahan_id) . '</td>';
				$html .= '<td style="padding:12px;">' . htmlspecialchars($row->nama_kebun) . '</td>';
				$html .= '<td style="padding:12px;"><span style="background:#e0eafc;color:#2193b0;padding:6px 14px;border-radius:8px;font-weight:500;box-shadow:0 2px 8px rgba(33,147,176,0.08);display:inline-block;">' . htmlspecialchars($row->luas_ha) . '</span></td>';
				$html .= '<td style="padding:12px;"><span style="display:inline-flex;align-items:center;"><svg width="18" height="18" fill="#e74c3c" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><text x="12" y="16" text-anchor="middle" font-size="12" fill="#fff">!</text></svg><span style="margin-left:7px;">' . htmlspecialchars($row->problem) . '</span></span></td>';
				$html .= '<td style="padding:12px;text-align:center;"><button onclick="SximoModal2(\'monitoringpica/getCorrectiveTableData?' . http_build_query(['lahan_id' => $row->lahan_id, 'id_problem' => $id_problem]) . '\',\'Corrective Action\')" style="padding:8px 18px;background:linear-gradient(90deg,#27ae60,#6dd5ed);color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600;box-shadow:0 2px 8px rgba(39,174,96,0.08);transition:background 0.2s;">Lihat Corrective Action</button></td>';
				$html .= '</tr>';
			}
		}

		$html .= '</tbody></table>';

		return response($html, 200)->header('Content-Type', 'text/html');
	}

	public function getCorrectiveTableData(Request $request)
	{
								config(['app.debug' => true]);
		$lahan_id = $request->input('lahan_id', '');
		$id_problem = $request->input('id_problem', '');

		$results = \DB::table('tx_pica_pi_corrective as a')
			->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_problem_pica as e', 'e.id', '=', 'b.id_problem')
			->join('master_corective_pica as f', 'f.id', '=', 'a.id_corrective')
			->leftJoin('tx_pica_pi_corrective_action as d', 'a.id', '=', 'd.id_pica_pi_correction')
			->select(
				'c.lahan_id',
				'e.problem',
				'f.corrective',
				'a.tanggal_target',
				'a.persen_target',
				'd.tgl_penyelesaian',
				'd.persen_peyelesaian',
				'd.keterangan',
				'd.foto'
			)
			->where('c.lahan_id', $lahan_id)
			->where('b.id_problem', $id_problem)
			->groupBy('a.id')
			->get();

		$html = '<table border="0" cellpadding="0" cellspacing="0" style="width:100%;border-collapse:collapse;margin:24px 0;background:#fff;border-radius:12px;box-shadow:0 4px 16px rgba(33,147,176,0.12);" class="table table-responsive">';
		$html .= '<thead style="background:linear-gradient(90deg,#6dd5ed,#2193b0);color:#fff;">';
		$html .= '<tr>';
		$html .= '<th style="padding:14px;">Lahan ID</th>';
		$html .= '<th style="padding:14px;">Problem</th>';
		$html .= '<th style="padding:14px;">Corrective</th>';
		$html .= '<th style="padding:14px;">Tanggal Target</th>';
		$html .= '<th style="padding:14px;">Persen Target</th>';
		$html .= '<th style="padding:14px;">Tgl Penyelesaian</th>';
		$html .= '<th style="padding:14px;">Persen Penyelesaian</th>';
		$html .= '<th style="padding:14px;">Keterangan</th>';
		$html .= '<th style="padding:14px;">Foto</th>';
		$html .= '</tr></thead><tbody>';

		if ($results->isEmpty()) {
			$html .= '<tr><td colspan="9" style="text-align:center;color:#e74c3c;padding:32px;">';
			$html .= '<span style="display:inline-flex;align-items:center;"><svg width="28" height="28" fill="#e74c3c" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><text x="12" y="16" text-anchor="middle" font-size="12" fill="#fff">!</text></svg> <span style="margin-left:10px;">Tidak ada data ditemukan.</span></span>';
			$html .= '</td></tr>';
		} else {
			foreach ($results as $row) {
				$html .= '<tr style="border-bottom:1px solid #f1f1f1;">';
				$html .= '<td style="padding:12px;">' . htmlspecialchars($row->lahan_id) . '</td>';
				$html .= '<td style="padding:12px;"><span style="display:inline-flex;align-items:center;"><svg width="18" height="18" fill="#e74c3c" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><text x="12" y="16" text-anchor="middle" font-size="12" fill="#fff">!</text></svg><span style="margin-left:7px;">' . htmlspecialchars($row->problem) . '</span></span></td>';
				$html .= '<td style="padding:12px;"><span style="display:inline-flex;align-items:center;"><svg width="18" height="18" fill="#27ae60" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><polyline points="8 12 11 15 16 10" fill="none" stroke="#fff" stroke-width="2"/></svg><span style="margin-left:7px;">' . htmlspecialchars($row->corrective) . '</span></span></td>';
				$html .= '<td style="padding:12px;"><span style="background:#f1f8e9;color:#388e3c;padding:6px 14px;border-radius:8px;font-weight:500;box-shadow:0 2px 8px rgba(56,142,60,0.08);display:inline-block;">' . ($row->tanggal_target ? date('d M Y', strtotime($row->tanggal_target)) : '-') . '</span></td>';
				// Persen Target Bar
				$persen_target = is_numeric($row->persen_target) ? (int)$row->persen_target : 0;
				$html .= '<td style="padding:12px;min-width:120px;"><div style="background:#e0eafc;border-radius:8px;overflow:hidden;height:22px;position:relative;"><div style="width:' . $persen_target . '%;background:linear-gradient(90deg,#2193b0,#6dd5ed);height:100%;border-radius:8px;"></div><span style="position:absolute;top:0;left:0;width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-weight:600;color:#FFF;">' . $persen_target . '%</span></div></td>';
				$html .= '<td style="padding:12px;">';
				if ($row->tgl_penyelesaian) {
					$html .= '<span style="background:#e3ffe3;color:#27ae60;padding:6px 14px;border-radius:8px;font-weight:500;box-shadow:0 2px 8px rgba(39,174,96,0.08);display:inline-block;">' . date('d M Y', strtotime($row->tgl_penyelesaian)) . '</span>';
				} else {
					$html .= '<span style="background:#f8d7da;color:#c0392b;padding:6px 14px;border-radius:8px;font-weight:500;box-shadow:0 2px 8px rgba(192,57,43,0.08);display:inline-block;">-</span>';
				}
				$html .= '</td>';
				// Persen Penyelesaian Bar
				$persen_penyelesaian = is_numeric($row->persen_peyelesaian) ? (int)$row->persen_peyelesaian : 0;
				$html .= '<td style="padding:12px;min-width:120px;"><div style="background:#e0eafc;border-radius:8px;overflow:hidden;height:22px;position:relative;"><div style="width:' . $persen_penyelesaian . '%;background:linear-gradient(90deg,#27ae60,#6dd5ed);height:100%;border-radius:8px;"></div><span style="position:absolute;top:0;left:0;width:100%;height:100%;display:flex;align-items:center;justify-content:center;font-weight:600;color:#FFF;">' . $persen_penyelesaian . '%</span></div></td>';
				$html .= '<td style="padding:12px;">' . htmlspecialchars($row->keterangan) . '</td>';
				if ($row->foto) {
					$html .= '<td style="padding:12px;"><img src="uploads/foto_pica/' . htmlspecialchars($row->foto) . '" alt="Foto" style="max-width:100px;max-height:100px;border-radius:8px;box-shadow:0 2px 8px rgba(33,147,176,0.12);"></td>';
				} else {
					$html .= '<td style="padding:12px;text-align:center;color:#aaa;">-</td>';
				}
				$html .= '</tr>';
			}
		}

		$html .= '</tbody></table>';

		return response($html, 200)->header('Content-Type', 'text/html');
	}

	public function formSasaranPicaKebun()
	{
		$this->data['pageTitle'] = 'Sasaran Pica Kebun';
		$this->data['pageNote'] = 'Form untuk melihat sasaran Pica di tingkat kebun berdasarkan kategori, area problem, dan problem group.';

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

	public function getSasaranPicaKebun(Request $request)
	{
		$kode_kebun = $request->input('kebun', '');
		$kategori = $request->input('kategori', '');
		$area_problem = $request->input('area', '');

		$results = \DB::select('CALL sp_sasaran_pica_kebun(?, ?, ?)', [
			$kode_kebun,
			$kategori,
			$area_problem
		]);

		$html = '<div style="overflow-x:auto;max-width:100vw;">';
		$html .= '<table id="sasaranPicaKebunTable" border="0" cellpadding="0" cellspacing="0" style="width:100%;border-collapse:collapse;margin:24px 0;background:#fff;border-radius:12px;box-shadow:0 4px 16px rgba(33,147,176,0.12);height: 600px;" class="table table-responsive">';
		$html .= '<thead style="background:linear-gradient(90deg,#6dd5ed,#2193b0);color:#fff;position:sticky;top:0;z-index:20;">';
		$html .= '<tr>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Kode Kebun</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Kategori</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Area Problem</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Problem</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Corrective Action</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Kuanta</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Satuan</th>';
		$html .= '<th style=""></th>';
		$html .= '<th style="padding:14px;background:#4CAF50;color:#fff;position:sticky;top:0;z-index:21;">Januari</th>';
		$html .= '<th style="padding:14px;background:#45a049;color:#fff;position:sticky;top:0;z-index:21;">Februari</th>';
		$html .= '<th style="padding:14px;background:#3d8b40;color:#fff;position:sticky;top:0;z-index:21;">Maret</th>';
		$html .= '<th style="padding:14px;background:#357a35;color:#fff;position:sticky;top:0;z-index:21;">April</th>';
		$html .= '<th style="padding:14px;background:#2d692b;color:#fff;position:sticky;top:0;z-index:21;">Mei</th>';
		$html .= '<th style="padding:14px;background:#FF9800;color:#fff;position:sticky;top:0;z-index:21;">Juni</th>';
		$html .= '<th style="padding:14px;background:#F57C00;color:#fff;position:sticky;top:0;z-index:21;">Juli</th>';
		$html .= '<th style="padding:14px;background:#E65100;color:#fff;position:sticky;top:0;z-index:21;">Agustus</th>';
		$html .= '<th style="padding:14px;background:#2196F3;color:#fff;position:sticky;top:0;z-index:21;">September</th>';
		$html .= '<th style="padding:14px;background:#1976D2;color:#fff;position:sticky;top:0;z-index:21;">Oktober</th>';
		$html .= '<th style="padding:14px;background:#1565C0;color:#fff;position:sticky;top:0;z-index:21;">November</th>';
		$html .= '<th style="padding:14px;background:#0D47A1;color:#fff;position:sticky;top:0;z-index:21;">Desember</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Jumlah</th>';
		$html .= '</tr></thead><tbody>';

		if (empty($results)) {
			$html .= '<tr><td colspan="21" style="text-align:center;color:#e74c3c;padding:32px;">';
			$html .= '<span style="display:inline-flex;align-items:center;"><svg width="28" height="28" fill="#e74c3c" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><text x="12" y="16" text-anchor="middle" font-size="12" fill="#fff">!</text></svg> <span style="margin-left:10px;">Tidak ada data ditemukan.</span></span>';
			$html .= '</td></tr>';
		} else {
			foreach ($results as $row) {
				$html .= '<tr style="border-bottom: 1.9px solid #bcbcbc;">';
				$html .= '<td style="padding:12px;position:sticky;left:0;background:#fff;z-index:10;">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
				$html .= '<td style="padding:12px;position:sticky;left:80px;background:#fff;z-index:10;">' . htmlspecialchars($row->kategori ?? '') . '</td>';
				$html .= '<td style="padding:12px;position:sticky;left:160px;background:#fff;z-index:10;white-space:break-spaces;">' . htmlspecialchars($row->area_problem ?? '') . '</td>';
				$html .= '<td style="padding:12px;position:sticky;left:240px;background:#fff;z-index:10;white-space:break-spaces;">' . htmlspecialchars($row->problem ?? '') . '</td>';
				$html .= '<td style="padding:12px;position:sticky;left:320px;background:#fff;z-index:10;white-space:break-spaces;">' . htmlspecialchars($row->corrective_action ?? '') . '</td>';
				$html .= '<td style="padding:12px;text-align:center;position:sticky;left:400px;background:#fff;z-index:10;">' . htmlspecialchars($row->kuanta ?? '') . '</td>';
				$html .= '<td style="padding:12px;position:sticky;left:480px;background:#fff;z-index:10;">' . htmlspecialchars($row->satuan ?? '') . '</td>';
				$html .= '<td><span class="tw-value">Sasaran</span><br>';
				$html .= '<span style="font-size:11px;color:#27ae60;font-weight:600;">Realisasi</span><br>';
				$html .= '<span style="font-size:10px;color:#666;">Persen Capaian</span>';
				$html .= '</td>';
			
				$months = ['januari', 'februari', 'maret', 'april', 'mei', 'juni', 'juli', 'agustus', 'september', 'oktober', 'november', 'desember'];
				foreach ($months as $month) {
					$realMonthProperty = 'real_' . $month;
					$keteranganProperty = 'ket_' . $month;
					$monthValue = (float)($row->$month ?? 0);
					$realValue = (float)($row->$realMonthProperty ?? 0);
					$percentage = $monthValue > 0 ? round(($realValue / $monthValue) * 100) : 0;
					
					$html .= '<td style="padding:12px;text-align:center;position:relative;" class="month-cell" data-month="' . $month . '" onmouseover="this.querySelector(\'.edit-btn\').style.display=\'' . ($monthValue > 0 ? 'inline-block' : 'none') . '\'" onmouseout="this.querySelector(\'.edit-btn\').style.display=\'none\'">';
					$html .= '<span class="month-value">' . number_format($monthValue, 1, ',', '.') . '</span><br>';
					$html .= '<span style="font-size:11px;color:#27ae60;font-weight:600;">' . number_format($realValue, 1, ',', '.') . '</span><br>';
					$html .= '<span style="font-size:10px;color:#666;">' . $percentage . '% ';
							if (!empty($row->$keteranganProperty)) {
								$html .= '<i class="fa fa-info-circle" style="cursor:pointer;margin-left:4px;" onclick="showKeteranganModal(\'' . htmlspecialchars($row->$keteranganProperty ?? '') . '\')" title="' . htmlspecialchars($row->$keteranganProperty ?? '-') . '"></i>';
							}
					$html .= '</span><br>';

					if ($monthValue > 0) {
						$html .= '<button type="button" class="edit-btn" style="display:none;padding:4px 8px;background:#2193b0;color:#fff;border:none;border-radius:3px;cursor:pointer;font-size:11px;margin-left:5px;" onclick="editMonthValue(\'' . $month . '\', ' . htmlspecialchars(json_encode($row)) . ')">Edit</button>';
					}
					$html .= '</td>';
				}
				
				$html .= '<td style="padding:12px;text-align:center;"><div>';
				$html .= '<span style="font-weight:600;">' . number_format((float)($row->jumlah ?? 0), 1, ',', '.') . '</span><br>';
				$html .= '<span style="font-size:11px;color:#27ae60;font-weight:600;">' . number_format((float)($row->jumlah_real ?? 0), 1, ',', '.') . '</span><br>';
				$jumlahTotal = (float)($row->jumlah ?? 0);
				$jumlahReal = (float)($row->jumlah_real ?? 0);
				$persenTotal = $jumlahTotal > 0 ? round(($jumlahReal / $jumlahTotal) * 100) : 0;
				$html .= '<span style="font-size:10px;color:#666;">' . $persenTotal . '%</span>';
				$html .= '</div></td>';
				$html .= '</tr>';
			}
		}

		$html .= '</tbody></table>';
		$html .= '</div>';
		
		$html .= '<div id="editMonthModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="editMonthModalLabel" aria-hidden="true">';
		$html .= '<div class="modal-dialog" role="document">';
		$html .= '<div class="modal-content">';
		$html .= '<div class="modal-header">';
		$html .= '<h5 class="modal-title" id="editMonthModalLabel">Edit Nilai Bulan</h5>';
		$html .= '<button type="button" class="close" data-dismiss="modal" aria-label="Close">';
		$html .= '<span aria-hidden="true">&times;</span>';
		$html .= '</button>';
		$html .= '</div>';
		$html .= '<div class="modal-body">';
		$html .= '<form id="editMonthForm">';
		$html .= '<div class="form-group">';
		$html .= '<label for="monthName">Bulan</label>';
		$html .= '<input type="text" class="form-control" id="monthName" disabled>';
		$html .= '</div>';
		$html .= '<div class="form-group">';
		$html .= '<label for="monthValue">Nilai Realisasi</label>';
		$html .= '<input type="number" class="form-control" id="monthValue" name="monthValue" required>';
		$html .= '</div>';
		$html .= '<div class="form-group">';
		$html .= '<label for="monthKeterangan">Keterangan</label>';
		$html .= '<input type="text" class="form-control" id="monthKeterangan" name="monthKeterangan">';
		$html .= '</div>';
		$html .= '<button type="button" id="saveMonthValueBtn" class="btn btn-primary">Simpan</button>';
		$html .= '</form>';
		$html .= '</div>';
		$html .= '</div>';
		$html .= '</div>';
		
		$html .= '<script>
			let currentRowData = {};
			let currentMonth = "";
			
			function editMonthValue(month, rowData) {
				currentRowData = rowData;
				currentMonth = month;
				document.getElementById("monthName").value = month.charAt(0).toUpperCase() + month.slice(1);
				document.getElementById("monthValue").value = rowData[month] || "0";
				$("#editMonthModal").modal("show");
			}
			
			document.getElementById("saveMonthValueBtn").addEventListener("click", function() {
				const newValue = document.getElementById("monthValue").value;
				const newKeterangan = document.getElementById("monthKeterangan").value;
				$.ajax({
					url: "'.url('monitoringpica?action_task=updateMonthValue').'",
					type: "POST",
					data: {
						kode_kebun: currentRowData.kode_kebun,
						kategori: currentRowData.kategori,
						area_problem: currentRowData.area_problem,
						problem: currentRowData.problem,
						corrective_action: currentRowData.corrective_action,
						month: currentMonth,
						value: newValue,
						keterangan: newKeterangan
					},
					success: function(response) {
						alert("Nilai berhasil diperbarui!");
						$("#editMonthModal").modal("hide");
						location.reload();
					},
					error: function() {
						alert("Terjadi kesalahan saat menyimpan nilai.");
					}
				});
			});

			function showKeteranganModal(keterangan) {
				alert("Keterangan: " + (keterangan || "Tidak ada keterangan"));
			}
		</script>';
		
		$html .= '<style>
			#sasaranPicaKebunTable th, #sasaranPicaKebunTable td {
				vertical-align: middle;
			}
			#sasaranPicaKebunTable thead th {
				position: sticky;
				top: 0;
				z-index: 21;
			}
			.month-cell {
				position: relative;
			}
			.edit-btn {
				transition: background 0.2s;
			}
			.edit-btn:hover {
				background: #1976D2 !important;
			}
		</style>';

		return response($html, 200)->header('Content-Type', 'text/html');
	}

	function updateMonthValue(Request $request)
	{
		$kode_kebun = $request->input('kode_kebun', '');
		$kategori = $request->input('kategori', '');
		$area_problem = $request->input('area_problem', '');
		$problem = $request->input('problem', '');
		$corrective_action = $request->input('corrective_action', '');
		$month = $request->input('month', '');
		$value = $request->input('value', 0);
		$keterangan = $request->input('keterangan', '');
		try {
			\DB::table('realisasi_pica_kebun')
			->updateOrInsert(
				[
					'kode_kebun' => $kode_kebun,
					'kategori' => $kategori,
					'area_problem' => $area_problem,
					'problem' => $problem,
					'corrective_action' => $corrective_action,
				],
				[
					$month => $value,
					'ket_' . $month => $keterangan,
					'updated_at' => now()
				]
			);

			return response()->json(['message' => 'Nilai berhasil diperbarui!']);
		} catch (\Exception $e) {
			return response()->json(['message' => 'Terjadi kesalahan saat menyimpan nilai.'], 500);
		}
	}

	public function formSasaranPicaKebunTriwulan()
	{
		$this->data['pageTitle'] = 'Sasaran Pica Kebun Triwulan';
		$this->data['pageNote'] = 'Form untuk melihat sasaran Pica di tingkat kebun berdasarkan triwulan, kategori, dan area problem.';

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

	public function getSasaranPicaKebunTriwulan(Request $request)
	{
		$kode_kebun = $request->input('kebun', '');
		$kategori = $request->input('kategori', '');
		$area_problem = $request->input('area', '');
		$triwulan = $request->input('triwulan', '');
		

		$results = \DB::select('CALL sp_pica_kebun_triwulan(?, ?, ?, ?)', [
			$kode_kebun,
			$kategori,
			$area_problem,
			$triwulan
		]);

		$html = '<div style="overflow-x:auto;max-width:100vw;">';
		$html .= '<table id="sasaranPicaKebunTriwulanTable" border="0" cellpadding="0" cellspacing="0" style="width:100%;border-collapse:collapse;margin:24px 0;background:#fff;border-radius:12px;box-shadow:0 4px 16px rgba(33,147,176,0.12);height: 600px;" class="table table-responsive">';
		$html .= '<thead style="background:linear-gradient(90deg,#6dd5ed,#2193b0);color:#fff;position:sticky;top:0;z-index:20;">';
		$html .= '<tr>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Kode Kebun</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Kategori</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Area Problem</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Problem</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Corrective Action</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Kuanta</th>';
		$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Satuan</th>';
		$html .= '<th style=""></th>';
		
		$triwulans = ['tw1', 'tw2', 'tw3', 'tw4'];
		$triwulanColors = ['#4CAF50', '#45a049', '#3d8b40', '#357a35'];
		$triwulanLabels = ['TW1', 'TW2', 'TW3', 'TW4'];
		$displayTriwulans = [];
		
		if (!empty($triwulan)) {
			$displayTriwulans = [$triwulan];
		} else {
			$displayTriwulans = $triwulans;
		}
		
		foreach ($displayTriwulans as $tw) {
			$index = array_search($tw, $triwulans);
			$html .= '<th style="padding:14px;background:#4CAF50;color:#fff;position:sticky;top:0;z-index:21;">' . $triwulanLabels[$index] . '</th>';
		}
		
		if (empty($triwulan)) {
			$html .= '<th style="padding:14px;color:#fff;position:sticky;top:0;z-index:21;background:#6dd5ed;">Jumlah</th>';
		}
		$html .= '</tr></thead><tbody>';

		if (empty($results)) {
			$colspanCount = 8 + count($displayTriwulans) + (empty($triwulan) ? 1 : 0);
			$html .= '<tr><td colspan="' . $colspanCount . '" style="text-align:center;color:#e74c3c;padding:32px;">';
			$html .= '<span style="display:inline-flex;align-items:center;"><svg width="28" height="28" fill="#e74c3c" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><text x="12" y="16" text-anchor="middle" font-size="12" fill="#fff">!</text></svg> <span style="margin-left:10px;">Tidak ada data ditemukan.</span></span>';
			$html .= '</td></tr>';
		} else {
			foreach ($results as $row) {
				$html .= '<tr style="border-bottom: 1.9px solid #bcbcbc;">';
				$html .= '<td style="padding:12px;position:sticky;left:0;background:#fff;z-index:10;">' . htmlspecialchars($row->kode_kebun ?? '') . '</td>';
				$html .= '<td style="padding:12px;position:sticky;left:80px;background:#fff;z-index:10;">' . htmlspecialchars($row->kategori ?? '') . '</td>';
				$html .= '<td style="padding:12px;position:sticky;left:160px;background:#fff;z-index:10;white-space:break-spaces;">' . htmlspecialchars($row->area_problem ?? '') . '</td>';
				$html .= '<td style="padding:12px;position:sticky;left:240px;background:#fff;z-index:10;white-space:break-spaces;">' . htmlspecialchars($row->problem ?? '') . '</td>';
				$html .= '<td style="padding:12px;position:sticky;left:320px;background:#fff;z-index:10;white-space:break-spaces;">' . htmlspecialchars($row->corrective_action ?? '') . '</td>';
				$html .= '<td style="padding:12px;text-align:center;position:sticky;left:400px;background:#fff;z-index:10;">' . htmlspecialchars($row->kuanta ?? '') . '</td>';
				$html .= '<td style="padding:12px;position:sticky;left:480px;background:#fff;z-index:10;">' . htmlspecialchars($row->satuan ?? '') . '</td>';
				$html .= '<td><span class="tw-value">Sasaran</span><br>';
				$html .= '<span style="font-size:11px;color:#27ae60;font-weight:600;">Realisasi</span><br>';
				$html .= '<span style="font-size:10px;color:#666;">Persen Capaian</span>';
				$html .= '</td>';

				foreach ($displayTriwulans as $tw) {
					$realTwProperty = 'real_' . $tw;
					$twValue = (int)($row->$tw ?? 0);
					$realValue = (int)($row->$realTwProperty ?? 0);
					$percentage = $twValue > 0 ? round(($realValue / $twValue) * 100) : 0;
					
					$html .= '<td style="padding:12px;text-align:center;position:relative;" class="tw-cell" data-triwulan="' . $tw . '" onmouseover="this.querySelector(\'.edit-btn\').style.display=\'' . ($twValue > 0 ? 'inline-block' : 'none') . '\'" onmouseout="this.querySelector(\'.edit-btn\').style.display=\'none\'">';
					$html .= '<span class="tw-value">' . number_format($twValue, 1, ',', '.') . '</span><br>';
					$html .= '<span style="font-size:11px;color:#27ae60;font-weight:600;">' . number_format($realValue, 1, ',', '.') . '</span><br>';
					$html .= '<span style="font-size:10px;color:#666;">' . $percentage . '%</span>';
					$html .= '</td>';
				}
				
				if (empty($triwulan)) {
					$html .= '<td style="padding:12px;text-align:center;"><div>';
					$jumlahTotal = (float)($row->jumlah ?? 0);
					$jumlahReal = (float)($row->jumlah_real ?? 0);
					$html .= '<span style="font-weight:600;">' . number_format($jumlahTotal, 1, ',', '.') . '</span><br>';
					$html .= '<span style="font-size:11px;color:#27ae60;font-weight:600;">' . number_format($jumlahReal, 1, ',', '.') . '</span><br>';
					$persenTotal = $jumlahTotal > 0 ? round(($jumlahReal / $jumlahTotal) * 100) : 0;
					$html .= '<span style="font-size:10px;color:#666;">' . $persenTotal . '%</span>';
					$html .= '</div></td>';
				}
				$html .= '</tr>';
			}
		}

		$html .= '</tbody></table>';
		$html .= '</div>';
		
		$html .= '<div id="editTriwulanModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="editTriwulanModalLabel" aria-hidden="true">';
		$html .= '<div class="modal-dialog" role="document">';
		$html .= '<div class="modal-content">';
		$html .= '<div class="modal-header">';
		$html .= '<h5 class="modal-title" id="editTriwulanModalLabel">Edit Nilai Triwulan</h5>';
		$html .= '<button type="button" class="close" data-dismiss="modal" aria-label="Close">';
		$html .= '<span aria-hidden="true">&times;</span>';
		$html .= '</button>';
		$html .= '</div>';
		$html .= '<div class="modal-body">';
		$html .= '<form id="editTriwulanForm">';
		$html .= '<div class="form-group">';
		$html .= '<label for="triwulanName">Triwulan</label>';
		$html .= '<input type="text" class="form-control" id="triwulanName" disabled>';
		$html .= '</div>';
		$html .= '<div class="form-group">';
		$html .= '<label for="triwulanValue">Nilai Realisasi</label>';
		$html .= '<input type="number" class="form-control" id="triwulanValue" name="triwulanValue" required>';
		$html .= '</div>';
		$html .= '<button type="button" id="saveTriwulanValueBtn" class="btn btn-primary">Simpan</button>';
		$html .= '</form>';
		$html .= '</div>';
		$html .= '</div>';
		$html .= '</div>';
		
		$html .= '<script>
			
		</script>';
		
		$html .= '<style>
			#sasaranPicaKebunTriwulanTable th, #sasaranPicaKebunTriwulanTable td {
				vertical-align: middle;
			}
			#sasaranPicaKebunTriwulanTable thead th {
				position: sticky;
				top: 0;
				z-index: 21;
			}
			.tw-cell {
				position: relative;
			}
		</style>';

		return response($html, 200)->header('Content-Type', 'text/html');
	}

	

	function show( Request $request , $id ) 
	{
		/* Handle import , export and view */
		$task =$id ;
		switch( $task)
		{

			case 'export':
				return $this->getExport( $request );
				break;
			case 'getDataByParams':
				return $this->getDataByParams( $request );
				break;
			case 'getColumnChartData':
				return $this->getColumnChartData( $request );
				break;
			case 'getStackedColumnChartData':
				return $this->getStackedColumnChartData( $request );
				break;
			case 'getTableDataByParams':
				return $this->getTableDataByParams( $request );
				break;
			case 'getCorrectiveTableData':
				return $this->getCorrectiveTableData( $request );
				break;
			case 'formSasaranPicaKebun':
				return $this->formSasaranPicaKebun( $request );
				break;
			case 'getSasaranPicaKebun':
				return $this->getSasaranPicaKebun( $request );
				break;	
			case 'formSasaranPicaKebunTriwulan':
				return $this->formSasaranPicaKebunTriwulan( $request );
				break;
			case 'getSasaranPicaKebunTriwulan':
				return $this->getSasaranPicaKebunTriwulan( $request );
				break;	

		}
	}

	function store( Request $request)
	{		

			$task = $request->input('action_task');
			switch ($task)
			{
				case 'updateMonthValue':
					return $this->updateMonthValue( $request );
					break;
			}

	}
}