<?php namespace App\Http\Controllers;

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



class ConsolespreadsheetController extends Controller {

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

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

		
		
	}

	public function index(Request $request)
{
	// Ambil level user
	$getlevel = DB::table('tb_groups')
		->select('level')
		->where('group_id', \Session::get('gid'))
		->first();

	// Inisialisasi filter
	$filter = ' WHERE 0 = 0';

	// Jika level user >= 3, filter kebun
	if ($getlevel->level >= 3) {
		$filter .= ' AND kode_kebun = "' . \Session::get('fid') . '"';
	}

	// Ambil parameter tanggal dari request
	$tanggalRange = $request->input('tanggal_range');

	// Jika ada filter tanggal_range, tambahkan ke query
	if ($tanggalRange) {
		// Format input: "2025-07-10 - 2025-07-16"
		$parts = preg_split('/\s* - \s*/', $tanggalRange);
		if (count($parts) == 2) {
			$tanggalAwal = trim($parts[0]);
			$tanggalAkhir = trim($parts[1]);
			$filter .= " AND tgl_giling BETWEEN '{$tanggalAwal}' AND '{$tanggalAkhir}'";
		}
	}

	$params = array(
		'params' => $filter,
		'limit' => 10,
	);

	// Jika parameter download=1, export ke Excel
	if ($request->input('download') == 1) {
		// Pastikan filter tidak hanya default
		if (trim($filter) === 'WHERE 0 = 0') {
			return response('Filter tidak boleh kosong saat download.', 400);
		}
		// Ambil data sesuai filter
		$data = DB::select("SELECT * FROM q_prod_rekap_console_spta_lempar_spreadsheet $filter");
		if (empty($data)) {
			return response('Tidak ada data', 404);
		}
		$headers = array_keys((array)$data[0]);
		$output = '<table><thead><tr>';
		foreach ($headers as $header) {
			$output .= '<th>' . htmlspecialchars($header) . '</th>';
		}
		$output .= '</tr></thead><tbody>';
		foreach ($data as $row) {
			$output .= '<tr>';
			foreach ($headers as $header) {
				$output .= '<td>' . htmlspecialchars($row->$header) . '</td>';
			}
			$output .= '</tr>';
		}
		$output .= '</tbody></table>';
		return response($output)
			->header('Content-Type', 'application/vnd.ms-excel')
			->header('Content-Disposition', 'attachment; filename="data_prodis_console.xls"');
	}

	$this->grab($request, $params);

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

}


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

			case 'export':
				return $this->getExport( $request );
				break;
			case 'tarikdataconsolelkpforexcel':
				return $this->tarikdataconsolelkpforexcel( $request );
			case 'tarikdatatimbang':
				return $this->tarikdatatimbang( $request );
			case 'tarikdatamejatebu':
				return $this->tarikdatamejatebu( $request );	
				break;	
			case 'tarikdataprodptpn':
				return $this->tarikdataprodptpn( $request );	
				break;			
			case 'tarikdatatimbangmutu':
				return $this->tarikdatatimbangmutu( $request );
				break;
			case 'tescurl':
				return $this->tescurl( $request );	
				break;	
			case 'mydate':
				return $this->mydate($request);
				break;
			case 'exportdata':
				return $this->exportdata($request);
				break;	
			case 'tarikdatasbh':
				return $this->tarikdatasbh($request);
				break;
			case 'saveOrUpdateCookieProdisPg':
				return $this->saveOrUpdateCookieProdisPg( $request);
				break;
			case 'getMasterCookieProdisPg':
				return $this->getMasterCookieProdisPg($request);
				break;
			case 'getdataselektor':
				return $this->getdataselektor( $request);
				break;	
			case 'getdatatimbangnew':
				return $this->getdatatimbangnew($request);
				break;
			case 'getdatamejatebunew':
				return $this->getdatamejatebunew($request);
				break;		
			case 'tarikdatasbhnew':
				return $this->tarikdatasbhnew($request);
				break;
			case 'getdatatimbangnewjrgtebu':
				return $this->getdatatimbangnewjrgtebu($request);
				break;
			case 'getdatamejatebunewjrgtebu':
				return $this->getdatamejatebunewjrgtebu($request);
				break;
			case 'getdatamejatebunewjrgtebu2':
				return $this->getdatamejatebunewjrgtebu2($request);
				break;
	
		}
	}

	public function store( Request $request){

		$task = $request->input('action_task');
		switch ($task)
		{
			default:
				return $this->postData( $request);
				break;
			case 'saveOrUpdateCookieProdisPg':
				return $this->saveOrUpdateCookieProdisPg( $request);
				break;

		}
	}

	public function tarikdataconsolelkpforexcel(Request $request)
	{
			$url = "https://sigula.sinergigula.com/index.php/consolelhpmkso";
			$url2 = "https://sigula.sinergigula.com/index.php/consolelhpmkso/getdata";
			
			    $tgl = $request->input('tgl');
                $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" => $tgl,
                    "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);
			
			// echo $response;
			echo $response2;
	}

	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 tarikdataprodptpn(Request $request)
	{
		// if (!\Auth::check()) 
		// 	return response()->json(array('status' => 'error', 'message' => 'You are not logged in'));

			$pabrik_gula = $request->input('pabrik_gula');
			$datebefore = date('Y-m-d',strtotime('-1 days'));
			$tgl1 = $datebefore;
			$tgl2 = $datebefore;
			$url = "https://sigula.sinergigula.com/index.php/dataprodptpn/grids?tgl1=".$tgl1."&tgl2=".$tgl2."&pg=&jenis_tgl=1";

			$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/dashboard",
			];
			
			// $postData = "draw=1&columns%5B0%5D%5Bdata%5D=0&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false"; // Truncated data for brevity
			
			$postData = [
				"draw" => 3,
				"start" => 0,
				"length" => 10000000,
				"search[value]" => "",
				"search[regex]" => false,
				"order[0][column]" => 0,
				"order[0][dir]" => "asc",
			];
			
			$columns = 42; // Sesuaikan dengan jumlah kolom
			
			for ($i = 0; $i < $columns; $i++) {
				$postData["columns[$i][data]"] = $i;
				$postData["columns[$i][name]"] = "";
				$postData["columns[$i][searchable]"] = true;
				$postData["columns[$i][orderable]"] = ($i != 41); // Kolom ke-41 tidak dapat diurutkan
				$postData["columns[$i][search][value]"] = "";
				$postData["columns[$i][search][regex]"] = false;
			}
			
			
			$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);
			
			// echo $response;
			// Decode JSON ke dalam array PHP
			$dataArray = json_decode($response, true);
			
			// Ambil hanya bagian "data"
			$dataOnly = $dataArray["data"];
			foreach ($dataOnly as $data) {
				$insertData = [
					'kode_pg' => $data[1],
					'no_spta' => $data[2],
					'no_analisa' => $data[3],
					'asal_kebun' => $data[4],
					'no_kontrak' => $data[5],
					'kode_afd' => $data[6],
					'nama_asman' => $data[7],
					'kode_blok' => $data[8],
					'deskripsi_blok' => $data[9],
					'id_petani' => $data[10],
					'petani' => $data[11],
					'koperasi' => $data[12],
					'netto_tebu' => $data[13],
					'jenis_spta' => $data[14],
					'no_pol' => $data[15],
					'kategori' => $data[16],
					'bulan_tanam' => $data[17],
					'usia_tebu' => $data[18],
					'mutu_tebu' => $data[19],
					'varietas' => $data[20],
					'kemasakan' => $data[21],
					'kesegaran' => $data[22],
					'luas_ha' => $data[23],
					'luas_tebang' => $data[24],
					'tgljam_tebang' => $data[25],
					'tgljam_selektor' => $data[26],
					'tgljam_timbang' => $data[27],
					'tgljam_mejatebu' => $data[28],
					'tgl_spta' => $data[29],
					'tgl_timbang' => $data[30],
					'tgl_giling' => $data[31],
					'rendemen' => $data[32],
					'rend_ptr' => $data[33],
					'gula_ptr' => $data[34],
					'tetes_ptr' => $data[35],
					'tebang_pg' => $data[36],
					'angkut_pg' => $data[37],
					'jenis_pembayaran' => $data[38],
					'nokontrak_giling' => $data[39],
					'date_syn' => $data[40],
					// Map other columns as needed
				];
				\DB::table('data_prodis_console')->updateOrInsert(
					['no_spta' => $data[2]], // Assuming 'no_spta' is the unique key
					$insertData
				);
			}
			if ($dataArray) {
				return response()->json(array('status' => 'success', 'message' => 'Data successfully imported'));
			} else {
				return response()->json(array('status' => 'error', 'message' => 'No data found'));
			}
	}

	function getcookielogin(){
		// URL tujuan
	$url = "https://sigula.sinergigula.com/index.php/user/postlogin";
	
	// Data POST
	$postData = [
		"username" => "rizki.r",
		"password" => "rizki.r",
		"tahungiling" => "2025"
	];
	
	// 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 tescurl(Request $request)
	{
		return "data tes";
	}
	public function tarikdatatimbang(Request $request)
	{
		// if (!\Auth::check()) 
		// 	return response()->json(array('status' => 'error', 'message' => 'You are not logged in'));

			$pabrik_gula = $request->input('pabrik_gula');
			$datebefore = $request->input('tgl', date('Y-m-d',strtotime('-1 days')));
			$tgl1 = $datebefore;
			$tgl2 = $datebefore;
			// URL endpoint

			if($pabrik_gula == 'SG01'){
				$url = "https://kwm.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG02'){
				$url = "https://ssm.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG03'){
				$url = "https://bgm.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG04'){
				$url = "https://ctm.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG05'){
				$url = "https://sg05.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG06'){
				$url = "https://srg.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG07'){
				$url = "https://rdg.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG08'){
				$url = "https://mjo.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG09'){
				$url = "https://sg09.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG10'){
				$url = "https://krb.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG11'){
				$url = "https://gkr.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG12'){
				$url = "https://djb.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG13'){
				$url = "https://tjk.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG14'){
				$url = "https://lst.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG15'){
				$url = "https://mrt.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG16'){
				$url = "https://psb.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG17'){
				$url = "https://nga.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG18'){
				$url = "https://mpg.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG19'){
				$url = "https://sud.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG20'){
				$url = "https://pur.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG21'){
				$url = "https://rej.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG22'){
				$url = "https://pag.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG23'){
				$url = "https://ked.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG24'){
				$url = "https://won.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG25'){
				$url = "https://gen.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG26'){
				$url = "https://jat.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG27'){
				$url = "https://sem.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG28'){
				$url = "https://wri.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG30'){
				$url = "https://pan.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG31'){
				$url = "https://ase.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG32'){
				$url = "https://pra.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG33'){
				$url = "https://glm.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG34'){
				$url = "https://bon.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG35'){
				$url = "https://cmg.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else if($pabrik_gula == 'SG36'){
				$url = "https://tkl.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";
			}else{
				$url = "https://kwm.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";	
			}
			// $url = "https://kwm.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";


			$data = [
				'tgl1' => $tgl1,
				'tgl2' => $tgl2,
				'byr' => '',
				'jns' => '2',
				'bln' => date('n'),
				'thn' => date('Y'),
				'rjns' => '1',
				'tebangan' => '',
				'kat' => '',
				'angkutan' => '',
				'divisi' => '',
				'kode_blok' => '',
				'metode_tma' => ''
			];
			
			$cookie = $this->getcookieloginprodis($pabrik_gula); // Gantilah dengan sesi yang valid
			
			$headers = [
				"Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
				"X-Requested-With: XMLHttpRequest",
				"User-Agent: ".$_SERVER['HTTP_USER_AGENT'],
				"Cookie: $cookie"
			];
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			
			$response = curl_exec($ch);
			curl_close($ch);

			// Cek jika terjadi error
			// if (curl_errno($ch)) {
			// 	echo 'Error: ' . curl_error($ch);
			// 	curl_close($ch);
			// 	exit;
			// }


			// Tutup cURL
			// curl_close($ch);


			// Ekstrak tabel dengan class "tableizer-table"
			$dom = new DOMDocument();
			libxml_use_internal_errors(true);
			$dom->loadHTML($response);
			libxml_clear_errors();

			// Cari elemen tabel dengan class "tableizer-table"
			$xpath = new DOMXPath($dom);
			$tables = $xpath->query("//table[contains(@class, 'tableizer-table')]");

			$data = []; // Array untuk menyimpan hasil JSON
			if ($tables->length > 0) {
				$table = $tables->item(0);
				$rows = $table->getElementsByTagName('tr');
				$headers = [];

				// Ambil header tabel (baris pertama)
				foreach ($rows->item(0)->getElementsByTagName('th') as $header) {
					$headers[] = trim($header->textContent);
				}

				// Jika tidak ada <th>, coba ambil <td> dari baris pertama
				if (empty($headers)) {
					foreach ($rows->item(0)->getElementsByTagName('td') as $header) {
						$headers[] = trim($header->textContent);
					}
				}

				// Ambil data baris (mulai dari baris kedua)
				for ($i = 1; $i < $rows->length; $i++) {
					$row = $rows->item($i);
					$cells = $row->getElementsByTagName('td');

					if (count($cells)>1) {
						$rowData = [];
						foreach ($cells as $index => $cell) {
							$rowData[] = trim($cell->textContent);
						}
						if ($rowData != null) {
							$data[] = $rowData;
	
						}
					}					
				}
				// Insert data into the table
				foreach ($data as $rowData) {
					if (substr($rowData[1], 0, 2) == 'SG') {
						if (strpos($rowData[7], 'TS') !== false) {

							$insertData = [
								'no_spta' => $rowData[1],
								'afd' => $rowData[2],
								'nomer_kontrak' => $rowData[3],
								'nomer_petak' => $rowData[4],
								'kebun' => $rowData[5],
								'nama_petani' => $rowData[6],
								'kategori' => $rowData[7],
								'pembayaran' => $rowData[8],
								'blok' => $rowData[9],
								'mandor' => $rowData[10],
								'pta' => $rowData[11],
								'no_truk' => $rowData[12],
								'no_trans' => $rowData[13],
								'truk' => $rowData[14],
								'lori' => $rowData[15],
								'odong2' => $rowData[16],
								'traktor' => $rowData[17],
								'hektar' => $rowData[18],
								'bruto_kg' => str_replace(',', '', $rowData[19]),
								'tara_kg' => str_replace(',', '', $rowData[20]),
								'netto_kg' => str_replace(',', '', $rowData[21]),
								'rafaksi_kg' => str_replace(',', '', $rowData[22]),
								'netto_final_kg' => str_replace(',', '', $rowData[23]),
								'kode_timbangan' => $rowData[24],
								'kategori_tebang' => $rowData[25],
								'jenis_tebangan' => $rowData[26],
								'jenis_tebu' => $rowData[27],
								'range_jarak' => $rowData[28],
								'no_trainstat' => $rowData[29],
								'no_hv' => $rowData[30],
								'op_hv' => $rowData[31],
								'no_stipping' => $rowData[32],
								'op_stipping' => $rowData[33],
								'tgl_netto' => $rowData[34],
								'no_analisa' => $rowData[35],
								'tgl_timbang' => $rowData[36],
								// Map other columns as needed
							];
							\DB::table('data_timbangan')->updateOrInsert(
								['no_spta' => $rowData[1]], // Assuming 'no_spta' is the unique key
								$insertData
							);
						}
				}
					// var_dump($rowData[1]);
				}
			}

			// var_dump($this->getcookielogin());

			if ($data) {
				return response()->json(array('status' => 'success', 'message' => 'Data successfully imported'));
			} else {
				return response()->json(array('status' => 'error', 'message' => 'No data found'));
			}
	}


	public function tarikdatamejatebu(Request $request)
	{
		// if (!\Auth::check()) 
		// 	return response()->json(array('status' => 'error', 'message' => 'You are not logged in'));

			$pabrik_gula = $request->input('pabrik_gula');
			$datebefore = $request->input('tgl', date('Y-m-d',strtotime('-1 days')));
			$tgl1 = $datebefore;
			$tgl2 = $datebefore;
			// URL endpoint
			if($pabrik_gula == 'SG01'){
				$url = "https://kwm.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG02'){
				$url = "https://ssm.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG03'){
				$url = "https://bgm.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG04'){
				$url = "https://ctm.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG05'){
				$url = "https://sg05.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG06'){
				$url = "https://srg.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG07'){
				$url = "https://rdg.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG08'){
				$url = "https://mjo.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG09'){
				$url = "https://sg09.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG10'){
				$url = "https://krb.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG11'){
				$url = "https://gkr.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG12'){
				$url = "https://djb.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG13'){
				$url = "https://tjk.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG14'){
				$url = "https://lst.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG15'){
				$url = "https://mrt.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG16'){
				$url = "https://psb.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG17'){
				$url = "https://nga.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG18'){
				$url = "https://mpg.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG19'){
				$url = "https://sud.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG20'){
				$url = "https://pur.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG21'){
				$url = "https://rej.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG22'){
				$url = "https://pag.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG23'){
				$url = "https://ked.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG24'){
				$url = "https://won.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG25'){
				$url = "https://gen.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG26'){
				$url = "https://jat.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG27'){
				$url = "https://sem.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG28'){
				$url = "https://wri.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG30'){
				$url = "https://pan.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG31'){
				$url = "https://ase.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG32'){
				$url = "https://pra.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG33'){
				$url = "https://glm.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG34'){
				$url = "https://bon.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG35'){
				$url = "https://cmg.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else if($pabrik_gula == 'SG36'){
				$url = "https://tkl.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";
			}else{
				$url = "https://kwm.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";	
			}
			// $url = "https://kwm.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";

			$data = [
				'tgl1' => $tgl1,
				'tgl2' => $tgl2,
				'jns' => '1',
				'bln' => date('n'),
				'thn' => date('Y'),
				'rjns' => '1',
				'metode_tma' => ''
			];

			$cookie = $this->getcookieloginprodis($pabrik_gula); // Gantilah dengan sesi yang valid
			// echo $cookie;
			$headers = [
				"Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
				"X-Requested-With: XMLHttpRequest",
				"User-Agent: ".$_SERVER['HTTP_USER_AGENT'],
				"Accept: */*",
				"Origin: https://kwm.prodis.sinergigula.com",
				"Sec-Fetch-Site: same-origin",
				"Sec-Fetch-Mode: cors",
				"Sec-Fetch-Dest: empty",
				"Referer: https://kwm.prodis.sinergigula.com/index.php/laporanmejatebu",
				"Cookie: $cookie"
			];
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_HEADER, true);
			
			$response = curl_exec($ch);
			curl_close($ch);
			

			// echo $response;
			


			// Ekstrak tabel dengan class "tableizer-table"
			$dom = new DOMDocument();
			libxml_use_internal_errors(true);
			$dom->loadHTML($response);
			libxml_clear_errors();

			// Cari elemen tabel dengan class "tableizer-table"
			$xpath = new DOMXPath($dom);
			$tables = $xpath->query("//table[contains(@class, 'tableizer-table')]");

			$data = []; // Array untuk menyimpan hasil JSON
			if ($tables->length > 0) {
				$table = $tables->item(1);

				$rows = $table->getElementsByTagName('tr');
					// print_r($rows);
				$headers = [];


				// Ambil header tabel (baris pertama)
				foreach ($rows->item(1)->getElementsByTagName('th') as $header) {
					$headers[] = trim($header->textContent);
				}

				// Jika tidak ada <th>, coba ambil <td> dari baris pertama
				if (empty($headers)) {
					foreach ($rows->item(1)->getElementsByTagName('td') as $header) {
						$headers[] = trim($header->textContent);
					}
				}

				// Ambil data baris (mulai dari baris kedua)
				for ($i = 1; $i < $rows->length; $i++) {
					$row = $rows->item($i);
					$cells = $row->getElementsByTagName('td');

					if (count($cells)>1) {
						$rowData = [];
						foreach ($cells as $index => $cell) {
							$rowData[] = trim($cell->textContent);
						}
					}

					if ($rowData != null) {
						$data[] = $rowData;

					}

					
				}

			// var_dump($this->getcookielogin());

			// Insert data into the table
			foreach ($data as $rowData) {
				// var_dump(substr($rowData[3], 0, 2));
				if(!empty($rowData[3])){
				if (substr($rowData[3], 0, 2) == 'SG') {

				if (strpos($rowData[9], 'TS') !== false) {
					$insertData = [
						'mt' => $rowData[1],
						'no_analisa' => $rowData[2],
						'no_spta' => $rowData[3],
						'afd' => $rowData[4],
						'mandor' => $rowData[5],
						'pta' => $rowData[6],
						'no_petak' => $rowData[7],
						'kebun' => $rowData[8],
						'kategori' => $rowData[9],
						'angkutan' => $rowData[10],
						'no_angkutan' => $rowData[11],
						'transloading' => $rowData[12],
						'netto' => str_replace(',', '', $rowData[13]),
						'brix' => $rowData[14],
						'ph' => $rowData[15],
						'terbakar' => $rowData[16],
						'kualitas' => $rowData[17],
						'ha_tertebang' => $rowData[18],
						'tebang' => $rowData[19],
						'selektor' => $rowData[20],
						'meja_tebu' => $rowData[21],
						'cut_to_crush' => $rowData[22],
						'foto' => $rowData[23],
						'tgl_giling' => $rowData[24],
						// Map other columns as needed
					];
					\DB::table('data_meja_tebu')->updateOrInsert(
						['no_spta' => $rowData[3]], // Assuming 'no_spta' is the unique key
						$insertData
					);
				}
			}
		}
				// var_dump($rowData[1]);
			}
			if ($data) {
				return response()->json(array('status' => 'success', 'message' => 'Data successfully imported'));
			} else {
				return response()->json(array('status' => 'error', 'message' => 'No data found'));
			}
			
	}

}


