<?php namespace App\Http\Controllers;

use App\Models\Dataprodisconsole;
use App\Library\DataHelpers;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ;
use Illuminate\Support\Facades\DB; 
use DOMDocument;
use DOMXPath;


class DataprodisconsoleController extends Controller {

	protected $layout = "layouts.main";
	protected $data = array();	
	public $module = 'dataprodisconsole';
	static $per_page	= '10';
	
	public function __construct() 
	{
		parent::__construct();
		$this->model = new Dataprodisconsole();
		
		$this->info = $this->model->makeInfo( $this->module);
		$this->access = $this->model->validAccess($this->info['id']);
	
		$this->data = array(
			'pageTitle'			=> 	$this->info['title'],
			'pageNote'			=>  $this->info['note'],
			'pageModule'		=> 'dataprodisconsole',
			'pageUrl'			=>  url('dataprodisconsole'),
			'return' 			=> 	self::returnUrl()	
		);	
			
				
	} 
	public function index()
	{
		if(!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message','You are not login');

		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));
		if($this->access['is_view'] ==0) 
			return redirect('dashboard')->with('message',__('core.note_restric'))->with('status','error');
		
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['tableForm'] 	= $this->info['config']['forms'];
		$this->data['tableGrid'] 	= $this->info['config']['grid'];
		usort($this->data['tableGrid'], "SiteHelpers::_sort");
			$cols = '{"data":"rowId"},';
			if($this->data['setting']['view-method'] =='expand'){
				$cols .= '{"className": "details-control","orderable": false,"data": null,"defaultContent": ""},';
			}		
				
			foreach($this->data['tableGrid'] as $field)
			{				
				
				if($field['view'] =='1')
				{
					$cols .= '{"data":"'.$field['field'].'"},';
				}						
			}
			$cols .= '{"data":"action"},';
		$this->data['column'] = $cols ;	
		$this->data['access']		= $this->access;	
		$this->data['setting'] 		= $this->info['setting'];
		return view('dataprodisconsole.index',$this->data);
	}
	function create( Request $request ) 
	{
		$this->hook( $request  );
		if($this->access['is_add'] ==0) 
			return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');

		$this->data['row'] = $this->model->getColumnTable( $this->info['table']); 
		
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['id'] = '';
		return view($this->module.'.form',$this->data);
	}
	function edit( Request $request , $id ) 
	{
		$this->hook( $request , $id );
		if(!isset($this->data['row']))
			return redirect($this->module)->with('message','Record Not Found !')->with('status','error');
		if($this->access['is_edit'] ==0 )
			return redirect('dashboard')->with('message',__('core.note_restric'))->with('status','error');
		$this->data['row'] = (array) $this->data['row'];
		
		$this->data['setting'] 		= $this->info['setting'];
		$this->data['id'] = $id;
		return view($this->module.'.form',$this->data);
	}
	function show( Request $request , $id ) 
	{
		/* Handle import , export and view */
		$task =$id ;
		switch( $task)
		{
			case 'search':
				return $this->getSearch();
				break;
			case 'lookup':
				return $this->getLookup($request );
				break;
			case 'comboselect':
				return $this->getComboselect( $request );
				break;
			case 'import':
				return $this->getImport( $request );
			case 'removefiles':
				return $this->getRemovefiles( $request );	
				break;
			case 'export':
				return $this->getExport( $request );
				break;
			case 'tarikdata':
				return $this->tarikdata($request);
				break;

			case 'getdates':
				return $this->getDates($request);
				break;
				
			case 'tarikdataconsolelkp':
				return $this->tarikdataconsolelkp($request);
				break;
            
            case 'tarikdataconsolelkpdashboard':
				return $this->tarikdataconsolelkpdashboard($request);
				break;
			case 'tarikdataconsolelkpsimpan':
				return $this->tarikdataconsolelkpsimpan($request);
				break;
			case 'tarikdataconsolelkppgsimpan':
				return $this->tarikdataconsolelkppgsimpan($request);
				break;
			case 'tarikdataconsolelkphightlight':
				return $this->tarikdataconsolelkphightlight($request);
				break;



			default:
				$this->hook( $request , $id );
				if(!isset($this->data['row']))
					return redirect($this->module)->with('message','Record Not Found !')->with('status','error');

				if($this->access['is_detail'] ==0) 
					return redirect('dashboard')->with('message', __('core.note_restric'))->with('status','error');

				return view($this->module.'.view',$this->data);	
				break;		
		}
	}	
	public function store( Request $request){

		$task = $request->input('action_task');
		switch ($task)
		{
			default:
				return $this->postData( $request);
				break;
			case 'save':
				$rules = $this->validateForm();
				$validator = Validator::make($request->all(), $rules);
				if ($validator->passes()) 
				{
					$data = $this->validatePost( $request );
					$id = $this->model->insertRow($data , $request->input( $this->info['key']));
					
					/* Insert logs */
					$this->model->logs($request , $id);
					return response()->json(array('status'=>'success','message'=> __('core.note_success')));	
					
				} 
				else {
					$message = $this->validateListError(  $validator->getMessageBag()->toArray() );
					return response()->json(array(
						'message'	=> $message,
						'status'	=> 'error'
					));	
				}
				break;
			case 'delete':
				return $result = $this->destroy( $request );
				break;

			case 'import':
				return $this->PostImport( $request );
				break;

			case 'copy':
				$result = $this->copy( $request );
				return response()->json($result);
				break;		

		}
	}
	public function postData( $request)
	{ 
		
		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));

		$tables 	= $this->info['config']['grid'];
		$cols = array();
		foreach($tables as $field)
		{				
			//$cols[$this->info['key']]	= array('db'=> $field['alias'] ,$this->info['key'] );
			if($field['view'] =='1')
			{
				$cols[] = array('db'=> $field['alias'],'dt'=> $field['field'] );
			}					
		}
		$conf = DataHelpers::simple($request->all(),$cols);
		$filter =  '';
		if(!is_null($request->input('search')))
		{
			$filter .= $this->liveSearch( $request);
		}

		$params = array(
			'page'		=> $conf['page'] ,
			'limit'		=> $conf['limit'] ,
			'sort'		=> ($conf['order']['sort'] !='' ? $conf['order']['sort'] : $this->info['setting']['orderby']) ,
			'order'		=> ($conf['order']['by'] !='' ? $conf['order']['by'] : $this->info['setting']['ordertype']),
			'params'	=> $filter,
			'global'	=> (isset($this->access['is_global']) ? $this->access['is_global'] : 0 )
		);


		$results = $this->model->getRows($params);
		
		$array = array();
		foreach($results['rows'] as $row)
		{
			$values = array();
			$values['rowId'] = $row->{$this->info['key']};
			foreach($tables as $field)
			{			
				
				if($field['view'] =='1')
				{
					$values[$field['field']] = \SiteHelpers::formatRows($row->{$field['field']}, $field , $row);
				}	
			}
			$values['action'] =  \SiteHelpers::buttonAction($this->module,$this->access ,$row->{$this->info['key']} ,$this->info['setting']) ;
			$array[] = $values; 	
		}
		
		$data = array(
			'draw'			=> (!is_null($request->input('draw')) ? intval($request->input('draw') ) : 0), 
			'recordsTotal'	=> $results['total'] ,
			'recordsFiltered'	=> $results['total'],
			'data'				=> $array

		);
		return response()->json($data);
	}

	public function destroy( Request $request)
	{

		if(!\Auth::check()) 
			return response()->json(array(
				'status'=>'error',
				'message'=> 'You are not login'
			));

		$this->access = $this->model->validAccess($this->info['id'] , session('gid'));
		if($this->access['is_remove'] ==0) 
			return response()->json(array('status'=>'error','message'=> __('core.note_restric')));	


		// delete multipe rows 
		if(count($request->input('ids')) >=1)
		{
			$this->model->destroy($request->input('ids'));
			
			return response()->json(array(
				'status'=>'success',
				'message'=> __('core.note_success_delete')
			));
		} else {
			return response()->json(array(
				'status'=>'error',
				'message'=> __('core.note_error')
			));

		} 		

	}

	public function tarikdata(Request $request)
	{
		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');
			$tgl2 = $request->input('tgl2');
			$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'));
			}
	}
	
		public function tarikdataconsolelkp(Request $request)
	{
		if (!\Auth::check()) 
			return response()->json(array('status' => 'error', 'message' => 'You are not logged in'));

			$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);
			
			// Parse HTML to extract the table element
           
			 $outtt = $this->parsedom($response);
			 $outtt2 = $this->parsedom($response2);
			$this->data['loaddata'] = $outtt;
			$this->data['loaddata2'] = $outtt2;
				return view('consolelhpmkso.index',$this->data);
	}


	
	
