<?php namespace App\Http\Controllers;

use App\Models\Webhook;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ; 
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;
use PDF ;
use DOMDocument;
use DOMXPath;
use Config;


class WebhookController extends Controller {

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

	public function __construct()
	{
		parent::__construct();
		$this->model = new Webhook();
		$this->info = $this->model->makeInfo( $this->module);
		$this->access = array();
	
		$this->data = array_merge(array(
			'pageTitle'	=> 	$this->info['title'],
			'pageNote'	=>  $this->info['note'],
			'pageModule'=> 'webhook',
			'return'	=> self::returnUrl()
			
		),$this->data);

		
	}

	public function index( Request $request )
	{		
		//return view('webhook.index',$this->data);
			return "test";
	}
	function show( Request $request , $id ) 
	{
		/* Handle import , export and view */
		$task =$id ;
		switch( $task)
		{

			case 'getReportKlentekPerKebun':
				return $this->getReportKlentekPerKebun( $request );
				break;
			case 'kirimPesanKeSemua':
				return $this->kirimPesanKeSemua( $request );
				break;
			case 'getReportLHPConsole':
				return $this->getReportLHPConsole( $request );
				break;
			case 'getReportSisaTeburayon':
				return $this->getReportSisaTeburayon( $request );
				break;	
			case 'getReportMutuTeburayon':
				return $this->getReportMutuTeburayon( $request );
				break;
			case 'getReportProtasRendemen':
				return $this->getReportProtasRendemen( $request );
			case 'formLkp2025Html':
				return $this->formLkp2025Html( $request );
				break;	
			case 'autocompletePetak':
				return $this->autocompletePetak( $request );
				break;
			case 'autocompletePetak2':
				return $this->autocompletePetak2( $request );
				break;
			case 'formMorfologi2025Html':
				return $this->formMorfologi2025Html( $request );
				break;	
			case 'formFotoTebangLahanHtml':
				return $this->formFotoTebangLahanHtml( $request );
				break;
			case 'formFotoDroneHtml':
				return $this->formFotoDroneHtml( $request );
				break;	
			case 'formTebuRoboh2025Html':
				return $this->formTebuRoboh2025Html( $request );
				break;
			case 'formHama2025Html':
				return $this->formHama2025Html( $request );
				break;
			case 'formTebuBanjir2025Html':
				return $this->formTebuBanjir2025Html( $request );
				break;
			case  'viewPdfFromUrl':
				return $this->viewPdfFromUrl( $request );
				break;
			case 'testN8nWebhook':
				return $this->testN8nWebhook( $request );
				break;
			case 'formPicaHtml':
				return $this->formPicaHtml( $request );
				break;
			case 'formPicaActionHtml':
				return $this->formPicaActionHtml( $request );
				break;
			case 'getPicaProblemByLahan':
				return $this->getPicaProblemByLahan( $request );
				break;	
			case 'getPicaActionDetail':
				return $this->getPicaActionDetail( $request );
				break;
			case 'getEarlyWarningMorfologiUnitMessage':
				return $this->getEarlyWarningMorfologiUnitMessage( $request );
				break;	
			case 'getEarlyWarningLKPUnitMessage':
				return $this->getEarlyWarningLKPUnitMessage( $request );
				break;	
			// case 'kirimpesandariai':
			// 	return $this->kirimpesandariai( $request );
			// 	break;	



	
		}
	}
	public function sendToN8nWebhook($data, $prod=true, $versi=null)
	{
		if($prod){
			if($versi == 'Y') {
				// difa 1
				$url = env('N8N_URL') . '/webhook/a176a61a-f662-4ced-bc4b-34ba98a57d48';
			} else if($versi == 'Z') {
				//difa 3
				$url = env('N8N_URL') . '/webhook/b7bc866a-c0c7-4d19-bbcc-ecc00e55d190';
			} else if($versi == 'X'){
				//difa 2
				$url = env('N8N_URL') . '/webhook/a6d98677-3902-446a-b337-3abc2eb6f7d6';
			}

			
		}else{
			$url = env('N8N_URL') . '/webhook-test/a176a61a-f662-4ced-bc4b-34ba98a57d48';
		}

		$ch = curl_init();
		
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, [
			'Content-Type: application/json',
			'Accept: application/json',
			'n8nwebhook: ' . env('API_KEY_N8N')
		]);
		
		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		
		curl_close($ch);
		
		if ($httpCode >= 200 && $httpCode < 300) {
			return response()->json(['message' => 'Data sent to n8n successfully', 'response' => json_decode($response)], 200);
		}
		