public function tarikdatasbh(Request $request)
	{
		// if (!\Auth::check()) 
		// 	return response()->json(array('status' => 'error', 'message' => 'You are not logged in'));
			config(['app.debug' => true]);	
			$pabrik_gula = $request->input('pabrik_gula');
			$datebefore = $request->input('tgl');
			$tgl1 = $datebefore;
			$tgl2 = $datebefore;
			// URL endpoint

			if($pabrik_gula == 'SG01'){
				$url = "https://kwm.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG02'){
				$url = "https://ssm.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG03'){
				$url = "https://bgm.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG04'){
				$url = "https://ctm.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG05'){
				$url = "https://sg05.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG06'){
				$url = "https://srg.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG07'){
				$url = "https://rdg.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG08'){
				$url = "https://mjo.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG09'){
				$url = "https://sg09.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG10'){
				$url = "https://krb.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG11'){
				$url = "https://gkr.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG12'){
				$url = "https://djb.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG13'){
				$url = "https://tjk.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG14'){
				$url = "https://lst.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG15'){
				$url = "https://mrt.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG16'){
				$url = "https://psb.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG17'){
				$url = "https://nga.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG18'){
				$url = "https://mpg.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG19'){
				$url = "https://sud.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG20'){
				$url = "https://pur.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG21'){
				$url = "https://rej.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG22'){
				$url = "https://pag.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG23'){
				$url = "https://ked.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG24'){
				$url = "https://won.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG25'){
				$url = "https://gen.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG26'){
				$url = "https://jat.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG27'){
				$url = "https://sem.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG28'){
				$url = "https://wri.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG30'){
				$url = "https://pan.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG31'){
				$url = "https://ase.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG32'){
				$url = "https://pra.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG33'){
				$url = "https://glm.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG34'){
				$url = "https://bon.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG35'){
				$url = "https://cmg.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else if($pabrik_gula == 'SG36'){
				$url = "https://tkl.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;
			}else{
				$url = "https://kwm.prodis.sinergigula.com/index.php/tsbh/downloaded/3/".$tgl1."/".$tgl2;	
			}
			// $url = "https://kwm.prodis.sinergigula.com/index.php/laporantimbangan/printlaporan";


	
			
			$cookie = $this->getcookieloginprodissbh($pabrik_gula); // Gantilah dengan sesi yang valid
			
			$headers = [
				"Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
				"X-Requested-With: XMLHttpRequest",
				"User-Agent: ".$_SERVER['HTTP_USER_AGENT'],
				"Cookie: $cookie"
			];
			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			// Tidak perlu set POST dan POSTFIELDS untuk GET
			$response = curl_exec($ch);
			curl_close($ch);

			

			// Cek jika terjadi error
			// if (curl_errno($ch)) {
			// 	echo 'Error: ' . curl_error($ch);
			// 	curl_close($ch);
			// 	exit;
			// }


			// Tutup cURL
			// curl_close($ch);


			// Ekstrak tabel dengan class "tableizer-table"
			$dom = new DOMDocument();
			libxml_use_internal_errors(true);
			$dom->loadHTML($response);
			libxml_clear_errors();

			// Cari elemen tabel dengan class "tableizer-table"
			$xpath = new DOMXPath($dom);
			$tables = $xpath->query("//table[contains(@class, 'tableizer-table')]");

			$data = []; // Array untuk menyimpan hasil JSON
			if ($tables->length > 0) {
				$table = $tables->item(0);
				$rows = $table->getElementsByTagName('tr');
				$headers = [];

				// Ambil header tabel (baris pertama)
				foreach ($rows->item(0)->getElementsByTagName('th') as $header) {
					$headers[] = trim($header->textContent);
				}

				// Jika tidak ada <th>, coba ambil <td> dari baris pertama
				if (empty($headers)) {
					foreach ($rows->item(0)->getElementsByTagName('td') as $header) {
						$headers[] = trim($header->textContent);
					}
				}

				// Ambil data baris (mulai dari baris kedua)
				for ($i = 1; $i < $rows->length; $i++) {
					$row = $rows->item($i);
					$cells = $row->getElementsByTagName('td');

					if (count($cells)>1) {
						$rowData = [];
						foreach ($cells as $index => $cell) {
							$rowData[] = trim($cell->textContent);
						}
						if ($rowData != null) {
							$data[] = $rowData;
	
						}
					}					
				}
				// Insert data into the table
				foreach ($data as $rowData) {
					if (substr($rowData[1], 0, 2) == 'SG') {
						if (strpos($rowData[2], 'SK') !== false) {

								$insertData = [
									'kode_pg' => $pabrik_gula,
									'no_spta' => $rowData[1],
									'no_analisa' => '',
									'asal_kebun' => $rowData[2],
									'no_kontrak' => $rowData[3],
									'kode_afd' => $rowData[5],
									'nama_asman' => $rowData[6],
									'kode_blok' => $rowData[4],
									'deskripsi_blok' => '',
									'id_petani' => '',
									'petani' => $rowData[7],
									'koperasi' => $rowData[8],
									'netto_tebu' => $rowData[9],
									'jenis_spta' => $rowData[10],
									'no_pol' => $rowData[11],
									'kategori' => $rowData[12],
									'bulan_tanam' => '',
									'usia_tebu' => '',
									'mutu_tebu' => $rowData[13],
									'varietas' => $rowData[14],
									'kemasakan' => $rowData[15],
									'kesegaran' => $rowData[16],
									'luas_ha' => $rowData[17],
									'luas_tebang' => $rowData[18],
									'tgljam_tebang' => $rowData[19],
									'tgljam_selektor' => $rowData[20],
									'tgljam_timbang' => $rowData[21],
									'tgljam_mejatebu' => $rowData[22],
									'tgl_spta' => '',
									'tgl_timbang' => '',
									'tgl_giling' => $rowData[23],
									'rendemen' => $rowData[24],
									'rend_ptr' => $rowData[28],
									'gula_ptr' => $rowData[29],
									'tetes_ptr' => $rowData[31],
									'tebang_pg' => '',
									'angkut_pg' => '',
									'jenis_pembayaran' => '',
									'nokontrak_giling' => '',
									'date_syn' => '',
									// Map other columns as needed
								];
								\DB::table('data_prodis_console')->updateOrInsert(
									['no_spta' => $rowData[1]], // Assuming 'no_spta' is the unique key
									$insertData
								);
						}
				}
					// var_dump($rowData[1]);
				}
			}

			// var_dump($this->getcookielogin());

			if ($data) {
				return response()->json(array('status' => 'success', 'message' => 'Data successfully imported'));
			} else {
				return response()->json(array('status' => 'error', 'message' => 'No data found'));
			}
	}

	function getcookieloginprodis($pg){

		if($pg == 'SG01'){
			$url = "https://kwm.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho123'];
		}else if($pg == 'SG02'){
			$url = "https://ssm.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG03'){
			$url = "https://bgm.prodis.sinergigula.com/index.php/user/postlogin";
			// $data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG04'){
			$url = "https://ctm.prodis.sinergigula.com/index.php/user/postlogin";
			// $data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG05'){
			$url = "https://sg05.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG06'){
			$url = "https://srg.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG07'){
			$url = "https://rdg.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG08'){
			$url = "https://mjo.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG09'){
			$url = "https://sg09.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG10'){
			$url = "https://krb.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG11'){
			$url = "https://gkr.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG12'){
			$url = "https://djb.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG13'){
			$url = "https://tjk.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG14'){
			$url = "https://lst.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG15'){
			$url = "https://mrt.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG16'){
			$url = "https://psb.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG17'){
			$url = "https://nga.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG18'){
			$url = "https://mpg.prodis.sinergigula.com/index.php/user/postlogin";
			// $data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG19'){
			$url = "https://sud.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG20'){
			$url = "https://pur.prodis.sinergigula.com/index.php/user/postlogin";
			// $data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG21'){
			$url = "https://rej.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG22'){
			$url = "https://pag.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG23'){
			$url = "https://ked.prodis.sinergigula.com/index.php/user/postlogin";
			// $data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG24'){
			$url = "https://won.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG25'){
			$url = "https://gen.prodis.sinergigula.com/index.php/user/postlogin";
			// $data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG26'){
			$url = "https://jat.prodis.sinergigula.com/index.php/user/postlogin";
			// $data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG27'){
			$url = "https://sem.prodis.sinergigula.com/index.php/user/postlogin";
			// $data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG28'){
			$url = "https://wri.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG30'){
			$url = "https://pan.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG31'){
			$url = "https://ase.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG32'){
			$url = "https://pra.prodis.sinergigula.com/index.php/user/postlogin";
			// $data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG33'){
			$url = "https://glm.prodis.sinergigula.com/index.php/user/postlogin";
			// $data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG34'){
			$url = "https://bon.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG35'){
			$url = "https://cmg.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else if($pg == 'SG36'){
			$url = "https://tkl.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];
		}else{
			$url = "https://kwm.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'mkso.ho','password' => 'mkso.ho'];	
		}

		

		// $url = "https://kwm.prodis.sinergigula.com/index.php/user/postlogin";

		// $data = [
		// 	'username' => 'mkso.ho',
		// 	'password' => 'mkso.ho123'
		// ];
		
		$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0';
		$cookie = "ci_session=a%3A6%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22677c985afd7cca79976781ce45847fa9%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%22".$this->myipaddress()."%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A117%3A%22".urlencode($userAgent)."%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1739174392%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3Bs%3A4%3A%22lang%22%3Bs%3A2%3A%22en%22%3B%7Dc9f7347c8cb35c0e99abc9930aff63ecec15ce59"; // Gantilah dengan sesi yang valid
		
		$headers = [
			"Content-Type: application/x-www-form-urlencoded",
			"Upgrade-Insecure-Requests: 1",
			"User-Agent: ".$_SERVER['HTTP_USER_AGENT'],
			"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",
			"Referer: https://kwm.prodis.sinergigula.com/index.php/user/login",
			"Cookie: $cookie"
		];
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HEADER, true); // Ambil juga header respons
		
		$response = curl_exec($ch);
		$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
		$header = substr($response, 0, $header_size);
		$body = substr($response, $header_size);
		curl_close($ch);
		
		// Cari Set-Cookie di header
		preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches);
		$cookies = $matches[1];
		
		// Tampilkan Set-Cookie
		// echo "Set-Cookie dari response:\n";
		return $cookies[3];

	}

	function getcookieloginprodissbh($pg){

		if($pg == 'SG01'){
			$url = "https://kwm.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG02'){
			$url = "https://ssm.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG03'){
			$url = "https://bgm.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG04'){
			$url = "https://ctm.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG05'){
			$url = "https://sg05.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG06'){
			$url = "https://srg.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG07'){
			$url = "https://rdg.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG08'){
			$url = "https://mjo.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG09'){
			$url = "https://sg09.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG10'){
			$url = "https://krb.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG11'){
			$url = "https://gkr.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG12'){
			$url = "https://djb.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG13'){
			$url = "https://tjk.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG14'){
			$url = "https://lst.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG15'){
			$url = "https://mrt.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG16'){
			$url = "https://psb.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG17'){
			$url = "https://nga.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG18'){
			$url = "https://mpg.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG19'){
			$url = "https://sud.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG20'){
			$url = "https://pur.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG21'){
			$url = "https://rej.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG22'){
			$url = "https://pag.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG23'){
			$url = "https://ked.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG24'){
			$url = "https://won.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG25'){
			$url = "https://gen.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG26'){
			$url = "https://jat.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG27'){
			$url = "https://sem.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG28'){
			$url = "https://wri.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG30'){
			$url = "https://pan.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG31'){
			$url = "https://ase.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG32'){
			$url = "https://pra.prodis.sinergigula.com/index.php/user/postlogin";			
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG33'){
			$url = "https://glm.prodis.sinergigula.com/index.php/user/postlogin";			
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG34'){
			$url = "https://bon.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG35'){
			$url = "https://cmg.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else if($pg == 'SG36'){
			$url = "https://tkl.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
		}else{
			$url = "https://kwm.prodis.sinergigula.com/index.php/user/postlogin";
			$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];	
		}

		

		// $url = "https://kwm.prodis.sinergigula.com/index.php/user/postlogin";

		// $data = [
		// 	'username' => 'mkso.ho',
		// 	'password' => 'mkso.ho123'
		// ];
		
		$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0';
		$cookie = "ci_session=a%3A6%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22677c985afd7cca79976781ce45847fa9%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%22".$this->myipaddress()."%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A117%3A%22".urlencode($userAgent)."%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1739174392%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3Bs%3A4%3A%22lang%22%3Bs%3A2%3A%22en%22%3B%7Dc9f7347c8cb35c0e99abc9930aff63ecec15ce59"; // Gantilah dengan sesi yang valid
		
		$headers = [
			"Content-Type: application/x-www-form-urlencoded",
			"Upgrade-Insecure-Requests: 1",
			"User-Agent: ".$_SERVER['HTTP_USER_AGENT'],
			"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",
			"Referer: https://kwm.prodis.sinergigula.com/index.php/user/login",
			"Cookie: $cookie"
		];
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HEADER, true); // Ambil juga header respons
		
		$response = curl_exec($ch);
		$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
		$header = substr($response, 0, $header_size);
		$body = substr($response, $header_size);
		curl_close($ch);
		
		// Cari Set-Cookie di header
		preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches);
		$cookies = $matches[1];
		
		// Tampilkan Set-Cookie
		// echo "Set-Cookie dari response:\n";
		return $cookies[3];

	}

	function getcookieloginprodis2($pg){


		// URL endpoint
			if($pg == 1){
				$url = "https://jat.prodis.sinergigula.com/index.php/user/postlogin";
				$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
			}else if($pg == 9){
				$url = "https://ked.prodis.sinergigula.com/index.php/user/postlogin";
				$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
			}else if($pg == 2){
				$url = "https://sem.prodis.sinergigula.com/index.php/user/postlogin";
				$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
			}else if($pg == 8){
				$url = "https://won.prodis.sinergigula.com/index.php/user/postlogin";
				$data = ['username' => 'luluk.erma','password' => 'luluk.erma'];
			}

		
		

		// $url = "https://kwm.prodis.sinergigula.com/index.php/user/postlogin";

		// $data = [
		// 	'username' => 'mkso.ho',
		// 	'password' => 'mkso.ho123'
		// ];
		
		$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0';
		$cookie = "ci_session=a%3A6%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22677c985afd7cca79976781ce45847fa9%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%22".$this->myipaddress()."%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A117%3A%22".urlencode($userAgent)."%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1739174392%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3Bs%3A4%3A%22lang%22%3Bs%3A2%3A%22en%22%3B%7Dc9f7347c8cb35c0e99abc9930aff63ecec15ce59"; // Gantilah dengan sesi yang valid

		$headers = [
			"Content-Type: application/x-www-form-urlencoded",
			"Upgrade-Insecure-Requests: 1",
			"User-Agent: ".$userAgent,
			"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",
			"Referer: https://kwm.prodis.sinergigula.com/index.php/user/login",
			"Cookie: $cookie"
		];
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_HEADER, true); // Ambil juga header respons
		
		$response = curl_exec($ch);
		$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
		$header = substr($response, 0, $header_size);
		$body = substr($response, $header_size);
		curl_close($ch);
		
		// Cari Set-Cookie di header
		preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches);
		$cookies = $matches[1];
		
		// Tampilkan Set-Cookie
		// echo "Set-Cookie dari response:\n";
		return $cookies[3];

	}

	public function tarikdatatimbangmutu(Request $request)
	{
		config(['app.debug' => true]);
		// if (!\Auth::check()) 
		// 	return response()->json(array('status' => 'error', 'message' => 'You are not logged in'));

			$pabrik_gula = $request->input('pabrik_gula');
			$tgl1 = $request->input('tgl1');
			$petani = $request->input('petani');

			// URL endpoint
			if($pabrik_gula == 1){
				$url = "https://jat.prodis.sinergigula.com/index.php/laporanari/printlaporan/?kat=1";
			}else if($pabrik_gula == 9){
				$url = "https://ked.prodis.sinergigula.com/index.php/laporanari/printlaporan/?kat=1";
			}else if($pabrik_gula == 2){
				$url = "https://sem.prodis.sinergigula.com/index.php/laporanari/printlaporan/?kat=1";
			}else if($pabrik_gula == 8){
				$url = "https://won.prodis.sinergigula.com/index.php/laporanari/printlaporan/?kat=1";
			}
			
		
			// $url = "https://kwm.prodis.sinergigula.com/index.php/laporanmejatebu/printlaporan";

			$data = [
				'tglgiling' => $tgl1
			];

			$cookie = $this->getcookieloginprodis2($pabrik_gula); // Gantilah dengan sesi yang valid
			// echo $cookie;
					$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0';
			$headers = [
				"Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
				"X-Requested-With: XMLHttpRequest",
				"User-Agent: ".$userAgent,
				"Accept: */*",
				"Origin: https://kwm.prodis.sinergigula.com",
				"Sec-Fetch-Site: same-origin",
				"Sec-Fetch-Mode: cors",
				"Sec-Fetch-Dest: empty",
				"Referer: https://kwm.prodis.sinergigula.com/index.php/laporanari",
				"Cookie: $cookie"
			];
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_HEADER, true);
			
			$response = curl_exec($ch);
			curl_close($ch);
			

			// echo $response;
			


			// Ekstrak tabel dengan class "tableizer-table"
			$dom = new DOMDocument();
			libxml_use_internal_errors(true);
			$dom->loadHTML($response);
			libxml_clear_errors();

			// Cari elemen tabel dengan class "tableizer-table"
			$xpath = new DOMXPath($dom);
			$tables = $xpath->query("//table[contains(@class, 'tableizer-table')]");

			$data = []; // Array untuk menyimpan hasil JSON
			if ($tables->length > 0) {
				$table = $tables->item(0);

				$rows = $table->getElementsByTagName('tr');
					// print_r($rows);
				$headers = [];


				// Ambil header tabel (baris pertama)
				foreach ($rows->item(1)->getElementsByTagName('th') as $header) {
					$headers[] = trim($header->textContent);
				}

				// Jika tidak ada <th>, coba ambil <td> dari baris pertama
				if (empty($headers)) {
					foreach ($rows->item(1)->getElementsByTagName('td') as $header) {
						$headers[] = trim($header->textContent);
					}
				}

				// Ambil data baris (mulai dari baris kedua)
				for ($i = 1; $i < $rows->length; $i++) {
					$row = $rows->item($i);
					$cells = $row->getElementsByTagName('td');
						$rowData = [];
					if (count($cells)>1) {

						foreach ($cells as $index => $cell) {
							$rowData[] = trim($cell->textContent);
						}
					}

					if ($rowData != null) {
						$data[] = $rowData;

					}

					
				}

			}


			// Filter data berdasarkan nama "SUMU" (kolom ke-7, index 7)
			$filtered = array_filter($data, function($row) use ($petani) {
				return isset($row[7]) && strtolower($row[7]) === strtolower($petani);
			});
			echo json_encode(array_values($filtered));

}

	function myipaddress(){
		// Ambil alamat IP publik
		$ch = curl_init("https://ipinfo.io/ip");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$ip = curl_exec($ch);
		curl_close($ch);
	
		return trim($ip);
	}

	function mydate(){
		$dattee = date('Y-m-d H:i:s');
		return $dattee;
	}

	function exportdata(Request $request)
	{
		$table = $request->input('table');
		$param = $request->input('param');

		$data = \DB::table($table)
			->whereBetween($param, [$request->input('start_date'), $request->input('end_date')])
			->get();
		$headers = array_keys((array)$data->first());
		$output = '<table><thead><tr>';
		foreach ($headers as $header) {
			$output .= '<th>' . htmlspecialchars($header) . '</th>';
		}
		$output .= '</tr></thead><tbody>';
		foreach ($data as $row) {
			$output .= '<tr>';
			foreach ($headers as $header) {
				$output .= '<td>' . htmlspecialchars($row->$header) . '</td>';
			}
			$output .= '</tr>';
		}
		$output .= '</tbody></table>';
		return $output;
	}
	
	public function saveOrUpdateCookieProdisPg(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2526'));
		$kode_pg = $request->input('kode_pg');
		$cookie = $request->input('cookie');
		$expired = $request->input('expired');
		$token = $request->input('token', null);
		$now = date('Y-m-d H:i:s');

		\DB::table('master_cookie_prodis_pg')->updateOrInsert(
			['kode_pg' => $kode_pg],
			[
				'cookie'    => $cookie,
				'expired'   => $expired,
				'token'     => $token,
				'createdOn' => $now,
				'updatedOn' => $now
			]
		);

		return response()->json(['status' => 'success', 'message' => 'Cookie saved or updated']);
	}

	public function getMasterCookieProdisPg(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2526'));
		$pabrikgula = $request->input('pabrik_gula');
		$data = \DB::table('master_cookie_prodis_pg')
			->select(
				'cookie'

			)
			->where('kode_pg', $pabrikgula)
			->get();

		$result = [];
		foreach ($data as $item) {
			$cookies = json_decode($item->cookie, true);
			foreach ($cookies as $cookie) {
				$result[] = [
					'domain' => $cookie['domain'] ?? '',
					'expirationDate' => $cookie['expirationDate'] ?? null,
					'hostOnly' => $cookie['hostOnly'] ?? true,
					'httpOnly' => $cookie['httpOnly'] ?? false,
					'name' => $cookie['name'] ?? '',
					'path' => $cookie['path'] ?? '/',
					'sameSite' => $cookie['sameSite'] ?? 'lax',
					'secure' => $cookie['secure'] ?? false,
					'session' => $cookie['session'] ?? false,
					'storeId' => $cookie['storeId'] ?? '0',
					'value' => $cookie['value'] ?? ''
				];
			}
		}
		return response()->json($result);
	}
	

	function getdataselektor(Request $request){
		Config::set('database.default', session('database_name', 'mysql_2526'));
		config(['app.debug' => true]);
			$tgl1 = date('Y-m-d');
			$tgl2 = date('Y-m-d');
			$pg = $request->input('pabrik_gula');
			$baseUrl = "https://prodis.sinergigula.com";
			$loginUrl = $baseUrl . "/login";
			$laporanUrl = $baseUrl . "/laporan-selektor/get-laporan";
 
			

				// Build query parameters dynamically
				$queryParams = [
					'jangka_waktu' => 1,
					'periode_tanggal_mulai' => $tgl1,
					'periode_tanggal_selesai' => $tgl2,
					'bulan' => 1,
					'tahun' => date('Y'),
					'asal_blok' => '',
					'jenis_angkutan' => '',
					'jenis_laporan' => 2,
					'affdeling' => '',
					'jenis_pembayaran' => '',
					'kode_blok_filter' => ''
				];

				$url = "https://prodis.sinergigula.com/laporan-selektor/get-laporan?" . http_build_query($queryParams);

				$cookieRow = \DB::table('master_cookie_prodis_pg')->where('kode_pg', $pg)->first();
				if (!$cookieRow || empty($cookieRow->cookie)) {
					return response()->json(['status' => 'error', 'message' => 'Cookie not found for this PG']);
				}
				$cookies_json = $cookieRow->cookie;
				$cookies = json_decode($cookies_json, true);

				$cookieString = "";
				foreach ($cookies as $cookie) {
					$cookieString .= $cookie['name'] . "=" . $cookie['value'] . "; ";
				}
				$cookieString = rtrim($cookieString, "; ");

				// ==== 3. Akses halaman dashboard dengan cookies ====
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, [
						"Cookie: $cookieString",
						"User-Agent: Mozilla/5.0",
				]);

				$data = curl_exec($ch);
				curl_close($ch);

				// --- HASIL LAPORAN ---
				// echo "=== HASIL LAPORAN ===\n";
				$rawdata1 = json_decode($data)->data;
					foreach ($rawdata1 as $rowData) {
							if (substr($rowData->no_spta, 0, 2) == 'SG') {

							$insertData = [
								'no_urut' => $rowData->no_antrian ?? null,
								'no_rfid' => $rowData->no_rfid ?? null,
								'no_spta' => $rowData->no_spta ?? null,
								'afd' => $rowData->afd ?? null,
								'mandor' => $rowData->mandor ?? null,
								'pta' => $rowData->pta ?? null,
								'no_kontrak' => $rowData->nomer_kontrak ?? null,
								'no_petak' => $rowData->nomer_petak ?? null,
								'kebun' => $rowData->kebun ?? null,
								'id_petani' => $rowData->id_petani ?? null,
								'nama_petani' => $rowData->nama_petani ?? null,
								'kategori' => $rowData->kategori ?? null,
								'pembayaran' => $rowData->pembayaran ?? null,
								'jenis_angkutan' => $rowData->jenis_angkutan ?? null,
								'angkutan' => $rowData->angkutan ?? null,
								'no_angkutan' => $rowData->no_angkutan ?? null,
								'supir' => $rowData->supir ?? null,
								'terbakar' => $rowData->terbakar ?? null,
								'tebang' => $rowData->tebang ?? null,
								'selektor' => $rowData->selektor ?? null,
								'bruto' => $rowData->bruto ?? null,
								'tara' => $rowData->tara ?? null,
								'netto' => $rowData->netto ?? null,
								'ditolak' => $rowData->ditolak ?? null,
								'alasan' => $rowData->alasan ?? null,
								'user' => $rowData->created_by ?? null,
								'no_analisa' => $rowData->no_analisa ?? null,
								'tgl_selektor' => $rowData->tgl_urut ?? null,
							];

							if (substr($rowData->kategori, 0, 2) == 'TS') {
								\DB::table('data_selektor')->updateOrInsert(
									['no_spta' => $rowData->no_spta], // Assuming 'no_spta' is the unique key
									$insertData
								);
							}
						}
							// var_dump($rowData[1]);
						}
					if ($data) {
						return response()->json(array('status' => 'success', 'message' => 'Data successfully imported'));
					} else {
						return response()->json(array('status' => 'error', 'message' => 'No data found'));
					}
	}

	function getdatatimbangnew(Request $request){
		Config::set('database.default', session('database_name', 'mysql_2526'));
		config(['app.debug' => true]);
			$tgl1 = date('Y-m-d', strtotime('-1 days'));
			$tgl2 = date('Y-m-d', strtotime('-1 days'));
			$pg = $request->input('pabrik_gula');
			$baseUrl = "https://prodis.sinergigula.com";
			$loginUrl = $baseUrl . "/login";
			$laporanUrl = $baseUrl . "/laporan-timbangan/get-laporan";
		
			// --- REQUEST DATA LAPORAN ---
			
				// Build query parameters dynamically
				$queryParams = [
					'jangka_waktu' => 1,
					'periode_tanggal_mulai' => $tgl1,
					'periode_tanggal_selesai' => $tgl2,
					'bulan' => 1,
					'tahun' => 2025,
					'asal_blok' => '',
					'jenis_angkutan' => '',
					'kebun' => '',
					'jenis_laporan' => 2,
					'affdeling' => '',
					'jenis_pembayaran' => '',
					'metode_tma' => '',
					'jenis_tma' => '',
					'kode_blok_filter' => ''
				];

				$url = "https://prodis.sinergigula.com/laporan-timbangan/get-laporan?" . http_build_query($queryParams);

				// Ambil cookie dari database berdasarkan kode_pg
				$cookieRow = \DB::table('master_cookie_prodis_pg')->where('kode_pg', $pg)->first();
				if (!$cookieRow || empty($cookieRow->cookie)) {
					return response()->json(['status' => 'error', 'message' => 'Cookie not found for this PG']);
				}
				$cookies_json = $cookieRow->cookie;
				$cookies = json_decode($cookies_json, true);

				$cookieString = "";
				foreach ($cookies as $cookie) {
					$cookieString .= $cookie['name'] . "=" . $cookie['value'] . "; ";
				}
				$cookieString = rtrim($cookieString, "; ");

				// ==== 3. Akses halaman dashboard dengan cookies ====
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, [
					"Cookie: $cookieString",
					"User-Agent: Mozilla/5.0",
				]);

				$data = curl_exec($ch);
				curl_close($ch);
				//var_dump($data);
				// --- HASIL LAPORAN ---
				// echo "=== HASIL LAPORAN ===\n";
				$rawdata1 = json_decode($data)->data;
					foreach ($rawdata1 as $rowData) {
							if (substr($rowData->no_spta, 0, 2) == 'SG') {

							$insertData = [
								'no_spta' => $rowData->no_spta,
								'afd' => $rowData->afd,
								'nomer_kontrak' => $rowData->nomer_kontrak,
								'nomer_petak' => $rowData->nomer_petak,
								'kebun' => $rowData->kebun,
								'nama_petani' => $rowData->nama_petani,
								'kategori' => $rowData->kategori,
								'pembayaran' => $rowData->pembayaran,
								'blok' => $rowData->blok,
								'mandor' => $rowData->mandor,
								'pta' => $rowData->pta,
								'no_truk' => $rowData->no_truk,
								'no_trans' => $rowData->no_trans,
								'truk' => $rowData->truk,
								'lori' => $rowData->lori,
								'odong2' => $rowData->odong2,
								'traktor' => $rowData->traktor,
								'hektar' => $rowData->ha_tertebang,
								'bruto_kg' => str_replace(',', '', $rowData->bruto),
								'tara_kg' => str_replace(',', '', $rowData->tara),
								'netto_kg' => str_replace(',', '', $rowData->netto),
								'rafaksi_kg' => str_replace(',', '', $rowData->rafaksi),
								'netto_final_kg' => str_replace(',', '', $rowData->netto_final),
								'kode_timbangan' => $rowData->kode_timbangan,
								'kategori_tebang' => $rowData->kategori_tebang,
								'jenis_tebangan' => $rowData->jenis_tebangan,
								'jenis_tebu' => $rowData->jenis_tebu,
								'range_jarak' => $rowData->range_jarak,
								'no_trainstat' => $rowData->no_trainstat,
								'no_hv' => $rowData->no_hv,
								'op_hv' => $rowData->op_hv,
								'no_stipping' => $rowData->no_stipping,
								'op_stipping' => $rowData->op_stipping,
								'tgl_netto' => $rowData->tgl_netto,
								'no_analisa' => $rowData->no_analisa,
								'tgl_timbang' => $rowData->tgl_timbang,
								// Map other columns as needed
							];

							if (substr($rowData->kategori, 0, 2) == 'TS') {
								\DB::table('data_timbangan')->updateOrInsert(
									['no_spta' => $rowData->no_spta], // Assuming 'no_spta' is the unique key
									$insertData
								);
							}
						}

						}
					if ($data) {
						return response()->json(array('status' => 'success', 'message' => 'Data successfully imported'));
					} else {
						return response()->json(array('status' => 'error', 'message' => 'No data found'));
					}
	}

	function getdatamejatebunew(Request $request){
		Config::set('database.default', session('database_name', 'mysql_2526'));
		config(['app.debug' => true]);
			$tgl1 = date('Y-m-d', strtotime('-1 days'));
			$tgl2 = date('Y-m-d', strtotime('-1 days'));
			$pg = $request->input('pabrik_gula');
			$baseUrl = "https://prodis.sinergigula.com";
			$loginUrl = $baseUrl . "/login";
			$laporanUrl = $baseUrl . "/laporan-meja-tebu/get-laporan";

			

				// Build query parameters dynamically
				$queryParams = [
					'jangka_waktu' => 1,
					'periode_tanggal_mulai' => $tgl1,
					'periode_tanggal_selesai' => $tgl2,
					'bulan' => 1,
					'tahun' => 2025,
					'jenis_laporan' => 2,
					'metode_tma' => '',
					'kode_blok_filter' => ''
				];

				$url = "https://prodis.sinergigula.com/laporan-meja-tebu/get-laporan?" . http_build_query($queryParams);

				$cookieRow = \DB::table('master_cookie_prodis_pg')->where('kode_pg', $pg)->first();
				if (!$cookieRow || empty($cookieRow->cookie)) {
					return response()->json(['status' => 'error', 'message' => 'Cookie not found for this PG']);
				}
				$cookies_json = $cookieRow->cookie;
				$cookies = json_decode($cookies_json, true);

				$cookieString = "";
				foreach ($cookies as $cookie) {
					$cookieString .= $cookie['name'] . "=" . $cookie['value'] . "; ";
				}
				$cookieString = rtrim($cookieString, "; ");

				// ==== 3. Akses halaman dashboard dengan cookies ====
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, [
					"Cookie: $cookieString",
					"User-Agent: Mozilla/5.0",
				]);

				$data = curl_exec($ch);
				curl_close($ch);

				// --- HASIL LAPORAN ---
				// echo "=== HASIL LAPORAN ===\n";
				$rawdata1 = json_decode($data)->data;
					foreach ($rawdata1 as $rowData) {
							if (substr($rowData->no_spta, 0, 2) == 'SG') {

							$insertData = [
								'mt' => $rowData->no_mt,
								'no_analisa' => $rowData->no_analisa,
								'no_spta' => $rowData->no_spta,
								'afd' => $rowData->afd,
								'mandor' => $rowData->mandor,
								'pta' => $rowData->pta,
								'no_petak' => $rowData->nomer_petak,
								'kebun' => $rowData->kebun,
								'kategori' => $rowData->kategori,
								'angkutan' => $rowData->jenis_angkutan,
								'no_angkutan' => $rowData->no_truk,
								'transloading' => $rowData->no_trans,
								'netto' => str_replace(',', '', $rowData->netto),
								'brix' => '',
								'ph' => '',
								'terbakar' => $rowData->terbakar,
								'kualitas' => $rowData->kualitas,
								'ha_tertebang' => $rowData->ha_tertebang,
								'tebang' => (function($v){
									if(empty($v)) return null;
									$dt = \DateTime::createFromFormat('d-m-Y H:i', $v);
									return $dt ? $dt->format('Y-m-d H:i') : null;
								})($rowData->tgl_tebang),
								'selektor' => (function($v){
									if(empty($v)) return null;
									$dt = \DateTime::createFromFormat('d-m-Y H:i', $v);
									return $dt ? $dt->format('Y-m-d H:i') : null;
								})($rowData->tgl_selektor),
								'meja_tebu' => (function($v){
									if(empty($v)) return null;
									$dt = \DateTime::createFromFormat('d-m-Y H:i', $v);
									return $dt ? $dt->format('Y-m-d H:i') : null;
								})($rowData->tgl_meja_tebu),
								'cut_to_crush' => $rowData->tgl_cut,
								'foto' => '',
								'tgl_giling' => (function($v){
									if(empty($v)) return null;
									// Try d-m-Y H:i
									$dt = \DateTime::createFromFormat('d-m-Y H:i', $v);
									if($dt) return $dt->format('Y-m-d');
									// Try d-m-Y
									$dt = \DateTime::createFromFormat('d-m-Y', $v);
									if($dt) return $dt->format('Y-m-d');
									// Fallback to strtotime
									$ts = strtotime($v);
									return $ts ? date('Y-m-d', $ts) : null;
								})($rowData->tgl_giling),
								
								// Map other columns as needed
							];

							if (substr($rowData->kategori, 0, 2) == 'TS') {
								\DB::table('data_meja_tebu')->updateOrInsert(
									['no_spta' => $rowData->no_spta], // Assuming 'no_spta' is the unique key
									$insertData
								);
							}
						}
							// var_dump($rowData[1]);
						}
					if ($data) {
						return response()->json(array('status' => 'success', 'message' => 'Data successfully imported'));
					} else {
						return response()->json(array('status' => 'error', 'message' => 'No data found'));
					}
	}

	function tarikdatasbhnew(Request $request){
		Config::set('database.default', session('database_name', 'mysql_2526'));
		config(['app.debug' => true]);
			$tgl1 = $request->input('tgl');
			$tgl2 = $request->input('tgl');
			$pg = $request->input('pabrik_gula');
			$baseUrl = "https://prodis.sinergigula.com";
			$loginUrl = $baseUrl . "/login";
			$laporanUrl = $baseUrl . "/transaksi-sbh/get-data-date-range";

			
			$url = "https://prodis.sinergigula.com/transaksi-sbh/get-data-date-range";

			$cookieRow = \DB::table('master_cookie_prodis_pg')->where('kode_pg', $pg)->first();
			if (!$cookieRow || empty($cookieRow->cookie)) {
				return response()->json(['status' => 'error', 'message' => 'Cookie not found for this PG']);
			}
			$cookies_json = $cookieRow->cookie;
			$cookies = json_decode($cookies_json, true);

			$cookieString = "";
			foreach ($cookies as $cookie) {
				$cookieString .= $cookie['name'] . "=" . $cookie['value'] . "; ";
			}
			$cookieString = rtrim($cookieString, "; ");

			// Prepare POST data for DataTables
			$postData = [
				'draw' => 1,
				'start' => 0,
				'length' => -1,
				'search[value]' => '',
				'search[regex]' => 'false',
				'order[0][column]' => 0,
				'order[0][dir]' => 'asc',
				'tanggal_giling_awal' => $tgl1,
				'tanggal_giling_akhir' => $tgl2,
				'_token' => $cookieRow->token ?? '' // Pastikan token diambil dari database jika diperlukan,
			];

			// ==== 3. Akses halaman dengan cookies ====
			$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, [
				"Cookie: $cookieString",
				"User-Agent: Mozilla/5.0",
				"Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
				"X-Requested-With: XMLHttpRequest",
			]);

			$data = curl_exec($ch);
			curl_close($ch);
			

			// --- HASIL LAPORAN ---

		$rawdata1 = json_decode($data, true)['data'];
		foreach ($rawdata1 as $rowData) {
			if (substr($rowData['no_spta'], 0, 2) == 'SG') {
				if (strpos($rowData['asal_blok'], 'SK') !== false) {
					$insertData = [
						'kode_pg' => $pg,
						'no_spta' => $rowData['no_spta'],
						'no_analisa' => $rowData['no_analisa'] ?? '',
						'asal_kebun' => $rowData['asal_blok'],
						'no_kontrak' => '',
						'kode_afd' => $rowData['kode_affd'],
						'nama_asman' => $rowData['nama_asman'],
						'kode_blok' => $rowData['kode_blok'],
						'deskripsi_blok' => $rowData['deskripsi_blok'] ?? '',
						'id_petani' => $rowData['id_petani_sap'] ?? '',
						'petani' => $rowData['nama_petani'],
						'koperasi' => $rowData['koperasi'],
						'netto_tebu' => $rowData['netto_final'],
						'jenis_spta' => $rowData['jenis_spta'],
						'no_pol' => $rowData['no_angkutan'],
						'kategori' => $rowData['kode_kat_lahan'],
						'bulan_tanam' => $rowData['bulan_tanam'],
						'usia_tebu' => $rowData['usia_tebu'],
						'mutu_tebu' => $rowData['kondisi_tebu'],
						'varietas' => $rowData['kode_varietas'],
						'kemasakan' => $rowData['kemasakan'],
						'kesegaran' => $rowData['kesegaran'],
						'luas_ha' => $rowData['luas_ha'],
						'luas_tebang' => $rowData['ha_tertebang'],
						'tgljam_tebang' => $rowData['tgl_tebang'],
						'tgljam_selektor' => $rowData['selektor_tgl'],
						'tgljam_timbang' => $rowData['timb_netto_tgl'],
						'tgljam_mejatebu' => $rowData['meja_tebu_tgl'],
						'tgl_spta' => $rowData['tgl_spta'],
						'tgl_timbang' => $rowData['timb_netto_tgl'],
						'tgl_giling' => $rowData['tgl_giling'],
						'rendemen' => $rowData['rendemen_ari'],
						'rend_ptr' => $rowData['rendemen_ptr'],
						'gula_ptr' => $rowData['gula_ptr'],
						'tetes_ptr' => $rowData['tetes_ptr'],
						'tebang_pg' => $rowData['tebang_pg'] ? 1 : 0,
						'angkut_pg' => $rowData['angkut_pg'] ? 1 : 0,
						'jenis_pembayaran' => $rowData['jenis_pembayaran'],
						'nokontrak_giling' => '',
						'date_syn' => date('Y-m-d H:i:s'),
						'hablur_ari' => $rowData['hablur_ari'],
					];
					\DB::table('data_prodis_console')->updateOrInsert(
						['no_spta' => $rowData['no_spta']],
						$insertData
					);
				}
			}
		}

		return response()->json(['status' => 'success', 'message' => 'Data successfully imported']);
	}

	function getdatatimbangnewjrgtebu(Request $request){
		Config::set('database.default', session('database_name', 'mysql_2526'));
		config(['app.debug' => true]);
			$tgl1 = $request->input('tgl1');
			$tgl2 = $request->input('tgl2');
			$pg = $request->input('pabrik_gula');
			$petani = $request->input('petani');

			// URL endpoint
			if($pg == 1){
				$pg = "SG26";
			}else if($pg == 9){
				$pg = "SG23";
			}else if($pg == 2){
				$pg = "SG27";
			}else if($pg == 8){
				$pg = "SG24";
			}else if($pg == 16){
				$pg = "SG33";
			}
			
			$baseUrl = "https://prodis.sinergigula.com";
			$loginUrl = $baseUrl . "/login";
			$laporanUrl = $baseUrl . "/laporan-timbangan/get-laporan";
		
			// --- REQUEST DATA LAPORAN ---
			
				// Build query parameters dynamically
				$queryParams = [
					'jangka_waktu' => 1,
					'periode_tanggal_mulai' => $tgl1,
					'periode_tanggal_selesai' => $tgl2,
					'bulan' => date('m', strtotime($tgl1)),
					'tahun' => date('Y', strtotime($tgl1)),
					'asal_blok' => '',
					'jenis_angkutan' => '',
					'kebun' => '',
					'jenis_laporan' => 2,
					'affdeling' => '',
					'jenis_pembayaran' => '',
					'metode_tma' => '',
					'jenis_tma' => '',
					'kode_blok_filter' => ''
				];

				$url = "https://prodis.sinergigula.com/laporan-timbangan/get-laporan?" . http_build_query($queryParams);

				// Ambil cookie dari database berdasarkan kode_pg
				$cookieRow = \DB::table('master_cookie_prodis_pg')->where('kode_pg', $pg)->first();
				if (!$cookieRow || empty($cookieRow->cookie)) {
					return response()->json(['status' => 'error', 'message' => 'Cookie not found for this PG']);
				}
				$cookies_json = $cookieRow->cookie;
				$cookies = json_decode($cookies_json, true);

				$cookieString = "";
				foreach ($cookies as $cookie) {
					$cookieString .= $cookie['name'] . "=" . $cookie['value'] . "; ";
				}
				$cookieString = rtrim($cookieString, "; ");

				// ==== 3. Akses halaman dashboard dengan cookies ====
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, [
					"Cookie: $cookieString",
					"User-Agent: Mozilla/5.0",
				]);

				$data = curl_exec($ch);
				curl_close($ch);
				//var_dump($data);
				// --- HASIL LAPORAN ---
				// echo "=== HASIL LAPORAN ===\n";
				$rawdata1 = json_decode($data)->data;

					$filtered = array_filter($rawdata1, function($row) use ($petani) {
						return isset($row->nama_petani) && strtolower($row->nama_petani) === strtolower($petani);
					});
					echo json_encode(array_values($filtered));
				
	}

