<?php namespace App\Http\Controllers;

use App\Models\Petakebun;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Illuminate\Support\Facades\DB;
use Validator, Input, Redirect ; 


class PetakebunController extends Controller {

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

	public function __construct()
	{
		
		parent::__construct();
		$this->model = new Petakebun();
		$this->info = $this->model->makeInfo( $this->module);
		$this->access = array();
	
		$this->data = array_merge(array(
			'pageTitle'	=> 	$this->info['title'],
			'pageNote'	=>  $this->info['note'],
			'pageModule'=> 'petakebun',
			'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');
		$fileMap = DB::table('master_peta_kebun')->select('file_map', 'updatedOn')->first();
		$this->data['file_map'] = $fileMap->file_map;
		$this->data['file_map_updatedOn'] = date('d-m-Y H:i:s', strtotime($fileMap->updatedOn));
		// $this->grab( $request) ;
		// if($this->access['is_view'] ==0) 
			// return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');				
		// Render into template
		return view( $this->module.'.index',$this->data);
	}	
	function show( Request $request , $id ) 
	{
		/* Handle import , export and view */
		$task =$id ;
		switch( $task)
		{

			case 'export':
				return $this->getExport( $request );
				break;
			case 'getlokasikantor':
				return $this->getlokasikantor( $request );
				break;
			case 'getfoto':
				return $this->getfoto( $request );
				break;		
			case 'cekmapidlahannonfilter':
				return $this->cekmapidlahannonfilter( $request );
				break;	
			case 'getGisPetak':
				return $this->getGisPetak( $request );
				break;	
	
		}
	}

	public function store( Request $request){

		$task = $request->input('action_task');
		switch ($task)
		{
			default:
				return $this->postData( $request);
				break;
			case 'import':
				return $this->importExcel( $request );
				break;
			case 'cekmapidlahan':
				return $this->cekmapidlahan( $request );
				break;
			case 'uploadfoto':
				return $this->uploadfoto( $request );
				break;		
			case 'cekmapidlahannonfilter':
				return $this->cekmapidlahannonfilter( $request );
				break;
			case 'cekmapidlahanlkp':
				return $this->cekmapidlahanlkp( $request );	
				break;
			case 'cekmapidlahancluster':
				return $this->cekmapidlahancluster( $request );	
				break;	

		}
	}

	function getlokasikantor( Request $request )
	{
		$lokasikantor = DB::table('koordinat_kebun')
			->select('Kebun','Kategori', 'Latitude', 'Longitude')
			->get();
	
		return response()->json($lokasikantor);
	}

	function cekmapidlahan(Request $request)
	{
		$lahanIds = $request->input('lahan_ids');

		if(\Session::get('tahuntanam') == "2526"){
			$datapetak = DB::table('q_prod_rekap_mejatebu_petak_aff as p')
				->select(
					DB::raw('COALESCE(p.ket_aff_manual, p.ket_aff_auto) as ket_aff_manual'),
					'p.id_lahan',
					'p.protas_aff',
					DB::raw('GROUP_CONCAT(f.foto) as foto'),
					DB::raw('GROUP_CONCAT(date(f.createdOn)) as tgl_foto')
				)
				->leftJoin('tx_foto_tebangan_lahan as f', function($join) {
					$join->on('f.lahan_id', '=', 'p.id_lahan');
				})
				->whereIn('p.id_lahan', $lahanIds)
				->groupBy('p.id_lahan', 'p.ket_aff_manual', 'p.ket_aff_auto', 'p.protas_aff')
				->get();


		}else if(\Session::get('tahuntanam') == "2627"){
			$datapetak = DB::table('master_petak as p')
			->select(
				DB::raw('0 as ket_aff_manual, p.lahan_id as id_lahan, 0 as protas_aff'),
				DB::raw('GROUP_CONCAT(f.foto) as foto'),
				DB::raw('GROUP_CONCAT(date(f.createdOn)) as tgl_foto')
			)
			->leftJoin('tx_foto_tebangan_lahan as f', function($join) {
				$join->on('f.lahan_id', '=', 'p.lahan_id');
			})
			->whereIn('p.lahan_id', $lahanIds)
			->groupBy('p.lahan_id')
			->get();

		}else{
			$datapetak = DB::table('master_petak as p')
			->whereIn('p.lahan_id', $lahanIds)
			->get();

		}

		

		$response = [];
		if ($datapetak->isNotEmpty()) {
			foreach ($datapetak as $data) {
				// Status warna dan realisasi
				if (!empty($data->ket_aff_manual)) {
					$response[$data->id_lahan] = 'red';
					$response['real_'.$data->id_lahan] = $data->protas_aff;
				} elseif (empty($data->ket_aff_manual) && !empty($data->id_lahan)) {
					$response[$data->id_lahan] = 'yellow';
					$response['real_'.$data->id_lahan] = $data->protas_aff;
				}
				// Foto: jadikan array jika lebih dari 1
				if (!empty($data->foto)) {
					$fotos = explode(',', $data->foto);
					$tgl_fotos = explode(',', $data->tgl_foto);
					// Tambahkan prefix '/uploads/foto_petakebun/' jika belum ada
					$fotoPaths = array_map(function($foto) {
						if (!$foto) return null;
						return (strpos($foto, 'uploads/') === 0 || strpos($foto, '/uploads/') === 0)
							? $foto
							: 'uploads/foto_petakebun/' . $foto;
					}, $fotos);
					$response['foto_'.$data->id_lahan] = count($fotoPaths) > 1 ? $fotoPaths : $fotoPaths[0];
					$response['tgl_foto_'.$data->id_lahan] = count($fotos) > 1 ? $tgl_fotos : $tgl_fotos[0];
				}
			}
		}

		// Default all lahan_ids to green if not explicitly set
		foreach ($lahanIds as $id) {
			if (!isset($response[$id])) {
				$response[$id] = 'green';
				$response['real_'.$id] = 0;
				$response['foto_'.$id] = null;
				$response['tgl_foto_'.$id] = null;
			} elseif (!isset($response['foto_'.$id])) {
				$response['foto_'.$id] = null;
				$response['tgl_foto_'.$id] = null;
			}
		}

		return response()->json($response);
	}

	function cekmapidlahanlkp(Request $request)
	{
		$lahanIds = $request->input('lahan_ids');

		
			$datapetak = DB::table('TX_TOTAL_KSO as p')
				->Join('master_petak as m', 'p.id_lahan', '=', 'm.lahan_id')
				//left join v_rekap_timbangan_petak_petakebun 
				->leftJoin('v_rekap_timbangan_petak_petakebun as t', 'p.id_lahan', '=', 't.lahan_id')
			
				->whereIn('p.id_lahan', $lahanIds)
				->groupBy('p.id_lahan')
				->get();

		

		

		$response = [];
		if ($datapetak->isNotEmpty()) {
			foreach ($datapetak as $data) {
				// Status warna dan realisasi
				if (!empty($data->ha)) {
					if(!empty($data->luas_poligon)){
						$response[$data->id_lahan] = 'yellow';
					}else{
						$response[$data->id_lahan] = 'green';
					}					
				} else{
					$response[$data->id_lahan] = 'blue';
				}
				// Foto: jadikan array jika lebih dari 1
				// if (!empty($data->foto)) {
				// 	$fotos = explode(',', $data->foto);
				// 	$tgl_fotos = explode(',', $data->tgl_foto);
				// 	$response['foto_'.$data->id_lahan] = count($fotos) > 1 ? $fotos : $fotos[0];
				// 	$response['tgl_foto_'.$data->id_lahan] = count($fotos) > 1 ? $tgl_fotos : $tgl_fotos[0];
				// }
			}
		}

	
		return response()->json($response);
	}

	function cekmapidlahancluster(Request $request)
	{
		$lahanIds = $request->input('lahan_ids');

		
		
			// Panggil stored procedure dan filter hasil berdasarkan lahanIds
			$spResults = DB::select("CALL sp_console_spta_petak_petakebun(?)", [date('Y-m-d', strtotime('-1 day'))]);
			// ubah hasil menjadi collection dan filter berdasarkan input lahan ids
			$datapetak = collect($spResults)->whereIn('lahan_id', $lahanIds);

		

		$response = [];
		if ($datapetak->isNotEmpty()) {
			foreach ($datapetak as $data) {
					switch ($data->clusterisasi) {
						case 'HIJAU':
							$response[$data->lahan_id] = 'green';
							break;
						case 'KUNING':
							$response[$data->lahan_id] = 'yellow';
							break;
						case 'MERAH':
							$response[$data->lahan_id] = 'red';
							break;
						case 'EMAS':
							$response[$data->lahan_id] = 'gold';
							break;	
						case 'HITAM':
							$response[$data->lahan_id] = 'black';
							break;
						case 'PLATINUM':
							$response[$data->lahan_id] = 'platinum';
							break;
						default:
							$response[$data->lahan_id] = 'blue';
					}
			}
		}

	
		return response()->json($response);
	}

	function cekmapidlahannonfilter(Request $request)
	{
		config(['app.debug' => true]);						
		$lahanIds = $request->input('lahan_ids');

		
			// Ambil data dan group by lahan_id
			$datapetak = DB::table('q_detail_petak_pekerjaan')
				->whereIn('lahan_id', $lahanIds);

				
	
			$html = '';
			$response = [];
			// dd($datapetak->get());
			if ($datapetak->get()->isNotEmpty()) {
				// Ambil hanya lahan_id pertama yang ditemukan
				$firstLahanId = $datapetak->first()->lahan_id;
				$rows = $datapetak->where('lahan_id', $firstLahanId)->get();

				$html .= '<div class="row">';
				$html .= '<div class="col-lg-6">';
				$html .= '<table style="border-collapse:collapse;width:100%;box-shadow:0 2px 8px rgba(0,0,0,0.07);font-size:12px;">';
				$html .= '<tbody>';

				// Siapkan data chart
				$chartLabels = [];
				$chartFotos = [];
				$chartData = [];
				$luasPolig = 0;
				foreach ($rows as $row) {
					$nohp = DB::table('master_nohp')
					->join('master_afd', 'master_afd.kode_afd', '=', 'master_nohp.afdeling')
					->where('master_nohp.afdeling', $row->kode_afd)
					->select('master_nohp.nama', 'master_nohp.nohp', 'master_afd.nik')
					->first();
					
					// Foto Asman
					$fotoAsmanPath = !empty($nohp->nik) && file_exists(public_path('uploads/foto_asman/' . $nohp->nik . '.jpg'))
						? 'uploads/foto_asman/' . $nohp->nik . '.jpg'
						: 'uploads/foto_asman/avatar.png';
					$fotoAsmanUrl = url($fotoAsmanPath);

					if ($nohp && !empty($nohp->nohp)) {
						$rawNumber = trim($nohp->nohp);
						$displayNumber = htmlspecialchars($rawNumber);
						$digits = preg_replace('/\D+/', '', $rawNumber);
						if (strpos($digits, '0') === 0) {
							$waNumber = '62' . substr($digits, 1);
						} else {
							$waNumber = ltrim($digits, '+');
						}
						$telHref = 'tel:' . $digits;
						$waHref = 'https://wa.me/' . $waNumber;

						$phoneLinks = '<div style="display:flex;align-items:center;justify-content:center;gap:16px;     background: url(assets/images/bganim2.gif);background-position: center;background-size: cover;">'
							. '<div style="display:inline-block;box-shadow:0 4px 16px rgba(0,0,0,0.10);border-radius:50%;overflow:hidden;width:70px;height:70px;background:#f7f7f7;position:relative;">'
							. '<img src="' . $fotoAsmanUrl . '" alt="Foto Asman" style="width:70px;height:70px;object-fit:cover;display:block;border-radius:50%;border:2px solid #0d6efd;box-shadow:0 2px 8px rgba(13,110,253,0.10);transition:transform .15s;" onclick="showImageModal(\'' . $fotoAsmanUrl . '\')" title="Klik untuk memperbesar foto">'
							. '<span style="position:absolute;bottom:0;right:12px;background:#0d6efd;color:#fff;font-size:10px;padding:2px 6px;border-radius:12px 0 12px 0;box-shadow:0 2px 8px rgba(13,110,253,0.10);font-weight:600;">Asman</span>'
							. '</div>'
							. '<div style="display:flex;gap:8px;">'
							. '<a href="' . $telHref . '" style="display:inline-flex;align-items:center;gap:8px;padding:8px 12px;background:#0d6efd;color:#fff;border-radius:10px;text-decoration:none;box-shadow:0 4px 10px rgba(13,110,253,0.15);font-weight:700;font-size:14px;transition:transform .08s;" title="Telepon" aria-label="Telepon">'
							. '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:middle;"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.86 19.86 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.86 19.86 0 0 1 2.09 4.18 2 2 0 0 1 4 2h3a2 2 0 0 1 2 1.72c.12 1.05.38 2.08.78 3.03a2 2 0 0 1-.45 2.11L9.91 10.09a16 16 0 0 0 6 6l1.23-1.23a2 2 0 0 1 2.11-.45c.95.4 1.98.66 3.03.78A2 2 0 0 1 22 16.92z"/></svg>'
							. '<span style="line-height:1;color:#fff;margin-left:4px;">Telpon</span>'
							. '</a>'
							. '<a href="' . $waHref . '" target="_blank" rel="noopener" style="display:inline-flex;align-items:center;gap:8px;padding:8px 12px;background:#25D366;color:#fff;border-radius:10px;text-decoration:none;box-shadow:0 4px 10px rgba(37,211,102,0.12);font-weight:700;font-size:14px;transition:transform .08s;" title="WhatsApp" aria-label="WhatsApp">'
							. '<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:middle;"><path d="M21.05 11.18a9 9 0 1 0-2.47 5.86L21 23l5.05-2.1A9 9 0 0 0 21.05 11.18z"/><path d="M17.2 14.65c-.3-.15-1.78-.88-2.06-.98-.28-.1-.48-.15-.68.15-.2.3-.78.98-.96 1.18-.18.2-.36.22-.66.07-.3-.15-1.26-.46-2.4-1.47-.89-.79-1.48-1.77-1.66-2.07-.18-.3-.02-.46.13-.61.13-.13.3-.36.45-.54.15-.18.2-.3.3-.5.1-.2 0-.38-.05-.53-.05-.15-.68-1.62-.93-2.22-.24-.57-.49-.5-.67-.51l-.57-.01c-.19 0-.5.07-.76.37-.26.3-1 1-1 2.45s1.03 2.84 1.18 3.04c.15.2 2.03 3.1 4.92 4.35 1.41.6 1.99.8 2.68.82.69.02 1.69-.28 1.93-1.09.24-.8.24-1.48.17-1.62-.07-.14-.26-.23-.56-.38z"/></svg>'
							. '<span style="line-height:1;color:#fff;margin-left:4px;">WA</span>'
							. '</a>'
							. '</div>'
							. '</div>';
					} else {
						$phoneLinks = '<div style="display:flex;align-items:center;justify-content:center;gap:16px;">'
							. '<div style="display:inline-block;box-shadow:0 4px 16px rgba(0,0,0,0.10);border-radius:50%;overflow:hidden;width:70px;height:70px;background:#f7f7f7;position:relative;">'
							. '<img src="' . $fotoAsmanUrl . '" alt="Foto Asman" loading="lazy" style="width:70px;height:70px;object-fit:cover;display:block;border-radius:50%;border:2px solid #0d6efd;box-shadow:0 2px 8px rgba(13,110,253,0.10);transition:transform .15s;" onclick="showImageModal(\'' . $fotoAsmanUrl . '\')" title="Klik untuk memperbesar foto">'
							. '<span style="position:absolute;bottom:0;right:0;background:#0d6efd;color:#fff;font-size:10px;padding:2px 6px;border-radius:12px 0 12px 0;box-shadow:0 2px 8px rgba(13,110,253,0.10);font-weight:600;">Asman</span>'
							. '</div>'
							. '<div style="display:flex;flex-direction:column;gap:8px;">-</div>'
							. '</div>';
					}

					$html .= '<tr><td colspan="2" style="padding:10px 0;text-align:center;border-bottom:1px solid #e3e3e3;">' . $phoneLinks . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Nama Asman</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->nama_asman) . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Lahan ID</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->lahan_id) . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Cluster</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->cluster) . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Kebun</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->kebun) . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Kode Rayon</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->kode_rayon) . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Rayon</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->rayon) . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Nama Kebun</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->nama_kebun) . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Luas Poligon</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->luas_polig) . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Kategori</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->kategori_n) . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Bulan Tanam</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->bulan_tana) . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Afdeling</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->kode_afd) . '</td></tr>';
					
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Faktor Juring</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . htmlspecialchars($row->faktor_juring_perha) . '</td></tr>';
					// Data untuk chart

					$rekapTimbangan = DB::table('v_rekap_timbangan_petak_petakebun')
						->where('lahan_id', $row->lahan_id)
						->first();

					$taksasi = DB::table('q_takdes_petak')
						->where('lahan_id', $row->lahan_id)
						->first();
						

					//data aff diambil dari ini CALL sp_rekap_timbangan_petak_sd_petakebun('24198687','2026-08-10');
					$afftebang = DB::select("CALL sp_rekap_timbangan_petak_sd_petakebun(?, ?)", [$row->lahan_id, date('Y-m-d')]);
					
 

					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Taksasi (Ton/Ha)</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . ($taksasi->takdes_tonperha ?? '-') . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Pra Tebang (Ton/Ha)</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . ($rekapTimbangan->protas_pratebang ?? '-') . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Real Ha (Ha)</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . ($rekapTimbangan->ha_tebang_sd ?? '-') . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Real Tebu (Ton)</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . ($rekapTimbangan->netto_ton_sd ?? '-') . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Real Protas (Ton/Ha)</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . ($rekapTimbangan->protas_sd ?? '-') . '</td></tr>';
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Real Rendemen (%)</td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . ($rekapTimbangan->rendemen_sd ?? '-') . '</td></tr>';
					$affStatus = '-';
					if (!empty($afftebang) && isset($afftebang[0]->aff_tebang, $afftebang[0]->tgl_aff)) {
						$affStatus = $afftebang[0]->aff_tebang . ' (' . date('d-m-Y', strtotime($afftebang[0]->tgl_aff)) . ')';
					}
					$html .= '<tr><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;font-weight:bold;white-space:nowrap;">Status AFF </td><td style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">' . $affStatus . '</td></tr>';
					$persenTakdes = ($rekapTimbangan && $rekapTimbangan->takdes_tonperha > 0 && $rekapTimbangan->protas_sd > 0)
						? round(($rekapTimbangan->protas_sd / $rekapTimbangan->takdes_tonperha) * 100, 2)
						: 0;
					$persenPratebang = ($rekapTimbangan && $rekapTimbangan->protas_pratebang > 0 && $rekapTimbangan->protas_sd > 0)
						? round(($rekapTimbangan->protas_sd / $rekapTimbangan->protas_pratebang) * 100, 2)
						: 0;

					// Progress bar style
					function progressBar($percent, $label) {
						$barWidth = min($percent, 100);
						$r = round(255 - (255 * ($barWidth / 100)));
						$g = round(0 + (200 * ($barWidth / 100)));
						$b = 0;
						$barColor = "rgb($r,$g,$b)";
						return '<div style="margin:4px 0 8px 0;">
							<div style="font-size:12px;font-weight:bold;margin-bottom:2px;">' . $label . '</div>
							<div style="background:#b1afaf;width:100%;height:18px;border-radius:3px;position:relative;max-width:220px;">
								<div style="background:' . $barColor . ';height:18px;width:' . $barWidth . '%;min-width:2px;border-radius:3px;position:absolute;top:0;left:0;display:flex;align-items:center;justify-content:flex-end;"></div>
								<span style="position: absolute; right: 0; font-size: 11px; color: #fff2f2; font-weight: bold; padding-right: 6px">' . $percent . '%</span>
							</div>
						</div>';
					}

					$html .= '<tr><td colspan="2" style="padding:7px 12px;border-bottom:1px solid #e3e3e3;">'
						. progressBar($persenTakdes, '% Taksasi')
						. progressBar($persenPratebang, '% Pra tebang')
						. '</td></tr>';

					$luasPolig = $row->luas_polig;
				}
				$html .= '</tbody></table>';
					$protasMorfologi = collect(DB::select('
						select x.* from ( SELECT
						tm.tanggal,
						(mp.faktor_juring_perha * tm.jumlah_batang * mp.panjang_juring_m * tm.tinggi_batang * tm.berat_batang_per_meter) / 1000 as protas_morfologi,
						ss.protas_sasaran
					FROM master_petak mp
					JOIN q_lkp_rekap_id_lahan_pekerjaan tx ON tx.id_lahan = mp.lahan_id
					JOIN tx_morfologi tm ON tm.lahan_id = mp.lahan_id
					JOIN master_sasaran2526_petak ss ON ss.id_lahan = tm.lahan_id
					LEFT JOIN tb_users us ON us.id = tm.entry_by
					WHERE tm.lahan_id != 0 AND tm.lahan_id = ?
					ORDER BY tm.tanggal desc
					LIMIT 7) as x order by x.tanggal asc 
				', [$firstLahanId]));

					if ($protasMorfologi && $protasMorfologi->count() > 0) {
						$html .= '<div style="margin-top:18px;">';
						$html .= '<div style="font-weight:bold;margin-bottom:5px;">Grafik Protas Morfologi & Sasaran (7 Data Terakhir)</div>';
						$html .= '<div id="protasMorfologiHighchart" style="width:100%;max-width:600px;height:280px;"></div>';
						// Prepare data for Highcharts
						$labels = [];
						$data = [];
						$sasaran = [];
						foreach ($protasMorfologi as $row) {
							$labels[] = date('d-m-Y', strtotime($row->tanggal));
							$data[] = round($row->protas_morfologi, 2);
							$sasaran[] = is_numeric($row->protas_sasaran) ? round($row->protas_sasaran, 2) : null;
						}
						$response['labels'] = $labels;
						$response['data'] = $data;
						$response['sasaran'] = $sasaran;
						// Pastikan Highcharts sudah dimuat sebelum menjalankan script ini
						$html .= '<script>
	
						</script>';
						$html .= '</div>';
					}
				$html .= '</div><div class="col-lg-6">';
				$datapetak2 = DB::table('q_detail_petak_pekerjaan as a')
					->leftJoin(DB::raw('(SELECT no_pekerjaan, MAX(foto) AS last_foto FROM q_detail_petak_pekerjaan WHERE foto IS NOT NULL AND foto <> "" AND lahan_id IN (' . implode(',', $lahanIds) . ') AND ha_dikerjakan > 0 GROUP BY no_pekerjaan) b'), function($join) {
						$join->on('a.no_pekerjaan', '=', 'b.no_pekerjaan');
					})
					->where(function($query) use ($lahanIds) {
						$query->whereRaw('(a.foto = b.last_foto OR b.last_foto IS NULL)');
						$query->whereIn('a.lahan_id', $lahanIds);
						$query->where('a.ha_dikerjakan', '>', 0);
					})
					->get();

				foreach($datapetak2 as $row) {
					$chartLabels[] = $row->pekerjaan;
					$chartFotos[] = $row->foto;
					// Hitung prosentase ha_dikerjakan terhadap luas_polig
					$prosentase = ($luasPolig > 0) ? round(($row->ha_dikerjakan / $luasPolig) * 100, 2) : 0;
					$chartData[] = $prosentase;
					$luasdikerjakan[] = $row->ha_dikerjakan;
				}

				// Bar chart: prosentase ha_dikerjakan per pekerjaan, overlay target 100%
				$maxValue = 100;
				$html .= '<div><b>Prosentase HA per Pekerjaan</b></div>';
				$html .= '<table class="table-responsive" style="width:100%;max-width:500px;font-size:12px;border-collapse:collapse;margin-top:8px;box-shadow:0 2px 8px rgba(0,0,0,0.07);">';
				$html .= '<thead><tr style="background:#f7f7f7;">';
				$html .= '<th style="padding:7px 8px;border:1px solid #e3e3e3;">Foto</th>';
				$html .= '<th style="padding:7px 8px;border:1px solid #e3e3e3;">Pekerjaan</th>';
				$html .= '<th style="padding:7px 8px;border:1px solid #e3e3e3;">Progress (Ha)</th>';
				$html .= '<th style="padding:7px 8px;border:1px solid #e3e3e3;">% Progress</th>';
				$html .= '</tr></thead><tbody>';

				foreach ($chartLabels as $i => $label) {
					$value = $chartData[$i];
					$barWidth = ($value / $maxValue) * 100;

					// Interpolasi warna dari merah (0%) ke hijau (100%)
					$r = round(255 - (255 * ($value / 100)));
					$g = round(0 + (200 * ($value / 100)));
					$b = 0;
					$barColor = "rgb($r,$g,$b)";

					$html .= '<tr>';
					// Foto
					$html .= '<td style="padding:4px 6px;border:1px solid #e3e3e3;text-align:center;">';
					if (!empty($chartFotos[$i])) {
						$fotoPath = $chartFotos[$i];
						//	$fotoUrl = (strpos($fotoPath, 'uploads/') === 0) ? url($fotoPath) : url('uploads/foto_kebun/' . $fotoPath);
						$localFoto = (strpos($fotoPath, 'uploads/') === 0)
							? public_path($fotoPath)
							: public_path('uploads/foto_kebun/' . $fotoPath);

						$localUrl = (strpos($fotoPath, 'uploads/') === 0)
							? url($fotoPath)
							: url('uploads/foto_kebun/' . $fotoPath);

						$cdnUrl = env('ASSET_CDN_URL') . '/uploads/foto_kebun/thumb_' . $fotoPath;

						$fotoUrl = file_exists($localFoto) ? $localUrl : $cdnUrl;
						$html .= '<img src="' . $fotoUrl . '" alt="foto" loading="eager" style="width:40px;height:40px;object-fit:cover;border-radius:4px;border:1px solid #ccc;cursor:pointer;" onclick="showImageModal(\'' . $fotoUrl . '\')" title="Klik untuk melihat gambar lebih besar">';
					} else {
						$html .= '-';
					}
					$html .= '</td>';
					// Pekerjaan
					$html .= '<td style="padding:4px 6px;border:1px solid #e3e3e3;">' . htmlspecialchars($label) . '</td>';
					// Progress bar
					$html .= '<td style="padding:4px 6px;border:1px solid #e3e3e3;">';
					$html .= '<div style="background:#b1afaf;width:100%;height:18px;border-radius:3px;position:relative;">';
					$html .= '<div style="background:' . $barColor . ';height:18px;width:' . $barWidth . '%;min-width:2px;border-radius:3px;position:absolute;top:0;left:0;display:flex;align-items:center;justify-content:flex-end;"> </div>';
					$html .= '<span style="position: absolute; right: 0;float: right;font-size: 11px;color: #fff2f2;font-weight: bold;padding-right: 6px">' . $luasdikerjakan[$i] . '</span>';
					// Target line (100%)
					$html .= '</div>';
					$html .= '</td>';
					// Persentase
					$html .= '<td style="padding:4px 6px;border:1px solid #e3e3e3;text-align:right;">' . $value . ' %</td>';
					$html .= '</tr>';
				}
				$html .= '</tbody></table>';
			

				// Tambahkan foto morfologi jika ada
				$fotoMorfologi = DB::table('tx_morfologi')
					->where('lahan_id', $firstLahanId)
					->orderBy('createdOn', 'desc')
					->limit(3)
					->get();

				

				$response['protas_morfologi'] = $protasMorfologi;	

				if ($fotoMorfologi && $fotoMorfologi->count() > 0) {
					$html .= '<div style="margin-top:18px;">';
					$html .= '<div style="font-weight:bold;margin-bottom:5px;">Foto Morfologi</div>';
					// horizontal scroll container
					$html .= '<div style="display:flex;flex-wrap:nowrap;overflow-x:auto;overflow-y:hidden;gap:8px;padding:8px 2px;-webkit-overflow-scrolling:touch;scrollbar-width:none;-ms-overflow-style:none;">';
					foreach ($fotoMorfologi as $foto) {
						$fotoMorfologiPath = $foto->foto;
						//$fotoMorfologiUrl = (strpos($fotoMorfologiPath, 'uploads/') === 0)
						//	? url($fotoMorfologiPath)
						//	: url('uploads/foto_morfologi/' . $fotoMorfologiPath);
						$localMorfologi = public_path('uploads/foto_morfologi/' . $fotoMorfologiPath);
						$localMorfologiUrl = url('uploads/foto_morfologi/' . $fotoMorfologiPath);
						$cdnMorfologiUrl = env('ASSET_CDN_URL') . '/uploads/foto_morfologi/thumb_' . $fotoMorfologiPath;

						$fotoMorfologiUrl = file_exists($localMorfologi)
							? $localMorfologiUrl
							: $cdnMorfologiUrl;

							if(!empty($fotoMorfologiPath)){
								$html .= '<div style="flex:0 0 auto;">';
								$html .= '<img src="' . $fotoMorfologiUrl . '" alt="foto morfologi" loading="eager" style="width:70px;height:70px;object-fit:cover;border-radius:4px;border:1px solid #ccc;cursor:pointer;display:block;" onclick="showImageModal(\'' . $fotoMorfologiUrl . '\')" title="Klik untuk melihat gambar lebih besar">';
								$html .= '<div style="text-align:center;font-size:11px;color:#333;margin-top:2px;background:linear-gradient(90deg,#e0eafc 0%,#cfdef3 100%);padding:2px 0;border-radius:4px;">' . (isset($foto->tanggal) ? date('d-m-Y', strtotime($foto->tanggal)) : '') . '</div>';
								$html .= '</div>';
							}
					}
					$html .= '</div>'; // close scroll container
					$html .= '</div>';
				}


				$fotoDrone = DB::table('tx_foto_drone')
					->where('lahan_id', $firstLahanId)
					->orderBy('createdOn', 'desc')
					->limit(3)
					->get();

				
				if ($fotoDrone && $fotoDrone->count() > 0) {
					$html .= '<div style="margin-top:0px;">';
					$html .= '<div style="font-weight:bold;margin-bottom:5px;">Foto Drone</div>';
					foreach ($fotoDrone as $foto) {
						$fotoDronePath = $foto->foto;
						//$fotoDroneUrl = (strpos($fotoDronePath, 'uploads/') === 0)
						//	? url($fotoDronePath)
						//	: url('uploads/foto_drone/' . $fotoDronePath);
						$localDrone = public_path('uploads/foto_drone/' . $fotoDronePath);
						$localDroneUrl = url('uploads/foto_drone/' . $fotoDronePath);
						$cdnDroneUrl = env('ASSET_CDN_URL') . '/uploads/foto_drone/thumb_' . $fotoDronePath;

						$fotoDroneUrl = file_exists($localDrone)
							? $localDroneUrl
							: $cdnDroneUrl;

						$html .= '<div style="display:inline-block;text-align:center;margin-right:8px;margin-bottom:8px;">';
						$html .= '<img src="' . $fotoDroneUrl . '" alt="foto drone" loading="eager" style="width:70px;height:70px;object-fit:cover;border-radius:4px;border:1px solid #ccc;cursor:pointer;display:block;" onclick="showImageModal(\'' . $fotoDroneUrl . '\')" title="Klik untuk melihat gambar lebih besar">';
						$html .= '<div style="font-size:11px;color:#333;margin-top:2px;background:linear-gradient(90deg,#e0eafc 0%,#cfdef3 100%);padding:2px 0;border-radius:4px;">' . (isset($foto->tanggal) ? date('d-m-Y', strtotime($foto->tanggal)) : (isset($foto->createdOn) ? date('d-m-Y', strtotime($foto->createdOn)) : '')) . '</div>';
						$html .= '</div>';
					}
					$html .= '</div>';
				}
				$html .= '</div></div></div>'; // Close col-6 and row divs


			}

			$response['html'] = $html;

			return response()->json($response);

		
	}
	
	public function uploadfoto(Request $request)
{
    // Validasi file
    $validator = Validator::make($request->all(), [
        'foto_lahan' => 'required|image|mimes:jpeg,png,jpg,gif|max:10096', // max ~10MB
    ]);

    if ($validator->fails()) {
        return response()->json([
            'message' => $validator->errors()->first('foto_lahan')
        ], 422);
    }

    if ($request->hasFile('foto_lahan')) {
        $file = $request->file('foto_lahan');
        $filename = time() . '_' . uniqid() . '.jpg'; // Simpan sebagai JPG
        $folder = public_path('uploads/foto_petakebun');

        // Buat folder jika belum ada
        if (!file_exists($folder)) {
            mkdir($folder, 0755, true);
        }

        // Kompres gambar sebelum disimpan
        $image = imagecreatefromstring(file_get_contents($file->getRealPath()));
        $fullPath = $folder . '/' . $filename;
        imagejpeg($image, $fullPath, 70); // 70 = kualitas (kompresi)

        // Simpan path (relatif) ke database
        DB::table('tx_foto_tebangan_lahan')->insert([
            'lahan_id'   => $request->input('lahan_id'),
            'foto'       => 'uploads/foto_petakebun/' . $filename, // simpan path relatif
            'entry_by'   => \Auth::id(),
            'createdOn'  => now(),
            'updatedOn'  => now()
        ]);

        return response()->json([
            'message' => 'Foto berhasil diupload & disimpan!',
            'path' => url('uploads/foto_petakebun/' . $filename)
        ]);
    }

    return response()->json([
        'message' => 'File tidak ditemukan.'
    ], 400);
}




	public function getfoto(Request $request)
	{
		$lahan_id = $request->input('lahan_id');
		if (!$lahan_id) {
			return response()->json([
				'message' => 'Parameter lahan_id diperlukan.'
			], 400);
		}

		$fotos = DB::table('tx_foto_tebangan_lahan')
			->where('lahan_id', $lahan_id)
			->orderBy('createdOn', 'desc')
			->get(['id', 'lahan_id', 'foto', 'createdOn', 'entry_by']);

		return response()->json($fotos);
	}

	public function getGisPetak(Request $request)
	{
		// Ambil data peta kebun dari database
		// Konfigurasi JWT
		$jwtSecret = '5c0fd82b-b65c-423d-9e63-f41f8d8fd3c8'; // Ganti dengan secret key yang sesuai
		$jwtIssuer = env('GIS_URL_WITHOUT_HTTP');
		$jwtAudience = env('GIS_URL_WITHOUT_HTTP');
		$jwtExpiration = time() + 3600; // 1 jam

		$payload = [
			'iss' => $jwtIssuer,
			'aud' => $jwtAudience,
			'iat' => time(),
			'exp' => $jwtExpiration,
			'sub' => \Auth::id(),
			'user' => [
				'id' => \Auth::id(),
				'name' => \Auth::user()->name,
				'email' => \Auth::user()->email,
			]
		];

		$token = $this->generateJwtToken($payload, $jwtSecret);
		return redirect()->to(env('GIS_URL') . '\app\?token=' . $token);
	}

	public function generateJwtToken($payload, $secretKey, $algorithm = 'HS256')
	{
		$header = json_encode(['typ' => 'JWT', 'alg' => $algorithm]);
		$base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
		$base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(json_encode($payload)));
		$signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, $secretKey, true);
		$base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
		return $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
	}
}