		return response()->json(['error' => 'Failed to send data to n8n', 'response' => $response], $httpCode);
	}

	public function N8nWebhook($phone, $name, $message, $afd=null, $versi=null)
	{
		$phone = $phone;
		$name = $name;
		$message = $message;
		$chatId = $phone . '@c.us';
		
		if (empty($phone) || empty($message)) {
			return response()->json(['error' => 'Phone and message are required'], 400);
		}

		if (!empty($afd)) {
			$category = "KEBUN";
		}else{
			$category = "UMUM";
		}
		$aisystem = \DB::table('ai_system_content')
								->select('content_system')
								->where('category', $category)
								->first();
		
		$testData = [
			'sessionId' => md5($phone.date('Y-m-d')),
			'chatId' => $chatId,
			'message' => $message,
			'name' => $name,
			'phone' => $phone,
			'aisystem' => $aisystem->content_system ?? null,
			'timestamp' => now()->toDateTimeString(),
			'source' => 'webhook_controller'
		];
		
		return $this->sendToN8nWebhook($testData, true, $versi);
	}

	public function testN8nWebhook(Request $request)
	{
		$phone = $request->input('phone');
		$name = $request->input('name');
		$message = $request->input('message');
				$chatId = $phone . '@c.us';
		
		if (empty($phone) || empty($message)) {
			return response()->json(['error' => 'Phone and message are required'], 400);
		}
		$testData = [
			'sessionId' => $phone,
			'chatId' => $chatId,
			'message' => $message,
			'name' => $name,
			'phone' => $phone,
			'timestamp' => now()->toDateTimeString(),
			'source' => 'webhook_controller'
		];
		
		return $this->sendToN8nWebhook($testData, false);
	}


	public function create( $id = null)
	{		
		return view('webhook.form',$this->data);	
	}	
	public function edit( $id = null)
	{		
		return view('webhook.form',$this->data);	
	}	
	function store( Request $request)
	{		
		Config::set('app.debug', true);
		$task = $request->input('action_task');
		switch ($task)
		{
			case 'formLkp2025':
				return $this->formLkp2025( $request );
				break;
			case 'formMorfologi2025':
				return $this->formMorfologi2025( $request );
				break;
			case 'formFotoTebangLahan':
				return $this->formFotoTebangLahan( $request );
				break;
			case 'formFotoDrone':
				return $this->formFotoDrone( $request );
				break;
			case 'formTebuRoboh':
				return $this->formTebuRoboh( $request );
				break;	
			case 'formHama2025':
				return $this->formHama2025( $request );
				break;
			case 'formTebuBanjir':
				return $this->formTebuBanjir( $request );
				break;
			case 'formPica':
				return $this->formPica( $request );
				break;
			case 'formPicaAction':
				return $this->formPicaAction( $request );
				break;
			default:
				$body = file_get_contents('php://input');
				$jsonparse = json_decode($body);

				// Extract WhatsApp number from new structure
				$whatsapp_number = null;
				$pesan = '';

				// Get phone number from remoteJidAlt or remoteJid in new format
				// if (isset($jsonparse->payload->_data->key->remoteJidAlt) && strpos($jsonparse->payload->_data->key->remoteJidAlt, '@s.whatsapp.net') !== false) {
				// 	$whatsapp_number = preg_replace('/@s\.whatsapp\.net$/', '', $jsonparse->payload->_data->key->remoteJidAlt);
				// } elseif (isset($jsonparse->payload->_data->key->remoteJid) && strpos($jsonparse->payload->_data->key->remoteJid, '@s.whatsapp.net') !== false) {
				// 	$whatsapp_number = preg_replace('/@s\.whatsapp\.net$/', '', $jsonparse->payload->_data->key->remoteJid);
				// }

				if (isset($jsonparse->payload->_data->Info->SenderAlt) && strpos($jsonparse->payload->_data->Info->SenderAlt, '@s.whatsapp.net') !== false) {
					$senderAlt = $jsonparse->payload->_data->Info->SenderAlt;
					$senderParts = explode(":",$senderAlt);
					$firstSender = $senderParts[0] ?? $senderAlt;
					$whatsapp_number = preg_replace('/@s\.whatsapp\.net$/', '', $firstSender);
				} 

				// Get message body
				if (isset($jsonparse->payload->body)) {
					$pesan = $jsonparse->payload->body;
				}

				// Simpan semua webhook ke master_webhook
				if (!empty($body)) {
					$webhookId = \DB::table('master_webhook')->insertGetId([
						'webhook' => 'WAAPI',
						'text' => $body,
						'nohp' => $whatsapp_number,
						'pesan' => $pesan,
						'status' => 'pending',
						'date' => now()
					]);
				}

				// Check if this is a message from self (bot's own message)
				if (isset($jsonparse->payload->fromMe) && $jsonparse->payload->fromMe === true) {
					\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'ignored_self']);
					return response()->json(['status' => 'ignored', 'reason' => 'message from self']);
				}

				// Check if message already processed based on message ID
				$messageId = $jsonparse->payload->id ?? null;
				if ($messageId) {
					$exists_message = \DB::table('tx_logs_wa')
						->where('message_id', $messageId)
						->first();
					
					if ($exists_message) {
						\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'ignored_duplicate']);
						return response()->json(['status' => 'ignored', 'reason' => 'message already processed']);
					}
				}

				if ($whatsapp_number && strlen($pesan) > 0) {
					
					$exists = \DB::table('master_nohp')
						->where('nohp', $whatsapp_number)
						->orderBy('nik', 'desc')
						->first();
					
					if (!empty($exists->nohp)) {
						$parts = explode(' ', $pesan, 2);
						if (count($parts) > 1) {
							$kode = strtoupper(preg_replace('/[^a-zA-Z0-9]/', '', $parts[0]));
							$filter_tgl = preg_replace('/[^0-9]/', '', $parts[1]);
							$filter_tgl2 = str_replace('-', '', $parts[1]);
						} else {
							$kode = strtoupper(preg_replace('/[^a-zA-Z0-9]/', '', $parts[0]));
							$filter_tgl = date('dmY');
							$filter_tgl2 = null;
						}

						$jwtPayload = [
							'user' => $exists->nama,
							'nohp' => $exists->nohp,
							'exp' => time() + 900
						];
						$secretKey = '8uUC1YWkHD';
						$jwtToken = $this->generateJwtToken($jwtPayload, $secretKey);

						// Check if message content already processed (duplicate content check)
						$contentHash = md5($pesan);
						$exists_content = \DB::table('tx_logs_wa')
							->where('nomer_wa', $whatsapp_number)
							->where('content_hash', $contentHash)
							->where('date', '>=', now()->subMinutes(5)) // Check last 5 minutes
							->first();
						
						if ($exists_content) {
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'ignored_duplicate_content']);
							return response()->json(['status' => 'ignored', 'reason' => 'duplicate message content']);
						}

						if ($kode == 'LAP1') {
							$documentUrl = 'https://prodis.ksotebu.com/webhook/getReportKlentekPerKebun?filter_tgl=' . $filter_tgl . '&jwt=' . $jwtToken;
							$caption = 'Laporan Klentek Harian Kebun';
							$this->sendDocument2($exists->nohp, $documentUrl, $caption);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'LAP1']);
						
						} else if ($kode == 'LAP2') {
							$documentUrl = 'https://prodis.ksotebu.com/webhook/getReportMutuTeburayon?jwt=' . $jwtToken;
							$caption = 'Laporan Mutu Tebu Harian Rayon';
							$this->sendMessage2($documentUrl, $exists->nohp);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'LAP2']);
						
						} elseif ($kode == 'LAP3') {
							$documentUrl = 'https://prodis.ksotebu.com/webhook/getReportSisaTeburayon?jwt=' . $jwtToken;
							$caption = 'Laporan Realisasi Timbangan TS KSO MT 24/25';
							$this->sendDocument2($exists->nohp, $documentUrl, $caption);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'LAP3']);
						}else if ($kode == 'LAP4') {
							$documentUrl = 'https://prodis.ksotebu.com/webhook/getReportLHPConsole?filter_tgl=' . $filter_tgl . '&regional=&jwt=' . $jwtToken;
							$caption = 'Laporan LHP Console';
							$this->sendMessage2($documentUrl, $exists->nohp);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'LAP4']);
						
						} 
						else if ($kode == 'LAP5') {
							$documentUrl = 'https://prodis.ksotebu.com/webhook/getReportProtasRendemen?jwt=' . $jwtToken;
							$caption = 'Laporan Protas Rendemen Rayon';
							$this->sendMessage2($documentUrl, $exists->nohp);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'LAP5']);
						
						}else if ($kode == 'APK') {
							$documentUrl = "Download Aplikasi Prodis KSO \n https://ksotebu.com/ProdisKSO.apk";
							$this->sendMessage2($documentUrl, $exists->nohp);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'APK']);
						
						}else if ($kode == 'LKP') {
							$message = "Silahkan isi dan upload LKP 2025 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formLkp2025Html?jwt=" . $jwtToken;
							$this->sendMessage2($message, $exists->nohp);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'LKP']);
						}else if ($kode == 'MORF') {
							//$message = "Silahkan isi dan upload Morfologi 2025 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formMorfologi2025Html?jwt=" . $jwtToken;
							//$this->sendMessage2($message, $exists->nohp);
							$this->sendUrl('https://prodis.ksotebu.com/webhook/formMorfologi2025Html?jwt=' . $jwtToken, $exists->nohp, 'https://prodis.ksotebu.com/webhook/formMorfologi2025Html?jwt=' . $jwtToken, 'Form Upload Morfologi 2025', 'Silahkan isi dan upload Morfologi 2025 di link berikut');
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'MORF']);
						}else if ($kode == 'TBG') {
							//$message = "Silahkan isi dan upload Tebangan 2024 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formFotoTebangLahanHtml?jwt=" . $jwtToken;
							//$this->sendMessage2($message, $exists->nohp);
							$this->sendUrl('https://prodis.ksotebu.com/webhook/formFotoTebangLahanHtml?jwt=' . $jwtToken, $exists->nohp, 'https://prodis.ksotebu.com/webhook/formFotoTebangLahanHtml?jwt=' . $jwtToken, 'Form Upload Tebangan 2025', 'Silahkan isi dan upload Tebangan 2025 di link berikut');
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'TBG']);
						}else if($kode == 'DRN'){
							//$message = "Silahkan isi dan upload Foto Drone Lahan 2025 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formFotoDroneHtml?jwt=" . $jwtToken;
							//$this->sendMessage2($message, $exists->nohp);
							$this->sendUrl('https://prodis.ksotebu.com/webhook/formFotoDroneHtml?jwt=' . $jwtToken, $exists->nohp, 'https://prodis.ksotebu.com/webhook/formFotoDroneHtml?jwt=' . $jwtToken, 'Form Upload Foto Drone Lahan 2025', 'Silahkan isi dan upload Foto Drone Lahan 2025 di link berikut');
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'DRN']);

						}else if($kode == 'ABSEN'){
							$message = "Silahkan Absensi Kehadiran Karyawan di link berikut (PeopleOne):\nhttps://peopleone.sinergigula.com/presensilogin";
							$this->sendMessage2($message, $exists->nohp);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'ABSEN']);

						}else if($kode == 'ROBOH'){
							//$message = "Silahkan isi dan upload Data Tebu Roboh 2025 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formTebuRoboh2025Html?jwt=" . $jwtToken;
							//$this->sendMessage2($message, $exists->nohp);
							$this->sendUrl('https://prodis.ksotebu.com/webhook/formTebuRoboh2025Html?jwt=' . $jwtToken, $exists->nohp, 'https://prodis.ksotebu.com/webhook/formTebuRoboh2025Html?jwt=' . $jwtToken, 'Form Upload Tebu Roboh 2025', 'Silahkan isi dan upload Data Tebu Roboh 2025 di link berikut');
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'ROBOH']);

						}else if($kode == 'HAMA'){
							//$message = "Silahkan isi dan upload Data Hama 2025 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formHama2025Html?jwt=" . $jwtToken;
							//$this->sendMessage2($message, $exists->nohp);
							$this->sendUrl('https://prodis.ksotebu.com/webhook/formHama2025Html?jwt=' . $jwtToken, $exists->nohp, 'https://prodis.ksotebu.com/webhook/formHama2025Html?jwt=' . $jwtToken, 'Form Upload Data Hama 2025', 'Silahkan isi dan upload Data Hama 2025 di link berikut');
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'HAMA']);

						}else if($kode == 'BANJIR'){
							//$message = "Silahkan isi dan upload Data Banjir 2025 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formTebuBanjir2025Html?jwt=" . $jwtToken;
							//$this->sendMessage2($message, $exists->nohp);
							$this->sendUrl('https://prodis.ksotebu.com/webhook/formTebuBanjir2025Html?jwt=' . $jwtToken, $exists->nohp, 'https://prodis.ksotebu.com/webhook/formTebuBanjir2025Html?jwt=' . $jwtToken, 'Form Upload Data Banjir 2025', 'Silahkan isi dan upload Data Banjir 2025 di link berikut');
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'BANJIR']);

						}else if($kode == 'APKTMA'){
							$documentUrl = "Download Aplikasi Digifarm TMA \n https://ksotebu.com/Digifarm-TMA.apk";
							$this->sendMessage2($documentUrl, $exists->nohp);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'APKTMA']);

						}else if($kode == 'APKDIFA'){
							$documentUrl = "Download Aplikasi Digifarm GROW \n https://ksotebu.com/Digifarm-GROW.apk";
							$this->sendMessage2($documentUrl, $exists->nohp);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'APKGROW']);

						}else if($kode == 'PICA'){
							$message = "Silahkan isi dan upload Data PICA KSO 2026 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formPicaHtml?jwt=" . $jwtToken;
							$this->sendMessage2($message, $exists->nohp);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'PICA']);
						}else if($kode == 'PICAACTION'){
							$message = "Silahkan isi dan upload Data Action PICA KSO 2026 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formPicaActionHtml?jwt=" . $jwtToken;
							$this->sendMessage2($message, $exists->nohp);
							\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'PICA_ACTION']);

						}
						else if($kode == 'SLIP'){
							$nikData = DB::table('master_nohp')
								->select('master_nohp.nik')
								->where('master_nohp.nohp', $exists->nohp)
								->whereNotNull('master_nohp.nik')
								->first();
							if (!empty($nikData) ) {
								
								$bulan = "09";
								$tahun = "2026";
								if(!empty($filter_tgl2) && strlen($filter_tgl2) ==6 ){
									$bulan = substr($filter_tgl2, 0, 2);
									$tahun = substr($filter_tgl2, 2, 4);
								}
								$encryptionKey = 'kso_secret_key_2025'; // Store this securely in .env
								//cek folder di $documentUrl = 'https://prodis.ksotebu.com/uploads/slipgaji/' . $bulan . $tahun . '
								if (!file_exists(public_path('uploads/slipgaji/' . $bulan . $tahun))) {
									$this->sendMessage2('Maaf, data slip gaji Anda tidak ditemukan.', $exists->nohp);
								}else{
									$documentUrl = 'https://prodis.ksotebu.com/uploads/slipgaji/' . $bulan . $tahun . '/' . $nikData->nik . '.pdf';
									$encryptedUrl = base64_encode(openssl_encrypt($documentUrl, 'AES-128-CBC', $encryptionKey, 0, substr(md5($encryptionKey), 0, 16)));
									$caption = 'Slip Gaji ' . date('m-Y');
									//$this->sendDocument2($exists->nohp, $documentUrl, $caption);
									$viewUrl = url('webhook/viewPdfFromUrl') . '?url=' . urlencode($encryptedUrl) . '&jwt=' . $jwtToken;
									$message = "Silahkan klik link berikut untuk melihat slip gaji Anda:\n" . $viewUrl;
									//$this->sendMessage2($message, $exists->nohp);
									$this->sendUrl('https://prodis.ksotebu.com/webhook/viewPdfFromUrl?url=' . urlencode($encryptedUrl) . '&jwt=' . $jwtToken, $exists->nohp, $viewUrl, 'Slip Gaji bulan '.$bulan.' '.$tahun, 'Silahkan klik untuk melihat slip gaji Anda');
									\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'SLIP']);
								}
							} else {
								$message = 'Maaf, data slip gaji Anda tidak ditemukan.';
								$this->sendMessage2($message, $exists->nohp);
								\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'SLIP_NOT_FOUND']);
							}	

						}else if (
							strpos($pesan, 'https://www.instagram.com/') !== false
						) {
							if (
								$whatsapp_number == '6285647384318' ||
								$whatsapp_number == '6289626396094' ||
								$whatsapp_number == '6281336606010'
							) {
								DB::table('tx_request_wa')->insert([
									'kategori' => 'instagram',
									'text' => $pesan,
									'whatsapp_number' => $whatsapp_number,
									'createdOn' => date('Y-m-d H:i:s')
								]);
								$this->sendMessage2("Update Pesan Sukses", $exists->nohp);
								\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'INSTAGRAM']);
							}
						}
						else{
							if($exists->use_ai == 'Y'){
								$this->N8nWebhook($whatsapp_number, $exists->nama,$pesan,$exists->afdeling, 'Y');
								\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'AI']);
							}else if($exists->use_ai == 'Z'){
								$this->N8nWebhook($whatsapp_number, $exists->nama,$pesan,$exists->afdeling, 'Z');
								\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'AI']);
							}else if($exists->use_ai == 'X'){
								$this->N8nWebhook($whatsapp_number, $exists->nama,$pesan,$exists->afdeling, 'X');
								\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'AI']);
							}else{
								$message = 'Halo Pak';
								if (isset($exists->nama)) {
									$message .= ' *' . $exists->nama . '*';
								}
								$message .= ' , Terimakasih sudah menghubungi kami. Berikut adalah layanan menu yang tersedia:';
								$message .= "\n\n*APK* - Download Aplikasi DigiFarm KSO";
								if(!empty($exists->afdeling)){
									$message .= "\n\n*LKP* - Upload Data LKP 2025";
									$message .= "\n\n*MORF* - Upload Data Morfologi 2025";
									$message .= "\n\n*TBG* - Upload Data Tebangan 2024";
									$message .= "\n\n*DRN* - Upload Foto Drone Lahan 2025";
									$message .= "\n\n*ROBOH* - Upload Data Tebu Roboh 2025";
									$message .= "\n\n*HAMA* - Upload Data Hama 2025";
									$message .= "\n\n*BANJIR* - Upload Data Banjir 2025";
									$message .= "\n\n*PICA* - Upload Data PICA KSO 2025";
									$message .= "\n\n*PICAACTION* - Upload Data Action PICA KSO 2025";
								}
								$message .= "\n\n*SLIP* - Download Slip Gaji Terbaru (cth: SLIP 122025)";
								$message .= "\n\n*ABSEN* - Presensi Kehadiran Karyawan (PeopleOne)";
								$message .= "\n\nSilakan ketik kode menu yang Anda inginkan untuk mendapatkan informasi lebih lanjut.";
								
								$this->sendMessage2($message,$exists->nohp);
								\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'replied', 'response' => 'MENU']);
							}
						}

						// Log message with message_id and content_hash to prevent duplicate processing
						\DB::table('tx_logs_wa')->insert([
							'nomer_wa' => $exists->nohp,
							'logs' => $body,
							'message_id' => $messageId,
							'content_hash' => $contentHash,
							'date' => now()
						]);

						
					} else {
						\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'no_user_found']);
					}
				} else {
					\DB::table('master_webhook')->where('id', $webhookId)->update(['status' => 'invalid_message']);
				}

				return response()->json(['status' => 'success']);
				break;
			}
		
	}
	public function destroy( Request $request)
	{
		
		
	}			
	
	// public function kirimpesandariai(){
	// 	$kode = request()->input('kode');
	// 	$nama = request()->input('nama');
	// 	$nohp = request()->input('nohp');
	// 	$bulan = request()->input('bulan', date('m'));
	// 	$tahun = request()->input('tahun', date('Y'));
	// 	$jwtPayload = [
	// 		'user' => $nama,
	// 		'nohp' => $nohp,
	// 		'exp' => time() + 900
	// 	];
	// 	$secretKey = '8uUC1YWkHD';
	// 	$jwtToken = $this->generateJwtToken($jwtPayload, $secretKey);
	// 	if ($kode == 'APK') {
	// 		$documentUrl = "Download Aplikasi Prodis KSO \n https://ksotebu.com/ProdisKSO.apk";
	// 		$this->sendMessage2($documentUrl, $nohp);
	// 	}else if ($kode == 'LKP') {
	// 		$message = "Silahkan isi dan upload LKP 2025 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formLkp2025Html?jwt=" . $jwtToken;
	// 		$this->sendMessage2($message, $nohp);
	// 	}else if ($kode == 'MORF') {
	// 		$this->sendUrl('https://prodis.ksotebu.com/webhook/formMorfologi2025Html?jwt=' . $jwtToken, $nohp, 'https://prodis.ksotebu.com/webhook/formMorfologi2025Html?jwt=' . $jwtToken, 'Form Upload Morfologi 2025', 'Silahkan isi dan upload Morfologi 2025 di link berikut');
	// 	}else if ($kode == 'TBG') {
	// 		$this->sendUrl('https://prodis.ksotebu.com/webhook/formFotoTebangLahanHtml?jwt=' . $jwtToken, $nohp, 'https://prodis.ksotebu.com/webhook/formFotoTebangLahanHtml?jwt=' . $jwtToken, 'Form Upload Tebangan 2025', 'Silahkan isi dan upload Tebangan 2025 di link berikut');
	// 	}else if($kode == 'DRN'){
	// 		$this->sendUrl('https://prodis.ksotebu.com/webhook/formFotoDroneHtml?jwt=' . $jwtToken, $nohp, 'https://prodis.ksotebu.com/webhook/formFotoDroneHtml?jwt=' . $jwtToken, 'Form Upload Foto Drone Lahan 2025', 'Silahkan isi dan upload Foto Drone Lahan 2025 di link berikut');
	// 	}else if($kode == 'ABSEN'){
	// 		$message = "Silahkan Absensi Kehadiran Karyawan di link berikut (PeopleOne):\nhttps://peopleone.sinergigula.com/presensilogin";
	// 		$this->sendMessage2($message, $nohp);
	// 	}else if($kode == 'ROBOH'){
	// 		$this->sendUrl('https://prodis.ksotebu.com/webhook/formTebuRoboh2025Html?jwt=' . $jwtToken, $nohp, 'https://prodis.ksotebu.com/webhook/formTebuRoboh2025Html?jwt=' . $jwtToken, 'Form Upload Tebu Roboh 2025', 'Silahkan isi dan upload Data Tebu Roboh 2025 di link berikut');
	// 	}else if($kode == 'HAMA'){
	// 		$this->sendUrl('https://prodis.ksotebu.com/webhook/formHama2025Html?jwt=' . $jwtToken, $nohp, 'https://prodis.ksotebu.com/webhook/formHama2025Html?jwt=' . $jwtToken, 'Form Upload Data Hama 2025', 'Silahkan isi dan upload Data Hama 2025 di link berikut');
	// 	}else if($kode == 'BANJIR'){
	// 		$this->sendUrl('https://prodis.ksotebu.com/webhook/formTebuBanjir2025Html?jwt=' . $jwtToken, $nohp, 'https://prodis.ksotebu.com/webhook/formTebuBanjir2025Html?jwt=' . $jwtToken, 'Form Upload Data Banjir 2025', 'Silahkan isi dan upload Data Banjir 2025 di link berikut');
	// 	}else if($kode == 'APKTMA'){
	// 		$documentUrl = "Download Aplikasi Digifarm TMA \n https://ksotebu.com/Digifarm-TMA.apk";
	// 		$this->sendMessage2($documentUrl, $nohp);
	// 	}else if($kode == 'APKDIFA'){
	// 		$documentUrl = "Download Aplikasi Digifarm GROW \n https://ksotebu.com/Digifarm-GROW.apk";
	// 		$this->sendMessage2($documentUrl, $nohp);
	// 	}else if($kode == 'PICA'){
	// 		$message = "Silahkan isi dan upload Data PICA KSO 2025 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formPicaHtml?jwt=" . $jwtToken;
	// 		$this->sendMessage2($message, $nohp);
	// 	}else if($kode == 'PICAACTION'){
	// 		$message = "Silahkan isi dan upload Data Action PICA KSO 2025 di link berikut:\nhttps://prodis.ksotebu.com/webhook/formPicaActionHtml?jwt=" . $jwtToken;
	// 		$this->sendMessage2($message, $nohp);
	// 	}
	// 	else if($kode == 'SLIP'){
	// 		$nikData = DB::table('master_nohp')
	// 			->select('master_nohp.nik')
	// 			->where('master_nohp.nohp', $nohp)
	// 			->whereNotNull('master_nohp.nik')
	// 			->first();
	// 		if (!empty($nikData) ) {


	// 			$encryptionKey = 'kso_secret_key_2025'; // Store this securely in .env
	// 			$documentUrl = 'https://prodis.ksotebu.com/uploads/slipgaji/' . $bulan . $tahun . '/' . $nikData->nik . '.pdf';
	// 			$encryptedUrl = base64_encode(openssl_encrypt($documentUrl, 'AES-128-CBC', $encryptionKey, 0, substr(md5($encryptionKey), 0, 16)));
	// 			$caption = 'Slip Gaji ' . date('m-Y');
	// 			//$this->sendDocument2($nohp, $documentUrl, $caption);
	// 			$viewUrl = url('webhook/viewPdfFromUrl') . '?url=' . urlencode($encryptedUrl) . '&jwt=' . $jwtToken;
	// 			$message = "Silahkan klik link berikut untuk melihat slip gaji Anda:\n" . $viewUrl;
	// 			//$this->sendMessage2($message, $nohp);
	// 			$this->sendUrl('https://prodis.ksotebu.com/webhook/viewPdfFromUrl?url=' . urlencode($encryptedUrl) . '&jwt=' . $jwtToken, $nohp, $viewUrl, 'Slip Gaji bulan '.$bulan.' '.$tahun, 'Silahkan klik untuk melihat slip gaji Anda');
	// 		} else {
	// 			$message = 'Maaf, data slip gaji Anda tidak ditemukan.';
	// 			$this->sendMessage2($message, $nohp);
	// 		}	

	// 	}
	// }
	


	public function sendMessage2($pesan, $nohp)
	{
		$this->startTyping($nohp);
		$payload = array(
			'chatId' => $nohp . '@c.us',
			'text' => $pesan,
			'session' => 'default'
		);

		$url = env('WAHA_URL') . '/api/sendText';

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, [
			'Content-Type: application/json',
			'Accept: application/json',
			'X-Api-Key: ' . env('API_KEY_WAHA')
		]);

		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		curl_close($ch);

		if ($httpCode >= 200 && $httpCode < 300) {
			$this->stopTyping($nohp);
			return response()->json(['message' => 'Message sent successfully'], 200);
		}else{
			
			$this->stopTyping($nohp);
		}

		return response()->json(['error' => 'Failed to send message'], $httpCode);
	}


	public function sendUrl($pesan, $nohp, $url, $title, $desc)
	{
		$payload = array(
			'chatId' => $nohp . '@c.us',
			'text' => $pesan,
			'session' => 'default',
			'linkPreviewHighQuality' => true,
			'preview' => array(
						"url" => $url,
						"title" => $title,
						"description" => $desc,
						"image" => array(
							"url" => "https://difa.ksotebu.com/assets/images/difa.png"
						)
			)
		);

		$url = env('WAHA_URL') . '/api/send/link-custom-preview';

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, [
			'Content-Type: application/json',
			'Accept: application/json',
			'X-Api-Key: ' . env('API_KEY_WAHA')
		]);

		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		curl_close($ch);

		if ($httpCode >= 200 && $httpCode < 300) {
			return response()->json(['message' => 'Message sent successfully'], 200);
		}

		return response()->json(['error' => 'Failed to send message, error: ' . $response], $httpCode);
	}

	

	public function sendDocument2($nohp, $documentUrl, $caption)
	{
		$payload = array(
			'session' => 'default',
			'chatId' => $nohp . '@c.us',
			'caption' => $caption,
			'file' => array(
				'mimetype' => 'application/pdf',
				'filename' => basename($documentUrl),
				'url' => $documentUrl
			)
		);

		$url = env('WAHA_URL') . '/api/sendFile';

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, [
			'Content-Type: application/json',
			'Accept: application/json',
			'X-Api-Key: ' . env('API_KEY_WAHA')
		]);

		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		curl_close($ch);

		if ($httpCode >= 200 && $httpCode < 300) {
			return response()->json(['message' => 'Document sent successfully'], 200);
		}

		return response()->json(['error' => 'Failed to send document'], $httpCode);
	}

	

	public function broadcastMessage($message, $recipients)
	{
		foreach ($recipients as $nohp) {
			$this->sendMessage2($message, $nohp);
			sleep(5); // Delay for 5 seconds between each message
		}

		return response()->json(['message' => 'Broadcast completed successfully'], 200);
	}

	public function getReportKlentekPerKebun(Request $request)
	{
		$jwt = $request->input('jwt');
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$decodedJwt = explode('.', $jwt);
			if (count($decodedJwt) !== 3) {
				throw new \Exception('Invalid JWT format');
			}

			$payload = json_decode(base64_decode($decodedJwt[1]), true);
			if (!$payload || !isset($payload['exp']) || $payload['exp'] < time()) {
				return response()->json(['error' => 'JWT token is invalid or expired'], 401);
			}
			

		} catch (\Exception $e) {
			return response()->json(['error' => 'Invalid JWT token'], 401);
		}
		$date = $request->input('filter_tgl', date('dmY'));
		$tanggal = $date; // format: ddmmyyyy
		$hari = substr($tanggal, 0, 2);   // 29
		$bulan = substr($tanggal, 2, 2);  // 04
		$tahun = substr($tanggal, 4, 4);  // 2025

		$hasiltgl = $tahun . '-' . $bulan . '-' . $hari;
 

		$results = \DB::select("CALL GetRekapKlentekPerHari(?)", [$hasiltgl]);
		$this->data['results'] = $results;
		$this->data['tanggal'] = $hasiltgl;
		$pdf = PDF::loadView('reportklentekkebun.exportpdf', $this->data);
		return $pdf->stream('reportklentek_per_kebun.pdf');
	}

	public function getReportSisaTeburayon(Request $request)
	{
		$jwt = $request->input('jwt');
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}
		$data11 = DB::table('q_sisa_tebu_tertebang_rayon')
		->select('nama_kebun','nama_rayon','takmar','takmar_tebu','takmar_protas','tertebang','real_tebu','real_protas','sisa','sisa_tebu','sisa_protas','persen_sisa','persen_sisa_tebu')
		->get();
		$this->data['datasisatebu'] = $data11;
		$pdf = PDF::loadView('dashboard.exportpdf', $this->data)->setPaper('a3', 'landscape');
		return $pdf->stream('sisatebu.pdf');
		// return view('dashboard.exportpdf', $this->data);
	}

	public function getReportMutuTeburayon(Request $request)
	{
		$jwt = $request->input('jwt');
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}
		
		    // Fetch data from the database based on the date range
		$html = '';
		$html .= '<h1 style="text-align: center;">Report Mutu Tebu Rayon</h1>';
		$html .='<script src="https://code.highcharts.com/highcharts.js"></script><script src="https://code.highcharts.com/highcharts-more.js"></script><script src="https://code.highcharts.com/highcharts-3d.js"></script>';

		$rayons = DB::table('master_rayon')->pluck('nama_rayon');
		foreach ($rayons as $rayon) {
			$html .= $this->getReportMutuTeburayonData($rayon);
		}
		// $this->data['mututebu'] = $data;
		// $pdf = PDF::loadView('dashboard.mututebuexportpdf', $this->data)->setPaper('a3', 'landscape');
		// return $pdf->stream('mututebu.pdf');
		// return view('dashboard.mututebuexportpdf', $this->data);
		return $html;
	}

	public function getReportMutuTeburayonData($nama_rayon)
	{
			$data = DB::table('q_prod_rekap_mutu_rayon_tgl')
				->select('nama_rayon','tgl_giling', 'mutu_A', 'mutu_B', 'mutu_C', 'mutu_D', 'mutu_E')
				->where('nama_rayon', $nama_rayon)
				->whereBetween('tgl_giling', [now()->subDays(14)->format('Y-m-d'), now()->format('Y-m-d')])
				->get();

			if ($data->isEmpty()) {
				return '';
			}

			// Return the data as JSON
			$this->data['mututebu'] = $data;
			$this->data['id'] = str_replace(' ', '_', $data[0]->nama_rayon);
			$this->data['nama_rayon'] = $data[0]->nama_rayon;
	
			// Return the first view or both views as needed
			return view('dashboard.mututebuexportpdf', $this->data);
	}

	public function getReportProtasRendemen(Request $request)
	{
		$jwt = $request->input('jwt');
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}
		
		    // Fetch data from the database based on the date range
		$html = '';
		$html .= '<h1 style="text-align: center;">Report Protas Rendemen Rayon</h1>';
		$html .='<script src="https://code.highcharts.com/highcharts.js"></script><script src="https://code.highcharts.com/highcharts-more.js"></script><script src="https://code.highcharts.com/highcharts-3d.js"></script>';

		$rayons = DB::table('master_rayon')->pluck('nama_rayon');
		foreach ($rayons as $rayon) {
			$html .= $this->getReportProtasRendemenData($rayon);
		}
		// $this->data['mututebu'] = $data;
		// $pdf = PDF::loadView('dashboard.mututebuexportpdf', $this->data)->setPaper('a3', 'landscape');
		// return $pdf->stream('mututebu.pdf');
		// return view('dashboard.mututebuexportpdf', $this->data);
		return $html;
	}

	public function getReportProtasRendemenData($nama_rayon)
	{
		$last14Days = collect(range(0, 13))->map(function ($day) {
			return date('Y-m-d', strtotime("-$day days"));
		})->reverse()->values();
		// Fetch data from the database
		$data = DB::select('call GetDataProtasRendemenRayon(?,?,?)', [
			$last14Days->first(),
			$last14Days->last(),
			$nama_rayon
		]);

		if (empty($data)) {
			return '';
		}

		// Map the data into a collection
		$data10 = collect($data)->mapWithKeys(function ($item) {
			return [date('Y-m-d', strtotime($item->tgl_giling)) => [
				'tgl_giling' => date_format(date_create($item->tgl_giling), "d-M"),
				'protas' => (float) str_replace(',', '.', $item->protas),
				'rendemen' => (float) str_replace(',', '.', $item->rendemen),
			]];
		});

		$this->data = [
					'tgl_giling'=> json_encode($data10->pluck('tgl_giling')->toArray()),
					'protas'=> json_encode($data10->pluck('protas')->toArray()),
					'rendemen'=> json_encode($data10->pluck('rendemen')->toArray()),
					'id' => str_replace(' ', '_', $nama_rayon),
					'nama_rayon' => $nama_rayon,
		];
		

			return view('dashboard.protasrendemen', $this->data);
		// Return the data as JSON		

	}

	public function kirimPesanKeSemua(Request $request)
	{
		// $recipients = \DB::table('master_nohp')->pluck('nohp')->toArray();
		// if (empty($recipients)) {
		// 	return response()->json(['error' => 'No recipients found'], 404);
		// }else{
		// 	$message = "Halo, ini adalah nomor admin KSO. Harap disimpan ya.";
		// 	return $this->broadcastMessage($message, $recipients);
		// }
		
	}

	function getcookielogin(){
			// URL tujuan
		$url = "https://sigula.sinergigula.com/index.php/user/postlogin";
		
		// $sess = \Session::get('tahuntanam');
		$tahunn = '2025';
		// if($sess == '2425'){
		// 	$tahunn = '2025';
		// }else if($sess == '2526'){
		// 	$tahunn = '2026';
		// }
		// Data POST
		$postData = [
			"username" => "rizki.r",
			"password" => "rizki.r",
			"tahungiling" => $tahunn
		];
		
		// Inisialisasi cURL
		$ch = curl_init($url);
		
		// Set opsi cURL
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
		curl_setopt($ch, CURLOPT_HEADER, true); // Untuk mendapatkan header
		curl_setopt($ch, CURLOPT_HTTPHEADER, [
			"Host: sigula.sinergigula.com",
			"Cookie: ci_session=a%3A6%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22f275b9aaacfd3807fd4622b61db3955d%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%2227.131.249.208%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A115%3A%22Mozilla%2F5.0%20%28Windows%20NT%2010.0%3B%20Win64%3B%20x64%29%20AppleWebKit%2F537.36%20%28KHTML%2C%20like%20Gecko%29%20Chrome%2F129.0.6668.71%20Safari%2F537.36%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1738732541%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3Bs%3A4%3A%22lang%22%3Bs%3A2%3A%22en%22%3B%7D213f39118e47cb0d3817ada9177d7b41d2b4eff1; PHPSESSID=63pq8d1kks2mil29lb87vequqi",
			"Content-Length: 50",
			"Cache-Control: max-age=0",
			"Sec-Ch-Ua: \"Chromium\";v=\"129\", \"Not=A?Brand\";v=\"8\"",
			"Sec-Ch-Ua-Mobile: ?0",
			"Sec-Ch-Ua-Platform: \"macOS\"",
			"Accept-Language: en-US,en;q=0.9",
			"Origin: https://sigula.sinergigula.com",
			"Content-Type: application/x-www-form-urlencoded",
			"Upgrade-Insecure-Requests: 1",
			"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.6668.71 Safari/537.36",
			"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
			"Sec-Fetch-Site: same-origin",
			"Sec-Fetch-Mode: navigate",
			"Sec-Fetch-User: ?1",
			"Sec-Fetch-Dest: document",
			"Referer: https://sigula.sinergigula.com/index.php/user/login",
			"Accept-Encoding: gzip, deflate, br",
			"Priority: u=0, i"
		]);
		
		// Eksekusi cURL
		$response = curl_exec($ch);
		
		// Ambil informasi header
		$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
		$headers = substr($response, 0, $header_size);
		
		// Ambil Set-Cookie dari header
		preg_match_all('/Set-Cookie: (.*?);/i', $headers, $cookies);
		$setCookies = $cookies[1];
		
		// Tampilkan hasil
		// echo "Set-Cookie Headers:\n";
		return $setCookies[3];
		
		// Tutup cURL
		curl_close($ch);
		}

		public function parsedom($request){
			$dom = new DOMDocument();
			   libxml_use_internal_errors(true); // To suppress warnings from malformed HTML
			   $dom->loadHTML($request);
			   libxml_clear_errors();
			   
			   // Find table element
			   $table = $dom->getElementsByTagName('table');
			   $outtt = "";
			   // Output the table
			   if ($table->length > 0) {
				   // Convert table to string to view the HTML
				   $tableHtml = $dom->saveHTML($table->item(0));
				   $this->data['loaddata'] = $tableHtml;  // Store the table HTML in your data array
				   return $tableHtml;  // Or you can display it directly
			   } else {
				  return "No table found in the response.";
			   }
	   }

	public function getReportLHPConsole(Request $request)
	{
		$jwt = $request->input('jwt');
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}
			$url = "https://sigula.sinergigula.com/index.php/consolelhpmkso";
			$url2 = "https://sigula.sinergigula.com/index.php/consolelhpmkso/getdata";
			
			
			$date = $request->input('filter_tgl', date('dmY'));
			$tanggal = $date; // format: ddmmyyyy
			$hari = substr($tanggal, 0, 2);   // 29
			$bulan = substr($tanggal, 2, 2);  // 04
			$tahun = substr($tanggal, 4, 4);  // 2025

			$hasiltgl = $tahun . '-' . $bulan . '-' . $hari;

		        $regional = $request->input('regional');    

			$headers = [
				"Host: sigula.sinergigula.com",
				"Cookie: PHPSESSID=buqhp3eiirpjc5a969qnrgemus; ".$this->getcookielogin(),
				"Accept-Language: en-US,en;q=0.9",
				"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.6668.71 Safari/537.36",
				"Accept: application/json, text/javascript, */*; q=0.01",
				"Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
				"Origin: https://sigula.sinergigula.com",
				"Referer: https://sigula.sinergigula.com/index.php/consolelhpmkso",
			];
			
			$postData = [
	                "tgl" => $hasiltgl,
                    "regional" => $regional
			];
	
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			
			$response = curl_exec($ch);
			if (curl_errno($ch)) {
				echo 'Error:' . curl_error($ch);
			}
			curl_close($ch);
			
			$ch2 = curl_init();
			curl_setopt($ch2, CURLOPT_URL, $url2);
			curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch2, CURLOPT_POST, true);
			curl_setopt($ch2, CURLOPT_POSTFIELDS, http_build_query($postData));
			curl_setopt($ch2, CURLOPT_HTTPHEADER, $headers);
			
			$response2 = curl_exec($ch2);
			if (curl_errno($ch2)) {
				echo 'Error:' . curl_error($ch2);
			}
			curl_close($ch2);
			
			// Parse HTML to extract the table element
           
			 $outtt = $this->parsedom($response);
			 $outtt2 = $this->parsedom($response2);
			$this->data['loaddata'] = $outtt;
			$this->data['loaddata2'] = $outtt2;
			return view('consolelhpmkso.exportpdf', $this->data);
			// $pdf = PDF::loadView('consolelhpmkso.exportpdf', $this->data);
			// return $pdf->stream('report_lhp_console.pdf');
	}

	public function formLkp2025Html(Request $request)
	{
		$jwt = $request->input('jwt');
		$nohp = '';
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}

		Config::set('database.default', session('database_name', 'mysql_2526'));
		// Ambil data lahan untuk dropdown
		$nohp = $payload['nohp'] ?? '';

		$pekerjaan = DB::table('master_pekerjaan')->pluck('pekerjaan', 'pekerjaan');
		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>';
		$html .= '<br><h2 class="text-center mb-4 fw-bold">Upload Data LKP 2025</h2>';
		$html .= '<div class="container py-4">';
		$html .= '<form id="form-lkp2025" action="' . url('webhook?action_task=formLkp2025') . '" method="POST" enctype="multipart/form-data" class="rounded shadow bg-white p-3" style="max-width:100%;width:100%;margin:auto;">';
		$html .= csrf_field();

		// Petak autocomplete
		$html .= '<div class="mb-3">';
		$html .= '<label for="petak_id" class="form-label fw-bold">Petak</label>';
		$html .= '<select name="petak_id" id="petak_id" class="form-select" style="width:100%;" required>';
		$html .= '</select>';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="tanggal" class="form-label fw-bold">Tanggal</label>';
		$html .= '<input type="date" name="tanggal" id="tanggal" class="form-control" required max="' . date('Y-m-d') . '">';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="pekerjaan" class="form-label fw-bold">Pekerjaan</label>';
		$html .= '<select name="pekerjaan" id="pekerjaan" class="form-select" required>';
		$html .= '<option value="">Pilih Pekerjaan</option>';
		foreach ($pekerjaan as $id => $nama) {
			$html .= '<option value="' . $id . '">' . htmlspecialchars($nama) . '</option>';
		}
		$html .= '</select>';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="kualitas" class="form-label fw-bold">Kualitas</label>';
		$html .= '<select name="kualitas" id="kualitas" class="form-select" required>';
		$html .= '<option value="">Pilih Kualitas</option>';
		$html .= '<option value="Baik">Baik</option>';
		$html .= '<option value="Sedang">Sedang</option>';
		$html .= '<option value="Kurang">Kurang</option>';
		$html .= '</select>';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="foto" class="form-label fw-bold">Foto</label>';
		$html .= '<input type="file" name="foto" id="foto" class="form-control" accept="image/jpeg,image/png,image/jpg" required>';
		$html .= '</div>';
		$html .= '<input type="hidden" name="nohp" value="' . htmlspecialchars($nohp) . '">';
		

		$html .= '<div class="d-grid">';
		$html .= '<button type="submit" id="btn-simpan" class="btn btn-primary btn-block">Simpan</button>';
		$html .= '</div>';
		// Loading spinner (hidden by default)
		$html .= '<div id="loading-spinner" class="text-center mt-3" style="display:none;">
			<div class="spinner-border text-primary" role="status">
				<span class="visually-hidden">Loading...</span>
			</div>
			<p class="mt-2">Menyimpan data, mohon tunggu...</p>
		</div>';
		$html .= '</form>';
		$html .= '</div>';

		// jQuery & Select2
		$html .= '<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />';
		$html .= '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>';
		$html .= '<script>
			$(document).ready(function() {
				function initPetakSelect() {
					$("#petak_id").select2({
						placeholder: "Cari Petak",
						ajax: {
							url: "' . url('webhook/autocompletePetak') . '",
							dataType: "json",
							delay: 250,
							data: function(params) {
								return {
									term: params.term,
									lahan_id: $("#lahan_id").val()
								};
							},
							processResults: function(data) {
								return {
									results: data
								};
							},
							cache: true
						},
						minimumInputLength: 3
					});
				}
				$("#lahan_id").on("change", function() {
					$("#petak_id").val(null).trigger("change");
					initPetakSelect();
				});
				initPetakSelect();

				$("#form-lkp2025").on("submit", function() {
					$("#btn-simpan").prop("disabled", true);
					$("#loading-spinner").show();
				});
			});
		</script>';


		return $html;
	}
	public function formMorfologi2025Html(Request $request)
	{
		$jwt = $request->input('jwt');
		$nohp = '';
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}
		Config::set('database.default', session('database_name', 'mysql_2526'));


		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>';
		$html .= '<br><h2 class="text-center mb-4 fw-bold">Input Data Morfologi</h2>';
		$html .= '<div class="container py-4">';
		$html .= '<form id="form-batang" action="' . url('webhook?action_task=formMorfologi2025') . '" method="POST" enctype="multipart/form-data" class="rounded shadow bg-white p-3" style="max-width:100%;width:100%;margin:auto;">';
		$html .= csrf_field();

		// lahan_id (autocomplete/select2)
		$html .= '<div class="mb-3">';
		$html .= '<label for="lahan_id" class="form-label fw-bold">Lahan</label>';
		$html .= '<select name="lahan_id" id="lahan_id" class="form-select" style="width:100%;" required>';
		$html .= '</select>';
		$html .= '</div>';

		// tanggal
		$html .= '<div class="mb-3">';
		$html .= '<label for="tanggal" class="form-label fw-bold">Tanggal</label>';
		$html .= '<input type="date" name="tanggal" id="tanggal" class="form-control" required max="' . date('Y-m-d') . '">';
		$html .= '</div>';

		// jumlah_batang
		$html .= '<div class="mb-3">';
		$html .= '<label for="jumlah_batang" class="form-label fw-bold">Jumlah Batang</label>';
		$html .= '<input type="number" name="jumlah_batang" id="jumlah_batang" class="form-control" min="0" max="30" required>';
		$html .= '</div>';

		// tinggi_batang
		$html .= '<div class="mb-3">';
		$html .= '<label for="tinggi_batang" class="form-label fw-bold">Tinggi Batang (meter)</label>';
		$html .= '<input type="number" step="0.01" name="tinggi_batang" id="tinggi_batang" class="form-control" min="0" max="5" required>';
		$html .= '</div>';

		// diameter_batang
		$html .= '<div class="mb-3">';
		$html .= '<label for="diameter_batang" class="form-label fw-bold">Diameter Batang (mm)</label>';
		$html .= '<input type="number" step="0.01" name="diameter_batang" id="diameter_batang" class="form-control" min="0" max="50" required>';
		$html .= '</div>';

		// berat_batang_per_meter
		$html .= '<div class="mb-3">';
		$html .= '<label for="berat_batang_per_meter" class="form-label fw-bold">Berat Batang per Meter (kg)</label>';
		$html .= '<input type="number" step="0.01" name="berat_batang_per_meter" id="berat_batang_per_meter" class="form-control" min="0" max="1" required>';
		$html .= '</div>';

		// jumlah_ruas
		$html .= '<div class="mb-3">';
		$html .= '<label for="jumlah_ruas" class="form-label fw-bold">Jumlah Ruas</label>';
		$html .= '<input type="number" name="jumlah_ruas" id="jumlah_ruas" class="form-control" min="0" max="36" required>';
		$html .= '</div>';

		// foto
		$html .= '<div class="mb-3">';
		$html .= '<label for="foto" class="form-label fw-bold">Foto</label>';
		$html .= '<input type="file" name="foto" id="foto" class="form-control" accept="image/jpeg,image/png,image/jpg" required>';
		$html .= '</div>';

		// nohp (hidden input)
		$html .= '<input type="hidden" name="nohp" value="' . htmlspecialchars($nohp) . '">';
		$html .= '<div class="d-grid">';
		$html .= '<button type="submit" id="btn-simpan" class="btn btn-primary btn-block">Simpan</button>';
		$html .= '</div>';

		$html .= '<div id="loading-spinner" class="text-center mt-3" style="display:none;">
			<div class="spinner-border text-primary" role="status">
				<span class="visually-hidden">Loading...</span>
			</div>
			<p class="mt-2">Menyimpan data, mohon tunggu...</p>
		</div>';
		$html .= '</form>';
		$html .= '</div>';

		// jQuery & Select2
		$html .= '<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />';
		$html .= '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>';
		$html .= '<script>
			$(document).ready(function() {
				$("#lahan_id").select2({
					placeholder: "Cari Lahan",
					ajax: {
						url: "' . url('webhook/autocompletePetak') . '",
						dataType: "json",
						delay: 250,
						data: function(params) {
							return {
								term: params.term
							};
						},
						processResults: function(data) {
							return {
								results: data
							};
						},
						cache: true
					},
					minimumInputLength: 3
				});
				$("#form-batang").on("submit", function() {
					$("#btn-simpan").prop("disabled", true);
					$("#loading-spinner").show();
				});
			});
		</script>';

		return $html;
	}

	public function formTebuRoboh2025Html(Request $request)
	{
		$jwt = $request->input('jwt');
		$nohp = '';
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>';
		$html .= '<br><h2 class="text-center mb-4 fw-bold">Input Data Tebu Roboh</h2>';
		$html .= '<div class="container py-4">';
		$html .= '<form id="form-tebu-roboh" action="' . url('webhook?action_task=formTebuRoboh') . '" method="POST" enctype="multipart/form-data" class="rounded shadow bg-white p-3" style="max-width:100%;width:100%;margin:auto;">';
		$html .= csrf_field();

		$html .= '<div class="mb-3">';
		$html .= '<label for="lahan_id" class="form-label fw-bold">Lahan</label>';
		$html .= '<select name="lahan_id" id="lahan_id" class="form-select" style="width:100%;" required></select>';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="tanggal" class="form-label fw-bold">Tanggal</label>';
		$html .= '<input type="date" name="tanggal" id="tanggal" class="form-control" required max="' . date('Y-m-d') . '">';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="luas_roboh" class="form-label fw-bold">Luas Roboh (ha)</label>';
		$html .= '<input type="number" step="0.01" name="luas_roboh" id="luas_roboh" class="form-control" min="0" required>';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="foto" class="form-label fw-bold">Foto</label>';
		$html .= '<input type="file" name="foto" id="foto" class="form-control" accept="image/jpeg,image/png,image/jpg" required>';
		$html .= '</div>';

		$html .= '<input type="hidden" name="nohp" value="' . htmlspecialchars($nohp) . '">';
		$html .= '<div class="d-grid">';
		$html .= '<button type="submit" id="btn-simpan" class="btn btn-primary btn-block">Simpan</button>';
		$html .= '</div>';

		$html .= '<div id="loading-spinner" class="text-center mt-3" style="display:none;">
			<div class="spinner-border text-primary" role="status">
				<span class="visually-hidden">Loading...</span>
			</div>
			<p class="mt-2">Menyimpan data, mohon tunggu...</p>
		</div>';
		$html .= '</form>';
		$html .= '</div>';

		$html .= '<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />';
		$html .= '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>';
		$html .= '<script>
			$(document).ready(function() {
				$("#lahan_id").select2({
					placeholder: "Cari Lahan",
					ajax: {
						url: "' . url('webhook/autocompletePetak') . '",
						dataType: "json",
						delay: 250,
						data: function(params) {
							return {
								term: params.term
							};
						},
						processResults: function(data) {
							return {
								results: data
							};
						},
						cache: true
					},
					minimumInputLength: 3
				});
				$("#form-tebu-roboh").on("submit", function() {
					$("#btn-simpan").prop("disabled", true);
					$("#loading-spinner").show();
				});
			});
		</script>';

		return $html;
	}

	public function formTebuBanjir2025Html(Request $request)
	{
		$jwt = $request->input('jwt');
		$nohp = '';
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>';
		$html .= '<br><h2 class="text-center mb-4 fw-bold">Input Data Tebu Banjir</h2>';
		$html .= '<div class="container py-4">';
		$html .= '<form id="form-tebu-roboh" action="' . url('webhook?action_task=formTebuBanjir') . '" method="POST" enctype="multipart/form-data" class="rounded shadow bg-white p-3" style="max-width:100%;width:100%;margin:auto;">';
		$html .= csrf_field();

		$html .= '<div class="mb-3">';
		$html .= '<label for="lahan_id" class="form-label fw-bold">Lahan</label>';
		$html .= '<select name="lahan_id" id="lahan_id" class="form-select" style="width:100%;" required></select>';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="tanggal" class="form-label fw-bold">Tanggal</label>';
		$html .= '<input type="date" name="tanggal" id="tanggal" class="form-control" required max="' . date('Y-m-d') . '">';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="luas_banjir" class="form-label fw-bold">Luas Banjir (ha)</label>';
		$html .= '<input type="number" step="0.01" name="luas_banjir" id="luas_banjir" class="form-control" min="0" required>';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="foto" class="form-label fw-bold">Foto</label>';
		$html .= '<input type="file" name="foto" id="foto" class="form-control" accept="image/jpeg,image/png,image/jpg" required>';
		$html .= '</div>';

		$html .= '<input type="hidden" name="nohp" value="' . htmlspecialchars($nohp) . '">';
		$html .= '<div class="d-grid">';
		$html .= '<button type="submit" id="btn-simpan" class="btn btn-primary btn-block">Simpan</button>';
		$html .= '</div>';

		$html .= '<div id="loading-spinner" class="text-center mt-3" style="display:none;">
			<div class="spinner-border text-primary" role="status">
				<span class="visually-hidden">Loading...</span>
			</div>
			<p class="mt-2">Menyimpan data, mohon tunggu...</p>
		</div>';
		$html .= '</form>';
		$html .= '</div>';

		$html .= '<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />';
		$html .= '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>';
		$html .= '<script>
			$(document).ready(function() {
				$("#lahan_id").select2({
					placeholder: "Cari Lahan",
					ajax: {
						url: "' . url('webhook/autocompletePetak') . '",
						dataType: "json",
						delay: 250,
						data: function(params) {
							return {
								term: params.term
							};
						},
						processResults: function(data) {
							return {
								results: data
							};
						},
						cache: true
					},
					minimumInputLength: 3
				});
				$("#form-tebu-roboh").on("submit", function() {
					$("#btn-simpan").prop("disabled", true);
					$("#loading-spinner").show();
				});
			});
		</script>';

		return $html;
	}

	public function formHama2025Html(Request $request)
	{
			$jwt = $request->input('jwt');
			$nohp = '';
			if (!$jwt) {
				return response()->json(['error' => 'JWT token is required'], 400);
			}

			try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}

			$hptOptions = DB::table('master_hpt')->select('id', 'nama_hpt', 'deskripsi')->get();

			$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
			$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
			$html .= '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>';
			$html .= '<br><h2 class="text-center mb-4 fw-bold">Input Data Hama/Penyakit</h2>';
			$html .= '<div class="container py-4">';
			$html .= '<form id="form-hama" action="' . url('webhook?action_task=formHama2025') . '" method="POST" enctype="multipart/form-data" class="rounded shadow bg-white p-3" style="max-width:100%;width:100%;margin:auto;">';
			$html .= csrf_field();

			$html .= '<div class="mb-3">';
			$html .= '<label for="lahan_id" class="form-label fw-bold">Lahan</label>';
			$html .= '<select name="lahan_id" id="lahan_id" class="form-select" style="width:100%;" required></select>';
			$html .= '</div>';

			$html .= '<div class="mb-3">';
			$html .= '<label for="tanggal" class="form-label fw-bold">Tanggal</label>';
			$html .= '<input type="date" name="tanggal" id="tanggal" class="form-control" required max="' . date('Y-m-d') . '">';
			$html .= '</div>';

			$html .= '<div class="mb-3">';
			$html .= '<label for="luas_serangan" class="form-label fw-bold">Luas Serangan (ha)</label>';
			$html .= '<input type="number" step="0.01" name="luas_serangan" id="luas_serangan" class="form-control" min="0" required>';
			$html .= '</div>';

			$html .= '<div class="mb-3">';
			$html .= '<label for="jenis_hama_penyakit" class="form-label fw-bold">Jenis Hama/Penyakit</label>';
			$html .= '<select name="jenis_hama_penyakit" id="jenis_hama_penyakit" class="form-select" required>';
			$html .= '<option value="">Pilih Hama/Penyakit</option>';
			foreach ($hptOptions as $option) {
				$html .= '<option value="' . $option->id . '">' . htmlspecialchars($option->nama_hpt . ' - ' . $option->deskripsi) . '</option>';
			}
			$html .= '</select>';
			$html .= '</div>';

			$html .= '<div class="mb-3">';
			$html .= '<label for="foto" class="form-label fw-bold">Foto</label>';
			$html .= '<input type="file" name="foto" id="foto" class="form-control" accept="image/jpeg,image/png,image/jpg" required>';
			$html .= '</div>';

			$html .= '<input type="hidden" name="nohp" value="' . htmlspecialchars($nohp) . '">';
			$html .= '<div class="d-grid">';
			$html .= '<button type="submit" id="btn-simpan" class="btn btn-primary btn-block">Simpan</button>';
			$html .= '</div>';

			$html .= '<div id="loading-spinner" class="text-center mt-3" style="display:none;">
				<div class="spinner-border text-primary" role="status">
					<span class="visually-hidden">Loading...</span>
				</div>
				<p class="mt-2">Menyimpan data, mohon tunggu...</p>
			</div>';
			$html .= '</form>';
			$html .= '</div>';

			$html .= '<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />';
			$html .= '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
			$html .= '<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>';
			$html .= '<script>
				$(document).ready(function() {
					$("#lahan_id").select2({
						placeholder: "Cari Lahan",
						ajax: {
							url: "' . url('webhook/autocompletePetak') . '",
							dataType: "json",
							delay: 250,
							data: function(params) {
								return {
									term: params.term
								};
							},
							processResults: function(data) {
								return {
									results: data
								};
							},
							cache: true
						},
						minimumInputLength: 3
					});
					$("#form-hama").on("submit", function() {
						$("#btn-simpan").prop("disabled", true);
						$("#loading-spinner").show();
					});
				});
			</script>';

			return $html;
	}

	public function autocompletePetak(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2526'));
		$lahanId = $request->input('lahan_id');
		$term = $request->input('term', '');

		$query = DB::table('master_petak');


		if ($term) {
			$query->where('lahan_id', 'like', '%' . $term . '%');
		}

		$results = $query->select('lahan_id as id', DB::raw('CONCAT(lahan_id, " - ", nama_kebun) as text'))->limit(20)->get();

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

	public function autocompletePetak2(Request $request)
	{
		$lahanId = $request->input('lahan_id');
		$term = $request->input('term', '');

		$query = DB::table('master_petak');

		if ($term) {
			$query->where('lahan_id', 'like', '%' . $term . '%');
		}

		$results = $query->select('lahan_id as id', DB::raw('CONCAT(lahan_id, " - ", nama_kebun) as text'))->limit(20)->get();

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

	public function formLkp2025(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2526'));

			$validated = $request->validate([
				'petak_id' => 'required|exists:master_petak,lahan_id',
				'tanggal' => 'required|date',
				'pekerjaan' => 'required|string|max:255',
				'foto' => 'required|image|mimes:jpeg,png,jpg'
			]);

			$filename = null;

		if ($request->hasFile('foto')) {

			$file = $request->file('foto');
			$filename = time() . '_' . $file->getClientOriginalName();
			$destinationPath = public_path('uploads/foto_kebun');

			if (!file_exists($destinationPath)) {
				mkdir($destinationPath, 0777, true);
			}

			$image = null;
			$mime = $file->getMimeType();

			if (in_array($mime, ['image/jpeg', 'image/jpg'])) {
				$image = imagecreatefromjpeg($file->getPathname());
			} elseif ($mime === 'image/png') {
				$image = imagecreatefrompng($file->getPathname());
			}

			if ($image) {

				$width  = imagesx($image);
				$height = imagesy($image);

				/*
				============================
				COMPRESS FILE ASLI
				============================
				*/

				$targetFile = $destinationPath . '/' . $filename;

				$quality = 85;
				do {
					ob_start();
					imagejpeg($image, null, $quality);
					$imageData = ob_get_clean();
					$size = strlen($imageData);
					$quality -= 5;
				} while ($size > 1024 * 1024 && $quality > 10);

				file_put_contents($targetFile, $imageData);


				/*
				============================
				THUMB SMALL (200px)
				============================
				*/

				$thumbWidth = 200;
				$thumbHeight = intval($height * $thumbWidth / $width);

				$thumb = imagecreatetruecolor($thumbWidth, $thumbHeight);

				imagecopyresampled(
					$thumb,
					$image,
					0,0,0,0,
					$thumbWidth,
					$thumbHeight,
					$width,
					$height
				);

				$thumbName = 'thumb_'.$filename;
				$thumbFile = $destinationPath.'/'.$thumbName;

				imagejpeg($thumb, $thumbFile, 75);


				/*
				============================
				UPLOAD KE CDN
				============================
				*/

				$this->uploadCDN($targetFile, $filename, 'foto_kebun');
				$this->uploadCDN($thumbFile, $thumbName, 'foto_kebun');


				imagedestroy($image);
				imagedestroy($thumb);

			} else {
				$file->move($destinationPath, $filename);

				$this->uploadCDN(
					$destinationPath.'/'.$filename,
					$filename,
					'foto_kebun'
				);
			}
		}

			// Simpan ke database (contoh, sesuaikan dengan model/tabel Anda)
			DB::table('tx_foto_kebun')->insert([
				'lahan_id' => $validated['petak_id'],
				'tanggal' => $validated['tanggal'],
				'pekerjaan' => $validated['pekerjaan'],
				'kualitas' => $request->input('kualitas', ''),
				'foto' => $filename,
				'entry_by' => $request->input('nohp', ''), // Ambil nohp dari input
				'createdOn' => now(),
				'updatedOn' => now()
			]);


			$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
			$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
			$html .= '<div class="alert alert-success" role="alert">';
			$html .= '<h4 class="alert-heading">Data LKP 2025 Berhasil Disimpan!</h4>';
			$html .= '<p>Terima kasih, data LKP 2025 Anda telah berhasil disimpan.</p>';
			$html .= '<hr>';
			$html .= '<p class="mb-0">Anda dapat melihat data LKP 2025 Anda di Prodis KSO Web - LKP 2025</a>.</p>';
			$html .= '</div>';
			return $html;
	}

	public function formMorfologi2025(Request $request)
	{
		
		Config::set('database.default', session('database_name', 'mysql_2526'));

		$validated = $request->validate([
			'lahan_id' => 'required|exists:master_petak,lahan_id',
			'tanggal' => 'required|date',
			'jumlah_batang' => 'required|integer|min:0',
			'tinggi_batang' => 'required|numeric|min:0',
			'diameter_batang' => 'required|numeric|min:0',
			'berat_batang_per_meter' => 'required|numeric|min:0',
			'jumlah_ruas' => 'required|integer|min:0',
			'foto' => 'required|image|mimes:jpeg,png,jpg'
		]);

		$filename = null;

		if ($request->hasFile('foto')) {

			$file = $request->file('foto');
			$filename = time() . '_' . $file->getClientOriginalName();
			$destinationPath = public_path('uploads/foto_morfologi');

			if (!file_exists($destinationPath)) {
				mkdir($destinationPath, 0777, true);
			}

			$image = null;
			$mime = $file->getMimeType();

			if (in_array($mime, ['image/jpeg', 'image/jpg'])) {
				$image = imagecreatefromjpeg($file->getPathname());
			} elseif ($mime === 'image/png') {
				$image = imagecreatefrompng($file->getPathname());
			}

			if ($image) {

				$width  = imagesx($image);
				$height = imagesy($image);

				/*
				============================
				COMPRESS FILE ASLI
				============================
				*/

				$targetFile = $destinationPath . '/' . $filename;

				$quality = 85;
				do {
					ob_start();
					imagejpeg($image, null, $quality);
					$imageData = ob_get_clean();
					$size = strlen($imageData);
					$quality -= 5;
				} while ($size > 1024 * 1024 && $quality > 10);

				file_put_contents($targetFile, $imageData);


				/*
				============================
				THUMB SMALL (200px)
				============================
				*/

				$thumbWidth = 200;
				$thumbHeight = intval($height * $thumbWidth / $width);

				$thumb = imagecreatetruecolor($thumbWidth, $thumbHeight);

				imagecopyresampled(
					$thumb,
					$image,
					0,0,0,0,
					$thumbWidth,
					$thumbHeight,
					$width,
					$height
				);

				$thumbName = 'thumb_'.$filename;
				$thumbFile = $destinationPath.'/'.$thumbName;

				imagejpeg($thumb, $thumbFile, 75);


				/*
				============================
				UPLOAD KE CDN
				============================
				*/

				$this->uploadCDN($targetFile, $filename, 'foto_morfologi');
				$this->uploadCDN($thumbFile, $thumbName, 'foto_morfologi');


				imagedestroy($image);
				imagedestroy($thumb);

			} else {
				$file->move($destinationPath, $filename);

				$this->uploadCDN(
					$destinationPath.'/'.$filename,
					$filename,
					'foto_morfologi'
				);
			}
		}

		DB::table('tx_morfologi')->insert([
			'lahan_id' => $validated['lahan_id'],
			'tanggal' => $validated['tanggal'],
			'jumlah_batang' => $validated['jumlah_batang'],
			'tinggi_batang' => $validated['tinggi_batang'],
			'diameter_batang' => $validated['diameter_batang'],
			'berat_batang_per_meter' => $validated['berat_batang_per_meter'],
			'jumlah_ruas' => $validated['jumlah_ruas'],
			'foto' => $filename,
			'entry_by' => $request->input('nohp', ''),
			'createdOn' => now(),
			'updatedOn' => now()
		]);

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<div class="alert alert-success" role="alert">';
		$html .= '<h4 class="alert-heading">Data Morfologi Berhasil Disimpan!</h4>';
		$html .= '<p>Terima kasih, data morfologi Anda telah berhasil disimpan.</p>';
		$html .= '<hr>';
		$html .= '<p class="mb-0">Anda dapat melihat data morfologi Anda di Prodis KSO Web - Morfologi.</p>';
		$html .= '</div>';
		return $html;
	}

	public function formTebuRoboh(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2526'));

		$validated = $request->validate([
			'lahan_id' => 'required|exists:master_petak,lahan_id',
			'tanggal' => 'required|date',
			'luas_roboh' => 'required|numeric|min:0',
			'foto' => 'required|image|mimes:jpeg,png,jpg'
		]);

		$filename = null;

		if ($request->hasFile('foto')) {

			$file = $request->file('foto');
			$filename = time() . '_' . $file->getClientOriginalName();
			$destinationPath = public_path('uploads/foto_tebu_roboh');

			if (!file_exists($destinationPath)) {
				mkdir($destinationPath, 0777, true);
			}

			$image = null;
			$mime = $file->getMimeType();

			if (in_array($mime, ['image/jpeg', 'image/jpg'])) {
				$image = imagecreatefromjpeg($file->getPathname());
			} elseif ($mime === 'image/png') {
				$image = imagecreatefrompng($file->getPathname());
			}

			if ($image) {

				$width  = imagesx($image);
				$height = imagesy($image);

				/*
				============================
				COMPRESS FILE ASLI
				============================
				*/

				$targetFile = $destinationPath . '/' . $filename;

				$quality = 85;
				do {
					ob_start();
					imagejpeg($image, null, $quality);
					$imageData = ob_get_clean();
					$size = strlen($imageData);
					$quality -= 5;
				} while ($size > 1024 * 1024 && $quality > 10);

				file_put_contents($targetFile, $imageData);


				/*
				============================
				THUMB SMALL (200px)
				============================
				*/

				$thumbWidth = 200;
				$thumbHeight = intval($height * $thumbWidth / $width);

				$thumb = imagecreatetruecolor($thumbWidth, $thumbHeight);

				imagecopyresampled(
					$thumb,
					$image,
					0,0,0,0,
					$thumbWidth,
					$thumbHeight,
					$width,
					$height
				);

				$thumbName = 'thumb_'.$filename;
				$thumbFile = $destinationPath.'/'.$thumbName;

				imagejpeg($thumb, $thumbFile, 75);


				/*
				============================
				UPLOAD KE CDN
				============================
				*/

				$this->uploadCDN($targetFile, $filename, 'foto_tebu_roboh');
				$this->uploadCDN($thumbFile, $thumbName, 'foto_tebu_roboh');


				imagedestroy($image);
				imagedestroy($thumb);

			} else {
				$file->move($destinationPath, $filename);

				$this->uploadCDN(
					$destinationPath.'/'.$filename,
					$filename,
					'foto_tebu_roboh'
				);
			}
		}


		DB::table('tx_tebu_roboh')->insert([
			'lahan_id' => $validated['lahan_id'],
			'tanggal' => $validated['tanggal'],
			'luas_roboh' => $validated['luas_roboh'],
			'foto' => $filename,
			'entry_by' => $request->input('nohp', ''),
			'createdOn' => now(),
			'updatedOn' => now()
		]);

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<div class="alert alert-success" role="alert">';
		$html .= '<h4 class="alert-heading">Data Tebu Roboh Berhasil Disimpan!</h4>';
		$html .= '<p>Terima kasih, data tebu roboh Anda telah berhasil disimpan.</p>';
		$html .= '<hr>';
		$html .= '<p class="mb-0">Anda dapat melihat data tebu roboh Anda di Prodis KSO Web - Tebu Roboh.</p>';
		$html .= '</div>';
		return $html;
	}

	public function formTebuBanjir(Request $request)
	{
		
		Config::set('database.default', session('database_name', 'mysql_2526'));

		$validated = $request->validate([
			'lahan_id' => 'required|exists:master_petak,lahan_id',
			'tanggal' => 'required|date',
			'luas_banjir' => 'required|numeric|min:0',
			'foto' => 'required|image|mimes:jpeg,png,jpg'
		]);

		$filename = null;

		if ($request->hasFile('foto')) {

			$file = $request->file('foto');
			$filename = time() . '_' . $file->getClientOriginalName();
			$destinationPath = public_path('uploads/foto_banjir');

			if (!file_exists($destinationPath)) {
				mkdir($destinationPath, 0777, true);
			}

			$image = null;
			$mime = $file->getMimeType();

			if (in_array($mime, ['image/jpeg', 'image/jpg'])) {
				$image = imagecreatefromjpeg($file->getPathname());
			} elseif ($mime === 'image/png') {
				$image = imagecreatefrompng($file->getPathname());
			}

			if ($image) {

				$width  = imagesx($image);
				$height = imagesy($image);

				/*
				============================
				COMPRESS FILE ASLI
				============================
				*/

				$targetFile = $destinationPath . '/' . $filename;

				$quality = 85;
				do {
					ob_start();
					imagejpeg($image, null, $quality);
					$imageData = ob_get_clean();
					$size = strlen($imageData);
					$quality -= 5;
				} while ($size > 1024 * 1024 && $quality > 10);

				file_put_contents($targetFile, $imageData);


				/*
				============================
				THUMB SMALL (200px)
				============================
				*/

				$thumbWidth = 200;
				$thumbHeight = intval($height * $thumbWidth / $width);

				$thumb = imagecreatetruecolor($thumbWidth, $thumbHeight);

				imagecopyresampled(
					$thumb,
					$image,
					0,0,0,0,
					$thumbWidth,
					$thumbHeight,
					$width,
					$height
				);

				$thumbName = 'thumb_'.$filename;
				$thumbFile = $destinationPath.'/'.$thumbName;

				imagejpeg($thumb, $thumbFile, 75);


				/*
				============================
				UPLOAD KE CDN
				============================
				*/

				$this->uploadCDN($targetFile, $filename, 'foto_banjir');
				$this->uploadCDN($thumbFile, $thumbName, 'foto_banjir');


				imagedestroy($image);
				imagedestroy($thumb);

			} else {
				$file->move($destinationPath, $filename);

				$this->uploadCDN(
					$destinationPath.'/'.$filename,
					$filename,
					'foto_banjir'
				);
			}
		}

		DB::table('tx_tebu_banjir')->insert([
			'lahan_id' => $validated['lahan_id'],
			'tanggal' => $validated['tanggal'],
			'luas_banjir' => $validated['luas_banjir'],
			'foto' => $filename,
			'entry_by' => $request->input('nohp', ''),
			'createdOn' => now(),
			'updatedOn' => now()
		]);

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<div class="alert alert-success" role="alert">';
		$html .= '<h4 class="alert-heading">Data Tebu Roboh Berhasil Disimpan!</h4>';
		$html .= '<p>Terima kasih, data tebu roboh Anda telah berhasil disimpan.</p>';
		$html .= '<hr>';
		$html .= '<p class="mb-0">Anda dapat melihat data tebu roboh Anda di Prodis KSO Web - Tebu Roboh.</p>';
		$html .= '</div>';
		return $html;
	}

		public function formHama2025(Request $request)
		{
			Config::set('database.default', session('database_name', 'mysql_2526'));

			$validated = $request->validate([
				'lahan_id' => 'required|exists:master_petak,lahan_id',
				'tanggal' => 'required|date',
				'luas_serangan' => 'required|numeric|min:0',
				'jenis_hama_penyakit' => 'required|exists:master_hpt,id',
				'foto' => 'required|image|mimes:jpeg,png,jpg'
			]);

			$filename = null;
			if ($request->hasFile('foto')) {
				$file = $request->file('foto');
				$filename = time() . '_' . $file->getClientOriginalName();
				$destinationPath = public_path('uploads/foto_serangan_hpt');

				if (!file_exists($destinationPath)) {
					mkdir($destinationPath, 0777, true);
				}

				$image = null;
				$mime = $file->getMimeType();
				if (in_array($mime, ['image/jpeg', 'image/jpg'])) {
					$image = imagecreatefromjpeg($file->getPathname());
				} elseif ($mime === 'image/png') {
					$image = imagecreatefrompng($file->getPathname());
				}

				if ($image) {
					$targetFile = $destinationPath . '/' . $filename;
					$quality = 85;
					do {
						ob_start();
						imagejpeg($image, null, $quality);
						$imageData = ob_get_clean();
						$size = strlen($imageData);
						$quality -= 5;
					} while ($size > 1024 * 1024 && $quality > 10);

					file_put_contents($targetFile, $imageData);
					imagedestroy($image);
				} else {
					$file->move($destinationPath, $filename);
				}
			}

			DB::table('tx_serangan_hpt')->insert([
				'lahan_id' => $validated['lahan_id'],
				'tanggal' => $validated['tanggal'],
				'luas_serangan' => $validated['luas_serangan'],
				'jenis_hama_penyakit' => $validated['jenis_hama_penyakit'],
				'foto' => $filename,
				'entry_by' => $request->input('nohp', ''),
				'createdOn' => now(),
				'updatedOn' => now()
			]);

			$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
			$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
			$html .= '<div class="alert alert-success" role="alert">';
			$html .= '<h4 class="alert-heading">Data Serangan Hama/Penyakit Berhasil Disimpan!</h4>';
			$html .= '<p>Terima kasih, data serangan hama/penyakit Anda telah berhasil disimpan.</p>';
			$html .= '<hr>';
			$html .= '<p class="mb-0">Anda dapat melihat data serangan hama/penyakit Anda di Prodis KSO Web - Serangan HPT.</p>';
			$html .= '</div>';
			return $html;
		}

	public function formFotoTebangLahanHtml(Request $request)
	{
		$jwt = $request->input('jwt');
		$nohp = '';
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>';
		$html .= '<br><h2 class="text-center mb-4 fw-bold">Upload Foto Tebangan Lahan</h2>';
		$html .= '<div class="container py-4">';
		$html .= '<form id="form-foto-lahan" action="' . url('webhook?action_task=formFotoTebangLahan') . '" method="POST" enctype="multipart/form-data" class="rounded shadow bg-white p-3" style="max-width:100%;width:100%;margin:auto;">';
		$html .= csrf_field();

		// lahan_id (autocomplete/select2)
		$html .= '<div class="mb-3">';
		$html .= '<label for="lahan_id" class="form-label fw-bold">Lahan</label>';
		$html .= '<select name="lahan_id" id="lahan_id" class="form-select" style="width:100%;" required></select>';
		$html .= '</div>';

		// tanggal
		$html .= '<div class="mb-3">';
		$html .= '<label for="tanggal" class="form-label fw-bold">Tanggal</label>';
		$html .= '<input type="date" name="tanggal" id="tanggal" class="form-control" required max="' . date('Y-m-d') . '">';
		$html .= '</div>';

		// foto
		$html .= '<div class="mb-3">';
		$html .= '<label for="foto" class="form-label fw-bold">Foto</label>';
		$html .= '<input type="file" name="foto" id="foto" class="form-control" accept="image/jpeg,image/png,image/jpg" required>';
		$html .= '</div>';

		// nohp (hidden input)
		$html .= '<input type="hidden" name="nohp" value="' . htmlspecialchars($nohp) . '">';
		$html .= '<div class="d-grid">';
		$html .= '<button type="submit" id="btn-simpan" class="btn btn-primary btn-block">Simpan</button>';
		$html .= '</div>';

		$html .= '<div id="loading-spinner" class="text-center mt-3" style="display:none;">
			<div class="spinner-border text-primary" role="status">
				<span class="visually-hidden">Loading...</span>
			</div>
			<p class="mt-2">Menyimpan data, mohon tunggu...</p>
		</div>';
		$html .= '</form>';
		$html .= '</div>';

		// jQuery & Select2
		$html .= '<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />';
		$html .= '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>';
		$html .= '<script>
			$(document).ready(function() {
				$("#lahan_id").select2({
					placeholder: "Cari Lahan",
					ajax: {
						url: "' . url('webhook/autocompletePetak2') . '",
						dataType: "json",
						delay: 250,
						data: function(params) {
							return {
								term: params.term
							};
						},
						processResults: function(data) {
							return {
								results: data
							};
						},
						cache: true
					},
					minimumInputLength: 3
				});
				$("#form-foto-lahan").on("submit", function() {
					$("#btn-simpan").prop("disabled", true);
					$("#loading-spinner").show();
				});
			});
		</script>';

		return $html;
	}

	public function formFotoTebangLahan(Request $request)
	{

		$validated = $request->validate([
			'lahan_id' => 'required|exists:master_petak,lahan_id',
			'tanggal' => 'required|date',
			'foto' => 'required|image|mimes:jpeg,png,jpg'
		]);

		$filename = null;
		if ($request->hasFile('foto')) {
			$file = $request->file('foto');
			$filename = time() . '_' . $file->getClientOriginalName();
			$destinationPath = public_path('uploads/foto_petakebun');

			if (!file_exists($destinationPath)) {
				mkdir($destinationPath, 0777, true);
			}

			$image = null;
			$mime = $file->getMimeType();
			if (in_array($mime, ['image/jpeg', 'image/jpg'])) {
				$image = imagecreatefromjpeg($file->getPathname());
			} elseif ($mime === 'image/png') {
				$image = imagecreatefrompng($file->getPathname());
			}

			if ($image) {
				$targetFile = $destinationPath . '/' . $filename;
				$quality = 85;
				do {
					ob_start();
					imagejpeg($image, null, $quality);
					$imageData = ob_get_clean();
					$size = strlen($imageData);
					$quality -= 5;
				} while ($size > 1024 * 1024 && $quality > 10);

				file_put_contents($targetFile, $imageData);
				imagedestroy($image);
			} else {
				$file->move($destinationPath, $filename);
			}
		}

		DB::table('tx_foto_tebangan_lahan')->insert([
			'lahan_id' => $validated['lahan_id'],
			'tanggal' => $validated['tanggal'],
			'foto' => $filename,
			'entry_by' => $request->input('nohp', ''),
			'createdOn' => now(),
			'updatedOn' => now()
		]);

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<div class="alert alert-success" role="alert">';
		$html .= '<h4 class="alert-heading">Data Tebangan Berhasil Disimpan!</h4>';
		$html .= '<p>Terima kasih, data Tebangan Anda telah berhasil disimpan.</p>';
		$html .= '<hr>';
		$html .= '<p class="mb-0">Anda dapat melihat data Tebangan Anda di Prodis KSO Web - Tebangan.</p>';
		$html .= '</div>';
		return $html;
	}

	public function formFotoDroneHtml(Request $request)
	{
		$jwt = $request->input('jwt');
		$nohp = '';
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>';
		$html .= '<br><h2 class="text-center mb-4 fw-bold">Upload Foto Drone Lahan</h2>';
		$html .= '<div class="container py-4">';
		$html .= '<form id="form-foto-drone" action="' . url('webhook?action_task=formFotoDrone') . '" method="POST" enctype="multipart/form-data" class="rounded shadow bg-white p-3" style="max-width:100%;width:100%;margin:auto;">';
		$html .= csrf_field();

		$html .= '<div class="mb-3">';
		$html .= '<label for="lahan_id" class="form-label fw-bold">Lahan</label>';
		$html .= '<select name="lahan_id" id="lahan_id" class="form-select" style="width:100%;" required></select>';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="tanggal" class="form-label fw-bold">Tanggal</label>';
		$html .= '<input type="date" name="tanggal" id="tanggal" class="form-control" required max="' . date('Y-m-d') . '">';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label for="foto" class="form-label fw-bold">Foto</label>';
		$html .= '<input type="file" name="foto" id="foto" class="form-control" accept="image/jpeg,image/png,image/jpg" required>';
		$html .= '</div>';

		$html .= '<input type="hidden" name="nohp" value="' . htmlspecialchars($nohp) . '">';
		$html .= '<div class="d-grid">';
		$html .= '<button type="submit" id="btn-simpan" class="btn btn-primary btn-block">Simpan</button>';
		$html .= '</div>';

		$html .= '<div id="loading-spinner" class="text-center mt-3" style="display:none;">
			<div class="spinner-border text-primary" role="status">
				<span class="visually-hidden">Loading...</span>
			</div>
			<p class="mt-2">Menyimpan data, mohon tunggu...</p>
		</div>';
		$html .= '</form>';
		$html .= '</div>';

		$html .= '<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />';
		$html .= '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>';
		$html .= '<script>
			$(document).ready(function() {
				$("#lahan_id").select2({
					placeholder: "Cari Lahan",
					ajax: {
						url: "' . url('webhook/autocompletePetak') . '",
						dataType: "json",
						delay: 250,
						data: function(params) {
							return {
								term: params.term
							};
						},
						processResults: function(data) {
							return {
								results: data
							};
						},
						cache: true
					},
					minimumInputLength: 3
				});
				$("#form-foto-drone").on("submit", function() {
					$("#btn-simpan").prop("disabled", true);
					$("#loading-spinner").show();
				});
			});
		</script>';

		return $html;
	}

	public function formFotoDrone(Request $request)
	{
				Config::set('database.default', session('database_name', 'mysql_2526'));	
		
		$validated = $request->validate([
			'lahan_id' => 'required|exists:master_petak,lahan_id',
			'tanggal' => 'required|date',
			'foto' => 'required|image|mimes:jpeg,png,jpg'
		]);

		$filename = null;

		if ($request->hasFile('foto')) {

			$file = $request->file('foto');
			$filename = time() . '_' . $file->getClientOriginalName();
			$destinationPath = public_path('uploads/foto_drone');

			if (!file_exists($destinationPath)) {
				mkdir($destinationPath, 0777, true);
			}

			$image = null;
			$mime = $file->getMimeType();

			if (in_array($mime, ['image/jpeg', 'image/jpg'])) {
				$image = imagecreatefromjpeg($file->getPathname());
			} elseif ($mime === 'image/png') {
				$image = imagecreatefrompng($file->getPathname());
			}

			if ($image) {

				$width  = imagesx($image);
				$height = imagesy($image);

				/*
				============================
				COMPRESS FILE ASLI
				============================
				*/

				$targetFile = $destinationPath . '/' . $filename;

				$quality = 85;
				do {
					ob_start();
					imagejpeg($image, null, $quality);
					$imageData = ob_get_clean();
					$size = strlen($imageData);
					$quality -= 5;
				} while ($size > 1024 * 1024 && $quality > 10);

				file_put_contents($targetFile, $imageData);


				/*
				============================
				THUMB SMALL (200px)
				============================
				*/

				$thumbWidth = 200;
				$thumbHeight = intval($height * $thumbWidth / $width);

				$thumb = imagecreatetruecolor($thumbWidth, $thumbHeight);

				imagecopyresampled(
					$thumb,
					$image,
					0,0,0,0,
					$thumbWidth,
					$thumbHeight,
					$width,
					$height
				);

				$thumbName = 'thumb_'.$filename;
				$thumbFile = $destinationPath.'/'.$thumbName;

				imagejpeg($thumb, $thumbFile, 75);


				/*
				============================
				UPLOAD KE CDN
				============================
				*/

				$this->uploadCDN($targetFile, $filename, 'foto_drone');
				$this->uploadCDN($thumbFile, $thumbName, 'foto_drone');


				imagedestroy($image);
				imagedestroy($thumb);

			} else {
				$file->move($destinationPath, $filename);

				$this->uploadCDN(
					$destinationPath.'/'.$filename,
					$filename,
					'foto_drone'
				);
			}
		}

		DB::table('tx_foto_drone')->insert([
			'lahan_id' => $validated['lahan_id'],
			'tanggal' => $validated['tanggal'],
			'foto' => $filename,
			'entry_by' => $request->input('nohp', ''),
			'createdOn' => now(),
			'updatedOn' => now()
		]);

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<div class="alert alert-success" role="alert">';
		$html .= '<h4 class="alert-heading">Data Foto Drone Berhasil Disimpan!</h4>';
		$html .= '<p>Terima kasih, data foto drone Anda telah berhasil disimpan.</p>';
		$html .= '<hr>';
		$html .= '<p class="mb-0">Anda dapat melihat data foto drone Anda di Prodis KSO Web - Foto Drone.</p>';
		$html .= '</div>';
		return $html;
	}

	public function formPicaHtml(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2627'));

		$jwt = $request->input('jwt');
		$nohp = '';

		if (!$jwt) {
				return response()->json(['error' => 'JWT token is required'], 400);
			}

			try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}

		$problemGroups = DB::table('master_problem_group_pica')
			->select('id', 'problem_group')
			->orderBy('problem_group')
			->get();

		$areaProblems = DB::table('master_area_pica')
			->select('id', 'area_problem')
			->orderBy('area_problem')
			->get();

		$problems = DB::table('master_problem_pica')
			->select('id', 'problem', 'kode_area_pica')
			->orderBy('problem')
			->get();

		$correctives = DB::table('master_corective_pica')
			->select('id', 'corrective', 'kode_area_pica')
			->orderBy('corrective')
			->get();
		
		$satuanOptions = DB::table('master_satuan_pica')
			->select('satuan')
			->distinct()
			->orderBy('satuan')
			->pluck('satuan');

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>';
		$html .= '<br><h2 class="text-center mb-4 fw-bold">Form PICA KSO</h2>';
		$html .= '<div class="container py-4">';
		$html .= '<form id="form-prioritas-ho" action="' . url('webhook?action_task=formPica') . '" method="POST" class="rounded shadow bg-white p-3" style="max-width:100%;width:100%;margin:auto;">';
		$html .= csrf_field();

		$html .= '<div class="mb-3">';
		$html .= '<label for="lahan_id" class="form-label fw-bold">Lahan</label>';
		$html .= '<select name="lahan_id" id="lahan_id" class="form-select" style="width:100%;" required></select>';
		$html .= '</div>';

		$html .= '<div class="mb-3">';
		$html .= '<label class="form-label fw-bold">Problem Group</label>';
		$html .= '<select name="problem_group_id" class="form-select" required>';
		$html .= '<option value="">Pilih Problem Group</option>';
		foreach ($problemGroups as $row) {
			$html .= '<option value="' . $row->id . '">' . htmlspecialchars($row->problem_group) . '</option>';
		}
		$html .= '</select></div>';

		$html .= '<div class="mb-3">';
		$html .= '<label class="form-label fw-bold">Area Problem</label>';
		$html .= '<select name="area_problem_id" id="area_problem_id" class="form-select" required>';
		$html .= '<option value="">Pilih Area Problem</option>';
		foreach ($areaProblems as $row) {
			$html .= '<option value="' . $row->id . '">' . htmlspecialchars($row->area_problem) . '</option>';
		}
		$html .= '</select></div>';

		$html .= '<div class="mb-3">';
		$html .= '<label class="form-label fw-bold">Problem</label>';
		$html .= '<select name="problem_id" id="problem_id" class="form-select" required>';
		$html .= '<option value="">Pilih Problem</option>';
		$html .= '</select></div>';

		$html .= '<div class="mb-3">';
		$html .= '<label class="form-label fw-bold">Corrective</label>';
		$html .= '<select name="corrective_id" id="corrective_id" class="form-select" required>';
		$html .= '<option value="">Pilih Corrective</option>';
		$html .= '</select></div>';

		$html .= '<div class="mb-3"><label class="form-label fw-bold">Tanggal Target</label><input type="date" name="tanggal_target" class="form-control" required></div>';
		$html .= '<div class="mb-3"><label class="form-label fw-bold">Persen Target (%)</label><input type="number" step="0.01" min="0" max="100" name="persen_target" class="form-control" required></div>';
		$html .= '<div class="mb-3"><label class="form-label fw-bold">Kuantum</label><input type="number" step="0.01" min="0" name="kuantum" class="form-control" required></div>';
		$html .= '<div class="mb-3"><label class="form-label fw-bold">Satuan</label>';
			$html .= '<select name="satuan" class="form-select" required>';
				$html .= '<option value="">Pilih Satuan</option>';
		foreach ($satuanOptions as $satuan) {
			$html .= '<option value="' . htmlspecialchars($satuan) . '">' . htmlspecialchars($satuan) . '</option>';
		}
		$html .= '</select></div>';
		$html .= '<div class="mb-3"><label class="form-label fw-bold">Rupiah</label><input type="number" step="1" min="0" name="rupiah" class="form-control" required></div>';
		$html .= '<div class="mb-3"><label class="form-label fw-bold">Prioritas HO</label>';
		$html .= '<select name="prioritas_ho" class="form-select" required>';
		$html .= '<option value="">Pilih Prioritas</option>';
		$html .= '<option value="1">Prioritas</option>';
		$html .= '</select></div>';

		$html .= '<input type="hidden" name="nohp" value="' . htmlspecialchars($nohp) . '">';
		$html .= '<div class="d-grid"><button type="submit" id="btn-simpan" class="btn btn-primary">Simpan</button></div>';

		$html .= '<div id="loading-spinner" class="text-center mt-3" style="display:none;">
			<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div>
			<p class="mt-2">Menyimpan data, mohon tunggu...</p>
		</div>';

		$html .= '</form></div>';
		$html .= '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>';
		$html .= '<script>
			const problemData = ' . json_encode($problems) . ';
			const correctiveData = ' . json_encode($correctives) . ';

			function fillProblem(areaId) {
				let html = \'<option value="">Pilih Problem</option>\';
				problemData.forEach(function(item) {
					if (String(item.kode_area_pica) === String(areaId)) {
						html += \'<option value="\' + item.id + \'">\' + item.problem + \'</option>\';
					}
				});
				$("#problem_id").html(html);
			}

			function fillCorrective(areaId) {
				let html = \'<option value="">Pilih Corrective</option>\';
				correctiveData.forEach(function(item) {
					if (String(item.kode_area_pica) === String(areaId)) {
						html += \'<option value="\' + item.id + \'">\' + item.corrective + \'</option>\';
					}
				});
				$("#corrective_id").html(html);
			}

			$(document).ready(function() {
				$("#lahan_id").select2({
					placeholder: "Cari Lahan",
					ajax: {
						url: "' . url('webhook/autocompletePetak') . '",
						dataType: "json",
						delay: 250,
						data: function(params) {
							return { term: params.term };
						},
						processResults: function(data) {
							return { results: data };
						},
						cache: true
					},
					minimumInputLength: 3
				});

				$("#area_problem_id").on("change", function() {
					const areaId = $(this).val();
					fillProblem(areaId);
					fillCorrective(areaId);
				});

				$("#form-prioritas-ho").on("submit", function() {
					$("#btn-simpan").prop("disabled", true);
					$("#loading-spinner").show();
				});
			});
		</script>';

		return $html;
	}

	public function formPica(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2627'));

		$validated = $request->validate([
			'lahan_id' => 'required|exists:master_petak,lahan_id',
			'problem_group_id' => 'required|exists:master_problem_group_pica,id',
			'area_problem_id' => 'required|exists:master_area_pica,id',
			'problem_id' => 'required|exists:master_problem_pica,id',
			'corrective_id' => 'required|exists:master_corective_pica,id',
			'tanggal_target' => 'required|date',
			'persen_target' => 'required|numeric|min:0|max:100',
			'kuantum' => 'required|numeric|min:0',
			'satuan' => 'required|string|max:100',
			'rupiah' => 'required|numeric|min:0',
			'prioritas_ho' => 'required|string|max:50',
		]);

		$problemGroup = DB::table('master_problem_group_pica')->where('id', $validated['problem_group_id'])->first();
		$areaProblem = DB::table('master_area_pica')->where('id', $validated['area_problem_id'])->first();
		$problem = DB::table('master_problem_pica')
			->where('id', $validated['problem_id'])
			->where('kode_area_pica', $validated['area_problem_id'])
			->first();
		$corrective = DB::table('master_corective_pica')
			->where('id', $validated['corrective_id'])
			->where('kode_area_pica', $validated['area_problem_id'])
			->first();

		if (!$problem || !$corrective) {
			return response('Problem/Corrective tidak sesuai Area Problem.', 422);
		}

		DB::transaction(function () use ($validated, $request) {
			$idPicaPi = DB::table('tx_pica_pi')->insertGetId([
				'lahan_id' => $validated['lahan_id'],
				'problem_group' => $validated['problem_group_id'],
				'area_problem' => $validated['area_problem_id'],
				'tanggal' => now()->toDateString(),
				'entry_by' => $request->input('nohp', ''),
				'createdOn' => now(),
				'updatedOn' => now(),
			]);

			$idPicaPiProblem = DB::table('tx_pica_pi_problem')->insertGetId([
				'id_pica_pi' => $idPicaPi,
				'id_problem' => $validated['problem_id'],
			]);

			DB::table('tx_pica_pi_corrective')->insert([
				'id_pica_pi_problem' => $idPicaPiProblem,
				'id_corrective' => $validated['corrective_id'],
				'priority' => $validated['prioritas_ho'],
				'tanggal_target' => $validated['tanggal_target'],
				'persen_target' => $validated['persen_target'],
				'kuantum' => $validated['kuantum'],
				'satuan' => $validated['satuan'],
				'rupiah' => $validated['rupiah'],
			]);
		});

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<div class="alert alert-success" role="alert">';
		$html .= '<h4 class="alert-heading">Data PICA Berhasil Disimpan!</h4>';
		$html .= '<p>Terima kasih, data berhasil disimpan.</p>';
		$html .= '</div>';

		return $html;
	}

	public function formPicaActionHtml(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2627'));
		$jwt = $request->input('jwt');
		$nohp = '';

		if (!$jwt) {
				return response()->json(['error' => 'JWT token is required'], 400);
			}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>';
		$html .= '<br><h2 class="text-center mb-4 fw-bold">Form Corrective Action PICA</h2>';
		$html .= '<div class="container py-4">';

		// Search section
		$html .= '<div class="card mb-4 shadow-sm">';
		$html .= '<div class="card-header fw-bold">Cari Data PICA</div>';
		$html .= '<div class="card-body">';
		$html .= '<div class="mb-3"><label class="form-label fw-bold">Cari Lahan</label>';
		$html .= '<select id="search_lahan_id" class="form-select" style="width:100%;"></select></div>';
		$html .= '<button type="button" id="btn-cari" class="btn btn-secondary">Cari Problem</button>';
		$html .= '<div id="result-problem" class="mt-3"></div>';
		$html .= '</div></div>';

		// Form section
		$html .= '<form id="form-pica-action" action="' . url('webhook?action_task=formPicaAction') . '" method="POST" enctype="multipart/form-data" class="rounded shadow bg-white p-3">';
		$html .= csrf_field();

		$html .= '<div class="mb-3"><label class="form-label fw-bold">ID Corrective PICA</label>';
		$html .= '<input type="number" name="id_pica_pi_corrective" id="id_pica_pi_corrective" class="form-control" readonly required placeholder="Pilih dari hasil pencarian di atas atau isi manual"></div>';

		$html .= '<div class="mb-3"><label class="form-label fw-bold">Tanggal Penyelesaian</label>';
		$html .= '<input type="date" name="tgl_penyelesaian" class="form-control" required max="' . date('Y-m-d') . '"></div>';

		$html .= '<div class="mb-3"><label class="form-label fw-bold">Persen Penyelesaian (%)</label>';
		$html .= '<input type="number" step="0.01" min="0" max="100" name="persen_penyelesaian" class="form-control" required></div>';

		$html .= '<div class="mb-3"><label class="form-label fw-bold">Foto</label>';
		$html .= '<div class="btn-group w-100 mb-2" role="group">';
		$html .= '<input type="radio" class="btn-check" name="foto-source" id="foto-gallery" value="gallery" checked>';
		$html .= '<label class="btn btn-outline-primary" for="foto-gallery">📷 Galeri</label>';
		$html .= '<input type="radio" class="btn-check" name="foto-source" id="foto-camera" value="camera">';
		$html .= '<label class="btn btn-outline-primary" for="foto-camera">📸 Kamera</label>';
		$html .= '</div>';
		$html .= '<input type="file" name="foto" id="foto-input" class="form-control" accept="image/jpeg,image/png,image/jpg" required>';
		$html .= '<input type="file" name="foto" id="camera-input" class="form-control" accept="image/*" capture="environment" style="display:none;" required>';
		$html .= '<div id="camera-preview" class="mt-2"></div>';
		$html .= '</div>';

		$html .= '<div class="mb-3"><label class="form-label fw-bold">Keterangan</label>';
		$html .= '<textarea name="keterangan" class="form-control" rows="3"></textarea></div>';

		$html .= '<input type="hidden" name="nohp" value="' . htmlspecialchars($nohp) . '">';
		$html .= '<div class="d-grid"><button type="submit" id="btn-simpan" class="btn btn-primary">Simpan</button></div>';

		$html .= '<div id="loading-spinner" class="text-center mt-3" style="display:none;">
			<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div>
			<p class="mt-2">Menyimpan data, mohon tunggu...</p>
		</div>';

		$html .= '</form></div>';

		// Modal untuk menampilkan detail corrective action
		$html .= '<div class="modal fade" id="detailActionModal" tabindex="-1" aria-hidden="true">';
		$html .= '<div class="modal-dialog modal-lg">';
		$html .= '<div class="modal-content">';
		$html .= '<div class="modal-header">';
		$html .= '<h5 class="modal-title">Riwayat Corrective Action</h5>';
		$html .= '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>';
		$html .= '</div>';
		$html .= '<div class="modal-body" id="modal-body-content">';
		$html .= '</div>';
		$html .= '<div class="modal-footer">';
		$html .= '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>';
		$html .= '</div>';
		$html .= '</div>';
		$html .= '</div>';

		$html .= '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
		$html .= '<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>';
		$html .= '<script>
			$(document).ready(function() {
				// Handle foto source toggle
				$("input[name=\"foto-source\"]").on("change", function() {
					if ($(this).val() === "camera") {
						$("#foto-input").hide().removeAttr("required");
						$("#camera-input").show().attr("required", "required").focus();
					} else {
						$("#camera-input").hide().removeAttr("required");
						$("#foto-input").show().attr("required", "required").focus();
					}
				});

				// Handle camera input preview
				$("#camera-input").on("change", function() {
					const file = this.files[0];
					if (file) {
						const reader = new FileReader();
						reader.onload = function(e) {
							$("#camera-preview").html("<img src=\"" + e.target.result + "\" class=\"img-fluid mt-2\" style=\"max-width: 300px; border-radius: 8px;\">");
						};
						reader.readAsDataURL(file);
					}
				});

				// Handle file input for gallery
				$("#foto-input").on("change", function() {
					const file = this.files[0];
					if (file) {
						const reader = new FileReader();
						reader.onload = function(e) {
							$("#camera-preview").html("<img src=\"" + e.target.result + "\" class=\"img-fluid mt-2\" style=\"max-width: 300px; border-radius: 8px;\">");
						};
						reader.readAsDataURL(file);
					}
				});

				$("#search_lahan_id").select2({
					placeholder: "Cari Lahan",
					ajax: {
						url: "' . url('webhook/autocompletePetak') . '",
						dataType: "json",
						delay: 250,
						data: function(params) { return { term: params.term }; },
						processResults: function(data) { return { results: data }; },
						cache: true
					},
					minimumInputLength: 3
				});

				$("#btn-cari").on("click", function() {
					const lahanId = $("#search_lahan_id").val();
					if (!lahanId) { alert("Pilih lahan terlebih dahulu"); return; }
					$.get("' . url('webhook/getPicaProblemByLahan') . '", { lahan_id: lahanId }, function(data) {
						if (!data.length) {
							$("#result-problem").html(\'<div class="alert alert-warning">Tidak ada data PICA ditemukan.</div>\');
							return;
						}
						let table = \'<div class="table-responsive"><table class="table table-sm table-bordered"><thead><tr><th>ID Corrective</th><th>Problem</th><th>Corrective</th><th>Prioritas</th><th>Target</th><th>Status</th><th>Aksi</th></tr></thead><tbody>\';
						data.forEach(function(row) {
							const actionButton = row.total_actions > 0 ? \'<button type="button" class="btn btn-sm btn-info btn-lihat" data-id="\' + row.id_corrective + \'" data-bs-toggle="modal" data-bs-target="#detailActionModal">Lihat (\' + row.total_actions + \')</button>\' : \'\';
							table += \'<tr>\';
							table += \'<td>\' + row.id_corrective + \'</td>\';
							table += \'<td>\' + row.problem + \'</td>\';
							table += \'<td>\' + row.corrective + \'</td>\';
							table += \'<td>\' + row.priority + \'</td>\';
							table += \'<td>\' + new Date(row.tanggal_target).toLocaleDateString("id-ID", { year: "numeric", month: "short", day: "2-digit" }) + \'</td>\';
							table += \'<td>\' + (row.total_actions > 0 ? \'<span class="badge bg-success">✓ \' + row.total_actions + \'</span>\' : \'<span class="badge bg-warning">Belum</span>\') + \'</td>\';
							table += \'<td><button type="button" class="btn btn-sm btn-primary btn-pilih" data-id="\' + row.id_corrective + \'">Pilih</button> \' + actionButton + \'</td>\';
							table += \'</tr>\';
						});
						table += \'</tbody></table></div>\';
						$("#result-problem").html(table);

						$(".btn-pilih").on("click", function() {
							const id = $(this).data("id");
							$("#id_pica_pi_corrective").val(id);
							$("html, body").animate({ scrollTop: $("#form-pica-action").offset().top }, 500);
						});

						$(document).on("click", ".btn-lihat", function() {
							const id = $(this).data("id");
							$.get("' . url('webhook/getPicaActionDetail') . '", { id_pica_pi_corrective: id }, function(data) {
								if (data.success && data.actions.length > 0) {
									let content = \'<div class="accordion" id="accordionActions">\';
									data.actions.forEach(function(action, index) {
										const collapseId = "collapse" + index;
										const headingId = "heading" + index;
										content += \'<div class="accordion-item">\';
										content += \'<h2 class="accordion-header" id="\' + headingId + \'">\';
										content += \'<button class="accordion-button\' + (index === 0 ? \'\' : \' collapsed\') + \'" type="button" data-bs-toggle="collapse" data-bs-target="#\' + collapseId + \'" aria-expanded="\' + (index === 0 ? \'true\' : \'false\') + \'" aria-controls="\' + collapseId + \'">\';
										content += \'Action \' + (index + 1) + \' - \' + new Date(action.createdOn).toLocaleDateString("id-ID", { year: "numeric", month: "long", day: "2-digit" });
										content += \'</button></h2>\';
										content += \'<div id="\' + collapseId + \'" class="accordion-collapse collapse\' + (index === 0 ? \' show\' : \'\') + \'" aria-labelledby="\' + headingId + \'" data-bs-parent="#accordionActions">\';
										content += \'<div class="accordion-body">\';
										content += \'<div class="row mb-2">\';
										content += \'<div class="col-md-6"><strong>Tanggal Penyelesaian:</strong><br>\' + new Date(action.tgl_penyelesaian).toLocaleDateString("id-ID", { year: "numeric", month: "long", day: "2-digit" }) + \'</div>\';
										content += \'<div class="col-md-6"><strong>Persen Penyelesaian:</strong><br>\' + action.persen_peyelesaian + \'%</div>\';
										content += \'</div>\';
										if (action.foto) {
											content += \'<div class="mb-2"><strong>Foto:</strong><br><img src="https://prodis.ksotebu.com/uploads/foto_pica/\' + action.foto + \'" class="img-fluid" style="max-width: 300px;"></div>\';
										}
										if (action.keterangan) {
											content += \'<div class="mb-2"><strong>Keterangan:</strong><br>\' + action.keterangan + \'</div>\';
										}
										content += \'<div class="mt-2"><strong>Dibuat Tanggal:</strong><br>\' + new Date(action.createdOn).toLocaleString("id-ID") + \'</div>\';
										content += \'</div></div>\';
										content += \'</div></div>\';
									});
									content += \'</div>\';
									$("#modal-body-content").html(content);
								} else {
									$("#modal-body-content").html(\'<div class="alert alert-warning">Belum ada corrective action.</div>\');
								}
							}, "json").fail(function() {
								$("#modal-body-content").html(\'<div class="alert alert-danger">Gagal mengambil data.</div>\');
							});
						});
					}, "json").fail(function() {
						$("#result-problem").html(\'<div class="alert alert-danger">Gagal mengambil data.</div>\');
					});
				});

				$("#form-pica-action").on("submit", function() {
					// Set the appropriate input to required based on selection
					const source = $("input[name=\"foto-source\"]:checked").val();
					if (source === "camera") {
						$("#camera-input").attr("required", "required");
						$("#foto-input").removeAttr("required");
					} else {
						$("#foto-input").attr("required", "required");
						$("#camera-input").removeAttr("required");
					}
					
					$("#btn-simpan").prop("disabled", true);
					$("#loading-spinner").show();
				});
			});
		</script>';

		return $html;
	}

	public function getPicaProblemByLahan(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2627'));
		$lahanId = $request->input('lahan_id');

		$data = DB::table('tx_pica_pi as pi')
			->join('tx_pica_pi_problem as pp', 'pp.id_pica_pi', '=', 'pi.id')
			->join('tx_pica_pi_corrective as pc', 'pc.id_pica_pi_problem', '=', 'pp.id')
			->join('master_problem_pica as mp', 'mp.id', '=', 'pp.id_problem')
			->join('master_corective_pica as mc', 'mc.id', '=', 'pc.id_corrective')
			->leftJoin('tx_pica_pi_corrective_action as pca', 'pca.id_pica_pi_correction', '=', 'pc.id')
			->where('pi.lahan_id', $lahanId)
			->select(
				'pc.id as id_corrective',
				'mp.problem',
				'mc.corrective',
				'pc.priority',
				'pc.tanggal_target',
				DB::raw('COUNT(pca.id) as total_actions')
			)
			->groupBy('pc.id', 'mp.problem', 'mc.corrective', 'pc.priority', 'pc.tanggal_target')
			->get();

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

	public function getPicaActionDetail(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2526'));
		$idCorrectiveAction = $request->input('id_pica_pi_corrective');

		$actions = DB::table('tx_pica_pi_corrective_action')
			->where('id_pica_pi_correction', $idCorrectiveAction)
			->orderBy('createdOn', 'desc')
			->get();

		if ($actions->count() > 0) {
			return response()->json(['success' => true, 'actions' => $actions]);
		}

		return response()->json(['success' => false, 'actions' => []]);
	}

	public function formPicaAction(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2627'));
		config(['app.debug' => true]);
		$validated = $request->validate([
			'id_pica_pi_corrective' => 'required|integer|exists:tx_pica_pi_corrective,id',
			'tgl_penyelesaian' => 'required|date',
			'persen_penyelesaian' => 'required|numeric|min:0|max:100',
			'foto' => 'required|image|mimes:jpeg,png,jpg',
			'keterangan' => 'nullable|string|max:1000',
		]);

		$filename = null;

		if ($request->hasFile('foto')) {
			$file = $request->file('foto');
			$filename = time() . '_' . $file->getClientOriginalName();
			$destinationPath = public_path('uploads/foto_pica');

			if (!file_exists($destinationPath)) {
				mkdir($destinationPath, 0777, true);
			}

			$mime = $file->getMimeType();
			$image = null;
			if (in_array($mime, ['image/jpeg', 'image/jpg'])) {
				$image = imagecreatefromjpeg($file->getPathname());
			} elseif ($mime === 'image/png') {
				$image = imagecreatefrompng($file->getPathname());
			}

			if ($image) {
				$targetFile = $destinationPath . '/' . $filename;
				$quality = 85;
				do {
					ob_start();
					imagejpeg($image, null, $quality);
					$imageData = ob_get_clean();
					$size = strlen($imageData);
					$quality -= 5;
				} while ($size > 1024 * 1024 && $quality > 10);
				file_put_contents($targetFile, $imageData);
				imagedestroy($image);
				$this->uploadCDN($targetFile, $filename, 'foto_pica');
			} else {
				$file->move($destinationPath, $filename);
				$this->uploadCDN($destinationPath . '/' . $filename, $filename, 'foto_pica');
			}
		}

		DB::table('tx_pica_pi_corrective_action')->insert([
			'id_pica_pi_correction' => $validated['id_pica_pi_corrective'],
			'tgl_penyelesaian' => $validated['tgl_penyelesaian'],
			'persen_peyelesaian' => $validated['persen_penyelesaian'],
			'foto' => $filename,
			'keterangan' => $request->input('keterangan', ''),
			'entry_by' => $request->input('nohp', ''),
			'createdOn' => now(),
			'updatedOn' => now()
		]);

		$html = '<meta name="viewport" content="width=device-width, initial-scale=1">';
		$html .= '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">';
		$html .= '<div class="alert alert-success" role="alert">';
		$html .= '<h4 class="alert-heading">Corrective Action Berhasil Disimpan!</h4>';
		$html .= '<p>Terima kasih, data corrective action PICA telah berhasil disimpan.</p>';
		$html .= '</div>';
		return $html;
	}

	


	public function getEarlyWarningMorfologiUnitMessage(Request $request)
	{
		

		$tahun = date('Y');
		$tanggal = date('Y-m-d'); 
		$tahun_tanam = $request->input('tahun_tanam', 'NULL');
		if ($tahun_tanam == '2526') {
			Config::set('database.default', session('database_name', 'mysql_2526'));
		}else if ($tahun_tanam == '2627') {
			Config::set('database.default', session('database_name', 'mysql_2627'));
		}else{
			Config::set('database.default', session('database_name', 'mysql_2526'));
		}
		$kebun = $request->input('kebun', 'NULL');


		$periode = $this->getPeriodeFromDate($tanggal);

		$gmData = DB::table('master_kebun as a')
			->join('master_nohp as b', 'a.nik_gm', '=', 'b.nik')
			->where('a.kode_kebun', $kebun)
			->select('a.nama_gm', 'b.nik', 'b.nohp')
			->first();

		$nama_gm = $gmData->nama_gm ?? 'Bapak GM';
		$nik_gm = $gmData->nik ?? null;
		$nohp_gm = $gmData->nohp ?? null;

		$data = DB::select(
			'call sp_rekap_morfologi_rayon_periode_dinamis(?, ?, ?, ?)',
			[$tahun, $periode, $kebun, 0]
		);

		$message = $this->buildEarlyWarningMorfologiUnitMessage($data, $tahun, $periode, $kebun, $nama_gm);

		return $this->sendMessage2($message, $nohp_gm);
	}

	public function getEarlyWarningLKPUnitMessage(Request $request)
	{
		config(['app.debug' => true]);
		Config::set('database.default', session('database_name', 'mysql_2627'));

		$tglAwal = $request->input('tgl_awal', $request->input('start_date', '2023-01-01'));
		$tglAkhir = $request->input('tgl_akhir', $request->input('end_date', date('Y-m-d')));
		$kebun = $request->input('kebun');

		$gmData = DB::table('master_kebun as a')
			->join('master_nohp as b', 'a.nik_gm', '=', 'b.nik')
			->where('a.kode_kebun', $kebun)
			->select('a.nama_gm', 'b.nohp')
			->first();

		$nama_gm = $gmData->nama_gm ?? 'Bapak/Ibu GM';
		$nohp_gm = $gmData->nohp ?? null;
		// $nohp_gm = "6285647384318";

		$data = DB::select(
			'call sp_lkp_rekap_pcrc_notif_wa(?, ?, ?, ?)',
			[$tglAwal, $tglAkhir, $kebun, null]
		);

		$message = $this->buildEarlyWarningLKPUnitMessage($data, $tglAwal, $tglAkhir, $kebun, $nama_gm);
		return $this->sendMessage2($message, $nohp_gm);
	}


	public function buildEarlyWarningMorfologiUnitMessage($data, $tahun, $periode, $kebun = 'NULL', $nama_gm = 'Bapak GM')
	{
		$rows = collect($data);

		$periodeKey = strtoupper(trim($periode));
		$sasaranField = 'jumlah_petak_tanamkepras_sd_' . $periodeKey;
		$realisasiField = 'morfologi_' . $periodeKey;

		if ($rows->isEmpty()) {
			return "📊 *EARLY WARNING LAPORAN INPUT DATA*\n\nYth. {$nama_gm},\n\nData tidak tersedia untuk periode {$periodeKey} tahun {$tahun}.";
		}

		// Fallback jika field periode dinamis tidak ada di hasil SP
		$firstRow = (array) $rows->first();
		if (!array_key_exists($sasaranField, $firstRow)) {
			$sasaranField = 'jumlah_petak_tanamkepras_sd_3A';
		}
		if (!array_key_exists($realisasiField, $firstRow)) {
			$realisasiField = 'morfologi_3A';
		}

		$totalSasaran = 0;
		$totalRealisasi = 0;
		$belowTargetRayons = [];

		$message = "📊 *EARLY WARNING LAPORAN INPUT DATA MORFOLOGI (MINGGUAN)*";
		$message .= "\n\nYth. Bapak/Ibu GM \n{$nama_gm},";
		$message .= "\n\nBerikut kami sampaikan progres pelaporan MORFOLOGI s.d. {$periodeKey}:";
		$message .= "\n";

		foreach ($rows as $row) {
			$namaRayon = $row->nama_rayon ?? '-';
			$luasPolig = (float) ($row->luas_polig ?? 0);
			$sasaran = (float) ($row->{$sasaranField} ?? 0);
			$realisasi = (float) ($row->{$realisasiField} ?? 0);
			$persen = $sasaran > 0 ? round(($realisasi / $sasaran) * 100, 2) : 0;

			$totalSasaran += $sasaran;
			$totalRealisasi += $realisasi;

			// Track rayons below 100%
			if ($persen < 100 && $persen > 0) {
				$belowTargetRayons[] = [
					'name' => $namaRayon,
					'persen' => $persen,
					'realisasi' => $realisasi,
					'sasaran' => $sasaran
				];
			}

			$message .= "\n*{$namaRayon}*";
			$message .= "\nLuas: " . $this->formatEarlyWarningNumber($luasPolig, 3);
			$message .= "\nSasaran: " . $this->formatEarlyWarningNumber($sasaran) . " petak";
			$message .= "\nRealisasi: " . $this->formatEarlyWarningNumber($realisasi) . " petak";
			$message .= "\nCapaian: " . $this->formatEarlyWarningNumber($persen, 2) . "%";
			$message .= "\n";
		}

		$totalPersen = $totalSasaran > 0 ? round(($totalRealisasi / $totalSasaran) * 100, 2) : 0;

		// Add notes section
		$message .= "\n📌 *CATATAN:*";

		if (count($belowTargetRayons) === 0 && $totalPersen >= 100) {
			$message .= "\nSecara umum progres sudah mencapai target. Terima kasih atas dedikasi tim.";
		} else {
			if ($totalPersen < 100) {
				$message .= "\nSecara umum progres masih di bawah target. ";
			} else {
				$message .= "\nSecara umum progres sudah berjalan baik, namun masih terdapat kekurangan input pada wilayah tertentu. ";
			}
			
			if (count($belowTargetRayons) > 0) {
				$message .= "Mohon perhatian untuk percepatan ";
				$message .= "Agar target mingguan dapat tercapai.";
			}
		}
		
		$message .= "\n\n💡 *CATATAN PENTING:*";
		$message .= "\nData ini akan digunakan untuk penyusunan Dashboard PICA yang akan disosialisasikan ke masing-masing GM Kebun.";

		$message .= "\n\nDemikian kami sampaikan sebagai early warning monitoring periode mingguan.";
		$message .= "\n\nTerima kasih.";
		$message .= "\n\n@cc Kabag Operasional";

		return $message;
	}

	public function buildEarlyWarningLKPUnitMessage($data, $startDate, $endDate, $kebun = 'SK09', $nama_gm = 'Bapak GM')
	{
		$rows = collect($data);

		if ($rows->isEmpty()) {
			return "EARLY WARNING LAPORAN INPUT LKP (MINGGUAN)\n\nYth. Bapak GM Kebun {$kebun}\n{$nama_gm} ,\n\nData tidak tersedia untuk periode {$startDate} s.d. {$endDate}.";
		}

		$totalSource = $rows->first(function ($row) {
			$rayon = trim((string) ($row->rayon ?? ''));
			return stripos($rayon, 'total') === 0;
		});

		$kebunLabel = $kebun;
		if ($totalSource && !empty($totalSource->rayon)) {
			$kebunLabel = trim(preg_replace('/^total\s*/i', '', (string) $totalSource->rayon));
		}

		$detailRows = $rows->filter(function ($row) {
			$rayon = trim((string) ($row->rayon ?? ''));
			return stripos($rayon, 'total') === false;
		});

		$totalRow = (object) [
			'ha_serah_tanah' => $detailRows->sum('ha_serah_tanah'),
			'ha_tanam_kepras_total' => $detailRows->sum('ha_tanam_kepras_total'),
			'ha_pupuk_1_total' => $detailRows->sum('ha_pupuk_1_total'),
			'ha_pupuk_2_total' => $detailRows->sum('ha_pupuk_2_total'),
			'ha_bumbun_1' => $detailRows->sum('ha_bumbun_1'),
			'ha_bumbun_2' => $detailRows->sum('ha_bumbun_2'),
			'ha_bumbun_3' => $detailRows->sum('ha_bumbun_3'),
			'ha_klentek_1' => $detailRows->sum('ha_klentek_1'),
			'ha_klentek_2' => $detailRows->sum('ha_klentek_2'),
			'ha_klentek_3' => $detailRows->sum('ha_klentek_3'),
		];

		$formattedEndDate = date('d-m-Y', strtotime($endDate));
		$mtYear = date('Y', strtotime($endDate));
		$nextMtYear = (int) $mtYear + 1;

		$message = "EARLY WARNING LAPORAN INPUT LKP (MINGGUAN)";
		$message .= "\n\nYth. Bapak GM Kebun {$kebunLabel}";
		$message .= "\n{$nama_gm} ,";
		$message .= "\n\nBerikut kami sampaikan progres pelaporan LKP TG MT {$mtYear}/{$nextMtYear} untuk Kebun {$kebunLabel} s.d. {$formattedEndDate} :";

		$message .= "\n\nTotal Kebun {$kebunLabel}";
		$message .= "\nSerah Tanah: " . $this->formatEarlyWarningNumber((float) ($totalRow->ha_serah_tanah ?? 0), 3) . " Ha";
		$message .= "\nTanam/Kepras: " . $this->formatEarlyWarningNumber((float) ($totalRow->ha_tanam_kepras_total ?? 0), 3) . " Ha";
		$message .= "\nPupuk 1: " . $this->formatEarlyWarningNumber((float) ($totalRow->ha_pupuk_1_total ?? 0), 3) . " Ha";
		$message .= "\nPupuk 2: " . $this->formatEarlyWarningNumber((float) ($totalRow->ha_pupuk_2_total ?? 0), 3) . " Ha";
		$message .= "\nBumbun 1: " . $this->formatEarlyWarningNumber((float) ($totalRow->ha_bumbun_1 ?? 0), 3) . " Ha";
		$message .= "\nBumbun 2: " . $this->formatEarlyWarningNumber((float) ($totalRow->ha_bumbun_2 ?? 0), 3) . " Ha";
		$message .= "\nBumbun 3: " . $this->formatEarlyWarningNumber((float) ($totalRow->ha_bumbun_3 ?? 0), 3) . " Ha";
		$message .= "\nKlentek 1: " . $this->formatEarlyWarningNumber((float) ($totalRow->ha_klentek_1 ?? 0), 3) . " Ha";
		$message .= "\nKlentek 2: " . $this->formatEarlyWarningNumber((float) ($totalRow->ha_klentek_2 ?? 0), 3) . " Ha";
		$message .= "\nKlentek 3: " . $this->formatEarlyWarningNumber((float) ($totalRow->ha_klentek_3 ?? 0), 3) . " Ha";

		foreach ($detailRows as $row) {
			$rayon = $row->rayon ?? '-';
			$rayonLabel = trim((string) $rayon);
			if (stripos($rayonLabel, 'rayon') !== 0) {
				$rayonLabel = 'Rayon ' . $rayonLabel;
			}

			$message .= "\n\n{$rayonLabel}";
			$message .= "\nSerah Tanah: " . $this->formatEarlyWarningNumber((float) ($row->ha_serah_tanah ?? 0), 3) . " Ha";
			$message .= "\nTanam/Kepras: " . $this->formatEarlyWarningNumber((float) ($row->ha_tanam_kepras_total ?? 0), 3) . " Ha";
			$message .= "\nPupuk 1: " . $this->formatEarlyWarningNumber((float) ($row->ha_pupuk_1_total ?? 0), 3) . " Ha";
			$message .= "\nPupuk 2: " . $this->formatEarlyWarningNumber((float) ($row->ha_pupuk_2_total ?? 0), 3) . " Ha";
			$message .= "\nBumbun 1: " . $this->formatEarlyWarningNumber((float) ($row->ha_bumbun_1 ?? 0), 3) . " Ha";
			$message .= "\nBumbun 2: " . $this->formatEarlyWarningNumber((float) ($row->ha_bumbun_2 ?? 0), 3) . " Ha";
			$message .= "\nBumbun 3: " . $this->formatEarlyWarningNumber((float) ($row->ha_bumbun_3 ?? 0), 3) . " Ha";
			$message .= "\nKlentek 1: " . $this->formatEarlyWarningNumber((float) ($row->ha_klentek_1 ?? 0), 3) . " Ha";
			$message .= "\nKlentek 2: " . $this->formatEarlyWarningNumber((float) ($row->ha_klentek_2 ?? 0), 3) . " Ha";
			$message .= "\nKlentek 3: " . $this->formatEarlyWarningNumber((float) ($row->ha_klentek_3 ?? 0), 3) . " Ha";
		}

		$message .= "\n\n📌 CATATAN:";
		$message .= "\n- Agar selalu melakukan pelaporan LKP harian melalui Aplikasi Digifarm Grow atau Prodis KSO";
		$message .= "\n\n💡 CATATAN PENTING:";
		$message .= "\nData ini akan digunakan untuk rapat weekly bersama BOD dan dasar persetujuan dropping biaya mingguan";
		$message .= "\n\nDemikian kami sampaikan sebagai early warning monitoring periode mingguan.";
		$message .= "\n\nTerima kasih.";
		$message .= "\n\nPesan ini dikirim otomatis dari Prodis KSO";

		return $message;
	}

	protected function formatEarlyWarningNumber($value, $decimals = 0)
	{
		return number_format((float) $value, $decimals, ',', '.');
	}

	protected function getPeriodeFromDate($date)
	{
		$day = (int) date('d', strtotime($date));
		$month = (int) date('m', strtotime($date));
		if ($day >= 1 && $day <= 15) {
			return $month . 'A';
		} else {
			return $month . 'B';
		}
	}



	

	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;
	}

	protected function validateJwtToken($jwt)
	{
		$decodedJwt = explode('.', $jwt);
		if (count($decodedJwt) !== 3) {
			throw new \Exception('Invalid JWT format');
		}

		$payload = json_decode(base64_decode($decodedJwt[1]), true);
		if (!$payload || !isset($payload['exp']) || $payload['exp'] < time()) {
			throw new \Exception('JWT token is invalid or expired');
		}

		$secret = env('JWT_SECRET', '8uUC1YWkHD');
		$headerB64 = $decodedJwt[0];
		$payloadB64 = $decodedJwt[1];
		$sigB64 = $decodedJwt[2];

		$expected = hash_hmac('sha256', $headerB64 . '.' . $payloadB64, $secret, true);
		$expected = rtrim(strtr(base64_encode($expected), '+/', '-_'), '=');

		if (!hash_equals($expected, $sigB64)) {
			throw new \Exception('JWT signature is invalid');
		}

		return $payload;
	}

	

	public function viewPdfFromUrl(Request $request)
	{
		$url = $request->input('url');
		// Decrypt the URL
		$encryptionKey = 'kso_secret_key_2025';
		try {
			$decryptedUrl = openssl_decrypt(
				base64_decode($url), 
				'AES-128-CBC', 
				$encryptionKey, 
				0, 
				substr(md5($encryptionKey), 0, 16)
			);
			
			if ($decryptedUrl === false) {
				return response()->json(['error' => 'Failed to decrypt URL'], 400);
			}
			
			$url = $decryptedUrl;
		} catch (\Exception $e) {
			return response()->json(['error' => 'Invalid encrypted URL'], 400);
		}
		$jwt = $request->input('jwt');
		if (!$jwt) {
			return response()->json(['error' => 'JWT token is required'], 400);
		}

		try {
			$payload = $this->validateJwtToken($jwt);
			$nohp = $payload['nohp'] ?? '';
		} catch (\Exception $e) {
			return response()->json(['error' => $e->getMessage()], 401);
		}
		
		if (!$url) {
			return response()->json(['error' => 'URL is required'], 400);
		}

		// Validate URL format
		if (!filter_var($url, FILTER_VALIDATE_URL)) {
			return response()->json(['error' => 'Invalid URL format'], 400);
		}

		try {
			// Fetch PDF content from URL
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_TIMEOUT, 30);
			
			$pdfContent = curl_exec($ch);
			$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
			
			curl_close($ch);

			if ($httpCode !== 200) {
				return response()->json(['error' => 'Failed to fetch PDF from URL'], $httpCode);
			}

			// Verify content is PDF
			if (strpos($contentType, 'application/pdf') === false && substr($pdfContent, 0, 4) !== '%PDF') {
				return response()->json(['error' => 'URL does not point to a valid PDF file'], 400);
			}

			// Return PDF with appropriate headers
			return response($pdfContent)
				->header('Content-Type', 'application/pdf')
				->header('Content-Disposition', 'inline; filename="slipgaji.pdf"');
				
		} catch (\Exception $e) {
			return response()->json(['error' => 'Error fetching PDF: ' . $e->getMessage()], 500);
		}
	}

	
	function uploadCDN($filePath, $fileName, $folder)
	{
		$remotePath = "/web/prodiskso/public/uploads/".$folder."/".$fileName;
		$url = env('CDN_URL') . $remotePath;

		$username = "cdnuser";
		$password = "5bCbmM2%";

		$fp = fopen($filePath, 'r');

		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_PUT, true);
		curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
		curl_setopt($ch, CURLOPT_INFILE, $fp);
		curl_setopt($ch, CURLOPT_INFILESIZE, filesize($filePath));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		curl_exec($ch);

		curl_close($ch);
		fclose($fp);
	}

	public function startTyping($chatId)
	{

		try {
			$url = env('WAHA_URL') . '/api/startTyping';
			$payload = [
				'chatId' => $chatId . '@c.us',
				'session' => 'default',
			];

			$ch = curl_init();

			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, [
				'Content-Type: application/json',
				'Accept: application/json',
				'X-Api-Key: ' . env('API_KEY_WAHA')
			]);

			$response = curl_exec($ch);
			$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

			curl_close($ch);

			return response()->json(json_decode($response, true), $httpCode);
		} catch (\Exception $e) {
			return response()->json(['error' => 'Error startTyping: ' . $e->getMessage()], 500);
		}
	}

	public function stopTyping($chatId)
	{
		try {
			$url = env('WAHA_URL') . '/api/stopTyping';
			$payload = [
				'chatId' => $chatId . '@c.us',
				'session' => 'default',
			];

			$ch = curl_init();

			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, [
				'Content-Type: application/json',
				'Accept: application/json',
				'X-Api-Key: ' . env('API_KEY_WAHA')
			]);

			$response = curl_exec($ch);
			$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

			curl_close($ch);

			return response()->json(json_decode($response, true), $httpCode);
		} catch (\Exception $e) {
			return response()->json(['error' => 'Error stopTyping: ' . $e->getMessage()], 500);
		}
	}

	
}