function getdatamejatebunewjrgtebu2(Request $request){
		Config::set('database.default', session('database_name', 'mysql_2526'));
		config(['app.debug' => true]);
			$tgl1 = $request->input('tgl1');
			$tgl2 = $request->input('tgl2');
			$pg = $request->input('pabrik_gula');
			$petani = $request->input('petani');

			// URL endpoint
			if($pg == 1){
				$pg = "SG26";
			}else if($pg == 9){
				$pg = "SG23";
			}else if($pg == 2){
				$pg = "SG27";
			}else if($pg == 8){
				$pg = "SG24";
			}else if($pg == 16){
				$pg = "SG33";
			}
			
			$baseUrl = "https://prodis.sinergigula.com";
			$loginUrl = $baseUrl . "/login";
			$laporanUrl = $baseUrl . "/laporan-meja-tebu/get-laporan";
		
			// --- REQUEST DATA LAPORAN ---
			
				// Build query parameters dynamically
				$queryParams = [
					'jangka_waktu' => 1,
					'periode_tanggal_mulai' => $tgl1,
					'periode_tanggal_selesai' => $tgl2,
					'bulan' => date('m', strtotime($tgl1)),
					'tahun' => date('Y', strtotime($tgl1)),
					'jenis_laporan' => 2,
					'metode_tma' => '',
					'kode_blok_filter' => ''
				];

				$url = "https://prodis.sinergigula.com/laporan-meja-tebu/get-laporan?" . http_build_query($queryParams);

				// Ambil cookie dari database berdasarkan kode_pg
				$cookieRow = \DB::table('master_cookie_prodis_pg')->where('kode_pg', $pg)->first();
				if (!$cookieRow || empty($cookieRow->cookie)) {
					return response()->json(['status' => 'error', 'message' => 'Cookie not found for this PG']);
				}
				$cookies_json = $cookieRow->cookie;
				$cookies = json_decode($cookies_json, true);

				$cookieString = "";
				foreach ($cookies as $cookie) {
					$cookieString .= $cookie['name'] . "=" . $cookie['value'] . "; ";
				}
				$cookieString = rtrim($cookieString, "; ");

				// ==== 3. Akses halaman dashboard dengan cookies ====
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_HTTPHEADER, [
					"Cookie: $cookieString",
					"User-Agent: Mozilla/5.0",
				]);

				$data = curl_exec($ch);
				curl_close($ch);
				//var_dump($data);
				// --- HASIL LAPORAN ---
				// echo "=== HASIL LAPORAN ===\n";
				$rawdata1 = json_decode($data)->data;
					echo json_encode(array_values($rawdata1));
				
	}	

	function getdatamejatebunewjrgtebu(Request $request){
		Config::set('database.default', session('database_name', 'mysql_2526'));
		config(['app.debug' => true]);
			$tgl1 = $request->input('tgl1');
			$tgl2 = $request->input('tgl1');
			$pg = $request->input('pabrik_gula');
			$petani = $request->input('petani');

			// URL endpoint
			if($pg == 1){
				$pg = "SG26";
			}else if($pg == 9){
				$pg = "SG23";
			}else if($pg == 2){
				$pg = "SG27";
			}else if($pg == 8){
				$pg = "SG24";
			}
			
			$baseUrl = "https://prodis.sinergigula.com";
			$loginUrl = $baseUrl . "/login";
			$laporanUrl = $baseUrl . "/laporan-meja-tebu/get-laporan";
		
			// --- REQUEST DATA LAPORAN ---
			

				$url = "https://prodis.sinergigula.com/transaksi-upah-tebang/get-list-spta-timbang";

				// Ambil cookie dari database berdasarkan kode_pg
				$cookieRow = \DB::table('master_cookie_prodis_pg')->where('kode_pg', $pg)->first();
				if (!$cookieRow || empty($cookieRow->cookie)) {
					return response()->json(['status' => 'error', 'message' => 'Cookie not found for this PG']);
				}
				$cookies_json = $cookieRow->cookie;
				$cookies = json_decode($cookies_json, true);

				$cookieString = "";
				foreach ($cookies as $cookie) {
					$cookieString .= $cookie['name'] . "=" . $cookie['value'] . "; ";
				}
				$cookieString = rtrim($cookieString, "; ");

								// Build query parameters dynamically
				$queryParams = [
				'_token' => $cookieRow->token,	
				'kode_blok' => '',
				'pta' => '',
				'mandor' => '',
				'tanggal_mulai' => $tgl1,
				'tanggal_sampai' => $tgl2,
				'jenis_tebangan' => ''
				];


				// ==== 3. Akses halaman dashboard dengan cookies ====
				$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($queryParams));
				curl_setopt($ch, CURLOPT_HTTPHEADER, [
					"Cookie: $cookieString",
					"User-Agent: Mozilla/5.0",
				]);