public function tarikdataconsolelkpdashboard(Request $request)
{
	
    if (!\Auth::check()) {
        return response()->json(array('status' => 'error', 'message' => 'You are not logged in'));
    }

    $url2 = "https://sigula.sinergigula.com/index.php/consolelhpmkso/getdata";
    
	$tgl = date('Y-m-d', strtotime('-1 day'));
    $regional = '';    

	$postData = [
	                "tgl" => $tgl,
                    "regional" => $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",
    ];

    $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)) {
        return response()->json(array('status' => 'error', 'message' => 'Curl error: ' . curl_error($ch2)));
    }
    curl_close($ch2);

    // Initialize DOMDocument to parse the HTML
    $dom = new \DOMDocument();
    @$dom->loadHTML($response2);  // Suppress warnings for malformed HTML
    
    // Use DOMXPath to query the document
    $xpath = new \DOMXPath($dom);
    
    // Get the third table element
    $tables = $xpath->query('//table');
	$jmltable = $tables->length - 1;
	// Check if the third table exists
	// This will select all tables
    if ($tables->length >= $jmltable) {
        $table = $tables->item($jmltable); // The third table (index starts from 0)
        
        $rows = $table->getElementsByTagName('tr'); // Get all rows
        $data = [];
        
        // Loop through each row
        foreach ($rows as $row) {
            $cols = $row->getElementsByTagName('td'); // Get all columns for each row
            $rowData = [];
            foreach ($cols as $col) {
                $columnValue = trim($col->nodeValue);  // Get the text content of each column, trimming whitespace
                
                // Only add non-empty values
                if (!empty($columnValue)) {
                  
                        $rowData[] = $columnValue; // Add the value if it's not empty
 
                }
            }
            
            // Only add rows that have at least one non-empty column
            if (count($rowData) > 0) {

                $data[] = $rowData;
            }
        }

        // Extract rows where the index is a multiple of 17 (i.e., 17th, 34th, 51st, ...)
        $multiplesOf17 = [];
        foreach ($data as $index => $row) {
            if (($index + 1) % 16 == 0) {  // +1 because array index starts from 0
                $multiplesOf17[] = $row;
            }
        }
        
        $arr_data = [];
        foreach ($multiplesOf17 as $key=> $value){
           foreach ($value as $key => $value2){
               if($key == 1)
               {
                  array_push($arr_data,$value2);
               }
               
           }
        }

		$SK01 = [];
		foreach ($data as $index => $row) {
                $SK01[] = $row;
        }
        
		$arr_tophead = [
			'ditebang',
			'digiling',
			'protas',
			'tebu',
			'rendemen',
			'hablur',
			'gula',
			'tetes'
		];
		$arr_head = [
			"SK01",
			"SK02",
			"SK03",
			"SK04",
			"SK05",
			"SK06",
			"SK07",
			"SK08",
			"SK09",
			"SK10",
			"SK11",
			"SK12",
			"SK13",
			"SK14",
			"SK15",
			"JMLTSKSO",	
		];

		$arr_joinheadtop = [];
		for ($i = 0; $i < count($arr_tophead); $i++) {
			for ($j = 0; $j < count($arr_head); $j++) {
					$arr_joinheadtop1 = $arr_tophead[$i] . '_' . $arr_head[$j];
					array_push($arr_joinheadtop, $arr_joinheadtop1);
			}
		}

        $arr_data_raw = [];
        foreach ($SK01 as $key=> $value){
			array_push($arr_data_raw,$value[1]);
        }
		
		$data_raw_with_keys = [];
		foreach ($arr_data_raw as $key => $value) {
			if (isset($arr_joinheadtop[$key])) {
				$data_raw_with_keys[$arr_joinheadtop[$key]] = floatval(str_replace(',', '', $value));
			}
		}

		$arr_jawa = [
			'SK06',
			'SK07',
			'SK08',
			'SK09',
			'SK10',
			'SK11',
			'SK12',
		];

		$arr_non_jawa = [
			'SK01',
			'SK02',
			'SK03',
			'SK04',
			'SK05',
			'SK13',
			'SK14',
			'SK15'
		];

		$luas_jawa = $data_raw_with_keys['digiling_SK06'] + $data_raw_with_keys['digiling_SK07'] + $data_raw_with_keys['digiling_SK08'] + $data_raw_with_keys['digiling_SK09'] + $data_raw_with_keys['digiling_SK10'] + $data_raw_with_keys['digiling_SK11'] + $data_raw_with_keys['digiling_SK12'];
		$luas_non_jawa = $data_raw_with_keys['digiling_SK01'] + $data_raw_with_keys['digiling_SK02'] + $data_raw_with_keys['digiling_SK03'] + $data_raw_with_keys['digiling_SK04'] + $data_raw_with_keys['digiling_SK05'] + $data_raw_with_keys['digiling_SK13'] + $data_raw_with_keys['digiling_SK14'] + $data_raw_with_keys['digiling_SK15'];

		$tebu_jawa = $data_raw_with_keys['tebu_SK06'] + $data_raw_with_keys['tebu_SK07'] + $data_raw_with_keys['tebu_SK08'] + $data_raw_with_keys['tebu_SK09'] + $data_raw_with_keys['tebu_SK10'] + $data_raw_with_keys['tebu_SK11'] + $data_raw_with_keys['tebu_SK12'];
		$tebu_non_jawa = $data_raw_with_keys['tebu_SK01'] + $data_raw_with_keys['tebu_SK02'] + $data_raw_with_keys['tebu_SK03'] + $data_raw_with_keys['tebu_SK04'] + $data_raw_with_keys['tebu_SK05'] + $data_raw_with_keys['tebu_SK13'] + $data_raw_with_keys['tebu_SK14'] + $data_raw_with_keys['tebu_SK15'];

		$gula_jawa = $data_raw_with_keys['gula_SK06'] + $data_raw_with_keys['gula_SK07'] + $data_raw_with_keys['gula_SK08'] + $data_raw_with_keys['gula_SK09'] + $data_raw_with_keys['gula_SK10'] + $data_raw_with_keys['gula_SK11'] + $data_raw_with_keys['gula_SK12'];
		$gula_non_jawa = $data_raw_with_keys['gula_SK01'] + $data_raw_with_keys['gula_SK02'] + $data_raw_with_keys['gula_SK03'] + $data_raw_with_keys['gula_SK04'] + $data_raw_with_keys['gula_SK05'] + $data_raw_with_keys['gula_SK13'] + $data_raw_with_keys['gula_SK14'] + $data_raw_with_keys['gula_SK15'];

		$tetes_jawa = $data_raw_with_keys['tetes_SK06'] + $data_raw_with_keys['tetes_SK07'] + $data_raw_with_keys['tetes_SK08'] + $data_raw_with_keys['tetes_SK09'] + $data_raw_with_keys['tetes_SK10'] + $data_raw_with_keys['tetes_SK11'] + $data_raw_with_keys['tetes_SK12'];
		$tetes_non_jawa = $data_raw_with_keys['tetes_SK01'] + $data_raw_with_keys['tetes_SK02'] + $data_raw_with_keys['tetes_SK03'] + $data_raw_with_keys['tetes_SK04'] + $data_raw_with_keys['tetes_SK05'] + $data_raw_with_keys['tetes_SK13'] + $data_raw_with_keys['tetes_SK14'] + $data_raw_with_keys['tetes_SK15'];

		$ditebang_jawa_sum = $data_raw_with_keys['digiling_SK06'] + $data_raw_with_keys['digiling_SK07'] + $data_raw_with_keys['digiling_SK08'] + $data_raw_with_keys['digiling_SK09'] + $data_raw_with_keys['digiling_SK10'] + $data_raw_with_keys['digiling_SK11'] + $data_raw_with_keys['digiling_SK12'];
		$protas_jawa = $ditebang_jawa_sum != 0 ? ($data_raw_with_keys['tebu_SK06'] + $data_raw_with_keys['tebu_SK07'] + $data_raw_with_keys['tebu_SK08'] + $data_raw_with_keys['tebu_SK09'] + $data_raw_with_keys['tebu_SK10'] + $data_raw_with_keys['tebu_SK11'] + $data_raw_with_keys['tebu_SK12']) / $ditebang_jawa_sum : 0;	 
		$ditebang_non_jawa_sum = $data_raw_with_keys['digiling_SK01'] + $data_raw_with_keys['digiling_SK02'] + $data_raw_with_keys['digiling_SK03'] + $data_raw_with_keys['digiling_SK04'] + $data_raw_with_keys['digiling_SK05'] + $data_raw_with_keys['digiling_SK13'] + $data_raw_with_keys['digiling_SK14'] + $data_raw_with_keys['digiling_SK15'];
		$protas_non_jawa = $ditebang_non_jawa_sum != 0 ? ($data_raw_with_keys['tebu_SK01'] + $data_raw_with_keys['tebu_SK02'] + $data_raw_with_keys['tebu_SK03'] + $data_raw_with_keys['tebu_SK04'] + $data_raw_with_keys['tebu_SK05'] + $data_raw_with_keys['tebu_SK13'] + $data_raw_with_keys['tebu_SK14'] + $data_raw_with_keys['tebu_SK15']) / $ditebang_non_jawa_sum : 0;

		$tebu_jawa_sum = $data_raw_with_keys['tebu_SK06'] + $data_raw_with_keys['tebu_SK07'] + $data_raw_with_keys['tebu_SK08'] + $data_raw_with_keys['tebu_SK09'] + $data_raw_with_keys['tebu_SK10'] + $data_raw_with_keys['tebu_SK11'] + $data_raw_with_keys['tebu_SK12'];
		$rendemen_jawa = $tebu_jawa_sum != 0 ? (($data_raw_with_keys['hablur_SK06'] + $data_raw_with_keys['hablur_SK07'] + $data_raw_with_keys['hablur_SK08'] + $data_raw_with_keys['hablur_SK09'] + $data_raw_with_keys['hablur_SK10'] + $data_raw_with_keys['hablur_SK11'] + $data_raw_with_keys['hablur_SK12']) / $tebu_jawa_sum) * 100 : 0;
		$tebu_non_jawa_sum = $data_raw_with_keys['tebu_SK01'] + $data_raw_with_keys['tebu_SK02'] + $data_raw_with_keys['tebu_SK03'] + $data_raw_with_keys['tebu_SK04'] + $data_raw_with_keys['tebu_SK05'] + $data_raw_with_keys['tebu_SK13'] + $data_raw_with_keys['tebu_SK14'] + $data_raw_with_keys['tebu_SK15'];
		$rendemen_non_jawa = $tebu_non_jawa_sum != 0 ? (($data_raw_with_keys['hablur_SK01'] + $data_raw_with_keys['hablur_SK02'] + $data_raw_with_keys['hablur_SK03'] + $data_raw_with_keys['hablur_SK04'] + $data_raw_with_keys['hablur_SK05'] + $data_raw_with_keys['hablur_SK13'] + $data_raw_with_keys['hablur_SK14'] + $data_raw_with_keys['hablur_SK15']) / $tebu_non_jawa_sum) * 100 : 0;

		$hablur_jawa =  $data_raw_with_keys['hablur_SK06'] + $data_raw_with_keys['hablur_SK07'] + $data_raw_with_keys['hablur_SK08'] + $data_raw_with_keys['hablur_SK09'] + $data_raw_with_keys['hablur_SK10'] + $data_raw_with_keys['hablur_SK11'] + $data_raw_with_keys['hablur_SK12'];
		$hablur_non_jawa =  $data_raw_with_keys['hablur_SK01'] + $data_raw_with_keys['hablur_SK02'] + $data_raw_with_keys['hablur_SK03'] + $data_raw_with_keys['hablur_SK04'] + $data_raw_with_keys['hablur_SK05'] + $data_raw_with_keys['hablur_SK13'] + $data_raw_with_keys['hablur_SK14'] + $data_raw_with_keys['hablur_SK15'];


		$rkap = DB::table('master_rkap2025_rekap')
			->selectRaw('
				ROUND(SUM(luas_ha), 2) AS luas_ha,

				ROUND(SUM(tebu_ton) / SUM(luas_ha), 2) AS protas,
								ROUND(SUM(tebu_ton), 2) AS tebu_ton,
				ROUND(SUM(hablur) / SUM(tebu_ton) * 100, 2) AS rendemen,
				ROUND(SUM(hablur),2) AS hablur,
				ROUND(SUM(gula_milik), 2) AS gula_milik,
				ROUND(SUM(tetes_milik), 2) AS tetes_milik
			')
			->first();

		// Return the rows that are multiples of 17 as JSON
        return response()->json(array('status' => 'success', 'data' => $arr_data, 'luas_jawa' => $luas_jawa, 'luas_non_jawa' => $luas_non_jawa, 'tebu_jawa' => $tebu_jawa, 'tebu_non_jawa' => $tebu_non_jawa, 'gula_jawa' => $gula_jawa, 'gula_non_jawa' => $gula_non_jawa, 'tetes_jawa' => $tetes_jawa, 'tetes_non_jawa' => $tetes_non_jawa, 'protas_jawa' => $protas_jawa, 'protas_non_jawa' => $protas_non_jawa, 'rendemen_jawa' => $rendemen_jawa, 'rendemen_non_jawa' => $rendemen_non_jawa, 'hablur_jawa' => $hablur_jawa, 'hablur_non_jawa' => $hablur_non_jawa,'rkap' => $rkap, 'raw' => $data_raw_with_keys));
    } else {
        return response()->json(array('status' => 'error', 'message' => 'Third table not found'));
    }
}