// Get timbangan data first
			$timbangan_queryParams = [
				'jangka_waktu' => 1,
				'periode_tanggal_mulai' => $tgl1,
				'periode_tanggal_selesai' => $tgl2,
				'bulan' => date('m', strtotime($tgl1)),
				'tahun' => date('Y', strtotime($tgl1)),
				'asal_blok' => '',
				'jenis_angkutan' => '',
				'kebun' => '',
				'jenis_laporan' => 2,
				'affdeling' => '',
				'jenis_pembayaran' => '',
				'metode_tma' => '',
				'jenis_tma' => '',
				'kode_blok_filter' => ''
			];
			
			$timbangan_url = "https://prodis.sinergigula.com/laporan-timbangan/get-laporan?" . http_build_query($timbangan_queryParams);
			
			$ch_timbangan = curl_init();
			curl_setopt($ch_timbangan, CURLOPT_URL, $timbangan_url);
			curl_setopt($ch_timbangan, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch_timbangan, CURLOPT_HTTPHEADER, [
				"Cookie: $cookieString",
				"User-Agent: Mozilla/5.0",
			]);
			
			$timbangan_data = curl_exec($ch_timbangan);
			curl_close($ch_timbangan);
			$timbangan_raw = json_decode($timbangan_data)->data;
			
			// Create indexed array for quick lookup by no_spta
			$timbangan_map = [];
			foreach ($timbangan_raw as $tmbg) {
				if (isset($tmbg->no_spta)) {
					$timbangan_map[$tmbg->no_spta] = $tmbg;
				}
			}
			
			// Now get meja tebu data
			$data = curl_exec($ch);
			curl_close($ch);
			//var_dump($data);
			// --- HASIL LAPORAN ---
			// echo "=== HASIL LAPORAN ===\n";
				// var_dump($data);
				
				// print_r($data);
				// exit;
		$rawdata1 = json_decode($data)->data;

				// Filter timbangan data by nama_petani first
				$filtered_timbangan = array_filter($timbangan_raw, function($tmbg) use ($petani) {
					return isset($tmbg->nama_petani) && strtolower($tmbg->nama_petani) === strtolower($petani);
				});

				
				$filtered = array_filter($rawdata1, function($row) use ($filtered_timbangan) {
					if (isset($row->no_spta)) {
						foreach ($filtered_timbangan as $tmbg) {
							if (isset($tmbg->no_spta) && $tmbg->no_spta === $row->no_spta) {
								return true;
							}
						}
					}
					return false;
				});
					
					// Join data and add kualitas column
					$joined_data = [];
					foreach ($filtered as $row) {
						$row_array = (array)$row;
						if (isset($row->no_spta)) {
							foreach ($filtered_timbangan as $tmbg) {
								if (isset($tmbg->no_spta) && $tmbg->no_spta === $row->no_spta) {
									$row_array['kualitas'] = $tmbg->mutu_tebu ?? null;
									$row_array['nama_petani'] = $tmbg->nama_petani ?? null;
									break;
								}
							}
						}
						$joined_data[] = (object)$row_array;
					}
					
					// Add timbangan data without no_spta
					foreach ($filtered_timbangan as $tmbg) {
						$found = false;
						foreach ($joined_data as $jd) {
							if (isset($jd->no_spta) && isset($tmbg->no_spta) && $jd->no_spta === $tmbg->no_spta) {
								$found = true;
								break;
							}
						}
						if (!$found) {
							$tmbg_array = (array)$tmbg;
							$tmbg_array['kualitas'] = $tmbg->mutu_tebu ?? null;
							$joined_data[] = (object)$tmbg_array;
						}
					}
					
					echo json_encode(array_values($joined_data));
				
	}
}