public function tarikdataconsolelkphightlight(Request $request)
{
	
    if (!\Auth::check()) {
        return response()->json(array('status' => 'error', 'message' => 'You are not logged in'));
    }

    $url2 = "https://sigula.sinergigula.com/index.php/consolelhpmkso/getdata";
    
	$tgl = $request->input('tgl', date('Y-m-d', strtotime('-1 day')));
    $regional = '';    

	$postData = [
	                "tgl" => $tgl,
                    "regional" => $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",
    ];

    $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)) {
        return response()->json(array('status' => 'error', 'message' => 'Curl error: ' . curl_error($ch2)));
    }
    curl_close($ch2);

    // Initialize DOMDocument to parse the HTML
    $dom = new \DOMDocument();
    @$dom->loadHTML($response2);  // Suppress warnings for malformed HTML
    
    // Use DOMXPath to query the document
    $xpath = new \DOMXPath($dom);
    
    // Get the third table element
    $tables = $xpath->query('//table');
	$jmltable = $tables->length - 1;
	// Check if the third table exists
	// This will select all tables
    if ($tables->length >= $jmltable) {
        $table = $tables->item($jmltable); // The third table (index starts from 0)
        
        $rows = $table->getElementsByTagName('tr'); // Get all rows
        $data = [];
        
        // Loop through each row
        foreach ($rows as $row) {
            $cols = $row->getElementsByTagName('td'); // Get all columns for each row
            $rowData = [];
            foreach ($cols as $col) {
                $columnValue = trim($col->nodeValue);  // Get the text content of each column, trimming whitespace
                
                // Only add non-empty values
                if (!empty($columnValue)) {
                  
                        $rowData[] = $columnValue; // Add the value if it's not empty
 
                }
            }
            
            // Only add rows that have at least one non-empty column
            if (count($rowData) > 0) {

                $data[] = $rowData;
            }
        }

        // Extract rows where the index is a multiple of 17 (i.e., 17th, 34th, 51st, ...)
        $multiplesOf17 = [];
        foreach ($data as $index => $row) {
            if (($index + 1) % 16 == 0) {  // +1 because array index starts from 0
                $multiplesOf17[] = $row;
            }
        }
        
        $arr_data = [];
        foreach ($multiplesOf17 as $key=> $value){
           foreach ($value as $key => $value2){
               if($key == 1)
               {
                  array_push($arr_data,$value2);
               }
               
           }
        }

		$SK01 = [];
		foreach ($data as $index => $row) {
                $SK01[] = $row;
        }
        
		$arr_tophead = [
			'ditebang',
			'digiling',
			'protas',
			'tebu',
			'rendemen',
			'hablur',
			'gula',
			'tetes'
		];
		$arr_head = [
			"SK01",
			"SK02",
			"SK03",
			"SK04",
			"SK05",
			"SK06",
			"SK07",
			"SK08",
			"SK09",
			"SK10",
			"SK11",
			"SK12",
			"SK13",
			"SK14",
			"SK15",
			"JMLTSKSO",	
		];

		$arr_joinheadtop = [];
		for ($i = 0; $i < count($arr_tophead); $i++) {
			for ($j = 0; $j < count($arr_head); $j++) {
					$arr_joinheadtop1 = $arr_tophead[$i] . '_' . $arr_head[$j];
					array_push($arr_joinheadtop, $arr_joinheadtop1);
			}
		}

        $arr_data_raw = [];
        foreach ($SK01 as $key=> $value){
			array_push($arr_data_raw,$value[1]);
        }
		
		$data_raw_with_keys = [];
		foreach ($arr_data_raw as $key => $value) {
			if (isset($arr_joinheadtop[$key])) {
				$data_raw_with_keys[$arr_joinheadtop[$key]] = floatval(str_replace(',', '', $value));
			}
		}

		$arr_jawa = [
			'SK06',
			'SK07',
			'SK08',
			'SK09',
			'SK10',
			'SK11',
			'SK12',
		];

		$arr_non_jawa = [
			'SK01',
			'SK02',
			'SK03',
			'SK04',
			'SK05',
			'SK13',
			'SK14',
			'SK15'
		];

		$luas_jawa = $data_raw_with_keys['digiling_SK06'] + $data_raw_with_keys['digiling_SK07'] + $data_raw_with_keys['digiling_SK08'] + $data_raw_with_keys['digiling_SK09'] + $data_raw_with_keys['digiling_SK10'] + $data_raw_with_keys['digiling_SK11'] + $data_raw_with_keys['digiling_SK12'];
		$luas_non_jawa = $data_raw_with_keys['digiling_SK01'] + $data_raw_with_keys['digiling_SK02'] + $data_raw_with_keys['digiling_SK03'] + $data_raw_with_keys['digiling_SK04'] + $data_raw_with_keys['digiling_SK05'] + $data_raw_with_keys['digiling_SK13'] + $data_raw_with_keys['digiling_SK14'] + $data_raw_with_keys['digiling_SK15'];

		$tebu_jawa = $data_raw_with_keys['tebu_SK06'] + $data_raw_with_keys['tebu_SK07'] + $data_raw_with_keys['tebu_SK08'] + $data_raw_with_keys['tebu_SK09'] + $data_raw_with_keys['tebu_SK10'] + $data_raw_with_keys['tebu_SK11'] + $data_raw_with_keys['tebu_SK12'];
		$tebu_non_jawa = $data_raw_with_keys['tebu_SK01'] + $data_raw_with_keys['tebu_SK02'] + $data_raw_with_keys['tebu_SK03'] + $data_raw_with_keys['tebu_SK04'] + $data_raw_with_keys['tebu_SK05'] + $data_raw_with_keys['tebu_SK13'] + $data_raw_with_keys['tebu_SK14'] + $data_raw_with_keys['tebu_SK15'];

		$gula_jawa = $data_raw_with_keys['gula_SK06'] + $data_raw_with_keys['gula_SK07'] + $data_raw_with_keys['gula_SK08'] + $data_raw_with_keys['gula_SK09'] + $data_raw_with_keys['gula_SK10'] + $data_raw_with_keys['gula_SK11'] + $data_raw_with_keys['gula_SK12'];
		$gula_non_jawa = $data_raw_with_keys['gula_SK01'] + $data_raw_with_keys['gula_SK02'] + $data_raw_with_keys['gula_SK03'] + $data_raw_with_keys['gula_SK04'] + $data_raw_with_keys['gula_SK05'] + $data_raw_with_keys['gula_SK13'] + $data_raw_with_keys['gula_SK14'] + $data_raw_with_keys['gula_SK15'];

		$tetes_jawa = $data_raw_with_keys['tetes_SK06'] + $data_raw_with_keys['tetes_SK07'] + $data_raw_with_keys['tetes_SK08'] + $data_raw_with_keys['tetes_SK09'] + $data_raw_with_keys['tetes_SK10'] + $data_raw_with_keys['tetes_SK11'] + $data_raw_with_keys['tetes_SK12'];
		$tetes_non_jawa = $data_raw_with_keys['tetes_SK01'] + $data_raw_with_keys['tetes_SK02'] + $data_raw_with_keys['tetes_SK03'] + $data_raw_with_keys['tetes_SK04'] + $data_raw_with_keys['tetes_SK05'] + $data_raw_with_keys['tetes_SK13'] + $data_raw_with_keys['tetes_SK14'] + $data_raw_with_keys['tetes_SK15'];

		$ditebang_jawa_sum = $data_raw_with_keys['digiling_SK06'] + $data_raw_with_keys['digiling_SK07'] + $data_raw_with_keys['digiling_SK08'] + $data_raw_with_keys['digiling_SK09'] + $data_raw_with_keys['digiling_SK10'] + $data_raw_with_keys['digiling_SK11'] + $data_raw_with_keys['digiling_SK12'];
		$protas_jawa = $ditebang_jawa_sum != 0 ? ($data_raw_with_keys['tebu_SK06'] + $data_raw_with_keys['tebu_SK07'] + $data_raw_with_keys['tebu_SK08'] + $data_raw_with_keys['tebu_SK09'] + $data_raw_with_keys['tebu_SK10'] + $data_raw_with_keys['tebu_SK11'] + $data_raw_with_keys['tebu_SK12']) / $ditebang_jawa_sum : 0;	 
		$ditebang_non_jawa_sum = $data_raw_with_keys['digiling_SK01'] + $data_raw_with_keys['digiling_SK02'] + $data_raw_with_keys['digiling_SK03'] + $data_raw_with_keys['digiling_SK04'] + $data_raw_with_keys['digiling_SK05'] + $data_raw_with_keys['digiling_SK13'] + $data_raw_with_keys['digiling_SK14'] + $data_raw_with_keys['digiling_SK15'];
		$protas_non_jawa = $ditebang_non_jawa_sum != 0 ? ($data_raw_with_keys['tebu_SK01'] + $data_raw_with_keys['tebu_SK02'] + $data_raw_with_keys['tebu_SK03'] + $data_raw_with_keys['tebu_SK04'] + $data_raw_with_keys['tebu_SK05'] + $data_raw_with_keys['tebu_SK13'] + $data_raw_with_keys['tebu_SK14'] + $data_raw_with_keys['tebu_SK15']) / $ditebang_non_jawa_sum : 0;

		$tebu_jawa_sum = $data_raw_with_keys['tebu_SK06'] + $data_raw_with_keys['tebu_SK07'] + $data_raw_with_keys['tebu_SK08'] + $data_raw_with_keys['tebu_SK09'] + $data_raw_with_keys['tebu_SK10'] + $data_raw_with_keys['tebu_SK11'] + $data_raw_with_keys['tebu_SK12'];
		$rendemen_jawa = $tebu_jawa_sum != 0 ? (($data_raw_with_keys['hablur_SK06'] + $data_raw_with_keys['hablur_SK07'] + $data_raw_with_keys['hablur_SK08'] + $data_raw_with_keys['hablur_SK09'] + $data_raw_with_keys['hablur_SK10'] + $data_raw_with_keys['hablur_SK11'] + $data_raw_with_keys['hablur_SK12']) / $tebu_jawa_sum) * 100 : 0;
		$tebu_non_jawa_sum = $data_raw_with_keys['tebu_SK01'] + $data_raw_with_keys['tebu_SK02'] + $data_raw_with_keys['tebu_SK03'] + $data_raw_with_keys['tebu_SK04'] + $data_raw_with_keys['tebu_SK05'] + $data_raw_with_keys['tebu_SK13'] + $data_raw_with_keys['tebu_SK14'] + $data_raw_with_keys['tebu_SK15'];
		$rendemen_non_jawa = $tebu_non_jawa_sum != 0 ? (($data_raw_with_keys['hablur_SK01'] + $data_raw_with_keys['hablur_SK02'] + $data_raw_with_keys['hablur_SK03'] + $data_raw_with_keys['hablur_SK04'] + $data_raw_with_keys['hablur_SK05'] + $data_raw_with_keys['hablur_SK13'] + $data_raw_with_keys['hablur_SK14'] + $data_raw_with_keys['hablur_SK15']) / $tebu_non_jawa_sum) * 100 : 0;

		$hablur_jawa =  $data_raw_with_keys['hablur_SK06'] + $data_raw_with_keys['hablur_SK07'] + $data_raw_with_keys['hablur_SK08'] + $data_raw_with_keys['hablur_SK09'] + $data_raw_with_keys['hablur_SK10'] + $data_raw_with_keys['hablur_SK11'] + $data_raw_with_keys['hablur_SK12'];
		$hablur_non_jawa =  $data_raw_with_keys['hablur_SK01'] + $data_raw_with_keys['hablur_SK02'] + $data_raw_with_keys['hablur_SK03'] + $data_raw_with_keys['hablur_SK04'] + $data_raw_with_keys['hablur_SK05'] + $data_raw_with_keys['hablur_SK13'] + $data_raw_with_keys['hablur_SK14'] + $data_raw_with_keys['hablur_SK15'];


		// $rkap = DB::table('master_rkap2025_rekap')
		// 	->selectRaw('
		// 		ROUND(SUM(luas_ha), 2) AS luas_ha,

		// 		ROUND(SUM(tebu_ton) / SUM(luas_ha), 2) AS protas,
		// 						ROUND(SUM(tebu_ton), 2) AS tebu_ton,
		// 		ROUND(SUM(hablur) / SUM(tebu_ton) * 100, 2) AS rendemen,
		// 		ROUND(SUM(hablur),2) AS hablur,
		// 		ROUND(SUM(gula_milik), 2) AS gula_milik,
		// 		ROUND(SUM(tetes_milik), 2) AS tetes_milik
		// 	')
		// 	->when($request->input('kebun') != null, function ($query) use ($request) {
		// 		return $query->where('kode_kebun', $request->input('kebun'));
		// 	})
		// 	->when($request->input('cluster') != null, function ($query) use ($request) {
		// 		return $query->where('cluster', $request->input('cluster'));
		// 	})
		// 	->first();

			$rkap = DB::select('CALL rkap_hgsama_lhp_new(?, ?, ?,?)', [$tgl, $request->input('regional'), $request->input('cluster'), $request->input('kebun')]);

			if($request->input('kebun') != null){
				$dataarr = [];
					$rendemendata = $data_raw_with_keys['tebu_'.$request->input('kebun')] != 0 ? $data_raw_with_keys['hablur_'.$request->input('kebun')] / $data_raw_with_keys['tebu_'.$request->input('kebun')] * 100 : 0;
					array_push($dataarr, (String)number_format($data_raw_with_keys['digiling_'.$request->input('kebun')], 2));
					array_push($dataarr, (String)number_format($data_raw_with_keys['digiling_'.$request->input('kebun')], 2));
					array_push($dataarr, (String)number_format($data_raw_with_keys['protas_'.$request->input('kebun')], 2));
					array_push($dataarr, (String)number_format($data_raw_with_keys['tebu_'.$request->input('kebun')], 2));
					array_push($dataarr, (String)number_format($rendemendata, 2));
			}else if($request->input('cluster') != null && $request->input('regional') == null && $request->input('kebun') == null && $request->input('kebun') == ''){
				$dataarr = [];
				$cluster = $request->input('cluster');

				// Ambil mapping cluster dari master_kebun dengan key regional_sgn2 dan value kode_kebun
				$clusterMap = DB::table('master_kebun')
					->select('regional_sgn2', 'kode_kebun')
					->whereNotNull('regional_sgn2')
					->whereNotNull('kode_kebun')
					->get()
					->groupBy('regional_sgn2')
					->map(function ($items) {
						return $items->pluck('kode_kebun')->filter()->values()->all();
					})
					->toArray();

				if (isset($clusterMap[$cluster])) {
					$kebunCodes = $clusterMap[$cluster];
					
					// Sum values for each metric across all kebun codes in the cluster
					$digiling_sum = 0;
					$tebu_sum = 0;
					$hablur_sum = 0;
					
					foreach ($kebunCodes as $kodeKebun) {
						$digiling_sum += $data_raw_with_keys['digiling_' . $kodeKebun] ?? 0;
						$tebu_sum += $data_raw_with_keys['tebu_' . $kodeKebun] ?? 0;
						$hablur_sum += $data_raw_with_keys['hablur_' . $kodeKebun] ?? 0;
					}
					
					$protas = $digiling_sum != 0 ? $tebu_sum / $digiling_sum : 0;
					$rendemen = $tebu_sum != 0 ? ($hablur_sum / $tebu_sum) * 100 : 0;
					
					array_push($dataarr, (String)number_format($digiling_sum, 2));
					array_push($dataarr, (String)number_format($digiling_sum, 2));
					array_push($dataarr, (String)number_format($protas, 2));
					array_push($dataarr, (String)number_format($tebu_sum, 2));
					array_push($dataarr, (String)number_format($rendemen, 2));
				}
			}else if($request->input('regional') != null && $request->input('cluster') == null  && $request->input('kebun') == null && $request->input('kebun') == ''){
				$dataarr = [];
				$regional = $request->input('regional');

				// Ambil mapping regional dari master_kebun dengan key regional_sgn2 dan value kode_kebun
				$regionalMap = DB::table('master_kebun')
					->select('regional_sgn', 'kode_kebun')
					->whereNotNull('regional_sgn')
					->whereNotNull('kode_kebun')
					->get()
					->groupBy('regional_sgn')
					->map(function ($items) {
						return $items->pluck('kode_kebun')->filter()->values()->all();
					})
					->toArray();

				if (isset($regionalMap[$regional])) {
					$kebunCodes = $regionalMap[$regional];
					
					// Sum values for each metric across all kebun codes in the regional
					$digiling_sum = 0;
					$tebu_sum = 0;
					$hablur_sum = 0;
					
					foreach ($kebunCodes as $kodeKebun) {
						$digiling_sum += $data_raw_with_keys['digiling_' . $kodeKebun] ?? 0;
						$tebu_sum += $data_raw_with_keys['tebu_' . $kodeKebun] ?? 0;
						$hablur_sum += $data_raw_with_keys['hablur_' . $kodeKebun] ?? 0;
					}
					
					$protas = $digiling_sum != 0 ? $tebu_sum / $digiling_sum : 0;
					$rendemen = $tebu_sum != 0 ? ($hablur_sum / $tebu_sum) * 100 : 0;
					
					array_push($dataarr, (String)number_format($digiling_sum, 2));
					array_push($dataarr, (String)number_format($digiling_sum, 2));
					array_push($dataarr, (String)number_format($protas, 2));
					array_push($dataarr, (String)number_format($tebu_sum, 2));
					array_push($dataarr, (String)number_format($rendemen, 2));
				}
			}else{
				$dataarr = $arr_data; 
			}

		// Return the rows that are multiples of 17 as JSON
        return response()->json(array('status' => 'success', 'data' => $dataarr, 'luas_jawa' => $luas_jawa, 'luas_non_jawa' => $luas_non_jawa, 'tebu_jawa' => $tebu_jawa, 'tebu_non_jawa' => $tebu_non_jawa, 'gula_jawa' => $gula_jawa, 'gula_non_jawa' => $gula_non_jawa, 'tetes_jawa' => $tetes_jawa, 'tetes_non_jawa' => $tetes_non_jawa, 'protas_jawa' => $protas_jawa, 'protas_non_jawa' => $protas_non_jawa, 'rendemen_jawa' => $rendemen_jawa, 'rendemen_non_jawa' => $rendemen_non_jawa, 'hablur_jawa' => $hablur_jawa, 'hablur_non_jawa' => $hablur_non_jawa,'rkap' => $rkap, 'raw' => $data_raw_with_keys));
    } else {
        return response()->json(array('status' => 'error', 'message' => 'Third table not found'));
    }
}

public function tarikdataconsolelkpsimpan(Request $request)
{
	
    if (!\Auth::check()) {
        return response()->json(array('status' => 'error', 'message' => 'You are not logged in'));
    }

    $url2 = "https://sigula.sinergigula.com/index.php/consolelhpmkso/getdata";
    
	$tgl = $request->input('tgl');
    $regional = '';    

	$postData = [
	                "tgl" => $tgl,
                    "regional" => $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",
    ];

    $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)) {
        return response()->json(array('status' => 'error', 'message' => 'Curl error: ' . curl_error($ch2)));
    }
    curl_close($ch2);

    // Initialize DOMDocument to parse the HTML
    $dom = new \DOMDocument();
    @$dom->loadHTML($response2);  // Suppress warnings for malformed HTML
    
    // Use DOMXPath to query the document
    $xpath = new \DOMXPath($dom);
    
    // Get the third table element
    $tables = $xpath->query('//table');
	$jmltable = $tables->length - 1;
	// Check if the third table exists
	// This will select all tables
    if ($tables->length >= $jmltable) {
        $table = $tables->item($jmltable); // The third table (index starts from 0)
        $rows = $table->getElementsByTagName('tr'); // Get all rows
        $data = [];
        
        // Loop through each row
        foreach ($rows as $row) {
            $cols = $row->getElementsByTagName('td'); // Get all columns for each row
            $rowData = [];
            foreach ($cols as $col) {
                $columnValue = trim($col->nodeValue);  // Get the text content of each column, trimming whitespace
                
                // Only add non-empty values
                if (!empty($columnValue)) {
                  
                        $rowData[] = $columnValue; // Add the value if it's not empty
 
                }
            }
 
            // Only add rows that have at least one non-empty column
            if (count($rowData) > 0) {

                $data[] = $rowData;
            }


        }

        // Extract rows where the index is a multiple of 17 (i.e., 17th, 34th, 51st, ...)
        $multiplesOf17 = [];
        foreach ($data as $index => $row) {
            if (($index + 1) % 16 == 0) {  // +1 because array index starts from 0
                $multiplesOf17[] = $row;
            }
        }
        
        $arr_data = [];
        foreach ($multiplesOf17 as $key=> $value){
           foreach ($value as $key => $value2){
               if($key == 1)
               {
                  array_push($arr_data,$value2);
               }
               
           }
        }

		$SK01 = [];
		foreach ($data as $index => $row) {
                $SK01[] = $row;
        }
        
		$arr_tophead = [
			'ditebang',
			'digiling',
			'protas',
			'tebu',
			'rendemen',
			'hablur',
			'gula',
			'tetes'
		];
		$arr_head = [
			"SK01",
			"SK02",
			"SK03",
			"SK04",
			"SK05",
			"SK06",
			"SK07",
			"SK08",
			"SK09",
			"SK10",
			"SK11",
			"SK12",
			"SK13",
			"SK14",
			"SK15",
			"JMLTSKSO",	
		];

		$arr_joinheadtop = [];
		for ($i = 0; $i < count($arr_tophead); $i++) {
			for ($j = 0; $j < count($arr_head); $j++) {
					$arr_joinheadtop1 = $arr_tophead[$i] . '_' . $arr_head[$j];
					array_push($arr_joinheadtop, $arr_joinheadtop1);
			}
		}

        $arr_data_raw_hi = [];
		$arr_data_raw_sd = [];
        foreach ($SK01 as $key=> $value){
			array_push($arr_data_raw_hi,$value[0]);
			array_push($arr_data_raw_sd,$value[1]);
        }
		
		$data_raw_with_keys_hi = [];
		foreach ($arr_data_raw_hi as $key => $value) {
			if (isset($arr_joinheadtop[$key])) {
				$data_raw_with_keys_hi[$arr_joinheadtop[$key]] = floatval(str_replace(',', '', $value));
			}
		}

		$data_raw_with_keys_sd = [];
		foreach ($arr_data_raw_sd as $key => $value) {
			if (isset($arr_joinheadtop[$key])) {
				$data_raw_with_keys_sd[$arr_joinheadtop[$key]] = floatval(str_replace(',', '', $value));
			}
		}
		$arr_tophead_list = ['ditebang', 'digiling', 'protas', 'tebu', 'rendemen', 'hablur', 'gula', 'tetes'];

		foreach ($arr_tophead_list as $metric) {
			$insertData = [
				'data_type' => 'data_hi',
				'metric_name' => $metric,
				'tgl_data' => $tgl,
				'sk01' => $data_raw_with_keys_hi[$metric . '_SK01'] ?? 0,
				'sk02' => $data_raw_with_keys_hi[$metric . '_SK02'] ?? 0,
				'sk03' => $data_raw_with_keys_hi[$metric . '_SK03'] ?? 0,
				'sk04' => $data_raw_with_keys_hi[$metric . '_SK04'] ?? 0,
				'sk05' => $data_raw_with_keys_hi[$metric . '_SK05'] ?? 0,
				'sk06' => $data_raw_with_keys_hi[$metric . '_SK06'] ?? 0,
				'sk07' => $data_raw_with_keys_hi[$metric . '_SK07'] ?? 0,
				'sk08' => $data_raw_with_keys_hi[$metric . '_SK08'] ?? 0,
				'sk09' => $data_raw_with_keys_hi[$metric . '_SK09'] ?? 0,
				'sk10' => $data_raw_with_keys_hi[$metric . '_SK10'] ?? 0,
				'sk11' => $data_raw_with_keys_hi[$metric . '_SK11'] ?? 0,
				'sk12' => $data_raw_with_keys_hi[$metric . '_SK12'] ?? 0,
				'sk13' => $data_raw_with_keys_hi[$metric . '_SK13'] ?? 0,
				'sk14' => $data_raw_with_keys_hi[$metric . '_SK14'] ?? 0,
				'sk15' => $data_raw_with_keys_hi[$metric . '_SK15'] ?? 0,
				'jmltskso' => $data_raw_with_keys_hi[$metric . '_JMLTSKSO'] ?? 0,
			];
			DB::table('tx_console_prodis')->updateOrInsert(
				['data_type' => 'data_hi', 'metric_name' => $metric, 'tgl_data' => $tgl],
				$insertData
			);

			$insertData['data_type'] = 'data_sd';
			$insertData['sk01'] = $data_raw_with_keys_sd[$metric . '_SK01'] ?? 0;
			$insertData['sk02'] = $data_raw_with_keys_sd[$metric . '_SK02'] ?? 0;
			$insertData['sk03'] = $data_raw_with_keys_sd[$metric . '_SK03'] ?? 0;
			$insertData['sk04'] = $data_raw_with_keys_sd[$metric . '_SK04'] ?? 0;
			$insertData['sk05'] = $data_raw_with_keys_sd[$metric . '_SK05'] ?? 0;
			$insertData['sk06'] = $data_raw_with_keys_sd[$metric . '_SK06'] ?? 0;
			$insertData['sk07'] = $data_raw_with_keys_sd[$metric . '_SK07'] ?? 0;
			$insertData['sk08'] = $data_raw_with_keys_sd[$metric . '_SK08'] ?? 0;
			$insertData['sk09'] = $data_raw_with_keys_sd[$metric . '_SK09'] ?? 0;
			$insertData['sk10'] = $data_raw_with_keys_sd[$metric . '_SK10'] ?? 0;
			$insertData['sk11'] = $data_raw_with_keys_sd[$metric . '_SK11'] ?? 0;
			$insertData['sk12'] = $data_raw_with_keys_sd[$metric . '_SK12'] ?? 0;
			$insertData['sk13'] = $data_raw_with_keys_sd[$metric . '_SK13'] ?? 0;
			$insertData['sk14'] = $data_raw_with_keys_sd[$metric . '_SK14'] ?? 0;
			$insertData['sk15'] = $data_raw_with_keys_sd[$metric . '_SK15'] ?? 0;
			$insertData['jmltskso'] = $data_raw_with_keys_sd[$metric . '_JMLTSKSO'] ?? 0;
			DB::table('tx_console_prodis')->updateOrInsert(
				['data_type' => 'data_sd', 'metric_name' => $metric, 'tgl_data' => $tgl],
				$insertData
			);
		}
		// Return the rows that are multiples of 17 as JSON
        return response()->json(array('status' => 'success','message' => 'Data berhasil disimpan', 'data_hi' => $data_raw_with_keys_hi, 'data_sd' => $data_raw_with_keys_sd));
    } else {
        return response()->json(array('status' => 'error', 'message' => 'Data tidak ditemukan'));
    }
}

public function tarikdataconsolelkppgsimpan(Request $request)
{
	
    if (!\Auth::check()) {
        return response()->json(array('status' => 'error', 'message' => 'You are not logged in'));
    }

    $url2 = "https://sigula.sinergigula.com/index.php/consolelhpmkso/getdata";
    
	$tgl = $request->input('tgl');
    $regional = '';    

	$postData = [
	                "tgl" => $tgl,
                    "regional" => $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",
    ];

    $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)) {
        return response()->json(array('status' => 'error', 'message' => 'Curl error: ' . curl_error($ch2)));
    }
    curl_close($ch2);

    // Initialize DOMDocument to parse the HTML
    $dom = new \DOMDocument();
    @$dom->loadHTML($response2);  // Suppress warnings for malformed HTML
    
    // Use DOMXPath to query the document
    $xpath = new \DOMXPath($dom);
    
    // Get the third table element
    $tables = $xpath->query('//table');
	$jmltable = $tables->length - 1;
	// Check if the third table exists
	// This will select all tables

	$dataall = [];
	for ($g = 2; $g <= $tables->length-2; $g++) {		
        $table = $tables->item($g); // The third table (index starts from 0)
        $rows = $table->getElementsByTagName('tr'); // Get all rows
        $data = [];

		//var_dump($table->nodeValue);


        
        // Loop through each row
        foreach ($rows as $row) {
            $cols = $row->getElementsByTagName('td'); // Get all columns for each row
            $rowData = [];
            foreach ($cols as $col) {
                $columnValue = trim($col->nodeValue);  // Get the text content of each column, trimming whitespace
                
                // Only add non-empty values
                if (!empty($columnValue)) {
                  
                        $rowData[] = $columnValue; // Add the value if it's not empty
 
                }
            }
            // Only add rows that have at least one non-empty column
            if (count($rowData) > 0) {

                $data[] = $rowData;
            }
			




        }



        // Extract rows where the index is a multiple of 17 (i.e., 17th, 34th, 51st, ...)
        $multiplesOf17 = [];
        foreach ($data as $index => $row) {
            if (($index + 1) % 16 == 0) {  // +1 because array index starts from 0
                $multiplesOf17[] = $row;
            }
        }

				// print_r(json_encode($data));

        
        $arr_data = [];
        foreach ($multiplesOf17 as $key=> $value){
           foreach ($value as $key => $value2){
               if($key == 1)
               {
                  array_push($arr_data,$value2);
               }
               
           }
        }

		$SK01 = [];
		foreach ($data as $index => $row) {
                $SK01[] = $row;
        }

		//print_r(json_encode($SK01));
        
		$arr_tophead = [
			'ditebang',
			'digiling',
			'protas',
			'tebu',
			'rendemen',
			'hablur',
			'gula',
			'tetes'
		];
		$arr_head = [
			"SK01",
			"SK02",
			"SK03",
			"SK04",
			"SK05",
			"SK06",
			"SK07",
			"SK08",
			"SK09",
			"SK10",
			"SK11",
			"SK12",
			"SK13",
			"SK14",
			"SK15",
			"JMLTSKSO",	
		];

		$arr_joinheadtop = [];
		for ($i = 0; $i < count($arr_tophead); $i++) {
			for ($j = 0; $j < count($arr_head); $j++) {
					$arr_joinheadtop1 = $arr_tophead[$i] . '_' . $arr_head[$j];
					array_push($arr_joinheadtop, $arr_joinheadtop1);				
			}
		}




        $arr_data_raw_hi = [];
		$arr_data_raw_sd = [];
		foreach ($SK01 as $key=> $value){
			// ensure offsets exist to avoid undefined offset notices
			if (isset($value[0]) && isset($value[1]) && $value[0] !== ' ' && $value[1] !== ' '){
				array_push($arr_data_raw_hi,$value[0]);
				array_push($arr_data_raw_sd,$value[1]);
			}
		}
						// print_r(json_encode($arr_data_raw_hi));
		
		$data_raw_with_keys_hi = [];
		foreach ($arr_data_raw_hi as $key => $value) {
			if (isset($arr_joinheadtop[$key])) {
					$data_raw_with_keys_hi[$arr_joinheadtop[$key]] = floatval(str_replace(',', '', $value));
								
			}
		}



		$data_raw_with_keys_sd = [];
		foreach ($arr_data_raw_sd as $key => $value) {
			if (isset($arr_joinheadtop[$key])) {
				$data_raw_with_keys_sd[$arr_joinheadtop[$key]] = floatval(str_replace(',', '', $value));
			}
		}
		$arr_tophead_list = ['ditebang', 'digiling', 'protas', 'tebu', 'rendemen', 'hablur', 'gula', 'tetes'];

		foreach ($arr_tophead_list as $metric) {
			$insertData = [
				'data_type' => 'data_hi',
				'metric_name' => $metric,
				'pg' => trim(preg_replace('/[^a-zA-Z\s]/', '', $rows[0]->nodeValue)),
				'tgl_data' => $tgl,
				'sk01' => $data_raw_with_keys_hi[$metric . '_SK01'] ?? 0,
				'sk02' => $data_raw_with_keys_hi[$metric . '_SK02'] ?? 0,
				'sk03' => $data_raw_with_keys_hi[$metric . '_SK03'] ?? 0,
				'sk04' => $data_raw_with_keys_hi[$metric . '_SK04'] ?? 0,
				'sk05' => $data_raw_with_keys_hi[$metric . '_SK05'] ?? 0,
				'sk06' => $data_raw_with_keys_hi[$metric . '_SK06'] ?? 0,
				'sk07' => $data_raw_with_keys_hi[$metric . '_SK07'] ?? 0,
				'sk08' => $data_raw_with_keys_hi[$metric . '_SK08'] ?? 0,
				'sk09' => $data_raw_with_keys_hi[$metric . '_SK09'] ?? 0,
				'sk10' => $data_raw_with_keys_hi[$metric . '_SK10'] ?? 0,
				'sk11' => $data_raw_with_keys_hi[$metric . '_SK11'] ?? 0,
				'sk12' => $data_raw_with_keys_hi[$metric . '_SK12'] ?? 0,
				'sk13' => $data_raw_with_keys_hi[$metric . '_SK13'] ?? 0,
				'sk14' => $data_raw_with_keys_hi[$metric . '_SK14'] ?? 0,
				'sk15' => $data_raw_with_keys_hi[$metric . '_SK15'] ?? 0,
				'jmltskso' => $data_raw_with_keys_hi[$metric . '_JMLTSKSO'] ?? 0,
			];
			if(trim(preg_replace('/[^a-zA-Z\s]/', '', $rows[0]->nodeValue)) != 'PG SEI SEMAYANG11'){
				DB::table('tx_console_prodis_pg')->updateOrInsert(
					['data_type' => 'data_hi', 'metric_name' => $metric, 'tgl_data' => $tgl, 'pg' => trim(preg_replace('/[^a-zA-Z\s]/', '', $rows[0]->nodeValue))],
					$insertData
				);
			}

			$insertData['data_type'] = 'data_sd';
			$insertData['pg'] = trim(preg_replace('/[^a-zA-Z\s]/', '', $rows[0]->nodeValue));
			$insertData['sk01'] = $data_raw_with_keys_sd[$metric . '_SK01'] ?? 0;
			$insertData['sk02'] = $data_raw_with_keys_sd[$metric . '_SK02'] ?? 0;
			$insertData['sk03'] = $data_raw_with_keys_sd[$metric . '_SK03'] ?? 0;
			$insertData['sk04'] = $data_raw_with_keys_sd[$metric . '_SK04'] ?? 0;
			$insertData['sk05'] = $data_raw_with_keys_sd[$metric . '_SK05'] ?? 0;
			$insertData['sk06'] = $data_raw_with_keys_sd[$metric . '_SK06'] ?? 0;
			$insertData['sk07'] = $data_raw_with_keys_sd[$metric . '_SK07'] ?? 0;
			$insertData['sk08'] = $data_raw_with_keys_sd[$metric . '_SK08'] ?? 0;
			$insertData['sk09'] = $data_raw_with_keys_sd[$metric . '_SK09'] ?? 0;
			$insertData['sk10'] = $data_raw_with_keys_sd[$metric . '_SK10'] ?? 0;
			$insertData['sk11'] = $data_raw_with_keys_sd[$metric . '_SK11'] ?? 0;
			$insertData['sk12'] = $data_raw_with_keys_sd[$metric . '_SK12'] ?? 0;
			$insertData['sk13'] = $data_raw_with_keys_sd[$metric . '_SK13'] ?? 0;
			$insertData['sk14'] = $data_raw_with_keys_sd[$metric . '_SK14'] ?? 0;
			$insertData['sk15'] = $data_raw_with_keys_sd[$metric . '_SK15'] ?? 0;
			$insertData['jmltskso'] = $data_raw_with_keys_sd[$metric . '_JMLTSKSO'] ?? 0;

			if(trim(preg_replace('/[^a-zA-Z\s]/', '', $rows[0]->nodeValue)) != 'PG SEI SEMAYANG11'){
				DB::table('tx_console_prodis_pg')->updateOrInsert(
					['data_type' => 'data_sd', 'metric_name' => $metric, 'tgl_data' => $tgl, 'pg' => trim(preg_replace('/[^a-zA-Z\s]/', '', $rows[0]->nodeValue))],
					$insertData
				);
			}
		}
		

	}



	
		// Return the rows that are multiples of 17 as JSON
        return response()->json(array('status' => 'success','message' => 'Data berhasil disimpan', 'data_hi' => $data_raw_with_keys_hi, 'data_sd' => $data_raw_with_keys_sd));
	
}
	
	
	
	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 getDates(Request $request)
	{
		$kd_plant = $request->input('pabrik_gula');
		$dates = \DB::table('data_unit')
					->select('awal_giling', 'akhir_giling')
					->where('plant_code', $kd_plant)
					->first();

		if ($dates) {
			return response()->json(array('status' => 'success', 'data' => $dates));
		} else {
			return response()->json(array('status' => 'error', 'message' => 'No dates found'));
		}
	}

	function getcookielogin(){
		// URL tujuan
		config(['app.debug' => true]);
	$url = "https://sigula.sinergigula.com/index.php/user/postlogin";
	
	$sess = \Session::get('tahuntanam');
	$tahunn = '2025';
	if($sess == '2425'){
		$tahunn = '2025';
	}else if($sess == '2526'){
		$tahunn = '2026';
	}
	// Data POST
	$postData = [
		"username" => "rizki.r",
		"password" => "rizki.r",
		"tahungiling" => $tahunn
	];
	
	// Inisialisasi cURL
	$ch = curl_init($url);
	
	// Set opsi cURL
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
	curl_setopt($ch, CURLOPT_HEADER, true); // Untuk mendapatkan header
	curl_setopt($ch, CURLOPT_HTTPHEADER, [
		"Host: sigula.sinergigula.com",
		"Cookie: ci_session=a%3A6%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22f275b9aaacfd3807fd4622b61db3955d%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%2227.131.249.208%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A115%3A%22Mozilla%2F5.0%20%28Windows%20NT%2010.0%3B%20Win64%3B%20x64%29%20AppleWebKit%2F537.36%20%28KHTML%2C%20like%20Gecko%29%20Chrome%2F129.0.6668.71%20Safari%2F537.36%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1738732541%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3Bs%3A4%3A%22lang%22%3Bs%3A2%3A%22en%22%3B%7D213f39118e47cb0d3817ada9177d7b41d2b4eff1; PHPSESSID=63pq8d1kks2mil29lb87vequqi",
		"Content-Length: 50",
		"Cache-Control: max-age=0",
		"Sec-Ch-Ua: \"Chromium\";v=\"129\", \"Not=A?Brand\";v=\"8\"",
		"Sec-Ch-Ua-Mobile: ?0",
		"Sec-Ch-Ua-Platform: \"macOS\"",
		"Accept-Language: en-US,en;q=0.9",
		"Origin: https://sigula.sinergigula.com",
		"Content-Type: application/x-www-form-urlencoded",
		"Upgrade-Insecure-Requests: 1",
		"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.6668.71 Safari/537.36",
		"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
		"Sec-Fetch-Site: same-origin",
		"Sec-Fetch-Mode: navigate",
		"Sec-Fetch-User: ?1",
		"Sec-Fetch-Dest: document",
		"Referer: https://sigula.sinergigula.com/index.php/user/login",
		"Accept-Encoding: gzip, deflate, br",
		"Priority: u=0, i"
	]);
	
	// Eksekusi cURL
	$response = curl_exec($ch);
	
	// Ambil informasi header
	$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
	$headers = substr($response, 0, $header_size);
	
	// Ambil Set-Cookie dari header
	preg_match_all('/Set-Cookie: (.*?);/i', $headers, $cookies);
	$setCookies = $cookies[1];
	
	// Tampilkan hasil
	// echo "Set-Cookie Headers:\n";
	return $setCookies[3];
	
	// Tutup cURL
	curl_close($ch);
	}
}