<?php namespace App\Http\Controllers;

use App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\User;
use Config;

$tahun;
$tahun_sebelumnya;
class DashboardController extends Controller {

	public function __construct()
	{
		parent::__construct();
		
        $this->data = array(
            'pageTitle' =>  $this->config['cnf_appname'],
            'pageNote'  =>  'Welcome to Dashboard',
            
        );			
            $this->tahun = date('Y');
            $this->tahun_sebelumnya = $this->tahun - 1;
	}

function show( Request $request , $id ) 
	{
		/* Handle import , export and view */
		$task =$id ;
		switch( $task)
		{
            case 'setdbsession':
                return $this->setdbsession( $request);
                break;
            case 'gettimezonee':
                return $this->gettimezonee( $request);
                break;    
			case 'getLkpPerRayon':
				return $this->getLkpPerRayon( $request);
				break;
            case 'getLkpPerRayonKlentek':
                return $this->getLkpPerRayonKlentek( $request);
                break;    
            case 'grafikmutu':
                return $this->grafikmutu( $request);
                break;    
            case 'protasperrayon':
                return $this->protasperrayon( $request);
                break;    
            case 'getChartDataMutu':
                return $this->getChartDataMutu( $request);
                break;
                case 'getChartDataMutu2':
                return $this->getChartDataMutu2( $request);
                break;
            case 'getLkpPerKebun':
                return $this->getLkpPerKebun( $request);
                break;
            case 'getLkpTebu':
                return $this->getLkpTebu( $request);
                break;
            case 'lkptebu':
                return $this->lkptebu( $request);
                break;
            case 'getLkpPerKebunKlentek':
                return $this->getLkpPerKebunKlentek( $request);
                break    ;
            case 'getLkpPerTotalKlentek':
                return $this->getLkpPerTotalKlentek( $request);
                break;    
            case 'getListLKP':
                return $this->getListLKP( $request);
                break;    
            
            case 'getChartBibit':
                return $this->getChartBibit( $request);
                break;
            
            case 'getChartMutuClusterisasi':
                return $this->getChartMutuClusterisasi( $request);
                break;
            case 'getDataProtasRendemen':
                return $this->getDataProtasRendemen( $request);
                break;    
            case 'getRendVsMutu':
                return $this->getRendVsMutu( $request);
                break;    
            case 'getRendVsMutuPerhari':
                return $this->getRendVsMutuPerhari( $request);    
            case 'getRendVsMutuPerhariKebun':
                return $this->getRendVsMutuPerhariKebun( $request);    

            case 'getRendVsMutuPerhari24vs25':
                return $this->getRendVsMutuPerhari24vs25( $request);  
            case 'getprotasranking':
                return $this->getprotasranking( $request);  
            case 'getprotastoptenasman':
                return $this->getprotastoptenasman($request);    
            case 'getrendemenrangking':
                return $this->getrendemenrangking( $request);
            case 'getmuturangking':
                return $this->getmuturangking( $request);
            case 'getrendemenhariangrafik':
                return $this->getRendemenHarianPgGrafik( $request);
            case 'grafikbiayasdm':
                return $this->grafikbiayasdm( $request);
            case 'gettotkaryawan':
                return $this->gettotkaryawan( $request);
            case 'getrataumurkaryawan':
                return $this->getrataumurkaryawan( $request);   
            case 'getratabiayakaryawan':
                return $this->getratabiayakaryawan( $request);
            case 'getprotasharian':
                return $this->getprotasharian( $request);
            case 'getprotashariankebun':
                return $this->getprotashariankebun( $request); 
            case 'getlabarugi':
                return $this->getlabarugi( $request);   
            case 'getlabarugi2':
                return $this->getlabarugi2( $request);                        
            case 'sisa_tertebang_tebu':
                return $this->sisa_tertebang_tebu( $request);
            case 'sisa_tertebang_tebu_rkap':
                return $this->sisa_tertebang_tebu_rkap( $request);   
            case 'sisa_tertebang_tebu_2024':
                return $this->sisa_tertebang_tebu_2024( $request);     
            case 'getRendVsMutuPerhari24vs25Terbakar':
                return $this->getRendVsMutuPerhari24vs25Terbakar( $request);    
            case 'getRekapMonevPasok':
                return $this->getRekapMonevPasok( $request);
            case 'getRekapMonevPasokRayon':
                return $this->getRekapMonevPasokRayon($request);    
            case 'getPasokHarianKebun':
                return $this->getPasokHarianKebun( $request);
            case 'getPasokHarianRayon':
                return $this->getPasokHarianRayon( $request);
            case 'getprotasrankingasman':
                return $this->getprotasrankingasman( $request);
            case 'getRendVsMutuPerhari24vs25kebun':
                return $this->getRendVsMutuPerhari24vs25Kebun( $request);    
            case 'getRendVsMutuPerhari24vs25Terbakarkebun':
                return $this->getRendVsMutuPerhari24vs25Terbakarkebun( $request);  
            case 'getRendVsMutuPerhari24vs25Terbakartotal':
                return $this->getRendVsMutuPerhari24vs25Terbakartotal( $request);
            case 'getRendVsMutuPerhari24vs25total':
                return $this->getRendVsMutuPerhari24vs25total( $request);
            case 'getChartDataMutuAsman':
                return $this->getChartDataMutuAsman( $request); 
                case 'getChartDataMutuAsman2':
                return $this->getChartDataMutuAsman2( $request);    
            case 'getChartDataProtasAsman':
                return $this->getChartDataProtasAsman( $request);    
            case 'getRekapMorfologiPerKategori':
                return $this->getRekapMorfologiPerKategori( $request);    
            case 'getRekapMorfologiPerKategoriDetail':
                return $this->getRekapMorfologiPerKategoriDetail( $request);    
            case 'getRekapMorfologiPerKategoriDetail2':
                return $this->getRekapMorfologiPerKategoriDetail2( $request);     
            case 'getRekapMorfologiKebun':
                return $this->getRekapMorfologiKebun( $request);
            case 'getRekapMorfologiRayon':  
                return $this->getRekapMorfologiRayon($request);    
            case 'mutuperrayon':
                return $this->mutuperrayon( $request);
            case 'mapdashboard':
                return $this->mapdashboard($request);
            case 'mapdashboard2025':
                return $this->mapdashboard2025($request);
            case 'detailmaps':
                return $this->detailmaps($request);
            case 'detailmaps25':
                return $this->detailmaps25($request);    
            case 'swipeboxgallery':
                return $this->swipeboxgallery($request);
            case 'swipeboxgallery2':
                return $this->swipeboxgallery2($request);
            case 'swipeboxgallery3':
                return $this->swipeboxgallery3($request);    
            case 'getRekapMorfologiPetakDetail':
                return $this->getRekapMorfologiPetakDetail($request);
            case 'getRekapLKPPetakDetail':
                return $this->getRekapLKPPetakDetail($request);
            case 'getRekapDronePetakDetail':
                return $this->getRekapDronePetakDetail($request);
            case 'dataswipebox':
                return $this->dataswipebox($request);    
            case 'getDetailFotoTitle':
                return $this->getDetailFotoTitle($request);
            case 'getTotalprotasKSOmap':
                return $this->getTotalprotasKSOmap($request); 
            case 'getTotallkpKSOmap':
                return $this->getTotallkpKSOmap($request);
            case 'getrankinglkpkebun':
                return $this->getrankinglkpkebun($request);
            case 'getrankinglkprayon':
                return $this->getrankinglkprayon($request);
            case 'getrankinglkpafdeling':
                return $this->getrankinglkpafdeling($request);    
            case 'getrankinglkp2kebun':
                return $this->getrankinglkp2kebun($request);
            case 'getrankinglkp2rayon':
                return $this->getrankinglkp2rayon($request);
            case 'getrankinglkp2afdeling':
                return $this->getrankinglkp2afdeling($request);
            case 'getLkpPerAfd':
                return $this->getLkpPerAfd($request);
            case 'getLkpPerAsman':
                return $this->getLkpPerAsman($request);
            case 'getSasaran2526KebunPopmie':
                return $this->getSasaran2526KebunPopmie($request);
            case 'produksi_2024':
                return $this->produksi_2024($request);
            case 'getLastMorfologiByLahanId':
                return $this->getLastMorfologiByLahanId($request);
            case 'getGrafikTanamBulananKebun':
                return $this->getGrafikTanamBulananKebun($request);
            case 'getGrafikTanamBulananRayon':
                return $this->getGrafikTanamBulananRayon($request);
            case 'getTakmarRekapKebun':
                return $this->getTakmarRekapKebun($request);


            case 'getbiayasdm':
                return $this->getbiayasdm( $request);
            case 'getbiayasdmunit':
                return $this->getbiayasdmunit( $request);
            case 'getgendersdmunit':
                return $this->getgendersdmunit( $request);    
            case 'geteducationsdmunit':
                return $this->geteducationsdmunit( $request);
            case 'getjabatansdmunit':
                return $this->getjabatansdmunit( $request);
            case 'getumursdmunit':
                return $this->getumursdmunit( $request);
            case 'getstatussdmunit':
                return $this->getstatussdmunit( $request);
            case 'getgolongansdmunit':
                return $this->getgolongansdmunit( $request);   
            case 'getGrafikDroneKebunPeriode':
                return $this->getGrafikDroneKebunPeriode( $request);
                break;
            case 'getGrafikDroneRayonPeriode':
                return $this->getGrafikDroneRayonPeriode( $request);
                break;     
            case 'getRankingDroneRayon':
                return $this->getRankingDroneRayon( $request);
                break;

            case 'getGrafikMorfKebunPeriode':
                return $this->getGrafikMorfKebunPeriode( $request);
                break;
            case 'getGrafikMorfRayonPeriode':
                return $this->getGrafikMorfRayonPeriode( $request);
                break;     
            case 'getRankingMorfRayon':
                return $this->getRankingMorfRayon( $request);
                break;    
            case 'getRekapCurahHujanPerRayon':
                return $this->getRekapCurahHujanPerRayon( $request);
                break;
            case 'getRekapCurahHujanTahunanKebun':
                return $this->getRekapCurahHujanTahunanKebun( $request);
                break;
            case 'getChartMutuTakdesPerCluster':
                return $this->getChartMutuTakdesPerCluster( $request);
                break;
            case 'getTakdesDataByCluster':
                return $this->getTakdesDataByCluster( $request);
                break;    
            case 'getFotoDrone':    
                return $this->getFotoDrone( $request);
                break;
            case 'getGrafikKlentekKebun':
                return $this->getGrafikKlentekKebun( $request);
                break;
            case 'getGrafikKlentekRayon':
                return $this->getGrafikKlentekRayon( $request);
                break;
            case 'getGrafikKlentekTotal':
                return $this->getGrafikKlentekTotal( $request);
                break;    
            case 'getRekapDronePetakPeriodeDinamis':
                return $this->getRekapDronePetakPeriodeDinamis( $request);
                break;
            case 'getRekapMorfPetakPeriodeDinamis':
                return $this->getRekapMorfPetakPeriodeDinamis( $request);
                break;    
            case 'getChartDataKesegaranAfd':
                return $this->getChartDataKesegaranAfd( $request);
                break;
            case 'infoluastebuprotas':
                return $this->infoluastebuprotas( $request);
                break;
            case 'getChartDataMutuAfdeling':
                return $this->getChartDataMutuAfdeling( $request);
                break;
            case 'getRekapMejaTebuMutuEvaluasi':
                return $this->getRekapMejaTebuMutuEvaluasi( $request);
                break;
            case 'getRekapMejaTebuMutuEvaluasi2':
                return $this->getRekapMejaTebuMutuEvaluasi2( $request);
                break;    
            case 'getRekapTimbanganProtasEvaluasi':
                return $this->getRekapTimbanganProtasEvaluasi( $request);
                break;    
            case 'getRekapTebuBerbungaDetail':
                return $this->getRekapTebuBerbungaDetail( $request);
                break;
            case 'getRekapTebuBanjirDetail':
                return $this->getRekapTebuBanjirDetail( $request);
                break;
            case 'getRekapTebuRobohDetail':
                return $this->getRekapTebuRobohDetail( $request);
                break;
            case 'mutuperrayonhi':
                return $this->mutuperrayonhi( $request);
                break; 
            case 'progressReport':
                return $this->progressReport( $request);
                break;
            case 'getLoginHistory':
                return $this->getLoginHistory( $request);
                break;
            case 'filterMenu':
                return $this->filterMenu( $request);
                break;    
            case 'managedashboard':
                return $this->managedashboard( $request);
                break;
                
			default:
				return 0;	
				break;		
		}
	}	

    function store( Request $request  )
	{
		$task = $request->input('action_task');
		switch ($task)
		{
			default:
				return $this->postSave( $request );
				break;
			case 'switchuser':
				return $this->switchuser( $request );
				break;
		}	
	
	}


    public function filterMenu( Request $request )
    {
        try {
            // Search query for menu name (used by UI search)
            $q = $request->input('q', null);
            
            $query = DB::table('tb_menu')
                ->select(
                    'menu_id',
                    'parent_id',
                    'module',
                    'url',
                    'menu_name',
                    'menu_type',
                    'role_id',
                    'deep',
                    'ordering',
                    'position',
                    'menu_icons',
                    'active',
                    'access_data',
                    'allow_guest',
                    'menu_lang'
                );
            
            // If search query provided, only filter by menu_name using LIKE
                $query->where('menu_name', 'like', '%' . $q . '%');
              
            // Filter to show only menu items that are not parents of any other menu
            $query->whereNotIn('menu_id', function($subquery) {
                $subquery->select('parent_id')
                    ->from('tb_menu')
                    ->whereNotNull('parent_id');
            });
            
            // Filter by role_id if role_id exists in access_data
                $menus = $query->orderBy('ordering', 'ASC')->get();
                
                $filteredMenus = [];
                foreach ($menus as $menu) {
                    $accessData = json_decode($menu->access_data, true);
                    if (isset($accessData[session('gid')])) {
                        if ($accessData[session('gid')] == 1) {
                            $filteredMenus[] = $menu;
                        }
                    }
                }
                
                return response()->json([
                    'status' => 'success',
                    'data' => $filteredMenus,
                    'count' => count($filteredMenus)
                ]);
            
            
            $menus = $query->orderBy('ordering', 'ASC')->get();
            
            return response()->json([
                'status' => 'success',
                'data' => $menus,
                'count' => count($menus)
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage()
            ], 500);
        }
    }

	public function index( Request $request )
	{

        $thntnm = \Session::get('tahuntanam');
        $tahunprod = "20" . substr($thntnm, 0, 2);


        if($thntnm == null){
            \Auth::logout();
            \Session::flush();
            return redirect('')->with(['message'=>'Your are now logged out!','status'=>'success']);
        }


        $getlevel = DB::table('tb_groups')
            ->select('level')
            ->where('group_id',\Session::get('gid'))
            ->first();

        $data1 = DB::table('q_prod_rekap_timbangan_cluster')
            ->select(
            DB::raw('SUM(ha_tebang) as ha_tebang'),
            DB::raw('SUM(netto_ton) as netto_ton'),
            DB::raw('SUM(netto_ton)/SUM(ha_tebang) as protas'),
            DB::raw('MAX(tgl_akhir) as tgl_akhir')
            )
            ->first();
        // $data2 = DB::table('q_prod_console_dashboard')
        //     ->select('ha_tebang', 'netto_ton', 'protas', 'rend_%', 'hablur_ton', 'gumil_ton', 'tetes_ton','tgl_akhir')
        //     ->first();
        // $data3 = DB::table('q_prod_mutu_dashboard')
        //     ->select('mutu_A', 'mutu_B', 'mutu_C', 'mutu_D', 'mutu_E')
        //     ->first();



    
        // $data6 = DB::table('q_lkp_rekapvssasaran')
        //     ->select('*')
        //     ->get();

if($getlevel->level < 3){
        $data7 = DB::table('master_rayon')
            ->select('*')
            ->get(); 
            
        $data8 = DB::table('master_kebun')
            ->select('*')
            ->get();

        $data9 = DB::table('master_kebun')
            ->select('*')
            ->groupBy('kode_cluster')
            ->get();

        $data10 = DB::table('master_kebun')
            ->select('*')
            ->groupBy('jawa_nonjawa')
            ->get();            
                        
}

else if($getlevel->level == 3){
        $data7 = DB::table('master_rayon')
                ->select('*')->where('kode_kebun',substr(\Session::get('fid'), 0, 4))
                ->get(); 
        $data8 = DB::table('master_kebun')
                ->select('*')->where('kode_kebun',substr(\Session::get('fid'), 0, 4))
                ->get();   
        $data9 = DB::table('master_kebun')
                ->select('*')->where('kode_kebun',substr(\Session::get('fid'), 0, 4))
                ->groupBy('kode_cluster')
                ->get();    
        $data10 = DB::table('master_kebun')
                ->select('*')->where('kode_kebun', substr(\Session::get('fid'), 0, 4))
                ->groupBy('jawa_nonjawa')
                ->get();             
}else if($getlevel->level == 4){
        $data7 = DB::table('master_rayon')
                ->select('*')->where('kode_rayon',substr(\Session::get('fid'), 0, 6))
                ->get(); 
        $data8 = DB::table('master_kebun')
                ->select('*')->where('kode_kebun',substr(\Session::get('fid'), 0, 4))
                ->get();   
        $data9 = DB::table('master_kebun')
                ->select('*')->where('kode_kebun',substr(\Session::get('fid'), 0, 4))
                ->groupBy('kode_cluster')
                ->get();    
        $data10 = DB::table('master_kebun')
                ->select('*')->where('kode_kebun', substr(\Session::get('fid'), 0, 4))
                ->groupBy('jawa_nonjawa')
                ->get();             
}else{
      $data7 = DB::table('master_rayon')
            ->select('*')->where('kode_kebun',substr(\Session::get('fid'), 0, 4))
            ->get(); 
      $data8 = DB::table('master_kebun')
            ->select('*')->where('kode_kebun',substr(\Session::get('fid'), 0, 4))
            ->get();   
      $data9 = DB::table('master_kebun')
            ->select('*')->where('kode_kebun',substr(\Session::get('fid'), 0, 4))
            ->groupBy('kode_cluster')
            ->get();    
      $data10 = DB::table('master_kebun')
            ->select('*')->where('kode_kebun',substr(\Session::get('fid'), 0, 4))
            ->groupBy('jawa_nonjawa')
            ->get();  
                        
}

// Generate the last 14 days as an array of dates
// $last14Days = collect(range(0, 13))->map(function ($day) {
//     return date('Y-m-d', strtotime("-$day days"));
// })->reverse()->values();

// Fetch data from the database
// $data = DB::select('call GetDataProtasRendemen(?,?)', [
//     $last14Days->first(),
//     $last14Days->last()
// ]);

// Map the data into a collection
// $data10 = collect($data)->mapWithKeys(function ($item) {
//     return [date('Y-m-d', strtotime($item->tgl_giling)) => [
//         'tgl_giling' => date_format(date_create($item->tgl_giling), "d M"),
//         'protas' => (float) str_replace(',', '.', $item->protas),
//         'rendemen' => (float) str_replace(',', '.', $item->rendemen),
//     ]];
// });

// Fill missing dates with empty data
// $data10 = $last14Days->map(function ($date) use ($data10) {
//     return $data10->get($date, [
//         'tgl_giling' => date_format(date_create($date), "d M"),
//         'protas' => null,
//         'rendemen' => null,
//     ]);
// });

        // Kirim data ke view
        
 $today = date('Y-m-d');
        $day = (int)date('j', strtotime($today));
        $month = (int)date('n', strtotime($today));
        $periode = '';

        if ($day >= 1 && $day <= 15) {
            $periode = $month . 'A-'.date('Y', strtotime($today));
        } else {
            $periode = $month . 'B-'.date('Y', strtotime($today));
        }
        



if($getlevel->level<3){
		// Memanggil stored procedure
        $data5 = DB::table('q_lkp_rekap_dashboard')
                ->select('pekerjaan', 'hektar')
                ->get();
        $data5 = $data5->map(function($item) {
        // Replace commas with dots and convert hektar to float
        $item->hektar = (float) str_replace(',', '.', $item->hektar);
        return $item;

        // Menentukan periode berdasarkan tanggal hari ini
       
            // Ambil data sasaran LKP dari stored procedure        
    });

        $data_sasaran_lkp = collect(DB::select("CALL sp_sum_sasaran_lkp_kebun(?, ?,?, ?)", [$periode,null, '',null]));

        // Siapkan data untuk chart
        // Gabungkan data dan data_sasaran_lkp berdasarkan pekerjaan
        $combinedData = $data5->map(function ($item) use ($data_sasaran_lkp) {
            $matchingSasaran = $data_sasaran_lkp->first(function ($sasaran) use ($item) {
                return $sasaran->pekerjaan == $item->pekerjaan;
            });
            return [
                'pekerjaan' => $item->pekerjaan,
                'hektar' => round($item->hektar, 0),
                'sasaran_hektar' => $matchingSasaran ? (float) str_replace(',', '.', round($matchingSasaran->total_sasaran_ha, 0)) : null,
            ];
        });

} else {
    	$data5 = DB::select('call lkp_hektar_by_entry(?)', [\Session::get('uid')]);
    	$data5 = collect($data5)->map(function($item) {
    // Replace commas with dots and convert hektar to float
    $item->hektar = (float) str_replace(',', '.', $item->hektar);
    return $item;
});

$data_sasaran_lkp = collect(DB::select("CALL sp_sum_sasaran_lkp_kebun(?, ?,?,?)", [$periode,substr(\Session::get('fid'), 0, 4), 'null','null']));

        // Siapkan data untuk chart
        // Gabungkan data dan data_sasaran_lkp berdasarkan pekerjaan
        $combinedData = $data5->map(function ($item) use ($data_sasaran_lkp) {
            $matchingSasaran = $data_sasaran_lkp->first(function ($sasaran) use ($item) {
                return $sasaran->pekerjaan == $item->pekerjaan;
            });
            return [
                'pekerjaan' => $item->pekerjaan,
                'hektar' => round($item->hektar, 0),
                'sasaran_hektar' => $matchingSasaran ? (float) str_replace(',', '.', round($matchingSasaran->total_sasaran_ha, 0)) : null,
            ];
        });
}

    

            
            
           if($data1){ 
         $this->data = [
                'luas_timbang'=> number_format($data1->ha_tebang, 2, ',', '.') . " Ha",
                'tebu_timbang'=> number_format($data1->netto_ton, 2, ',', '.') . " ton",
                'protas_timbang'=> number_format($data1->protas, 1, ',', '.') . " ton/ha",
                'tanggal_terakhir'=> date("d-m-Y", strtotime($data1->tgl_akhir)),
                // 'mutu_A' => number_format($data3->mutu_A, 1) . "",
                // 'mutu_B' => number_format($data3->mutu_B, 1) . "",
                // 'mutu_C' => number_format($data3->mutu_C, 1) . "",
                // 'mutu_D' => number_format($data3->mutu_D, 1) . "",
                // 'mutu_E' => number_format($data3->mutu_E, 1) . "",
                'pekerjaan' => json_encode($combinedData->pluck('pekerjaan')->toArray()),
                'hektar'=> json_encode($combinedData->pluck('hektar')->toArray()),
                'sasaran_hektar'=> json_encode($combinedData->pluck('sasaran_hektar')->toArray()),
                'datarayon'=> $data7,
                'datakebun'=> $data8,
                'datacluster'=> $data9,
                'datajawa'=> $data10,
                'tahunprod' => $tahunprod,
                
            ];

            
        }else{
            $this->data = [
                'luas_timbang'=> number_format(0, 2, ',', '.') . " Ha",
                'tebu_timbang'=> number_format(0, 2, ',', '.') . " ton",
                'protas_timbang'=> number_format(0, 2, ',', '.') . " ton/ha",
                'tanggal_terakhir'=> date("d-m-Y", strtotime(0)),
                // 'mutu_A' => number_format(0, 1) . "",
                // 'mutu_B' => number_format(0, 1) . "",
                // 'mutu_C' => number_format(0, 1) . "",
                // 'mutu_D' => number_format(0, 1) . "",
                // 'mutu_E' => number_format(0, 1) . "",
                'pekerjaan' => json_encode($data5->pluck('pekerjaan')->toArray()),
                'hektar'=> json_encode($data5->pluck('hektar')->toArray()),
                'sasaran_hektar'=> json_encode($data5->pluck('sasaran_hektar')->toArray()),
                'datarayon'=> $data7,
                'datakebun'=> $data8,
                'datacluster'=> $data9,
                'datajawa'=> $data10,     
                'tahunprod' => $tahunprod,
                                          
            ];
        }


            
        // Kirim data ke view dashboard.index
        if(\Session::get('gid') == 9)
        {
            return redirect('dashboard/grafikbiayasdm');	
        }

        if(\Session::get('gid') == 11)
        {
            return redirect('gudangarea/dashboard');	
        }

        if(\Session::get('gid') == 12)
        {
            return redirect('gudangarea/dashboard');	
        }

        if($getlevel->level == 10)
        {
                return redirect('mastertemplate/main_page');
        }

            try{
                $data_sasaran2526 = DB::table('master_sasaran2526_kebun')
                    ->selectRaw('SUM(ha_luas_sasaran) as total_ha_luas_sasaran, SUM(ton_tebu_sasaran) as total_ton_tebu_sasaran')
                    ->first();
                $total_ha = (float) $data_sasaran2526->total_ha_luas_sasaran;
                $total_ton = (float) $data_sasaran2526->total_ton_tebu_sasaran;
                $total_protas = $total_ha > 0 ? round($total_ton / $total_ha, 2) : 0;

                $this->data['sasaran'] = [
                    'ha_luas_sasaran' => $total_ha,
                    'ton_tebu_sasaran' => $total_ton,
                    'protas_sasaran' => $total_protas,
                ];
            } catch (\Exception $e) {
                $this->data['sasaran'] = [
                    'ha_luas_sasaran' => 0,
                    'ton_tebu_sasaran' => 0,
                    'protas_sasaran' => 0,
                ];
            }


            if($request->has('viewtype') && $request->input('viewtype') == 'masa-pemeliharaan'){
                return view('dashboard.'.str_replace('.blade.php', '', env('PEMELIHARAAN'.'_'.$thntnm)), $this->data);
            }else if($request->has('viewtype') && $request->input('viewtype') == 'masa-panen'){
                return view('dashboard.'.str_replace('.blade.php', '', env('PANEN'.'_'.$thntnm)), $this->data);
            }
            else{
                return view('dashboard.'.str_replace('.blade.php', '', env('DEFAULT'.'_'.$thntnm)), $this->data);
            }
              
	}	

    public function setdbsession(Request $request)
    {
        // Set session variable for the year
        $dbget = $request->input('dbget');

        $database_name = 'mysql_'.$dbget;
        Config::set('database.default', session('database_name', $database_name));
        session(['tahuntanam' => $dbget]);

        if (!\Auth::check()) 
			return redirect('user/login')->with('status', 'error')->with('message', 'You are not login');
        
        return redirect('dashboard');
    }

    public function switchuser(Request $request)
    {
        if(session('gid') != 1) {
            return json_encode(['status' => 'error', 'message' => 'Unauthorized']);
        }
        $userId = $request->input('user_id');
        $user = DB::table('tb_users')
            ->join('tb_groups', 'tb_users.group_id', '=', 'tb_groups.group_id')
            ->where('id', $userId)->first();

        if ($user) {
            // Log out the current user
            // \Auth::logout();
            // \Session::flush();

            // Log in as the new user
            // \Auth::loginUsingId($user->id);

            // Set session variables for the new user
            \Session::put('gid', $user->group_id);
            \Session::put('uid', $user->id);
            \Session::put('eid', $user->email);
            \Session::put('ll', $user->last_login);
            \Session::put('fid', $user->first_name.' '.$user->last_name);
            \Session::put('username', $user->username);
            \Session::put('join', $user->created_at);
            \Session::put('level', $user->level);
            \Session::put('tahuntanam', session('tahuntanam')); // Keep the year selection

            return json_encode(['status' => 'success', 'message' => 'Switched to user: ' . $user->username]);
        } else {
            return json_encode(['status' => 'error', 'message' => 'User not found']);
        }
    }

    public function managedashboard(Request $request)
    {
        if(session('gid') != 1){
            return redirect('dashboard');
        }
        $pemeliharaan = env('PEMELIHARAAN_'.\Session::get('tahuntanam'));
        $url_pemeliharaan = url('dashboard?viewtype=masa-pemeliharaan');
        $panen = env('PANEN_'.\Session::get('tahuntanam'));
        $url_panen = url('dashboard?viewtype=masa-panen');

        $this->data['data']['file']['pemeliharaan'] = $pemeliharaan? $pemeliharaan : '';
        $this->data['data']['file']['panen'] = $panen? $panen : '';
        $this->data['data']['url']['pemeliharaan'] = $url_pemeliharaan;
        $this->data['data']['url']['panen'] = $url_panen;
        return view('dashboard.maindashboard', $this->data);
    }

    public function gettimezonee(Request $request)
    {
        $now = DB::select("SELECT NOW() as tgl");
        $date = date('Y-m-d H:i:s');
        return response()->json(['now' => $now[0]->tgl, 'date' => $date]);
    }

    public function produksi_2024(Request $request)
    {
        // Ambil tanggal akhir dari request atau gunakan default
        if(\Session::get('tahuntanam') == '2425'){
        $datainyear =  date('Y-m-d', strtotime(date('Y-m-d') . ' -1 day'));

        $tgl_akhir = date('Y-m-d', strtotime($datainyear . ' -1 year'));

        // Ambil tanggal awal (tgl_giling paling awal)
        $tgl_awal = DB::table('master_console_2024')
            ->orderBy('tgl_giling', 'asc')
            ->limit(1)
            ->value('tgl_giling');

        // Query sesuai permintaan
        $data = DB::table('master_console_2024')
            ->selectRaw('
            ROUND(SUM(luas_tebang),2) as luas_tebang,
            ROUND(SUM(netto_tebu/1000),2) as netto_tebu,
            ROUND(SUM(netto_tebu/1000) / SUM(luas_tebang),2) as protas,
            ROUND(SUM(hablur)/SUM(netto_tebu/1000) * 100,2) as rendemen,
            ROUND(SUM(hablur),2) as hablur,
            ROUND(SUM(gula_ptr/1000),2) as gula,
            ROUND(SUM(tetes_ptr/1000),2) as tetes
            ')
            ->whereBetween('tgl_giling', [$tgl_awal, $tgl_akhir])
            ->first();
        }else if(\Session::get('tahuntanam') == '2526'){
            
            $datainyear =  $request->input('tgl', date('Y-m-d', strtotime(date('Y-m-d') . ' -1 day')));
            // Ambil data dari stored procedure
            $kebun = $request->input('kebun'); // Ambil input kebun, default ke 'all' jika tidak ada
            if($kebun == 'Total KSO'){
                $kebun = null;
            }else{
                $kebun = $request->input('kebun');
            }

            if($request->input('cluster') != null && $kebun == null && $request->input('regional') == null){
                config(['app.debug' => true]);
                $cluster = $request->input('cluster');
                $data = DB::select('CALL sp_real_2025_hgsama_by2026_cluster_new(?, ?)', [$datainyear, $cluster]);
            }else if($request->input('regional') != null && $request->input('cluster') == null && $kebun == null){
                config(['app.debug' => true]);
                $regional = $request->input('regional');
                $data = DB::select('CALL sp_real_2025_hgsama_by2026_regional(?, ?)', [$datainyear, $regional]);
            }else{
                $data = DB::select('CALL sp_real_2025_hgsama_by2026(?, ?)', [$datainyear, $kebun]);
            }
            

            // Format hasil sesuai struktur yang diharapkan
            if (!empty($data)) {
                // Find the row where uraian matches the expected values
               $hg = collect($data)->firstWhere('uraian', 'hg');

                $luasRow = collect($data)->firstWhere('uraian', 'luas_sd');
                $tebuRow = collect($data)->firstWhere('uraian', 'tebu_sd');
                $protasRow = collect($data)->firstWhere('uraian', 'protas_sd');
                $rendemenRow = collect($data)->firstWhere('uraian', 'rendemen_sd');
                $habluRow = collect($data)->firstWhere('uraian', 'hablur_sd');
                $gulaRow = collect($data)->firstWhere('uraian', 'gumil_sd');
                $tetesRow = collect($data)->firstWhere('uraian', 'tetes_sd');
                
                $data = (object)[
                    'hg' => (float)($hg->{'2025'} ?? 0),
                    'luas_tebang' => (float)($luasRow->{'2025'} ?? 0),
                    'netto_tebu' => (float)($tebuRow->{'2025'} ?? 0),
                    'protas' => (float)($protasRow->{'2025'} ?? 0),
                    'rendemen' => (float)($rendemenRow->{'2025'} ?? 0),
                    'hablur' => (float)($habluRow->{'2025'} ?? 0),
                    'gula' => (float)($gulaRow->{'2025'} ?? 0),
                    'tetes' => (float)($tetesRow->{'2025'} ?? 0)
                ];
            } else {
                $data = null;
            }
        }

        return response()->json($data);
    }

    public function progressReport(Request $request)
    {
        $tgl = $request->input('tgl');
        $cluster = $request->input('cluster');
        $regional = $request->input('regional');
        
        $data = DB::select('CALL sp_real_2026vs2025vsrkap_hgsama_lhp_new(?, ?, ?)', [$tgl, $regional,$cluster]);

        return response()->json($data);
    }

    public function infoluastebuprotas(Request $request)
    {
      $data1 = DB::table('q_prod_rekap_timbangan_cluster')
            ->select(
            DB::raw('SUM(ha_tebang) as ha_tebang'),
            DB::raw('SUM(netto_ton) as netto_ton'),
            DB::raw('SUM(netto_ton)/SUM(ha_tebang) as protas'),
            DB::raw('MAX(tgl_akhir) as tgl_akhir')
            )
            ->first();
        return response()->json([
            'luas_tebang' => number_format($data1->ha_tebang, 2, ',', '.') . " Ha",
            'tebu_timbang' => number_format($data1->netto_ton, 2, ',', '.') . " ton",
            'protas_timbang' => number_format($data1->protas, 1, ',', '.') . " ton/ha",
            'tanggal_terakhir' => date("d-m-Y", strtotime($data1->tgl_akhir)),
        ]);
    }

    public function sisa_tertebang_tebu(Request $request){
        // $data11 = DB::table('q_sisa_tebu_tertebang_new2')
        // ->select('nama_cluster','nama_kebun','takmar','takmar_tebu','takmar_protas','tertebang_takmar','ton_tebu_takmar','takmar_protas_real','tertebang','real_tebu','real_protas','sisa','sisa_tebu','sisa_protas','persen_luas','persen_tebu','persen_luas_real','persen_tebu_real')
        // ->get();

        $tgl = $request->input('tgl');
        $data11 = DB::select('call sp_sisa_tebu_tertebang(?)', [$tgl]);

        return view('dashboard.sisa_tertebang_tebu', [
            'datasisatebu' => $data11
        ]);
    }

     public function sisa_tertebang_tebu_rkap(Request $request){
        // $data11 = DB::table('q_sisa_tebu_tertebang_new2')
        // ->select('nama_cluster','nama_kebun','takmar','takmar_tebu','takmar_protas','tertebang_takmar','ton_tebu_takmar','takmar_protas_real','tertebang','real_tebu','real_protas','sisa','sisa_tebu','sisa_protas','persen_luas','persen_tebu','persen_luas_real','persen_tebu_real')
        // ->get();

        $tgl = $request->input('tgl');
        $data11 = DB::select('call sp_sisa_tebu_tertebang_rkap(?)', [$tgl]);

        return view('dashboard.sisa_tertebang_tebu_rkap', [
            'datasisatebu' => $data11
        ]);
    }

    public function sisa_tertebang_tebu_2024(Request $request){
        // $data11 = DB::table('q_sisa_tebu_tertebang_new2')
        // ->select('nama_cluster','nama_kebun','takmar','takmar_tebu','takmar_protas','tertebang_takmar','ton_tebu_takmar','takmar_protas_real','tertebang','real_tebu','real_protas','sisa','sisa_tebu','sisa_protas','persen_luas','persen_tebu','persen_luas_real','persen_tebu_real')
        // ->get();

        $tgl = $request->input('tgl');
        $tgl2 = date('Y-m-d', strtotime('-1 year', strtotime($request->input('tgl'))));
        $data11 = DB::select('call sp_sisa_tebu_tertebang_vs24(?,?)', [$tgl,$tgl2]);
        $thntnm = \Session::get('tahuntanam');
        if($thntnm == '2425'){
            $tahunprod = '2025';
        }else if($thntnm == '2526'){
            $tahunprod = '2026';
        }else if($thntnm == '2627'){
            $tahunprod = '2027';
        }

        return view('dashboard.sisa_tertebang_tebu_2024', [
            'datasisatebu' => $data11,
            'tahunprod' => $tahunprod
        ]);
    }
    
    public function mapdashboard(Request $request){
        // $data11 = DB::table('q_sisa_tebu_tertebang_new2')
        // ->select('nama_cluster','nama_kebun','takmar','takmar_tebu','takmar_protas','tertebang_takmar','ton_tebu_takmar','takmar_protas_real','tertebang','real_tebu','real_protas','sisa','sisa_tebu','sisa_protas','persen_luas','persen_tebu','persen_luas_real','persen_tebu_real')
        // ->get();


        return view('dashboard.mapdashboard', [
           
        ]);
    }

    public function mapdashboard2025(Request $request){
        // $data11 = DB::table('q_sisa_tebu_tertebang_new2')
        // ->select('nama_cluster','nama_kebun','takmar','takmar_tebu','takmar_protas','tertebang_takmar','ton_tebu_takmar','takmar_protas_real','tertebang','real_tebu','real_protas','sisa','sisa_tebu','sisa_protas','persen_luas','persen_tebu','persen_luas_real','persen_tebu_real')
        // ->get();


        return view('dashboard.mapdashboard2025', [
           
        ]);
    }

    public function getTotalprotasKSOmap(Request $request){
        $tgl = date('Y-m-d');
        $data11 = DB::select('call sp_sisa_tebu_tertebang_total(?)', [$tgl])[0] ?? [];
        echo json_encode($data11);
    }

    public function getTotallkpKSOmap(Request $request){
        $tgl = date('Y-m-d');
        $real_lkp = DB::table('TX_TOTAL_KSO')
            ->join('master_petak', 'TX_TOTAL_KSO.id_lahan', '=', 'master_petak.lahan_id')
            ->join('master_afd', 'master_petak.afd_new', '=', 'master_afd.kode_afd')
            ->join('master_rayon', 'master_afd.kode_rayon', '=', 'master_rayon.kode_rayon')
            ->join('master_kebun', 'master_rayon.kode_kebun', '=', 'master_kebun.kode_kebun')
            ->join('master_kategori', 'master_petak.kategori_n', '=', 'master_kategori.kat_lahan')
            ->where('TX_TOTAL_KSO.pekerjaan', 'serah_tanah')
            ->where('TX_TOTAL_KSO.tgl', '!=', '0000-00-00')
            ->whereBetween('TX_TOTAL_KSO.tgl', ['2024-12-01', date('Y-m-d')])
            ->sum('TX_TOTAL_KSO.ha');

        $sasaran = DB::table('master_sasaran2526_kebun')
            ->sum('ha_luas_sasaran');    
        $data11 = array(

            'sasaran' => $sasaran,
            'real_lkp' => $real_lkp,
        );
        echo json_encode($data11);
    }
    
    public function detailmaps(Request $request){
            $tgl = date('Y-m-d');
            $nama_kebun = $request->input('nama_kebun');
            $data11 = DB::select('call sp_sisa_tebu_tertebang_kebun(?,?)', [$tgl,$nama_kebun]);
            echo json_encode($data11);
    }

    public function detailmaps25(Request $request){
            $nama_kebun = $request->input('nama_kebun');
            $data = DB::table('TX_TOTAL_KSO')
                ->join('master_petak', 'TX_TOTAL_KSO.id_lahan', '=', 'master_petak.lahan_id')
                ->join('master_afd', 'master_petak.afd_new', '=', 'master_afd.kode_afd')
                ->join('master_rayon', 'master_afd.kode_rayon', '=', 'master_rayon.kode_rayon')
                ->join('master_kebun', 'master_rayon.kode_kebun', '=', 'master_kebun.kode_kebun')
                ->join('master_kategori', 'master_petak.kategori_n', '=', 'master_kategori.kat_lahan')
                ->join('master_sasaran2526_kebun_popmie as a', 'a.kode_kebun', '=', 'master_kebun.kode_kebun')
                ->select(
                    'master_kebun.nama_cluster',
                    'master_kebun.nama_kebun',
                    'a.ha_luas_sasaran',
                    DB::raw('SUM(TX_TOTAL_KSO.ha) as luas_real'),
                    DB::raw('ROUND(SUM(TX_TOTAL_KSO.ha)/a.ha_luas_sasaran*100,2) as persen_luas'),
                    'a.ton_tebu_sasaran',
                    DB::raw("'' as real_ton_tebu"),
                    DB::raw("0. as persen_ton_tebu"),
                    'a.protas_sasaran',
                    DB::raw("'' as real_protas"),
                    DB::raw("0. as persen_protas")
                )
                ->where('TX_TOTAL_KSO.pekerjaan', 'serah_tanah')
                ->where('TX_TOTAL_KSO.tgl', '!=', '0000-00-00')
                ->where('master_kebun.nama_cluster', $nama_kebun)
                ->whereBetween('TX_TOTAL_KSO.tgl', ['2024-12-01', date('Y-m-d')])
                ->groupBy('master_kebun.kode_kebun')
                ->get();
            echo json_encode($data);
    }

    public function getRekapMorfologiPetakDetail(Request $request)
    {
        					config(['app.debug' => true]);
        $kode_kebun = $request->input('kebun');
        $kode_rayon = $request->input('rayon');
        $afd = $request->input('afd');
        $tahun = $request->input('tahun');

        $data = DB::table('q_rekap_morfologi_petak_detail')
            
            ->when($kode_kebun, function ($query) use ($kode_kebun) {
                return $query->where('kode_kebun', $kode_kebun);
            })
            ->when($kode_rayon, function ($query) use ($kode_rayon) {
                return $query->where('kode_rayon', $kode_rayon);
            })
            ->when($afd, function ($query) use ($afd) {
                return $query->where('afd_new', $afd);
            })
            ->when($tahun, function ($query) use ($tahun) {
                return $query->whereYear('tanggal', $tahun);
            })
            ->get();

        $dir = 'uploads/foto_morfologi';
        $files = [];
        // Ambil daftar file foto dari database, bukan dari folder
        $files = [];
        // Ambil daftar file foto dari database, join dengan master_petak
        $query = DB::table('tx_morfologi')
            ->join('master_petak', 'tx_morfologi.lahan_id', '=', 'master_petak.lahan_id')
            ->whereNotNull('tx_morfologi.foto')
            ->select('tx_morfologi.foto');

        if (!empty($kebun)) {
            $query->where('master_petak.plant', $kebun);
        }
        if (!empty($rayon)) {
            $query->where('master_petak.kode_rayon', $rayon);
        }
        if (!empty($afd)) {
            $query->where('master_petak.afd_new', $afd);
        }
        if (!empty($tahun)) {
            $query->whereYear('tx_morfologi.tanggal', $tahun);
        }

        $fotoList = $query->groupBy('tx_morfologi.foto')->pluck('tx_morfologi.foto')->toArray();

        //foreach ($fotoList as $foto) {
        //    $filePath = $dir . '/' . $foto;
        //    if (file_exists($filePath)) {
        //    $files[] = $filePath;
        //    }
        //}
//
        //foreach ($files as $file) {
        //    $thumbPath = $dir . '/thumb_' . basename($file);
        //    if (!file_exists($thumbPath)) {
        //        try {
        //            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        //            if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'jfif'])) {
        //                $img = null;
        //                if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'jfif') {
        //                    $img = @imagecreatefromjpeg($file);
        //                } elseif ($ext === 'png') {
        //                    $img = @imagecreatefrompng($file);
        //                } elseif ($ext === 'gif') {
        //                    $img = @imagecreatefromgif($file);
        //                }
        //                if ($img) {
        //                    $width = imagesx($img);
        //                    $height = imagesy($img);
        //                    $thumbWidth = 200;
        //                    $thumbHeight = intval($height * $thumbWidth / $width);
        //                    $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
        //                    imagecopyresampled($thumbImg, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
        //                    if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'jfif') {
        //                        imagejpeg($thumbImg, $thumbPath, 80);
        //                    } elseif ($ext === 'png') {
        //                        imagepng($thumbImg, $thumbPath, 8);
        //                    } elseif ($ext === 'gif') {
        //                        imagegif($thumbImg, $thumbPath);
        //                    }
        //                    imagedestroy($thumbImg);
        //                    imagedestroy($img);
        //                }
        //            }
        //        } catch (\Exception $e) {
        //            // Ignore errors
        //        }
        //    }
        //}    

        $groups = [];
        $masaTanamOrder = [
            '1A','1B','2A','2B','3A','3B','4A','4B','5A','5B','6A','6B','7A','7B','8A','8B','9A','9B','10A','10B','11A','11B','12A','12B'
        ];

        // Group data by lahan_id
        foreach ($data as $row) {
            $lahan_id = $row->lahan_id;
            $masa_tanam = $row->masa_tanam_group;

            if (!isset($groups[$lahan_id])) {
            $groups[$lahan_id] = [];
            }
            if (!isset($groups[$lahan_id]['nama_kebun'])) {
            $groups[$lahan_id]['nama_kebun'] = $row->nama_kebun;
            }
            if (!isset($groups[$lahan_id]['luas_polig'])) {
            $groups[$lahan_id]['luas_polig'] = $row->luas_polig;
            }
            if (!isset($groups[$lahan_id]['afd'])) {
            $groups[$lahan_id]['afd'] = $row->afd_new;
            }
            if (!isset($groups[$lahan_id]['bulan_tana'])) {
            $groups[$lahan_id]['bulan_tana'] = $row->bulan_tana;
            }
            $groups[$lahan_id][$masa_tanam] = [
            'tanggal' => $row->tanggal,
            'foto' => $row->foto,
            ];
        }

        // Mapping masa tanam ke nama bulan
        $bulanMap = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
            7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
        ];

        // Build HTML table
        $html = '<style>
            .morfologi-petak-table th, .morfologi-petak-table td {
            text-align: center;
            vertical-align: middle;
            font-size: 13px;
            }
            .morfologi-petak-table thead th {

            background: #2962FF;
            color: #fff;
            font-size: 13px;
            position: sticky;
            top: 0;
            z-index: 2;
            }

            .morfologi-petak-table tbody tr:nth-child(even) {
            background: #f6f9fc;
            }
            .morfologi-petak-table tbody tr:hover {
            background: #e3e8f0;
            transition: background 0.2s;
            }
            .morfologi-petak-table td {
            font-size: 13px;
            border: 1px solid #e0e0e0;
            }
            .morfologi-petak-table .has-foto {
            background: #eafaf1;
            }
            .morfologi-petak-table .no-foto {
            background: #ffeaea;
            }
            .morfologi-petak-table .no-foto2 {
            background: #f3f3f3;
            }
            .morfologi-petak-table .tanggal-cell {
            color: #007bff;
            font-weight: bold;
            font-size: 12px;
            display: block;
            margin-top: 3px;
            }
            .morfologi-petak-table .lahanid-cell {
            background: #f0f4ff;
            font-weight: bold;
            }
            .morfologi-petak-table .afd-cell {
            background: #f7f7e6;
            }
            ::-webkit-scrollbar {
            width: 10px;
            }

            /* Track */
            ::-webkit-scrollbar-track {
            background: #f1f1f1; 
            }
            
            /* Handle */
            ::-webkit-scrollbar-thumb {
            background: #888; 
            }

            /* Handle on hover */
            ::-webkit-scrollbar-thumb:hover {
            background: #555; 
            }
        </style>';

        $html .= '<div style="overflow-x:auto;">';
        $html .= '<table class="table table-bordered table-sm table-responsive morfologi-petak-table" style="height: 640px;">';

        // Baris bulan di atas
        $html .= '<thead style="position:sticky;top:0;z-index:10;">';
        $html .= '<tr>';
        $html .= '<th rowspan="2" class="">Lahan Id</th>';
        $html .= '<th rowspan="2" class="">Afd</th>';
        $html .= '<th rowspan="2" class="">Nama Kebun</th>';
        $html .= '<th rowspan="2" class="">Bulan Tanam</th>';

        // Baris bulan
        $prevBulan = '';
        $colspan = 0;
        $bulanHeader = '';
        foreach ($masaTanamOrder as $idx => $mt) {
            $bulanNum = intval(preg_replace('/[^0-9]/', '', $mt));
            $bulanNama = isset($bulanMap[$bulanNum]) ? $bulanMap[$bulanNum] : '';
            if ($bulanNama !== $prevBulan) {
            if ($colspan > 0) {
                $bulanHeader .= '<th colspan="' . $colspan . '" style="position:sticky;top:0;z-index:11;background:#2962FF;color:#fff;">' . $prevBulan . '</th>';
            }
            $prevBulan = $bulanNama;
            $colspan = 1;
            } else {
            $colspan++;
            }
            // Jika terakhir, tutup
            if ($idx === count($masaTanamOrder) - 1) {
            $bulanHeader .= '<th colspan="' . $colspan . '" style="position:sticky;top:0;z-index:11;background:#2962FF;color:#fff;">' . $bulanNama . '</th>';
            }
        }
        $html .= $bulanHeader;
        $html .= '</tr>';

        // Baris masa tanam (1A, 1B, dst)
        $html .= '<tr>';
        foreach ($masaTanamOrder as $mt) {
            $html .= '<th style="position:sticky;top:32px;z-index:12;background:#1565C0;color:#fff;">' . $mt . '</th>';
        }
        $html .= '</tr>';
        $html .= '</thead><tbody>';

        foreach ($groups as $lahan_id => $rowGroup) {
            $html .= '<tr>';
            // Freeze first three columns (Lahan Id, Afd, Nama Kebun) using inline style for sticky
            $html .= '<td class="lahanid-cell" style="position:sticky;left:0;z-index:3;background:#FFF;">' . $lahan_id . '</td>';
            $html .= '<td class="afd-cell" style="position:sticky;left:85px;z-index:3;background:#FFF;">' . (isset($rowGroup['afd']) ? htmlspecialchars($rowGroup['afd']) : '') . '</td>';
            $html .= '<td style="position:sticky;left:143px;z-index:3;background:#FFF;">' . (isset($rowGroup['nama_kebun']) ? htmlspecialchars($rowGroup['nama_kebun']) : '') . '</td>';
            $html .= '<td style="position:sticky;left:238px;z-index:3;background:#FFF;    border-right: 1px solid #0D47A1;">' . (isset($rowGroup['bulan_tana']) ? htmlspecialchars($rowGroup['bulan_tana']) : '') . '</td>';
            foreach ($masaTanamOrder as $mt) {
            if (isset($rowGroup[$mt])) {
                $cell = '';
                if (!empty($rowGroup[$mt]['foto'])) {

                $fotoName = htmlspecialchars($rowGroup[$mt]['foto']);

                $localThumb = '/uploads/foto_morfologi/thumb_' . $fotoName;
                $cdnThumb   = env('ASSET_CDN_URL') . '/uploads/foto_morfologi/thumb_' . $fotoName;

                // cek file lokal
                $thumbSrc = file_exists(public_path('uploads/foto_morfologi/thumb_' . $rowGroup[$mt]['foto']))
                    ? $localThumb
                    : $cdnThumb;

                $cell .= '<a href="javascript:void(0);" onclick="showImageModal(\'' . htmlspecialchars($rowGroup[$mt]['foto']) . '\')">
                <img src="'.$thumbSrc.'" alt="Foto" 
                style="max-width: 100px; max-height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;">
                </a>';

                //$cell .= '<a href="javascript:void(0);" onclick="showImageModal(\'/uploads/foto_morfologi/' . htmlspecialchars($rowGroup[$mt]['foto']) . '\')"><img src="/uploads/foto_morfologi/thumb_' . htmlspecialchars($rowGroup[$mt]['foto']) . '" alt="Foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;"></a>';
                // Tambahkan modal hanya sekali di luar loop (bisa di bawah tabel)
                if (!isset($imageModalScriptAdded)) {
                    $html .= '
                    <div id="imageModalMorfologi" class="modal" tabindex="-1" role="dialog" style="display:none; background:rgba(0,0,0,0.7); position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999; align-items:center; justify-content:center;">
                        <span style="position:absolute;top:20px;right:40px;font-size:40px;color:#fff;cursor:pointer;" onclick="closeImageModal()">&times;</span>
                        <img id="imageModalMorfologiImg" src="" style="max-width:90vw;max-height:90vh;display:block;margin:auto;box-shadow:0 0 20px #000;">
                    </div>

                    <div id="infoModalMorfologi" class="modal" tabindex="-1" role="dialog" style="display:none; background:rgba(0,0,0,0.7); position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999; align-items:center; justify-content:center;">
                        <span style="position:absolute;top:20px;right:40px;font-size:40px;color:#fff;cursor:pointer;" onclick="closeInfoModal()">&times;</span>
                        <div style="#ffffff00; padding:20px; border-radius:8px; max-width:600px; width:100%; box-shadow:none;">

                    </div>
                    <script>
                    function showImageModal(src) {
                        var local = "/uploads/foto_morfologi/" + src.trim();
                        var cdn   = "' . rtrim(env('ASSET_CDN_URL'), '/') . '/uploads/foto_morfologi/" + src.trim();

                        var imgElement = document.getElementById("imageModalMorfologiImg");
                        imgElement.src = local;
                        imgElement.onerror = function() {
                            imgElement.src = cdn;
                        };
                        document.getElementById("imageModalMorfologi").style.display = "flex";
                    }
                    function closeImageModal() {
                        document.getElementById("imageModalMorfologi").style.display = "none";
                    }
                    function closeInfoModal() {
                        document.getElementById("infoModalMorfologi").style.display = "none";
                    }
                    // Close modal on background click
                    document.addEventListener("DOMContentLoaded", function() {
                        var modal = document.getElementById("imageModalMorfologi");
                        if(modal){
                            modal.addEventListener("click", function(e) {
                                if (e.target === modal) closeImageModal();
                            });
                        }
                    });

                    function showInfoPetak(lahanId, tanggal) {
                        fetch("/dashboard/getLastMorfologiByLahanId?lahan_id=" + encodeURIComponent(lahanId) + "&tanggal=" + encodeURIComponent(tanggal))
                            .then(response => response.json())
                            .then(res => {
                                if (res.status === "success" && res.data) {
                                    let html = "";
                                    html += `
                                        <div class="card shadow-sm animate-card" style="max-width:400px;margin:auto;border-radius:12px;overflow:hidden;">
                                            <div class="card-header bg-primary text-white text-center" style="font-size:18px;font-weight:bold;">
                                                <i class="fa fa-info-circle"></i> Informasi Petak
                                            </div>
                                            <div class="card-body" style="background:#f8f9fa;">
                                                <ul class="list-group list-group-flush" style="font-size:15px;">
                                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                                        <span><i class="fa fa-hashtag text-secondary"></i> <b>Lahan ID</b></span>
                                                        <span class="badge badge-pill badge-primary" style="font-size:15px;">${res.data.lahan_id || "-"}</span>
                                                    </li>
                                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                                        <span><i class="fa fa-calendar text-secondary"></i> <b>Tanggal</b></span>
                                                        <span class="badge badge-pill badge-info" style="font-size:15px;">${res.data.tanggal || "-"}</span>
                                                    </li>
                                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                                        <span><i class="fa fa-tree text-success"></i> <b>Jumlah Batang</b></span>
                                                        <span class="badge badge-pill badge-success" style="font-size:15px;">${res.data.jumlah_batang || "-"} /meter</span>
                                                    </li>
                                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                                        <span><i class="fa fa-arrows-v text-warning"></i> <b>Tinggi Batang</b></span>
                                                        <span class="badge badge-pill badge-warning" style="font-size:15px;">${res.data.tinggi_batang || "-"} meter</span>
                                                    </li>
                                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                                        <span><i class="fa fa-circle text-danger"></i> <b>Diameter Batang</b></span>
                                                        <span class="badge badge-pill badge-danger" style="font-size:15px;">${res.data.diameter_batang || "-"} mm</span>
                                                    </li>
                                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                                        <span><i class="fa fa-balance-scale text-secondary"></i> <b>Berat Batang/Meter</b></span>
                                                        <span class="badge badge-pill badge-secondary" style="font-size:15px;">${res.data.berat_batang_per_meter || "-"} kg/meter</span>
                                                    </li>
                                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                                        <span><i class="fa fa-bars text-dark"></i> <b>Jumlah Ruas</b></span>
                                                        <span class="badge badge-pill badge-dark" style="font-size:15px;">${res.data.jumlah_ruas || "-"}</span>
                                                    </li>
                                                </ul>
                                            </div>
                                        </div>
                                    `;
                                    document.querySelector("#infoModalMorfologi div").innerHTML = html;
                                } else {
                                    document.querySelector("#infoModalMorfologi div").innerHTML = "<h4>Informasi Petak</h4><div class=\"text-danger\">Data tidak ditemukan.</div>";
                                }
                                document.getElementById("infoModalMorfologi").style.display = "flex";
                            })
                            .catch(() => {
                                document.querySelector("#infoModalMorfologi div").innerHTML = "<h4>Informasi Petak</h4><div class=\"text-danger\">Gagal mengambil data.</div>";
                                document.getElementById("infoModalMorfologi").style.display = "flex";
                            });
                    }
                    </script>
                    ';
                    $imageModalScriptAdded = true;
                }
                $cellClass = 'has-foto';
                } else {
                // $cell .= '<img src="/assets/images/noimage.png" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px; opacity:0.7;">';
                $cell .= '<img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; opacity:0.5;">';
                $cellClass = 'no-foto';
                }
                $cell .= '<span class="tanggal-cell">' . date('d M Y', strtotime($rowGroup[$mt]['tanggal'])) . ' <span class="" onclick="showInfoPetak(\''
                    . $lahan_id . '\', \'' . $rowGroup[$mt]['tanggal'] . '\')"><i class="fa fa-info-circle"></i></span></span>';
                $html .= '<td class="' . $cellClass . '">' . $cell . '</td>';
            } else {
                $html .= '<td class="no-foto2"><img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; opacity:0.5;"></td>';
            }
            }
            $html .= '</tr>';
        }
        $html .= '</tbody></table></div>';

        return response($html);
    }

    public function getRekapTebuBerbungaDetail(Request $request)
    {
        $kode_kebun = $request->input('kebun');
        $kode_rayon = $request->input('rayon');
        $afd = $request->input('afd');
        $tahun = $request->input('tahun');

        $data = DB::table('q_rekap_tebu_berbunga_detail')
            
            ->when($kode_kebun, function ($query) use ($kode_kebun) {
                return $query->where('kode_kebun', $kode_kebun);
            })
            ->when($kode_rayon, function ($query) use ($kode_rayon) {
                return $query->where('kode_rayon', $kode_rayon);
            })
            ->when($afd, function ($query) use ($afd) {
                return $query->where('afd_new', $afd);
            })
            ->when($tahun, function ($query) use ($tahun) {
                return $query->whereYear('tanggal', $tahun);
            })
            ->get();

        $dir = 'uploads/foto_tebu_berbunga';
        $files = [];
        // Ambil daftar file foto dari database, bukan dari folder
        $files = [];
        // Ambil daftar file foto dari database, join dengan master_petak
        $query = DB::table('tx_tebu_berbunga')
            ->join('master_petak', 'tx_tebu_berbunga.lahan_id', '=', 'master_petak.lahan_id')
            ->whereNotNull('tx_tebu_berbunga.foto')
            ->select('tx_tebu_berbunga.foto');

        if (!empty($kebun)) {
            $query->where('master_petak.plant', $kebun);
        }
        if (!empty($rayon)) {
            $query->where('master_petak.kode_rayon', $rayon);
        }
        if (!empty($afd)) {
            $query->where('master_petak.afd_new', $afd);
        }
        if (!empty($tahun)) {
            $query->whereYear('tx_tebu_berbunga.tanggal', $tahun);
        }

        $fotoList = $query->groupBy('tx_tebu_berbunga.foto')->pluck('tx_tebu_berbunga.foto')->toArray();

        foreach ($fotoList as $foto) {
            $filePath = $dir . '/' . $foto;
            if (file_exists($filePath)) {
            $files[] = $filePath;
            }
        }

        foreach ($files as $file) {
            $thumbPath = $dir . '/thumb_' . basename($file);
            if (!file_exists($thumbPath)) {
                try {
                    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'jfif'])) {
                        $img = null;
                        if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'jfif') {
                            $img = @imagecreatefromjpeg($file);
                        } elseif ($ext === 'png') {
                            $img = @imagecreatefrompng($file);
                        } elseif ($ext === 'gif') {
                            $img = @imagecreatefromgif($file);
                        }
                        if ($img) {
                            $width = imagesx($img);
                            $height = imagesy($img);
                            $thumbWidth = 200;
                            $thumbHeight = intval($height * $thumbWidth / $width);
                            $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
                            imagecopyresampled($thumbImg, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
                            if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'jfif') {
                                imagejpeg($thumbImg, $thumbPath, 80);
                            } elseif ($ext === 'png') {
                                imagepng($thumbImg, $thumbPath, 8);
                            } elseif ($ext === 'gif') {
                                imagegif($thumbImg, $thumbPath);
                            }
                            imagedestroy($thumbImg);
                            imagedestroy($img);
                        }
                    }
                } catch (\Exception $e) {
                    // Ignore errors
                }
            }
        }    

        $groups = [];
        $masaTanamOrder = [
            '1A','1B','2A','2B','3A','3B','4A','4B','5A','5B','6A','6B','7A','7B','8A','8B','9A','9B','10A','10B','11A','11B','12A','12B'
        ];

        // Group data by lahan_id
        foreach ($data as $row) {
            $lahan_id = $row->lahan_id;
            $masa_tanam = $row->masa_tanam_group;

            if (!isset($groups[$lahan_id])) {
            $groups[$lahan_id] = [];
            }
            if (!isset($groups[$lahan_id]['nama_kebun'])) {
            $groups[$lahan_id]['nama_kebun'] = $row->nama_kebun;
            }
            if (!isset($groups[$lahan_id]['luas_polig'])) {
            $groups[$lahan_id]['luas_polig'] = $row->luas_polig;
            }
            if (!isset($groups[$lahan_id]['afd'])) {
            $groups[$lahan_id]['afd'] = $row->afd_new;
            }
            if (!isset($groups[$lahan_id]['bulan_tana'])) {
            $groups[$lahan_id]['bulan_tana'] = $row->bulan_tana;
            }
            $groups[$lahan_id][$masa_tanam] = [
            'tanggal' => $row->tanggal,
            'foto' => $row->foto,
            ];
        }

        // Mapping masa tanam ke nama bulan
        $bulanMap = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
            7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
        ];

        // Build HTML table
        $html = '<style>
            .morfologi-petak-table th, .morfologi-petak-table td {
            text-align: center;
            vertical-align: middle;
            font-size: 13px;
            }
            .morfologi-petak-table thead th {

            background: #2962FF;
            color: #fff;
            font-size: 13px;
            position: sticky;
            top: 0;
            z-index: 2;
            }

            .morfologi-petak-table tbody tr:nth-child(even) {
            background: #f6f9fc;
            }
            .morfologi-petak-table tbody tr:hover {
            background: #e3e8f0;
            transition: background 0.2s;
            }
            .morfologi-petak-table td {
            font-size: 13px;
            border: 1px solid #e0e0e0;
            }
            .morfologi-petak-table .has-foto {
            background: #eafaf1;
            }
            .morfologi-petak-table .no-foto {
            background: #ffeaea;
            }
            .morfologi-petak-table .no-foto2 {
            background: #f3f3f3;
            }
            .morfologi-petak-table .tanggal-cell {
            color: #007bff;
            font-weight: bold;
            font-size: 12px;
            display: block;
            margin-top: 3px;
            }
            .morfologi-petak-table .lahanid-cell {
            background: #f0f4ff;
            font-weight: bold;
            }
            .morfologi-petak-table .afd-cell {
            background: #f7f7e6;
            }
            ::-webkit-scrollbar {
            width: 10px;
            }

            /* Track */
            ::-webkit-scrollbar-track {
            background: #f1f1f1; 
            }
            
            /* Handle */
            ::-webkit-scrollbar-thumb {
            background: #888; 
            }

            /* Handle on hover */
            ::-webkit-scrollbar-thumb:hover {
            background: #555; 
            }
        </style>';

        $html .= '<div style="overflow-x:auto;">';
        $html .= '<table class="table table-bordered table-sm table-responsive morfologi-petak-table" style="height: 640px;">';

        // Baris bulan di atas
        $html .= '<thead style="position:sticky;top:0;z-index:10;">';
        $html .= '<tr>';
        $html .= '<th rowspan="2" class="">Lahan Id</th>';
        $html .= '<th rowspan="2" class="">Afd</th>';
        $html .= '<th rowspan="2" class="">Nama Kebun</th>';
        $html .= '<th rowspan="2" class="">Bulan Tanam</th>';

        // Baris bulan
        $prevBulan = '';
        $colspan = 0;
        $bulanHeader = '';
        foreach ($masaTanamOrder as $idx => $mt) {
            $bulanNum = intval(preg_replace('/[^0-9]/', '', $mt));
            $bulanNama = isset($bulanMap[$bulanNum]) ? $bulanMap[$bulanNum] : '';
            if ($bulanNama !== $prevBulan) {
            if ($colspan > 0) {
                $bulanHeader .= '<th colspan="' . $colspan . '" style="position:sticky;top:0;z-index:11;background:#2962FF;color:#fff;">' . $prevBulan . '</th>';
            }
            $prevBulan = $bulanNama;
            $colspan = 1;
            } else {
            $colspan++;
            }
            // Jika terakhir, tutup
            if ($idx === count($masaTanamOrder) - 1) {
            $bulanHeader .= '<th colspan="' . $colspan . '" style="position:sticky;top:0;z-index:11;background:#2962FF;color:#fff;">' . $bulanNama . '</th>';
            }
        }
        $html .= $bulanHeader;
        $html .= '</tr>';

        // Baris masa tanam (1A, 1B, dst)
        $html .= '<tr>';
        foreach ($masaTanamOrder as $mt) {
            $html .= '<th style="position:sticky;top:32px;z-index:12;background:#1565C0;color:#fff;">' . $mt . '</th>';
        }
        $html .= '</tr>';
        $html .= '</thead><tbody>';

        foreach ($groups as $lahan_id => $rowGroup) {
            $html .= '<tr>';
            // Freeze first three columns (Lahan Id, Afd, Nama Kebun) using inline style for sticky
            $html .= '<td class="lahanid-cell" style="position:sticky;left:0;z-index:3;background:#FFF;">' . $lahan_id . '</td>';
            $html .= '<td class="afd-cell" style="position:sticky;left:85px;z-index:3;background:#FFF;">' . (isset($rowGroup['afd']) ? htmlspecialchars($rowGroup['afd']) : '') . '</td>';
            $html .= '<td style="position:sticky;left:143px;z-index:3;background:#FFF;">' . (isset($rowGroup['nama_kebun']) ? htmlspecialchars($rowGroup['nama_kebun']) : '') . '</td>';
            $html .= '<td style="position:sticky;left:238px;z-index:3;background:#FFF;    border-right: 1px solid #0D47A1;">' . (isset($rowGroup['bulan_tana']) ? htmlspecialchars($rowGroup['bulan_tana']) : '') . '</td>';
            foreach ($masaTanamOrder as $mt) {
            if (isset($rowGroup[$mt])) {
                $cell = '';
                if (!empty($rowGroup[$mt]['foto'])) {
                $fotoName = htmlspecialchars($rowGroup[$mt]['foto']);
                $localThumb = '/uploads/foto_tebu_berbunga/thumb_' . $fotoName;
                $cdnThumb   = env('ASSET_CDN_URL') . '/uploads/foto_tebu_berbunga/thumb_' . $fotoName;

                // cek file lokal
                $thumbSrc = file_exists(public_path('uploads/foto_tebu_berbunga/thumb_' . $rowGroup[$mt]['foto']))
                    ? $localThumb
                    : $cdnThumb;

                $cell .= '<a href="javascript:void(0);" onclick="showImageModalbunga(\'' . htmlspecialchars($rowGroup[$mt]['foto']) . '\')">
                <img src="'.$thumbSrc.'" alt="Foto" 
                style="max-width: 100px; max-height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;">
                </a>';
                //$cell .= '<a href="javascript:void(0);" onclick="showImageModal(\'/uploads/foto_tebu_berbunga/' . htmlspecialchars($rowGroup[$mt]['foto']) . '\')"><img src="/uploads/foto_tebu_berbunga/thumb_' . htmlspecialchars($rowGroup[$mt]['foto']) . '" alt="Foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;"></a>';
                // Tambahkan modal hanya sekali di luar loop (bisa di bawah tabel)
                if (!isset($imageModalScriptAdded)) {
                    $html .= '
                    <div id="imageModalTebuBerbunga" class="modal" tabindex="-1" role="dialog" style="display:none; background:rgba(0,0,0,0.7); position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999; align-items:center; justify-content:center;">
                        <span style="position:absolute;top:20px;right:40px;font-size:40px;color:#fff;cursor:pointer;" onclick="closeImageModal()">&times;</span>
                        <img id="imageModalTebuBerbungaImg" src="" style="max-width:90vw;max-height:90vh;display:block;margin:auto;box-shadow:0 0 20px #000;">
                    </div>

                    <div id="infoModalTebuBerbunga" class="modal" tabindex="-1" role="dialog" style="display:none; background:rgba(0,0,0,0.7); position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999; align-items:center; justify-content:center;">
                        <span style="position:absolute;top:20px;right:40px;font-size:40px;color:#fff;cursor:pointer;" onclick="closeInfoModal()">&times;</span>
                        <div style="#ffffff00; padding:20px; border-radius:8px; max-width:600px; width:100%; box-shadow:none;">

                    </div>
                    <script>
                    function showImageModalbunga(src) {
                        document.getElementById("imageModalTebuBerbunga").style.display = "flex";
                        var imgElem = document.getElementById("imageModalTebuBerbungaImg");                        
                        var local = "/uploads/foto_tebu_berbunga/" + src;
                        var cdn   = "' . rtrim(env('ASSET_CDN_URL'), '/') . '/uploads/foto_tebu_berbunga/" + src;
                        imgElem.src = local;
                        imgElem.onerror = function() {
                            imgElem.src = cdn;
                        };
                    }
                    function closeImageModal() {
                        document.getElementById("imageModalTebuBerbunga").style.display = "none";
                    }
                    function closeInfoModal() {
                        document.getElementById("infoModalTebuBerbunga").style.display = "none";
                    }
                    // Close modal on background click
                    document.addEventListener("DOMContentLoaded", function() {
                        var modal = document.getElementById("imageModalTebuBerbunga");
                        if(modal){
                            modal.addEventListener("click", function(e) {
                                if (e.target === modal) closeImageModal();
                            });
                        }
                    });

                    function showInfoPetak(lahanId, tanggal) {
                       
                    }
                    </script>
                    ';
                    $imageModalScriptAdded = true;
                }
                $cellClass = 'has-foto';
                } else {
                // $cell .= '<img src="/assets/images/noimage.png" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px; opacity:0.7;">';
                $cell .= '<img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; opacity:0.5;">';
                $cellClass = 'no-foto';
                }
                $cell .= '<span class="tanggal-cell">' . date('d M Y', strtotime($rowGroup[$mt]['tanggal'])) . ' <span class="" onclick="showInfoPetak(\''
                    . $lahan_id . '\', \'' . $rowGroup[$mt]['tanggal'] . '\')"><i class="fa fa-info-circle"></i></span></span>';
                $html .= '<td class="' . $cellClass . '">' . $cell . '</td>';
            } else {
                $html .= '<td class="no-foto2"><img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; opacity:0.5;"></td>';
            }
            }
            $html .= '</tr>';
        }
        $html .= '</tbody></table></div>';

        return response($html);
    }

public function getRekapTebuRobohDetail(Request $request)
    {
        $kode_kebun = $request->input('kebun');
        $kode_rayon = $request->input('rayon');
        $afd = $request->input('afd');
        $tahun = $request->input('tahun');

        $data = DB::table('q_rekap_tebu_roboh_detail')
            
            ->when($kode_kebun, function ($query) use ($kode_kebun) {
                return $query->where('kode_kebun', $kode_kebun);
            })
            ->when($kode_rayon, function ($query) use ($kode_rayon) {
                return $query->where('kode_rayon', $kode_rayon);
            })
            ->when($afd, function ($query) use ($afd) {
                return $query->where('afd_new', $afd);
            })
            ->when($tahun, function ($query) use ($tahun) {
                return $query->whereYear('tanggal', $tahun);
            })
            ->get();

        $dir = 'uploads/foto_tebu_roboh';
        $files = [];
        // Ambil daftar file foto dari database, bukan dari folder
        $files = [];
        // Ambil daftar file foto dari database, join dengan master_petak
        $query = DB::table('tx_tebu_roboh')
            ->join('master_petak', 'tx_tebu_roboh.lahan_id', '=', 'master_petak.lahan_id')
            ->whereNotNull('tx_tebu_roboh.foto')
            ->select('tx_tebu_roboh.foto');

        if (!empty($kebun)) {
            $query->where('master_petak.plant', $kebun);
        }
        if (!empty($rayon)) {
            $query->where('master_petak.kode_rayon', $rayon);
        }
        if (!empty($afd)) {
            $query->where('master_petak.afd_new', $afd);
        }
        if (!empty($tahun)) {
            $query->whereYear('tx_tebu_roboh.tanggal', $tahun);
        }

        $fotoList = $query->groupBy('tx_tebu_roboh.foto')->pluck('tx_tebu_roboh.foto')->toArray();

        foreach ($fotoList as $foto) {
            $filePath = $dir . '/' . $foto;
            if (file_exists($filePath)) {
            $files[] = $filePath;
            }
        }

        foreach ($files as $file) {
            $thumbPath = $dir . '/thumb_' . basename($file);
            if (!file_exists($thumbPath)) {
                try {
                    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'jfif'])) {
                        $img = null;
                        if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'jfif') {
                            $img = @imagecreatefromjpeg($file);
                        } elseif ($ext === 'png') {
                            $img = @imagecreatefrompng($file);
                        } elseif ($ext === 'gif') {
                            $img = @imagecreatefromgif($file);
                        }
                        if ($img) {
                            $width = imagesx($img);
                            $height = imagesy($img);
                            $thumbWidth = 200;
                            $thumbHeight = intval($height * $thumbWidth / $width);
                            $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
                            imagecopyresampled($thumbImg, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
                            if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'jfif') {
                                imagejpeg($thumbImg, $thumbPath, 80);
                            } elseif ($ext === 'png') {
                                imagepng($thumbImg, $thumbPath, 8);
                            } elseif ($ext === 'gif') {
                                imagegif($thumbImg, $thumbPath);
                            }
                            imagedestroy($thumbImg);
                            imagedestroy($img);
                        }
                    }
                } catch (\Exception $e) {
                    // Ignore errors
                }
            }
        }    

        $groups = [];
        $masaTanamOrder = [
            '1A','1B','2A','2B','3A','3B','4A','4B','5A','5B','6A','6B','7A','7B','8A','8B','9A','9B','10A','10B','11A','11B','12A','12B'
        ];

        // Group data by lahan_id
        foreach ($data as $row) {
            $lahan_id = $row->lahan_id;
            $masa_tanam = $row->masa_tanam_group;

            if (!isset($groups[$lahan_id])) {
            $groups[$lahan_id] = [];
            }
            if (!isset($groups[$lahan_id]['nama_kebun'])) {
            $groups[$lahan_id]['nama_kebun'] = $row->nama_kebun;
            }
            if (!isset($groups[$lahan_id]['luas_polig'])) {
            $groups[$lahan_id]['luas_polig'] = $row->luas_polig;
            }
            if (!isset($groups[$lahan_id]['afd'])) {
            $groups[$lahan_id]['afd'] = $row->afd_new;
            }
            if (!isset($groups[$lahan_id]['bulan_tana'])) {
            $groups[$lahan_id]['bulan_tana'] = $row->bulan_tana;
            }
            $groups[$lahan_id][$masa_tanam] = [
            'tanggal' => $row->tanggal,
            'foto' => $row->foto,
            ];
        }

        // Mapping masa tanam ke nama bulan
        $bulanMap = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
            7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
        ];

        // Build HTML table
        $html = '<style>
            .morfologi-petak-table th, .morfologi-petak-table td {
            text-align: center;
            vertical-align: middle;
            font-size: 13px;
            }
            .morfologi-petak-table thead th {

            background: #2962FF;
            color: #fff;
            font-size: 13px;
            position: sticky;
            top: 0;
            z-index: 2;
            }

            .morfologi-petak-table tbody tr:nth-child(even) {
            background: #f6f9fc;
            }
            .morfologi-petak-table tbody tr:hover {
            background: #e3e8f0;
            transition: background 0.2s;
            }
            .morfologi-petak-table td {
            font-size: 13px;
            border: 1px solid #e0e0e0;
            }
            .morfologi-petak-table .has-foto {
            background: #eafaf1;
            }
            .morfologi-petak-table .no-foto {
            background: #ffeaea;
            }
            .morfologi-petak-table .no-foto2 {
            background: #f3f3f3;
            }
            .morfologi-petak-table .tanggal-cell {
            color: #007bff;
            font-weight: bold;
            font-size: 12px;
            display: block;
            margin-top: 3px;
            }
            .morfologi-petak-table .lahanid-cell {
            background: #f0f4ff;
            font-weight: bold;
            }
            .morfologi-petak-table .afd-cell {
            background: #f7f7e6;
            }
            ::-webkit-scrollbar {
            width: 10px;
            }

            /* Track */
            ::-webkit-scrollbar-track {
            background: #f1f1f1; 
            }
            
            /* Handle */
            ::-webkit-scrollbar-thumb {
            background: #888; 
            }

            /* Handle on hover */
            ::-webkit-scrollbar-thumb:hover {
            background: #555; 
            }
        </style>';

        $html .= '<div style="overflow-x:auto;">';
        $html .= '<table class="table table-bordered table-sm table-responsive morfologi-petak-table" style="height: 640px;">';

        // Baris bulan di atas
        $html .= '<thead style="position:sticky;top:0;z-index:10;">';
        $html .= '<tr>';
        $html .= '<th rowspan="2" class="">Lahan Id</th>';
        $html .= '<th rowspan="2" class="">Afd</th>';
        $html .= '<th rowspan="2" class="">Nama Kebun</th>';
        $html .= '<th rowspan="2" class="">Bulan Tanam</th>';

        // Baris bulan
        $prevBulan = '';
        $colspan = 0;
        $bulanHeader = '';
        foreach ($masaTanamOrder as $idx => $mt) {
            $bulanNum = intval(preg_replace('/[^0-9]/', '', $mt));
            $bulanNama = isset($bulanMap[$bulanNum]) ? $bulanMap[$bulanNum] : '';
            if ($bulanNama !== $prevBulan) {
            if ($colspan > 0) {
                $bulanHeader .= '<th colspan="' . $colspan . '" style="position:sticky;top:0;z-index:11;background:#2962FF;color:#fff;">' . $prevBulan . '</th>';
            }
            $prevBulan = $bulanNama;
            $colspan = 1;
            } else {
            $colspan++;
            }
            // Jika terakhir, tutup
            if ($idx === count($masaTanamOrder) - 1) {
            $bulanHeader .= '<th colspan="' . $colspan . '" style="position:sticky;top:0;z-index:11;background:#2962FF;color:#fff;">' . $bulanNama . '</th>';
            }
        }
        $html .= $bulanHeader;
        $html .= '</tr>';

        // Baris masa tanam (1A, 1B, dst)
        $html .= '<tr>';
        foreach ($masaTanamOrder as $mt) {
            $html .= '<th style="position:sticky;top:32px;z-index:12;background:#1565C0;color:#fff;">' . $mt . '</th>';
        }
        $html .= '</tr>';
        $html .= '</thead><tbody>';

        foreach ($groups as $lahan_id => $rowGroup) {
            $html .= '<tr>';
            // Freeze first three columns (Lahan Id, Afd, Nama Kebun) using inline style for sticky
            $html .= '<td class="lahanid-cell" style="position:sticky;left:0;z-index:3;background:#FFF;">' . $lahan_id . '</td>';
            $html .= '<td class="afd-cell" style="position:sticky;left:85px;z-index:3;background:#FFF;">' . (isset($rowGroup['afd']) ? htmlspecialchars($rowGroup['afd']) : '') . '</td>';
            $html .= '<td style="position:sticky;left:143px;z-index:3;background:#FFF;">' . (isset($rowGroup['nama_kebun']) ? htmlspecialchars($rowGroup['nama_kebun']) : '') . '</td>';
            $html .= '<td style="position:sticky;left:238px;z-index:3;background:#FFF;    border-right: 1px solid #0D47A1;">' . (isset($rowGroup['bulan_tana']) ? htmlspecialchars($rowGroup['bulan_tana']) : '') . '</td>';
            foreach ($masaTanamOrder as $mt) {
            if (isset($rowGroup[$mt])) {
                $cell = '';
                if (!empty($rowGroup[$mt]['foto'])) {
                $fotoName = htmlspecialchars($rowGroup[$mt]['foto']);
                $localThumb = '/uploads/foto_tebu_roboh/thumb_' . $fotoName;
                $cdnThumb   = env('ASSET_CDN_URL') . '/uploads/foto_tebu_roboh/thumb_' . $fotoName;

                // cek file lokal
                $thumbSrc = file_exists(public_path('uploads/foto_tebu_roboh/thumb_' . $rowGroup[$mt]['foto']))
                    ? $localThumb
                    : $cdnThumb;

                $cell .= '<a href="javascript:void(0);" onclick="showImageModal(\'' . htmlspecialchars($rowGroup[$mt]['foto']) . '\')">
                <img src="'.$thumbSrc.'" alt="Foto" 
                style="max-width: 100px; max-height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;">
                </a>';
                //$cell .= '<a href="javascript:void(0);" onclick="showImageModal(\'/uploads/foto_tebu_roboh/' . htmlspecialchars($rowGroup[$mt]['foto']) . '\')"><img src="/uploads/foto_tebu_roboh/thumb_' . htmlspecialchars($rowGroup[$mt]['foto']) . '" alt="Foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;"></a>';
                // Tambahkan modal hanya sekali di luar loop (bisa di bawah tabel)
                if (!isset($imageModalScriptAdded)) {
                    $html .= '
                    <div id="imageModalTebuRoboh" class="modal" tabindex="-1" role="dialog" style="display:none; background:rgba(0,0,0,0.7); position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999; align-items:center; justify-content:center;">
                        <span style="position:absolute;top:20px;right:40px;font-size:40px;color:#fff;cursor:pointer;" onclick="closeImageModal()">&times;</span>
                        <img id="imageModalTebuRobohImg" src="" style="max-width:90vw;max-height:90vh;display:block;margin:auto;box-shadow:0 0 20px #000;">
                    </div>

                    <div id="infoModalTebuRoboh" class="modal" tabindex="-1" role="dialog" style="display:none; background:rgba(0,0,0,0.7); position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999; align-items:center; justify-content:center;">
                        <span style="position:absolute;top:20px;right:40px;font-size:40px;color:#fff;cursor:pointer;" onclick="closeInfoModal()">&times;</span>
                        <div style="#ffffff00; padding:20px; border-radius:8px; max-width:600px; width:100%; box-shadow:none;">

                    </div>
                    <script>
                    function showImageModal(src) {
                        document.getElementById("imageModalTebuRoboh").style.display = "flex";
                        var imgElem = document.getElementById("imageModalTebuRobohImg");                        
                        var local = "/uploads/foto_tebu_roboh/" + src;
                        var cdn   = "' . rtrim(env('ASSET_CDN_URL'), '/') . '/uploads/foto_tebu_roboh/" + src;
                        imgElem.src = local;
                        imgElem.onerror = function() {
                            imgElem.src = cdn;
                        };
                    }
                    function closeImageModal() {
                        document.getElementById("imageModalTebuRoboh").style.display = "none";
                    }
                    function closeInfoModal() {
                        document.getElementById("infoModalTebuRoboh").style.display = "none";
                    }
                    // Close modal on background click
                    document.addEventListener("DOMContentLoaded", function() {
                        var modal = document.getElementById("imageModalTebuRoboh");
                        if(modal){
                            modal.addEventListener("click", function(e) {
                                if (e.target === modal) closeImageModal();
                            });
                        }
                    });

                    function showInfoPetak(lahanId, tanggal) {
                       
                    }
                    </script>
                    ';
                    $imageModalScriptAdded = true;
                }
                $cellClass = 'has-foto';
                } else {
                // $cell .= '<img src="/assets/images/noimage.png" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px; opacity:0.7;">';
                $cell .= '<img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; opacity:0.5;">';
                $cellClass = 'no-foto';
                }
                $cell .= '<span class="tanggal-cell">' . date('d M Y', strtotime($rowGroup[$mt]['tanggal'])) . ' <span class="" onclick="showInfoPetak(\''
                    . $lahan_id . '\', \'' . $rowGroup[$mt]['tanggal'] . '\')"><i class="fa fa-info-circle"></i></span></span>';
                $html .= '<td class="' . $cellClass . '">' . $cell . '</td>';
            } else {
                $html .= '<td class="no-foto2"><img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; opacity:0.5;"></td>';
            }
            }
            $html .= '</tr>';
        }
        $html .= '</tbody></table></div>';

        return response($html);
    }

    public function getRekapTebuBanjirDetail(Request $request)
    {
        $kode_kebun = $request->input('kebun');
        $kode_rayon = $request->input('rayon');
        $afd = $request->input('afd');
        $tahun = $request->input('tahun');

        $data = DB::table('q_rekap_tebu_banjir')
            
            ->when($kode_kebun, function ($query) use ($kode_kebun) {
                return $query->where('kode_kebun', $kode_kebun);
            })
            ->when($kode_rayon, function ($query) use ($kode_rayon) {
                return $query->where('kode_rayon', $kode_rayon);
            })
            ->when($afd, function ($query) use ($afd) {
                return $query->where('afd_new', $afd);
            })
            ->when($tahun, function ($query) use ($tahun) {
                return $query->whereYear('tanggal', $tahun);
            })
            ->get();

        $dir = 'uploads/foto_banjir';
        $files = [];
        // Ambil daftar file foto dari database, bukan dari folder
        $files = [];
        // Ambil daftar file foto dari database, join dengan master_petak
        $query = DB::table('tx_tebu_banjir')
            ->join('master_petak', 'tx_tebu_banjir.lahan_id', '=', 'master_petak.lahan_id')
            ->whereNotNull('tx_tebu_banjir.foto')
            ->select('tx_tebu_banjir.foto');

        if (!empty($kebun)) {
            $query->where('master_petak.plant', $kebun);
        }
        if (!empty($rayon)) {
            $query->where('master_petak.kode_rayon', $rayon);
        }
        if (!empty($afd)) {
            $query->where('master_petak.afd_new', $afd);
        }
        if (!empty($tahun)) {
            $query->whereYear('tx_tebu_banjir.tanggal', $tahun);
        }

        $fotoList = $query->groupBy('tx_tebu_banjir.foto')->pluck('tx_tebu_banjir.foto')->toArray();

     

        $groups = [];
        $masaTanamOrder = [
            '1A','1B','2A','2B','3A','3B','4A','4B','5A','5B','6A','6B','7A','7B','8A','8B','9A','9B','10A','10B','11A','11B','12A','12B'
        ];

        // Group data by lahan_id
        foreach ($data as $row) {
            $lahan_id = $row->lahan_id;
            $masa_tanam = $row->masa_tanam_group;

            if (!isset($groups[$lahan_id])) {
            $groups[$lahan_id] = [];
            }
            if (!isset($groups[$lahan_id]['nama_kebun'])) {
            $groups[$lahan_id]['nama_kebun'] = $row->nama_kebun;
            }
            if (!isset($groups[$lahan_id]['luas_polig'])) {
            $groups[$lahan_id]['luas_polig'] = $row->luas_polig;
            }
            if (!isset($groups[$lahan_id]['afd'])) {
            $groups[$lahan_id]['afd'] = $row->afd_new;
            }
            if (!isset($groups[$lahan_id]['bulan_tana'])) {
            $groups[$lahan_id]['bulan_tana'] = $row->bulan_tana;
            }
            $groups[$lahan_id][$masa_tanam] = [
            'tanggal' => $row->tanggal,
            'foto' => $row->foto,
            ];
        }

        // Mapping masa tanam ke nama bulan
        $bulanMap = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
            7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
        ];

        // Build HTML table
        $html = '<style>
            .morfologi-petak-table th, .morfologi-petak-table td {
            text-align: center;
            vertical-align: middle;
            font-size: 13px;
            }
            .morfologi-petak-table thead th {

            background: #2962FF;
            color: #fff;
            font-size: 13px;
            position: sticky;
            top: 0;
            z-index: 2;
            }

            .morfologi-petak-table tbody tr:nth-child(even) {
            background: #f6f9fc;
            }
            .morfologi-petak-table tbody tr:hover {
            background: #e3e8f0;
            transition: background 0.2s;
            }
            .morfologi-petak-table td {
            font-size: 13px;
            border: 1px solid #e0e0e0;
            }
            .morfologi-petak-table .has-foto {
            background: #eafaf1;
            }
            .morfologi-petak-table .no-foto {
            background: #ffeaea;
            }
            .morfologi-petak-table .no-foto2 {
            background: #f3f3f3;
            }
            .morfologi-petak-table .tanggal-cell {
            color: #007bff;
            font-weight: bold;
            font-size: 12px;
            display: block;
            margin-top: 3px;
            }
            .morfologi-petak-table .lahanid-cell {
            background: #f0f4ff;
            font-weight: bold;
            }
            .morfologi-petak-table .afd-cell {
            background: #f7f7e6;
            }
            ::-webkit-scrollbar {
            width: 10px;
            }

            /* Track */
            ::-webkit-scrollbar-track {
            background: #f1f1f1; 
            }
            
            /* Handle */
            ::-webkit-scrollbar-thumb {
            background: #888; 
            }

            /* Handle on hover */
            ::-webkit-scrollbar-thumb:hover {
            background: #555; 
            }
        </style>';

        $html .= '<div style="overflow-x:auto;">';
        $html .= '<table class="table table-bordered table-sm table-responsive morfologi-petak-table" style="height: 640px;">';

        // Baris bulan di atas
        $html .= '<thead style="position:sticky;top:0;z-index:10;">';
        $html .= '<tr>';
        $html .= '<th rowspan="2" class="">Lahan Id</th>';
        $html .= '<th rowspan="2" class="">Afd</th>';
        $html .= '<th rowspan="2" class="">Nama Kebun</th>';
        $html .= '<th rowspan="2" class="">Bulan Tanam</th>';

        // Baris bulan
        $prevBulan = '';
        $colspan = 0;
        $bulanHeader = '';
        foreach ($masaTanamOrder as $idx => $mt) {
            $bulanNum = intval(preg_replace('/[^0-9]/', '', $mt));
            $bulanNama = isset($bulanMap[$bulanNum]) ? $bulanMap[$bulanNum] : '';
            if ($bulanNama !== $prevBulan) {
            if ($colspan > 0) {
                $bulanHeader .= '<th colspan="' . $colspan . '" style="position:sticky;top:0;z-index:11;background:#2962FF;color:#fff;">' . $prevBulan . '</th>';
            }
            $prevBulan = $bulanNama;
            $colspan = 1;
            } else {
            $colspan++;
            }
            // Jika terakhir, tutup
            if ($idx === count($masaTanamOrder) - 1) {
            $bulanHeader .= '<th colspan="' . $colspan . '" style="position:sticky;top:0;z-index:11;background:#2962FF;color:#fff;">' . $bulanNama . '</th>';
            }
        }
        $html .= $bulanHeader;
        $html .= '</tr>';

        // Baris masa tanam (1A, 1B, dst)
        $html .= '<tr>';
        foreach ($masaTanamOrder as $mt) {
            $html .= '<th style="position:sticky;top:32px;z-index:12;background:#1565C0;color:#fff;">' . $mt . '</th>';
        }
        $html .= '</tr>';
        $html .= '</thead><tbody>';

        foreach ($groups as $lahan_id => $rowGroup) {
            $html .= '<tr>';
            // Freeze first three columns (Lahan Id, Afd, Nama Kebun) using inline style for sticky
            $html .= '<td class="lahanid-cell" style="position:sticky;left:0;z-index:3;background:#FFF;">' . $lahan_id . '</td>';
            $html .= '<td class="afd-cell" style="position:sticky;left:85px;z-index:3;background:#FFF;">' . (isset($rowGroup['afd']) ? htmlspecialchars($rowGroup['afd']) : '') . '</td>';
            $html .= '<td style="position:sticky;left:143px;z-index:3;background:#FFF;">' . (isset($rowGroup['nama_kebun']) ? htmlspecialchars($rowGroup['nama_kebun']) : '') . '</td>';
            $html .= '<td style="position:sticky;left:238px;z-index:3;background:#FFF;    border-right: 1px solid #0D47A1;">' . (isset($rowGroup['bulan_tana']) ? htmlspecialchars($rowGroup['bulan_tana']) : '') . '</td>';
            foreach ($masaTanamOrder as $mt) {
            if (isset($rowGroup[$mt])) {
                $cell = '';
                if (!empty($rowGroup[$mt]['foto'])) {
                $fotoName = htmlspecialchars($rowGroup[$mt]['foto']);
                $localThumb = '/uploads/foto_tebu_banjir/thumb_' . $fotoName;
                $cdnThumb   = env('ASSET_CDN_URL') . '/uploads/foto_tebu_banjir/thumb_' . $fotoName;

                // cek file lokal
                $thumbSrc = file_exists(public_path('uploads/foto_tebu_banjir/thumb_' . $rowGroup[$mt]['foto']))
                    ? $localThumb
                    : $cdnThumb;

                $cell .= '<a href="javascript:void(0);" onclick="showImageModal(\'' . htmlspecialchars($rowGroup[$mt]['foto']) . '\')">
                <img src="'.$thumbSrc.'" alt="Foto" 
                style="max-width: 100px; max-height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;">
                </a>';
                //$cell .= '<a href="javascript:void(0);" onclick="showImageModal(\'https://asset.nikochannel.com/uploads/foto_banjir/' . htmlspecialchars($rowGroup[$mt]['foto']) . '\')"><img src="https://asset.nikochannel.com/uploads/foto_banjir/thumb_' . htmlspecialchars($rowGroup[$mt]['foto']) . '" alt="Foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;"></a>';
                // Tambahkan modal hanya sekali di luar loop (bisa di bawah tabel)
                if (!isset($imageModalScriptAdded)) {
                    $html .= '
                    <div id="imageModalTebuBanjir" class="modal" tabindex="-1" role="dialog" style="display:none; background:rgba(0,0,0,0.7); position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999; align-items:center; justify-content:center;">
                        <span style="position:absolute;top:20px;right:40px;font-size:40px;color:#fff;cursor:pointer;" onclick="closeImageModal()">&times;</span>
                        <img id="imageModalTebuBanjirImg" src="" style="max-width:90vw;max-height:90vh;display:block;margin:auto;box-shadow:0 0 20px #000;">
                    </div>

                    <div id="infoModalTebuBanjir" class="modal" tabindex="-1" role="dialog" style="display:none; background:rgba(0,0,0,0.7); position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999; align-items:center; justify-content:center;">
                        <span style="position:absolute;top:20px;right:40px;font-size:40px;color:#fff;cursor:pointer;" onclick="closeInfoModal()">&times;</span>
                        <div style="#ffffff00; padding:20px; border-radius:8px; max-width:600px; width:100%; box-shadow:none;">

                    </div>
                    <script>
                    function showImageModal(src) {

                        document.getElementById("imageModalTebuBanjir").style.display = "flex";
                        var imgElem = document.getElementById("imageModalTebuBanjirImg");                        
                        var local = "/uploads/foto_tebu_banjir/" + src;
                        var cdn   = "' . rtrim(env('ASSET_CDN_URL'), '/') . '/uploads/foto_tebu_banjir/" + src;
                        imgElem.src = local;
                        imgElem.onerror = function() {
                            imgElem.src = cdn;
                        };

                    }
                    function closeImageModal() {
                        document.getElementById("imageModalTebuBanjir").style.display = "none";
                    }
                    function closeInfoModal() {
                        document.getElementById("infoModalTebuBanjir").style.display = "none";
                    }
                    // Close modal on background click
                    document.addEventListener("DOMContentLoaded", function() {
                        var modal = document.getElementById("imageModalTebuBanjir");
                        if(modal){
                            modal.addEventListener("click", function(e) {
                                if (e.target === modal) closeImageModal();
                            });
                        }
                    });

                    function showInfoPetak(lahanId, tanggal) {
                       
                    }
                    </script>
                    ';
                    $imageModalScriptAdded = true;
                }
                $cellClass = 'has-foto';
                } else {
                // $cell .= '<img src="/assets/images/noimage.png" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px; opacity:0.7;">';
                $cell .= '<img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; opacity:0.5;">';
                $cellClass = 'no-foto';
                }
                $cell .= '<span class="tanggal-cell">' . date('d M Y', strtotime($rowGroup[$mt]['tanggal'])) . ' <span class="" onclick="showInfoPetak(\''
                    . $lahan_id . '\', \'' . $rowGroup[$mt]['tanggal'] . '\')"><i class="fa fa-info-circle"></i></span></span>';
                $html .= '<td class="' . $cellClass . '">' . $cell . '</td>';
            } else {
                $html .= '<td class="no-foto2"><img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px;width: 100px; height: 100px; opacity:0.5;"></td>';
            }
            }
            $html .= '</tr>';
        }
        $html .= '</tbody></table></div>';

        return response($html);
    }


    public function getLastMorfologiByLahanId(Request $request)
    {
        $lahan_id = $request->input('lahan_id');
        $tanggal = $request->input('tanggal');
        if (empty($lahan_id)) {
            return response()->json(['status' => 'error', 'message' => 'lahan_id is required'], 400);
        }

        $data = DB::table('tx_morfologi')
            ->where('lahan_id', $lahan_id)
            ->where('tanggal', $tanggal)
            ->whereNotNull('foto')
            ->orderByDesc('tanggal')
            ->first();

        return response()->json([
            'status' => 'success',
            'data' => $data
        ]);
    }

     public function getRekapLKPPetakDetail(Request $request)
    {
        config(['app.debug' => true]);
        $kode_kebun = $request->input('kebun');
        $kode_rayon = $request->input('rayon');
        $afd = $request->input('afd');
        $pekerjaan_filter = $request->input('pekerjaan');
        $tahun = $request->input('tahun');
        $bulan = $request->input('bulan');
        $jenis_report = $request->input('jenis_report');

        $data = DB::table('q_rekap_lkp_petak_detail')
            ->when($kode_kebun, function ($query) use ($kode_kebun) {
                return $query->where('kode_kebun', $kode_kebun);
            })
            ->when($kode_rayon, function ($query) use ($kode_rayon) {
                return $query->where('kode_rayon', $kode_rayon);
            })
            ->when($afd, function ($query) use ($afd) {
                return $query->where('afd_new', $afd);
            })
            ->when($tahun, function ($query) use ($tahun) {
                return $query->whereYear('tanggal', $tahun);
            })
            ->when($bulan, function ($query) use ($bulan) {
                return $query->whereMonth('tanggal', $bulan);
            })
            ->get();

        $dir = 'uploads/foto_kebun';
            $files = [];
            // Ambil daftar file foto dari database, bukan dari folder
            $files = [];
            $query = DB::table('tx_foto_kebun')
            ->join('master_petak', 'tx_foto_kebun.lahan_id', '=', 'master_petak.lahan_id')
            ->whereNotNull('tx_foto_kebun.foto');

            if (!empty($kebun)) {
            $query->where('master_petak.plant', $kebun);
            }
            if (!empty($rayon)) {
            $query->where('master_petak.kode_rayon', $rayon);
            }
            if (!empty($afd)) {
                $query->where('master_petak.afd_new', $afd);
            }
            if (!empty($tahun)) {
                $query->whereYear('tx_foto_kebun.tanggal', $tahun);
            }

            $fotoList = $query->groupBy('tx_foto_kebun.foto')->pluck('tx_foto_kebun.foto')->toArray();

    //    foreach ($fotoList as $foto) {
    //        $filePath = $dir . '/' . $foto;
    //        if (file_exists($filePath)) {
    //        $files[] = $filePath;
    //        }
    //    }
//
    //    foreach ($files as $file) {
    //        $thumbPath = $dir . '/thumb_' . basename($file);
    //        if (!file_exists($thumbPath)) {
    //            try {
    //                $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    //                if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'jfif'])) {
    //                    $img = null;
    //                    if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'jfif') {
    //                        $img = @imagecreatefromjpeg($file);
    //                    } elseif ($ext === 'png') {
    //                        $img = @imagecreatefrompng($file);
    //                    } elseif ($ext === 'gif') {
    //                        $img = @imagecreatefromgif($file);
    //                    }
    //                    if ($img) {
    //                        $width = imagesx($img);
    //                        $height = imagesy($img);
    //                        $thumbWidth = 200;
    //                        $thumbHeight = intval($height * $thumbWidth / $width);
    //                        $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
    //                        imagecopyresampled($thumbImg, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
    //                        if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'jfif') {
    //                            imagejpeg($thumbImg, $thumbPath, 80);
    //                        } elseif ($ext === 'png') {
    //                            imagepng($thumbImg, $thumbPath, 8);
    //                        } elseif ($ext === 'gif') {
    //                            imagegif($thumbImg, $thumbPath);
    //                        }
    //                        imagedestroy($thumbImg);
    //                        imagedestroy($img);
    //                    }
    //                }
    //            } catch (\Exception $e) {
    //                // Ignore errors
    //            }
    //        }
    //    }    

        $groups = [];
        
        // Tentukan apakah grouping berdasarkan tanggal atau lahan_id
        if ($jenis_report == 1) {
            // Group data by tanggal (untuk laporan bulanan)
            foreach ($data as $row) {
            $tanggal = $row->tanggal;
            $bulan = date('m', strtotime($tanggal));
            $tahun = date('Y', strtotime($tanggal));
            $key = $bulan . '-' . $tahun;

            if (!isset($groups[$key])) {
                $groups[$key] = [
                'tanggal_display' => date('F Y', strtotime($tanggal)),
                'items' => []
                ];
            }
            $groups[$key]['items'][] = $row;
            }
        } else {
            // Group data by lahan_id (original behavior)
            foreach ($data as $row) {
            $lahan_id = $row->lahan_id;
            $pekerjaan = $row->pekerjaan;

            if (!isset($groups[$lahan_id])) {
                $groups[$lahan_id] = [];
            }
            if (!isset($groups[$lahan_id]['nama_kebun'])) {
                $groups[$lahan_id]['nama_kebun'] = $row->nama_kebun;
            }
            if (!isset($groups[$lahan_id]['luas_polig'])) {
                $groups[$lahan_id]['luas_polig'] = $row->luas_polig;
            }
            if (!isset($groups[$lahan_id]['afd'])) {
                $groups[$lahan_id]['afd'] = $row->afd_new;
            }
            if (!isset($groups[$lahan_id]['kualitas'])) {
                $groups[$lahan_id]['kualitas'] = $row->kualitas;
            }
            $groups[$lahan_id][$pekerjaan] = [
                'tanggal' => $row->tanggal,
                'foto' => $row->foto,
            ];
            }
        }

        // Ambil urutan pekerjaan dari tabel master_pekerjaan
        if (is_array($pekerjaan_filter)) {
            $pekerjaanList = $pekerjaan_filter;
        } elseif (!empty($pekerjaan_filter)) {
            $pekerjaanList = [$pekerjaan_filter];
        } else {
            $pekerjaanList = '';
        }
        $pekerjaanOrder = DB::table('master_pekerjaan')
            ->when(!empty($pekerjaanList), function ($query) use ($pekerjaanList) {
            return $query->whereIn('pekerjaan', $pekerjaanList);
            })
            ->orderBy('kode_pekerjaan')
            ->pluck('pekerjaan')
            ->toArray();



        // Build HTML table
        $html = '<style>
            .lkp-petak-table th, .lkp-petak-table td {
            text-align: center;
            vertical-align: middle;
            font-size: 13px;
            }
            .lkp-petak-table thead th {
            background: linear-gradient(90deg, #3345a1 0%, #4c4c80 100%);
            color: #fff;
            font-size: 13px;
            position: sticky;
            top: 0;
            z-index: 2;
            }
            .lkp-petak-table tbody tr:nth-child(even) {
            background: #f6f9fc;
            }
            .lkp-petak-table tbody tr:hover {
            background: #e3e8f0;
            transition: background 0.2s;
            }
            .lkp-petak-table td {
            font-size: 13px;
            border: 1px solid #e0e0e0;
            }
            .lkp-petak-table .has-foto {
            background: #eafaf1;
            }
            .lkp-petak-table .no-foto {
            background: #ffeaea;
            }
            .lkp-petak-table .no-foto2 {
            background: #f3f3f3;
            }
            .lkp-petak-table .tanggal-cell {
            color: #007bff;
            font-weight: bold;
            font-size: 12px;
            display: block;
            margin-top: 3px;
            }
            .lkp-petak-table .lahanid-cell {
            background: #f0f4ff;
            font-weight: bold;
            }
            .lkp-petak-table .afd-cell {
            background: #f7f7e6;
            }
            ::-webkit-scrollbar {
            width: 10px;
            }
            ::-webkit-scrollbar-track {
            background: #f1f1f1; 
            }
            ::-webkit-scrollbar-thumb {
            background: #888; 
            }
            ::-webkit-scrollbar-thumb:hover {
            background: #555; 
            }
        </style>';

        $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-sm table-responsive lkp-petak-table" style="height: 640px;">';

        if ($jenis_report == 1) {
            // Format untuk laporan bulanan
            // Ambil bulan dan tahun dari tanggal pertama dalam groups
            $firstDate = null;
            foreach ($groups as $groupData) {
            if (!empty($groupData['items'])) {
                $firstDate = $groupData['items'][0]->tanggal;
                break;
            }
            }
            
            // Generate tanggal-tanggal dalam bulan
            if ($firstDate) {
            $month = date('m', strtotime($firstDate));
            $year = date('Y', strtotime($firstDate));
            $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
            $pekerjaanOrder = [];
            for ($day = 1; $day <= $daysInMonth; $day++) {
                $pekerjaanOrder[] = str_pad($day, 2, '0', STR_PAD_LEFT);
            }
            }
            
            $html .= '<thead style="position:sticky;top:0;z-index:10;">';
            $html .= '<tr>';
            $html .= '<th class="">Tanggal</th>';
            $html .= '<th class="">Lahan ID</th>';
            $html .= '<th class="">Afd</th>';
            $html .= '<th class="">Nama Kebun</th>';
            foreach ($pekerjaanOrder as $day) {
            $html .= '<th>' . $day . '</th>';
            }
            $html .= '</tr>';
            $html .= '</thead><tbody>';

            foreach ($groups as $key => $groupData) {
            $html .= '<tr>';
            $html .= '<td style="background:#e8f4f8;font-weight:bold;">' . $groupData['tanggal_display'] . '</td>';
            $html .= '<td colspan="' . (3 + count($pekerjaanOrder)) . '"></td>';
            $html .= '</tr>';

            foreach ($groupData['items'] as $row) {
                $html .= '<tr>';
                $html .= '<td style="color:#666;">' . date('d-m-Y', strtotime($row->tanggal)) . '</td>';
                $html .= '<td class="lahanid-cell" style="position:sticky;left:0;z-index:3;background:#f0f4ff;">' . $row->lahan_id . '</td>';
                $html .= '<td class="afd-cell" style="position:sticky;left:78px;z-index:3;background:#f7f7e6;">' . htmlspecialchars($row->afd_new) . '</td>';
                $html .= '<td style="position:sticky;left:194px;z-index:3;background:#fff;">' . htmlspecialchars($row->nama_kebun) . '</td>';
                
                $rowDay = date('d', strtotime($row->tanggal));
                foreach ($pekerjaanOrder as $day) {
                $cell = '';
                if ($rowDay == $day && !empty($row->foto)) {
                    $fotoName = htmlspecialchars($row->foto);
                    $localThumb = '/uploads/foto_kebun/thumb_' . $fotoName;
                    $cdnThumb   = env('ASSET_CDN_URL') . '/uploads/foto_kebun/thumb_' . $fotoName;
                    $thumbSrc = file_exists(public_path('uploads/foto_kebun/thumb_' . $row->foto))
                    ? $localThumb
                    : $cdnThumb;
                    $cell .= '<a href="javascript:void(0);" onclick="showImageModallkp(\'' . $fotoName . '\')">
                    <img src="'.$thumbSrc.'" alt="Foto" 
                    style="max-width: 100px; max-height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;">
                    </a>';
                    $cell .= '<span class="tanggal-cell">' . date('d M Y', strtotime($row->tanggal)) . '</span>';
                    $html .= '<td class="has-foto">' . $cell . '</td>';
                } else {
                    $html .= '<td class="no-foto2"><img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px; opacity:0.5;"></td>';
                }
                }
                $html .= '</tr>';
            }
            }
        } else {
            // Format original (group by lahan_id)
            $html .= '<thead style="position:sticky;top:0;z-index:10;">';
            $html .= '<tr>';
            $html .= '<th class="">Lahan Id</th>';
            $html .= '<th class="">Afd</th>';
            $html .= '<th class="">Nama Kebun</th>';
            foreach ($pekerjaanOrder as $mt) {
            $html .= '<th>' . ucwords(str_replace('_', ' ', $mt)) . '</th>';
            }
            $html .= '</tr>';
            $html .= '</thead><tbody>';

            foreach ($groups as $lahan_id => $rowGroup) {
            $html .= '<tr>';
            $html .= '<td class="lahanid-cell" style="position:sticky;left:0;z-index:3;background:#f0f4ff;">' . $lahan_id . '</td>';
            $html .= '<td class="afd-cell" style="position:sticky;left:78px;z-index:3;background:#f7f7e6;">' . (isset($rowGroup['afd']) ? htmlspecialchars($rowGroup['afd']) : '') . '</td>';
            $html .= '<td style="position:sticky;left:194px;z-index:3;background:#fff;">' . (isset($rowGroup['nama_kebun']) ? htmlspecialchars($rowGroup['nama_kebun']) : '') . '</td>';
            
            foreach ($pekerjaanOrder as $mt) {
                if (isset($rowGroup[$mt])) {
                $cell = '';
                if (!empty($rowGroup[$mt]['foto'])) {
                    $fotoName = htmlspecialchars($rowGroup[$mt]['foto']);
                    $localThumb = '/uploads/foto_kebun/thumb_' . $fotoName;
                    $cdnThumb   = env('ASSET_CDN_URL') . '/uploads/foto_kebun/thumb_' . $fotoName;
                    $thumbSrc = file_exists(public_path('uploads/foto_kebun/thumb_' . $rowGroup[$mt]['foto']))
                    ? $localThumb
                    : $cdnThumb;
                    $cell .= '<a href="javascript:void(0);" onclick="showImageModallkp(\'' . $fotoName . '\')">
                    <img src="'.$thumbSrc.'" alt="Foto" 
                    style="max-width: 100px; max-height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;">
                    </a>';
                    $cell .= '<span class="tanggal-cell">' . date('d M Y', strtotime($rowGroup[$mt]['tanggal'])) . '</span>';
                    $cellClass = 'has-foto';
                    $kualitas = isset($rowGroup['kualitas']) ? $rowGroup['kualitas'] : '';
                    $kualitasColor = '';
                    $kualitasEmoji = '';

                    if ($kualitas == 'Baik') {
                        $kualitasColor = '#28a745';
                        $kualitasEmoji = '🟢';
                    } elseif ($kualitas == 'Sedang') {
                        $kualitasColor = '#ffc107';
                        $kualitasEmoji = '🟡';
                    } elseif ($kualitas == 'Kurang') {
                        $kualitasColor = '#dc3545';
                        $kualitasEmoji = '🔴';
                    }

                    $cell .= '<span class="tanggal-cell" style="background-color:' . $kualitasColor . ';padding:4px;border-radius:4px;color:white;">' . $kualitasEmoji . ' ' . htmlspecialchars($kualitas) . '</span>';
                    $html .= '<td class="has-foto">' . $cell . '</td>';
                } else {
                    $html .= '<td class="no-foto"><img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px; opacity:0.5;"></td>';
                }
                } else {
                $html .= '<td class="no-foto2"><img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px; opacity:0.5;"></td>';
                }
            }
            $html .= '</tr>';
            }
        }

        $html .= '</tbody></table></div>';

        // Modal script
        if (!isset($imageModalScriptAdded)) {
            $html .= '
            <div id="imageModalKebunlkp" class="modal" tabindex="-1" role="dialog" style="display:none; background:rgba(0,0,0,0.7); position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999; align-items:center; justify-content:center;">
            <span style="position:absolute;top:20px;right:40px;font-size:40px;color:#fff;cursor:pointer;" onclick="closeImageModal()">&times;</span>
            <img id="imageModalKebunImglkp" src="" style="max-width:90vw;max-height:90vh;display:block;margin:auto;box-shadow:0 0 20px #000;">
            </div>
            <script>
            function showImageModallkp(src) {
            document.getElementById("imageModalKebunlkp").style.display = "flex";
            var imgElem = document.getElementById("imageModalKebunImglkp");                        
            var local = "/uploads/foto_kebun/" + src;
            var cdn   = "' . rtrim(env('ASSET_CDN_URL'), '/') . '/uploads/foto_kebun/" + src;
            imgElem.src = local;
            imgElem.onerror = function() {
                imgElem.src = cdn;
            };
            }
            function closeImageModal() {
            document.getElementById("imageModalKebunlkp").style.display = "none";
            }
            document.addEventListener("DOMContentLoaded", function() {
            var modal = document.getElementById("imageModalKebunlkp");
            if(modal){
                modal.addEventListener("click", function(e) {
                if (e.target === modal) closeImageModal();
                });
            }
            });
            </script>
            ';
            $imageModalScriptAdded = true;
        }

        return response($html);
    }

    public function getRekapDronePetakDetail(Request $request)
    {
        config(['app.debug' => true]);
        $kode_kebun = $request->input('kebun');
        $kode_rayon = $request->input('rayon');
        $afd = $request->input('afd');
        $tahun = $request->input('tahun');

        $data = DB::table('q_rekap_drone_petak_detail2')
            ->when($kode_kebun, function ($query) use ($kode_kebun) {
                return $query->where('kode_kebun', $kode_kebun);
            })
            ->when($kode_rayon, function ($query) use ($kode_rayon) {
                return $query->where('kode_rayon', $kode_rayon);
            })
            ->when($afd, function ($query) use ($afd) {
                return $query->where('afd_new', $afd);
            })
            ->when($tahun, function ($query) use ($tahun) {
                return $query->whereYear('tanggal', $tahun);
            })  
            ->get();

            $dir = 'uploads/foto_drone';
            $files = [];
            // Ambil daftar file foto dari database, bukan dari folder
            $files = [];
            $query = DB::table('tx_foto_drone')
                ->join('master_petak', 'tx_foto_drone.lahan_id', '=', 'master_petak.lahan_id')
                ->whereNotNull('tx_foto_drone.foto');

            if (!empty($kebun)) {
                $query->where('master_petak.plant', $kebun);
            }
            if (!empty($rayon)) {
                $query->where('master_petak.kode_rayon', $rayon);
            }
            if (!empty($afd)) {
                $query->where('master_petak.afd_new', $afd);
            }
            if (!empty($tahun)) {
                $query->whereYear('tx_foto_drone.tanggal', $tahun);
            }

            $fotoList = $query->groupBy('tx_foto_drone.foto')->pluck('tx_foto_drone.foto')->toArray();

        //foreach ($fotoList as $foto) {
        //    $filePath = $dir . '/' . $foto;
        //    if (file_exists($filePath)) {
        //    $files[] = $filePath;
        //    }
        //}
//
        //foreach ($files as $file) {
        //    $thumbPath = $dir . '/thumb_' . basename($file);
        //    if (!file_exists($thumbPath)) {
        //
//
        //        try {
        //            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        //            if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'jfif'])) {
        //                $img = null;
        //                if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'jfif') {
        //                    $img = @imagecreatefromjpeg($file);
        //                } elseif ($ext === 'png') {
        //                    //$img = @imagecreatefrompng($file);
        //                    $img = @imagecreatefromjpeg($file);
        //                    // $img = @imagecreatefrompng($file);
        //                } elseif ($ext === 'gif') {
        //                    $img = @imagecreatefromgif($file);
        //                }
        //                if ($img) {
        //                    $width = imagesx($img);
        //                    $height = imagesy($img);
        //                    $thumbWidth = 200;
        //                    $thumbHeight = intval($height * $thumbWidth / $width);
        //                    $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
        //                    imagecopyresampled($thumbImg, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
        //                    if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'jfif') {
        //                        imagejpeg($thumbImg, $thumbPath, 80);
        //                    } elseif ($ext === 'png') {
        //                        imagepng($thumbImg, $thumbPath, 8);
        //                    } elseif ($ext === 'gif') {
        //                        imagegif($thumbImg, $thumbPath);
        //                    }
        //                    imagedestroy($thumbImg);
        //                    imagedestroy($img);
        //                }
        //            }
        //        } catch (\Exception $e) {
        //            // Ignore errors
 //
        //        }
        //    }
        //}    

        $groups = [];
        $masaTanamOrder = [
            '1A','1B','2A','2B','3A','3B','4A','4B','5A','5B','6A','6B','7A','7B','8A','8B','9A','9B','10A','10B','11A','11B','12A','12B'
        ];

        // Group data by lahan_id
        foreach ($data as $row) {
            $lahan_id = $row->lahan_id;
            $masa_tanam = $row->masa_tanam_group;


            if (!isset($groups[$lahan_id])) {
            $groups[$lahan_id] = [];
            }
            if (!isset($groups[$lahan_id]['nama_kebun'])) {
            $groups[$lahan_id]['nama_kebun'] = $row->nama_kebun;
            }
            if (!isset($groups[$lahan_id]['luas_polig'])) {
            $groups[$lahan_id]['luas_polig'] = $row->luas_polig;
            }
            if (!isset($groups[$lahan_id]['afd'])) {
            $groups[$lahan_id]['afd'] = $row->afd_new;
            }
            $groups[$lahan_id][$masa_tanam] = [
            'tanggal' => $row->tanggal,
            'foto' => $row->foto,
            ];
        }

        // Mapping masa tanam ke nama bulan
        $bulanMap = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 5 => 'Mei', 6 => 'Juni',
            7 => 'Juli', 8 => 'Agustus', 9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
        ];

        // Build HTML table
        $html = '<style>
            .morfologi-petak-table th, .morfologi-petak-table td {
            text-align: center;
            vertical-align: middle;
            font-size: 13px;
            }
            .morfologi-petak-table thead th {
            background: linear-gradient(90deg, #3345a1 0%, #4c4c80 100%);
            color: #fff;
            font-size: 13px;
            position: sticky;
            top: 0;
            z-index: 2;
            }
            .morfologi-petak-table tbody tr:nth-child(even) {
            background: #f6f9fc;
            }
            .morfologi-petak-table tbody tr:hover {
            background: #e3e8f0;
            transition: background 0.2s;
            }
            .morfologi-petak-table td {
            font-size: 13px;
            border: 1px solid #e0e0e0;
            }
            .morfologi-petak-table .has-foto {
            background: #eafaf1;
            }
            .morfologi-petak-table .no-foto {
            background: #ffeaea;
            }
            .morfologi-petak-table .no-foto2 {
            background: #f3f3f3;
            }
            .morfologi-petak-table .tanggal-cell {
            color: #007bff;
            font-weight: bold;
            font-size: 12px;
            display: block;
            margin-top: 3px;
            }
            .morfologi-petak-table .lahanid-cell {
            background: #f0f4ff;
            font-weight: bold;
            }
            .morfologi-petak-table .afd-cell {
            background: #f7f7e6;
            }
        </style>';

        $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-sm table-responsive morfologi-petak-table" style="height: 640px;">';

        // Baris bulan di atas
        $html .= '<thead style="position:sticky;top:0;z-index:10;">';
        $html .= '<tr>';
        $html .= '<th rowspan="2" class="">Lahan Id</th>';
        $html .= '<th rowspan="2" class="">Afd</th>';
        $html .= '<th rowspan="2" class="">Nama Kebun</th>';

        // Baris bulan
        $prevBulan = '';
        $colspan = 0;
        $bulanHeader = '';
        foreach ($masaTanamOrder as $idx => $mt) {
            $bulanNum = intval(preg_replace('/[^0-9]/', '', $mt));
            $bulanNama = isset($bulanMap[$bulanNum]) ? $bulanMap[$bulanNum] : '';
            if ($bulanNama !== $prevBulan) {
            if ($colspan > 0) {
                $bulanHeader .= '<th colspan="' . $colspan . '" style="position:sticky;top:0;z-index:11;background:#3345a1;color:#fff;">' . $prevBulan . '</th>';
            }
            $prevBulan = $bulanNama;
            $colspan = 1;
            } else {
            $colspan++;
            }
            // Jika terakhir, tutup
            if ($idx === count($masaTanamOrder) - 1) {
            $bulanHeader .= '<th colspan="' . $colspan . '" style="position:sticky;top:0;z-index:11;background:#3345a1;color:#fff;">' . $bulanNama . '</th>';
            }
        }
        $html .= $bulanHeader;
        $html .= '</tr>';

        // Baris masa tanam (1A, 1B, dst)
        $html .= '<tr>';
        foreach ($masaTanamOrder as $mt) {
            $html .= '<th style="position:sticky;top:32px;z-index:12;background:#4c4c80;color:#fff;">' . $mt . '</th>';
        }
        $html .= '</tr>';
        $html .= '</thead><tbody>';

        foreach ($groups as $lahan_id => $rowGroup) {
            $html .= '<tr>';
            // Freeze first three columns (Lahan Id, Afd, Nama Kebun) using inline style for sticky
            $html .= '<td class="lahanid-cell" style="position:sticky;left:0;z-index:3;background:#f0f4ff;">' . $lahan_id . '</td>';
            $html .= '<td class="afd-cell" style="position:sticky;left:78px;z-index:3;background:#f7f7e6;">' . (isset($rowGroup['afd']) ? htmlspecialchars($rowGroup['afd']) : '') . '</td>';
            $html .= '<td style="position:sticky;left:194px;z-index:3;background:#fff;">' . (isset($rowGroup['nama_kebun']) ? htmlspecialchars($rowGroup['nama_kebun']) : '') . '</td>';
            foreach ($masaTanamOrder as $mt) {
            if (isset($rowGroup[$mt])) {
                   
                      $getdatafoto = DB::table('q_rekap_drone_petak_detail2')
                     ->select(
                         'lahan_id',
                         DB::raw('GROUP_CONCAT(foto) as foto'),
                         DB::raw('GROUP_CONCAT(tanggal) as tanggal'),
                         DB::raw('count(*) as jml')
                     )
                     ->whereRaw('masa_tanam_group COLLATE utf8mb4_unicode_ci = ? COLLATE utf8mb4_unicode_ci', [$mt])
                     ->whereYear('tanggal', $tahun)
                     ->where('lahan_id', $lahan_id)
                     ->groupBy('lahan_id')
                     ->first();

                $cell = '';
                if (!empty($getdatafoto->foto)) {
                //$cell .= '<a href="javascript:void(0);" onclick="showImageModal3(\'' . htmlspecialchars($getdatafoto->foto) . '\')"><img src="/uploads/foto_drone/thumb_' . htmlspecialchars($rowGroup[$mt]['foto']) . '" alt="Foto" style="max-width: 100px; max-height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;"></a>';
                $fotoName = htmlspecialchars($rowGroup[$mt]['foto']);
                $localThumb = '/uploads/foto_drone/thumb_' . $fotoName;
                $cdnThumb   = env('ASSET_CDN_URL') . '/uploads/foto_drone/thumb_' . $fotoName;

                // cek file lokal
                $thumbSrc = file_exists(public_path('uploads/foto_drone/thumb_' . $rowGroup[$mt]['foto']))
                    ? $localThumb
                    : $cdnThumb;

                $cell .= '<a href="javascript:void(0);" onclick="showImageModal3(\'' . htmlspecialchars($getdatafoto->foto) . '\')">
                <img src="'.$thumbSrc.'" alt="Foto" 
                style="max-width: 100px; max-height: 100px; border-radius:6px; box-shadow:0 2px 8px #bbb;">
                </a>';
                // Tambahkan modal hanya sekali di luar loop (bisa di bawah tabel)
                if (!isset($imageModalScriptAdded)) {
                    $html .= '
                    <div id="imageModalFotoDrone2" class="modal" tabindex="-1" role="dialog" style="display:none; background:rgba(0,0,0,0.7); position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999; align-items:center; justify-content:center;">
                        <span style="position:absolute;top:20px;right:40px;font-size:40px;color:#fff;cursor:pointer;" onclick="closeImageModal3()">&times;</span>
                        <img id="imageModalFotoDrone" src="" style="max-width:90vw;max-height:90vh;display:block;margin:auto;box-shadow:0 0 20px #000;">
                    </div>
                    <script>
                    function showImageModal3(src) {
                        // Jika src berisi koma, berarti ada beberapa foto (slide show)
                        var images = src.split(",");
                        var currentIndex = 0;
                        var modal = document.getElementById("imageModalFotoDrone2");
                        var imgElem = document.getElementById("imageModalFotoDrone");

                        function showCurrentImage() {
                                var local = "/uploads/foto_drone/" + images[currentIndex].trim();
                                var cdn   = "' . rtrim(env('ASSET_CDN_URL'), '/') . '/uploads/foto_drone/" + images[currentIndex].trim();

                                imgElem.src = local;
                                imgElem.onerror = function() {
                                    imgElem.src = cdn;
                                };   
                        }

                        // Tampilkan modal dan gambar pertama
                        showCurrentImage();
                        modal.style.display = "flex";

                        // Hapus tombol jika sudah ada
                        var prevBtn = document.getElementById("dronePrevBtn");
                        var nextBtn = document.getElementById("droneNextBtn");
                        if (prevBtn) prevBtn.remove();
                        if (nextBtn) nextBtn.remove();

                        // Jika lebih dari satu gambar, tambahkan tombol prev/next
                        if (images.length > 1) {
                            var btnPrev = document.createElement("button");
                            btnPrev.id = "dronePrevBtn";
                            btnPrev.innerHTML = "&lt;";
                            btnPrev.style.position = "absolute";
                            btnPrev.style.left = "30px";
                            btnPrev.style.top = "50%";
                            btnPrev.style.transform = "translateY(-50%)";
                            btnPrev.style.fontSize = "30px";
                            btnPrev.style.background = "#fff";
                            btnPrev.style.border = "none";
                            btnPrev.style.borderRadius = "50%";
                            btnPrev.style.width = "40px";
                            btnPrev.style.height = "40px";
                            btnPrev.style.cursor = "pointer";
                            btnPrev.style.zIndex = "10000";
                            btnPrev.onclick = function() {
                                currentIndex = (currentIndex - 1 + images.length) % images.length;
                                showCurrentImage();
                            };
                            modal.appendChild(btnPrev);

                            var btnNext = document.createElement("button");
                            btnNext.id = "droneNextBtn";
                            btnNext.innerHTML = "&gt;";
                            btnNext.style.position = "absolute";
                            btnNext.style.right = "30px";
                            btnNext.style.top = "50%";
                            btnNext.style.transform = "translateY(-50%)";
                            btnNext.style.fontSize = "30px";
                            btnNext.style.background = "#fff";
                            btnNext.style.border = "none";
                            btnNext.style.borderRadius = "50%";
                            btnNext.style.width = "40px";
                            btnNext.style.height = "40px";
                            btnNext.style.cursor = "pointer";
                            btnNext.style.zIndex = "10000";
                            btnNext.onclick = function() {
                                currentIndex = (currentIndex + 1) % images.length;
                                showCurrentImage();
                            };
                            modal.appendChild(btnNext);
                        }
                    }
                    function closeImageModal3() {
                        document.getElementById("imageModalFotoDrone2").style.display = "none";
                    }
                    // Close modal on background click
                    document.addEventListener("DOMContentLoaded", function() {
                        var modal = document.getElementById("imageModalFotoDrone2");
                        if(modal){
                            modal.addEventListener("click", function(e) {
                                if (e.target === modal) closeImageModal3();
                            });
                        }
                    });
                    </script>
                    ';
                    $imageModalScriptAdded = true;
                }
                $cellClass = 'has-foto';
                } else {
                $cell .= '<img src="/assets/images/noimage.png" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px; opacity:0.7;">';
                $cellClass = 'no-foto';
                }
                $cell .= '<span class="tanggal-cell">' . date('d M Y', strtotime($rowGroup[$mt]['tanggal'])) . '</span>';
                $cell .= '<span class="tanggal-cell" style="font-size:11px;color:#28a745;font-weight:bold;">Jumlah Foto: ' . ($getdatafoto ? $getdatafoto->jml : 0) . '</span>';
                $html .= '<td class="' . $cellClass . '">' . $cell . '</td>';
            } else {
                $html .= '<td class="no-foto2"><img src="/assets/images/noimage2.jpg" alt="Tidak ada foto" style="max-width: 100px; max-height: 100px; opacity:0.5;"></td>';
            }
            }
            $html .= '</tr>';
        }
        $html .= '</tbody></table></div>';

        return response($html);
    }

    public function swipeboxgallery(Request $request){
        $kebun = $request->input('kebun', ''); // Default to empty string if not provided
        $rayon = $request->input('rayon', ''); // Default to empty string if not provided
        $afd = $request->input('afd', ''); // Default to empty string if not provided
        return view('dashboard.swipeboxgallery', [
            'kebun' => $kebun,
            'rayon' => $rayon,
            'afd' => $afd
        ]);
    }

    public function swipeboxgallery2(Request $request){
        $kebun = $request->input('kebun', ''); // Default to empty string if not provided
        $rayon = $request->input('rayon', ''); // Default to empty string if not provided
        $afd = $request->input('afd', ''); // Default to empty string if not provided
        return view('dashboard.swipeboxgallery2', [
            'kebun' => $kebun,
            'rayon' => $rayon,
            'afd' => $afd
        ]);
    }
    public function swipeboxgallery3(Request $request){
        $kebun = $request->input('kebun', ''); // Default to empty string if not provided
        $rayon = $request->input('rayon', ''); // Default to empty string if not provided
        $afd = $request->input('afd', ''); // Default to empty string if not provided
        return view('dashboard.swipeboxgallery3', [
            'kebun' => $kebun,
            'rayon' => $rayon,
            'afd' => $afd
        ]);
    }    

    public function dataswipebox(Request $request){
        $type = $request->input('type', 1); // Default to 1 if not provided
        $kebun = $request->input('kebun', ''); // Default to empty string if not provided
        $rayon = $request->input('rayon', ''); // Default to empty
        $afd = $request->input('afd', ''); // Default to empty string if not provided

        // Ambil daftar nama kebun dan nama rayon dari tabel master_kebun dan master_rayon
        $namaKebunList = DB::table('master_kebun')
            ->when(!empty($kebun), function ($query) use ($kebun) {
            return $query->where('kode_kebun', $kebun);
            })
            ->pluck('nama_kebun')
            ->first();
        $namaRayonList = DB::table('master_rayon')
            ->when(!empty($rayon), function ($query) use ($rayon) {
            return $query->where('kode_rayon', $rayon);
            })
            ->pluck('nama_rayon')
            ->first();

        if ($type == 1) {         
            $dir = 'uploads/foto_morfologi';
            $files = [];
            // Ambil daftar file foto dari database, bukan dari folder
            $files = [];
            // Ambil daftar file foto dari database, join dengan master_petak
            $query = DB::table('tx_morfologi')
                ->join('master_petak', 'tx_morfologi.lahan_id', '=', 'master_petak.lahan_id')
                ->whereNotNull('tx_morfologi.foto')
                ->select('tx_morfologi.foto');

            if (!empty($kebun)) {
                $query->where('master_petak.plant', $kebun);
            }
            if (!empty($rayon)) {
                $query->where('master_petak.kode_rayon', $rayon);
            }
            if (!empty($afd)) {
                $query->where('master_petak.afd_new', $afd);
            }

            $fotoList = $query->groupBy('tx_morfologi.foto')->pluck('tx_morfologi.foto')->toArray();
        }else if ($type == 2) {
            $dir = 'uploads/foto_kebun';
            $files = [];
            // Ambil daftar file foto dari database, bukan dari folder
            $files = [];
            $query = DB::table('tx_foto_kebun')
            ->join('master_petak', 'tx_foto_kebun.lahan_id', '=', 'master_petak.lahan_id')
            ->whereNotNull('tx_foto_kebun.foto');

            if (!empty($kebun)) {
            $query->where('master_petak.plant', $kebun);
            }
            if (!empty($rayon)) {
            $query->where('master_petak.kode_rayon', $rayon);
            }
            if (!empty($afd)) {
                $query->where('master_petak.afd_new', $afd);
            }

            $fotoList = $query->groupBy('tx_foto_kebun.foto')->pluck('tx_foto_kebun.foto')->toArray();

        } else if ($type == 3) {
            $dir = 'uploads/foto_drone';
            $files = [];
            // Ambil daftar file foto dari database, bukan dari folder
            $files = [];
            $query = DB::table('tx_foto_drone')
                ->join('master_petak', 'tx_foto_drone.lahan_id', '=', 'master_petak.lahan_id')
                ->whereNotNull('tx_foto_drone.foto');

            if (!empty($kebun)) {
                $query->where('master_petak.plant', $kebun);
            }
            if (!empty($rayon)) {
                $query->where('master_petak.kode_rayon', $rayon);
            }
            if (!empty($afd)) {
                $query->where('master_petak.afd_new', $afd);
            }

            $fotoList = $query->groupBy('tx_foto_drone.foto')->pluck('tx_foto_drone.foto')->toArray();
        } else {
            return response()->json(['error' => 'Invalid type'], 400);
        }


        foreach ($fotoList as $foto) {
            $filePath = $dir . '/' . $foto;
            if (file_exists($filePath)) {
            $files[] = $filePath;
            }
        }

        foreach ($files as $file) {
            $thumbPath = $dir . '/thumb_' . basename($file);
            if (!file_exists($thumbPath)) {
                try {
                    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
                        $img = null;
                        if ($ext === 'jpg' || $ext === 'jpeg') {
                            $img = @imagecreatefromjpeg($file);
                        } elseif ($ext === 'png') {
                            $img = @imagecreatefrompng($file);
                        } elseif ($ext === 'gif') {
                            $img = @imagecreatefromgif($file);
                        }
                        if ($img) {
                            $width = imagesx($img);
                            $height = imagesy($img);
                            $thumbWidth = 200;
                            $thumbHeight = intval($height * $thumbWidth / $width);
                            $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
                            imagecopyresampled($thumbImg, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $width, $height);
                            if ($ext === 'jpg' || $ext === 'jpeg') {
                                imagejpeg($thumbImg, $thumbPath, 80);
                            } elseif ($ext === 'png') {
                                imagepng($thumbImg, $thumbPath, 8);
                            } elseif ($ext === 'gif') {
                                imagegif($thumbImg, $thumbPath);
                            }
                            imagedestroy($thumbImg);
                            imagedestroy($img);
                        }
                    }
                } catch (\Exception $e) {
                    // Ignore errors
                }
            }
        }

        $files = array_filter($files, function($file) use ($dir) {
            $thumbPath = $dir . '/thumb_' . basename($file);
            return file_exists($thumbPath);
        });


        $data = [];
        $thumbs = [];
        $large = [];
        foreach ($files as $f) {
            $thumbPath = $dir . '/thumb_' . basename($f);
            $thumbUrl = str_replace('dashboard/', '', $thumbPath);
            $largeUrl = str_replace('dashboard/', '', $f);
            $data[] = [
            'thumb' => $thumbUrl,
            'large' => $largeUrl
            ];
            $thumbs[] = $thumbUrl;
            $large[] = $largeUrl;
        }


        
        return response()->json([
            'data' => $data,
            'nama_kebun' => empty($kebun) ? 'Semua Kebun' : $namaKebunList,
            'nama_rayon' => empty($rayon) ? 'Semua Rayon' : $namaRayonList,
        ]);


    }

    public function getDetailFotoTitle(Request $request)
    {
        $foto = $request->input('foto');
        $data = [];

        if ($foto) {
            $data = DB::select("
                select * from (
                    select
                        mp.lahan_id,
                        CASE 
                            WHEN tm.foto != '' THEN mp.nama_kebun
                            WHEN tf.foto != '' THEN concat(mp.nama_kebun,'<br>',tf.pekerjaan)
                            WHEN tfd.foto != '' THEN mp.nama_kebun	
                            ELSE mp.nama_kebun
                        END as nama_kebun,
                        mp.rayon,
                        CASE 
                            WHEN tm.foto != '' THEN tm.foto
                            WHEN tf.foto != '' THEN tf.foto
                            WHEN tfd.foto != '' THEN tfd.foto	
                            ELSE tm.foto
                        END as foto
                    from master_petak mp 
                    left join tx_morfologi tm on tm.lahan_id = mp.lahan_id and tm.foto = ?
                    left join tx_foto_kebun tf on tf.lahan_id = mp.lahan_id and tf.foto = ?
                    left join tx_foto_drone tfd on tfd.lahan_id = mp.lahan_id and tfd.foto = ?
                    where mp.lahan_id != 0 
                ) as z where z.foto != ''
            ", [$foto, $foto, $foto]);

            if (!empty($data)) {
                $data = (array) $data[0];
            }
        }

        return response()->json([
            'status' => 'success',
            'data' => $data,
        ]);
    }

public function getDataProtasRendemen(Request $request)
{
    $tgl1 = $request->input('tgl1');
    $tgl2 = $request->input('tgl2');
    $rayonId = $request->input('nama_rayon');


    // Fetch data from the stored procedure with additional filters
    if (empty($rayonId)) {
        $data = DB::select('call GetDataProtasRendemen(?, ?)', [$tgl1, $tgl2]);
    } else {
        $data = DB::select('call GetDataProtasRendemenRayon(?, ?, ?)', [$tgl1, $tgl2, urldecode($rayonId)]);
    }

    // Map the data into a collection for Highcharts
    $chartData = collect($data)->map(function ($item) {
        return [
            'tgl_giling' => date_format(date_create($item->tgl_giling), "d M"),
            'protas' => (float) str_replace(',', '.', $item->protas),
            'rendemen' => (float) str_replace(',', '.', $item->rendemen),
            'rendemen_takmar' => (float) str_replace(',', '.', $item->rendemen_takmar),
        ];
    });

    // Prepare data for Highcharts
    $categories = $chartData->pluck('tgl_giling')->toArray();
    $protasData = $chartData->pluck('protas')->toArray();
    $rendemenData = $chartData->pluck('rendemen')->toArray();
    $rendemenTakmarData = $chartData->pluck('rendemen_takmar')->toArray();

    // Return the data formatted for Highcharts
    return response()->json([
        'status' => 'success',
        'tgl_giling' => $categories,
                'protas' => $protasData,
                'rendemen' => $rendemenData,
                'rendemen_takmar' => $rendemenTakmarData,
    ]);
}

public function getRendVsMutu(Request $request){
    		
    $rayonId = $request->input('nama_rayon', '');
    $kebunId = $request->input('nama_kebun', '');
    if(!empty($kebunId) && empty($rayonId)){
        $data = DB::select('call GetRendemenVsMutuKebun(?)', [urldecode($kebunId)]);        
    }else if(!empty($kebunId) && !empty($rayonId)){
        $data = DB::select('call GetRendemenVsMutu(?)', [urldecode($rayonId)]);
    }else{
        $data = DB::select('call GetRendemenVsMutuTotal()');
    }
    

    // Prepare data for the line charts
    $chartData = [
        'categories' => ['A', 'B', 'C', 'D', 'E', 'F'], // Labels for the x-axis
        'rend' => [
            (float) $data[0]->rend_a,
            (float) $data[0]->rend_b,
            (float) $data[0]->rend_c,
            (float) $data[0]->rend_d,
            (float) $data[0]->rend_e,
            (float) $data[0]->rend_f,
        ],
        'mutu' => [
            (float) $data[0]->mutu_a,
            (float) $data[0]->mutu_b,
            (float) $data[0]->mutu_c,
            (float) $data[0]->mutu_d,
            (float) $data[0]->mutu_e,
            (float) $data[0]->mutu_f,
        ],
    ];

    // Return the data formatted for the line charts
    return response()->json([
        'status' => 'success',
        'data' => $chartData,
    ]);

}

public function getPasokHarianKebun(Request $request){
    $tgl = $request->input('tgl');
    $kebunId = $request->input('nama_kebun');

    // Fetch data from the stored procedure with additional filters
    // if (!empty($kebunId)) {
        $data = DB::select('call sp_pasok_harian_kebun(?, ?)', [$kebunId, $tgl]);
    // }

    // Map the data into a collection for Highcharts
    $chartData = collect($data)->map(function ($item) {
        return
        [
            'tgl_timbang' => date_format(date_create($item->tgl_timbang), "d M"),
            'sasaran' => (float) str_replace(',', '.', $item->sasaran_harian) ?: 0,
            'real' => (float) str_replace(',', '.', $item->real_hi) ?: 0,
        ];
    });

    // Prepare data for Highcharts
    $categories = $chartData->pluck('tgl_timbang')->toArray();
    $sasaranData = $chartData->pluck('sasaran')->toArray();
    $realData = $chartData->pluck('real')->toArray();

    // Return the data formatted for Highcharts
    return response()->json([
        'status' => 'success',
        'tgl_timbang' => $categories,
        'sasaran' => $sasaranData,
        'real' => $realData,
    ]);

}

public function getPasokHarianRayon(Request $request){
    $tgl = $request->input('tgl');
    $kebunId = $request->input('nama_kebun');

    // Fetch data from the stored procedure with additional filters
    if (!empty($kebunId)) {
        $data = DB::select('call sp_pasok_harian_rayon(?, ?)', [$kebunId, $tgl]);
    }

    // Map the data into a collection for Highcharts
    $chartData = collect($data)->map(function ($item) {
        return [
            'tgl_timbang' => date_format(date_create($item->tgl_timbang), "d M"),
            'sasaran' => (float) str_replace(',', '.', $item->sasaran_harian) ?: 0,
            'real' => (float) str_replace(',', '.', $item->real_hi) ?: 0,
        ];
    });

    // Prepare data for Highcharts
    $categories = $chartData->pluck('tgl_timbang')->toArray();
    $sasaranData = $chartData->pluck('sasaran')->toArray();
    $realData = $chartData->pluck('real')->toArray();

    // Return the data formatted for Highcharts
    return response()->json([
        'status' => 'success',
        'tgl_timbang' => $categories,
        'sasaran' => $sasaranData,
        'real' => $realData,
    ]);

}

public function getRendVsMutuPerhari(Request $request){
    $tgl1 = $request->input('tgl1');
    $tgl2 = $request->input('tgl2');
    $rayonId = $request->input('nama_rayon');
    $mutu = $request->input('mutu'); // Filter by 'a', 'b', 'c', 'd', or 'e'

    $data = DB::select('call GetRendemenVsMutuPerhari(?,?,?)', [urldecode($rayonId), $tgl1, $tgl2]);

    // Prepare data for the line charts filtered by the selected mutu
    $categories = collect($data)->pluck('tgl_giling')->map(function ($date) {
        return date('d M', strtotime($date));
    })->toArray();
    $rendKey = 'rend_' . strtolower($mutu);
    $mutuKey = 'mutu_' . strtolower($mutu);

    $chartData = [
        'categories' => $categories, // Dates for the x-axis
        'rend' => collect($data)->pluck($rendKey)->map(function ($value) {
            return (float) $value;
        })->toArray(),
        'mutu' => collect($data)->pluck($mutuKey)->map(function ($value) {
            return (float) $value;
        })->toArray(),
    ];

    // Return the data formatted for the line charts
    return response()->json([
        'status' => 'success',
        'data' => $chartData,
    ]);

}

public function getRendVsMutuPerhari24vs25(Request $request){
    $tgl1 = $request->input('tgl1');
    $rayonId = $request->input('nama_rayon');

    $data = DB::select('call sp_get_mutu_rayon2(?,?,?)', [urldecode($rayonId), $this->tahun, $tgl1]);

    $tanggalStopGiling = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('nama_rayon', $rayonId)
        ->where('tahun_giling', $this->tahun)
        ->value('tanggal_stop_giling');

    $tanggalStopGiling2 = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('nama_rayon', $rayonId)
        ->where('tahun_giling', $this->tahun_sebelumnya)
        ->value('tanggal_stop_giling');    
        

        if ($tanggalStopGiling) {
            $tanggalStopGiling = date('Y-m-d', strtotime($tanggalStopGiling));
        } else {
            $tanggalStopGiling = ''; // Set to null if not found
        }
        if ($tanggalStopGiling2) {
            $tanggalStopGiling2 = date('Y-m-d', strtotime($tanggalStopGiling2));
        } else {
            $tanggalStopGiling2 = ''; // Set to null if not found
        }
    $data2 = DB::select('CALL sp_get_filtered_date_range3(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun,
        $tanggalStopGiling,
        $tgl1
    ]);

    $data2 = collect($data2)->filter(function ($item) use ($tgl1) {
        return strtotime($item->tanggal) >= strtotime($tgl1);
    });

    $urut = collect($data2)->map(function ($item) {
        return $item->urut;
    })->toArray();

    $data3 = DB::select('CALL sp_get_filtered_date_range3(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun_sebelumnya,
        $tanggalStopGiling2,
        null
    ]);


    $data3 = collect($data3)->filter(function ($item) use ($urut) {
        return in_array($item->urut, $urut);
    });
    

    $tgl24 = collect($data3)->map(function ($item) {
        return $item->tanggal;
    })->toArray();

            // dd($data2);
    $firstKey = array_key_first($tgl24);
    $firstValue = isset($tgl24[$firstKey]) ? $tgl24[$firstKey] : null;

    $hg = array_key_first($urut);
    $hari_giling = isset($urut[$hg]) ? $urut[$hg] : null;

        $data4 = DB::select('call sp_get_mutu_rayon3(?, ?, ?)', [urldecode($rayonId), $this->tahun_sebelumnya, $firstValue]);
    // dd($data4);

    if (empty($data)) {
        return response()->json(['status' => 'error', 'message' => 'No data found'], 404);
    }

    

    if (empty($data)) {
        // Provide dummy data if $data is empty
        $chartData = [
            'categories' => ['A', 'B', 'C', 'D', 'E'], // Labels for the x-axis
            'mutu' => [0, 0, 0, 0, 0], // Dummy values
            'mutu2' => [0, 0, 0, 0, 0], // Dummy values
            'hari_giling' => ['No Data'], // Dummy value
        ];
    } else {
        $chartData = [
            'categories' => ['A', 'B', 'C', 'D', 'E', 'F'], // Labels for the x-axis
            'mutu' => [
                (float) $data[0]->mutu_a,
                (float) $data[0]->mutu_b,
                (float) $data[0]->mutu_c,
                (float) $data[0]->mutu_d,
                (float) $data[0]->mutu_e,
                (float) $data[0]->mutu_f,
            ],
            'mutu2' => [
                (float) $data4[0]->mutu_a,
                (float) $data4[0]->mutu_b,
                (float) $data4[0]->mutu_c,
                (float) $data4[0]->mutu_d,
                (float) $data4[0]->mutu_e,
                (float) $data4[0]->mutu_f,
            ],
            'hari_giling' => [
                $hari_giling
            ],
        ];
    }



    // Return the data formatted for the line charts
    return response()->json([
        'status' => 'success',
        'data' => $chartData,
    ]);

}

public function getRendVsMutuPerhari24vs25Kebun(Request $request){
    $tgl1 = $request->input('tgl1');
    $rayonId = $request->input('nama_rayon');

    $data = DB::select('call sp_get_mutu_kebun(?,?,?)', [urldecode($rayonId), $this->tahun, $tgl1]);

    $tanggalStopGiling = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('nama_kebun', $rayonId)
        ->where('tahun_giling', $this->tahun)
        ->value('tanggal_stop_giling');

    $tanggalStopGiling2 = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('nama_kebun', $rayonId)
        ->where('tahun_giling', $this->tahun_sebelumnya)
        ->value('tanggal_stop_giling');    
        

        if ($tanggalStopGiling) {
            $tanggalStopGiling = date('Y-m-d', strtotime($tanggalStopGiling));
        } else {
            $tanggalStopGiling = ''; // Set to null if not found
        }
        if ($tanggalStopGiling2) {
            $tanggalStopGiling2 = date('Y-m-d', strtotime($tanggalStopGiling2));
        } else {
            $tanggalStopGiling2 = ''; // Set to null if not found
        }
    $data2 = DB::select('CALL sp_get_filtered_date_range_kebun(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun,
        $tanggalStopGiling,
        $tgl1
    ]);

    $data2 = collect($data2)->filter(function ($item) use ($tgl1) {
        return strtotime($item->tanggal) >= strtotime($tgl1);
    });

    $urut = collect($data2)->map(function ($item) {
        return $item->urut;
    })->toArray();

    $data3 = DB::select('CALL sp_get_filtered_date_range_kebun(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun_sebelumnya,
        $tanggalStopGiling2,
        null
    ]);


    $data3 = collect($data3)->filter(function ($item) use ($urut) {
        return in_array($item->urut, $urut);
    });
    

    $tgl24 = collect($data3)->map(function ($item) {
        return $item->tanggal;
    })->toArray();

            // dd($data2);
    $firstKey = array_key_first($tgl24);
    $firstValue = isset($tgl24[$firstKey]) ? $tgl24[$firstKey] : null;

    $hg = array_key_first($urut);
    $hari_giling = isset($urut[$hg]) ? $urut[$hg] : null;


    $datainyear =  $request->input('tgl1', date('Y-m-d', strtotime(date('Y-m-d') . ' -1 day')));
    $data2 = DB::select('CALL sp_real_2025_hgsama_by2026(?, ?)', [$datainyear, $rayonId]); 
    $hgpg = collect($data2)->firstWhere('uraian', 'hg');

        $data4 = DB::select('call sp_get_mutu_kebun2(?, ?, ?)', [urldecode($rayonId), $this->tahun_sebelumnya, $firstValue]);
    // dd($data4);

    if (empty($data)) {
        return response()->json(['status' => 'error', 'message' => 'No data found'], 404);
    }

    

    if (empty($data)) {
        // Provide dummy data if $data is empty
        $chartData = [
            'categories' => ['A', 'B', 'C', 'D', 'E','F'], // Labels for the x-axis
            'mutu' => [0, 0, 0, 0, 0, 0], // Dummy values
            'mutu2' => [0, 0, 0, 0, 0, 0], // Dummy values
            'hari_giling' => ['No Data'], // Dummy value
        ];
    } else {
        $chartData = [
            'categories' => ['A', 'B', 'C', 'D', 'E','F'], // Labels for the x-axis
            'mutu' => [
                (float) $data[0]->mutu_a,
                (float) $data[0]->mutu_b,
                (float) $data[0]->mutu_c,
                (float) $data[0]->mutu_d,
                (float) $data[0]->mutu_e,
                (float) $data[0]->mutu_f,
            ],
            'mutu2' => [
                (float) $data4[0]->mutu_a,
                (float) $data4[0]->mutu_b,
                (float) $data4[0]->mutu_c,
                (float) $data4[0]->mutu_d,
                (float) $data4[0]->mutu_e,
                (float) $data4[0]->mutu_f,
            ],
            'hari_giling' => [
                (float)($hgpg->{'2025'} ?? 0)
            ],
        ];
    }



    // Return the data formatted for the line charts
    return response()->json([
        'status' => 'success',
        'data' => $chartData,
    ]);

}

public function getRendVsMutuPerhari24vs25total(Request $request){
    $tgl1 = $request->input('tgl1');
    $rayonId = $request->input('nama_rayon');

   $data = DB::select('call sp_get_mutu_total(?,?,?)', [urldecode($rayonId), $this->tahun, $tgl1]);

    $tanggalStopGiling = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('tahun_giling', $this->tahun)
        ->value('tanggal_stop_giling');

    $tanggalStopGiling2 = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('tahun_giling', $this->tahun_sebelumnya)
        ->value('tanggal_stop_giling');    
        

        // if ($tanggalStopGiling) {
        //     $tanggalStopGiling = date('Y-m-d', strtotime($tanggalStopGiling));
        // } else {
            $tanggalStopGiling = ''; // Set to null if not found
        // }
        // if ($tanggalStopGiling2) {
        //     $tanggalStopGiling2 = date('Y-m-d', strtotime($tanggalStopGiling2));
        // } else {
            $tanggalStopGiling2 = ''; // Set to null if not found
        // }
    $data2 = DB::select('CALL sp_get_filtered_date_range_total(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun,
        $tanggalStopGiling,
        $tgl1
    ]);

    $data2 = collect($data2)->filter(function ($item) use ($tgl1) {
        return strtotime($item->tanggal) >= strtotime($tgl1);
    });

    $urut = collect($data2)->map(function ($item) {
        return $item->urut;
    })->toArray();

    $data3 = DB::select('CALL sp_get_filtered_date_range_total(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun_sebelumnya,
        $tanggalStopGiling2,
        null
    ]);


    $data3 = collect($data3)->filter(function ($item) use ($urut) {
        return in_array($item->urut, $urut);
    });
    

    $tgl24 = collect($data3)->map(function ($item) {
        return $item->tanggal;
    })->toArray();

            // dd($data2);
    $firstKey = array_key_first($tgl24);
    $firstValue = isset($tgl24[$firstKey]) ? $tgl24[$firstKey] : null;

    $hg = array_key_first($urut);
    $hari_giling = isset($urut[$hg]) ? $urut[$hg] : null;

        $data4 = DB::select('call sp_get_mutu_total2(?, ?, ?)', [urldecode($rayonId), $this->tahun_sebelumnya, $tgl1]);
    // dd($data4);

    if (empty($data)) {
        return response()->json(['status' => 'error', 'message' => 'No data found'], 404);
    }

    

if (empty($data)) {
        // Provide dummy data if $data is empty
        $chartData = [
            'categories' => ['A', 'B', 'C', 'D', 'E', 'F'], // Labels for the x-axis
            'mutu' => [0, 0, 0, 0, 0], // Dummy values
            'mutu2' => [0, 0, 0, 0, 0], // Dummy values
            'hari_giling' => ['No Data'], // Dummy value
        ];
    } else {
        $chartData = [
            'categories' => ['A', 'B', 'C', 'D', 'E', 'F'], // Labels for the x-axis
            'mutu' => [
                (float) $data[0]->mutu_a,
                (float) $data[0]->mutu_b,
                (float) $data[0]->mutu_c,
                (float) $data[0]->mutu_d,
                (float) $data[0]->mutu_e,
                (float) $data[0]->mutu_f,
            ],
            'mutu2' => [
                (float) $data4[0]->mutu_a,
                (float) $data4[0]->mutu_b,
                (float) $data4[0]->mutu_c,
                (float) $data4[0]->mutu_d,
                (float) $data4[0]->mutu_e,
                (float) $data4[0]->mutu_f,
            ],
            'hari_giling' => [
                $hari_giling
            ],
        ];
    }




    // Return the data formatted for the line charts
    return response()->json([
        'status' => 'success',
        'data' => $chartData,
    ]);

}

public function getRendVsMutuPerhari24vs25Terbakar(Request $request){
    $tgl1 = $request->input('tgl1');
    $rayonId = $request->input('nama_rayon');

    $data = DB::select('call sp_get_mutu_rayon2(?,?,?)', [urldecode($rayonId), $this->tahun, $tgl1]);

    $tanggalStopGiling = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('nama_rayon', $rayonId)
        ->where('tahun_giling', $this->tahun)
        ->value('tanggal_stop_giling');

    $tanggalStopGiling2 = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('nama_rayon', $rayonId)
        ->where('tahun_giling', $this->tahun_sebelumnya)
        ->value('tanggal_stop_giling');    
        

        if ($tanggalStopGiling) {
            $tanggalStopGiling = date('Y-m-d', strtotime($tanggalStopGiling));
        } else {
            $tanggalStopGiling = ''; // Set to null if not found
        }
        if ($tanggalStopGiling2) {
            $tanggalStopGiling2 = date('Y-m-d', strtotime($tanggalStopGiling2));
        } else {
            $tanggalStopGiling2 = ''; // Set to null if not found
        }
    $data2 = DB::select('CALL sp_get_filtered_date_range3(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun,
        $tanggalStopGiling,
        $tgl1
    ]);

    $data2 = collect($data2)->filter(function ($item) use ($tgl1) {
        return strtotime($item->tanggal) >= strtotime($tgl1);
    });

    $urut = collect($data2)->map(function ($item) {
        return $item->urut;
    })->toArray();

    $data3 = DB::select('CALL sp_get_filtered_date_range3(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun_sebelumnya,
        $tanggalStopGiling2,
        null
    ]);


    $data3 = collect($data3)->filter(function ($item) use ($urut) {
        return in_array($item->urut, $urut);
    });
    

    $tgl24 = collect($data3)->map(function ($item) {
        return $item->tanggal;
    })->toArray();

            // dd($data2);
    $firstKey = array_key_first($tgl24);
    $firstValue = isset($tgl24[$firstKey]) ? $tgl24[$firstKey] : null;

    $hg = array_key_first($urut);
    $hari_giling = isset($urut[$hg]) ? $urut[$hg] : null;

        $data4 = DB::select('call sp_get_mutu_rayon3(?, ?, ?)', [urldecode($rayonId), $this->tahun_sebelumnya, $tgl1]);
    // dd($data4);

    if (empty($data)) {
        return response()->json(['status' => 'error', 'message' => 'No data found'], 404);
    }

    
    if (empty($data) || empty($data4)) {
        // Provide dummy data if $data or $data4 is empty
        $chartData = [
            'categories' => ['A', 'B', 'C', 'D', 'E'], // Labels for the x-axis
            'mutu' => [0, 0, 0, 0, 0], // Dummy values
            'mutu2' => [0, 0, 0, 0, 0], // Dummy values
            'hari_giling' => ['No Data'], // Dummy value
        ];
    } else {
        $chartData = [
            'categories' => ['E'], // Labels for the x-axis
            'mutu' => [
                (float) $data[0]->mutu_e,
            ],
            'mutu2' => [
                (float) $data4[0]->mutu_e,
            ],
            'hari_giling' => [
                $hari_giling
            ],
        ];
    }


    // Return the data formatted for the line charts
    return response()->json([
        'status' => 'success',
        'data' => $chartData,
    ]);

}

public function getRendVsMutuPerhari24vs25Terbakarkebun(Request $request){
    $tgl1 = $request->input('tgl1');
    $rayonId = $request->input('nama_rayon');

   $data = DB::select('call sp_get_mutu_kebun(?,?,?)', [urldecode($rayonId), $this->tahun, $tgl1]);

    $tanggalStopGiling = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('nama_kebun', $rayonId)
        ->where('tahun_giling', $this->tahun)
        ->value('tanggal_stop_giling');

    $tanggalStopGiling2 = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('nama_kebun', $rayonId)
        ->where('tahun_giling', $this->tahun_sebelumnya)
        ->value('tanggal_stop_giling');    
        

        if ($tanggalStopGiling) {
            $tanggalStopGiling = date('Y-m-d', strtotime($tanggalStopGiling));
        } else {
            $tanggalStopGiling = ''; // Set to null if not found
        }
        if ($tanggalStopGiling2) {
            $tanggalStopGiling2 = date('Y-m-d', strtotime($tanggalStopGiling2));
        } else {
            $tanggalStopGiling2 = ''; // Set to null if not found
        }
    $data2 = DB::select('CALL sp_get_filtered_date_range_kebun(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun,
        $tanggalStopGiling,
        $tgl1
    ]);

    $data2 = collect($data2)->filter(function ($item) use ($tgl1) {
        return strtotime($item->tanggal) >= strtotime($tgl1);
    });

    $urut = collect($data2)->map(function ($item) {
        return $item->urut;
    })->toArray();

    $data3 = DB::select('CALL sp_get_filtered_date_range_kebun(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun_sebelumnya,
        $tanggalStopGiling2,
        null
    ]);


    $data3 = collect($data3)->filter(function ($item) use ($urut) {
        return in_array($item->urut, $urut);
    });
    

    $tgl24 = collect($data3)->map(function ($item) {
        return $item->tanggal;
    })->toArray();

            // dd($data2);
    $firstKey = array_key_first($tgl24);
    $firstValue = isset($tgl24[$firstKey]) ? $tgl24[$firstKey] : null;

    $hg = array_key_first($urut);
    $hari_giling = isset($urut[$hg]) ? $urut[$hg] : null;

        $data4 = DB::select('call sp_get_mutu_kebun2(?, ?, ?)', [urldecode($rayonId), $this->tahun_sebelumnya, $firstValue]);
    // dd($data4);

    if (empty($data)) {
        return response()->json(['status' => 'error', 'message' => 'No data found'], 404);
    }

    

    if (empty($data)) {
        // Provide dummy data if $data is empty
        $chartData = [
            'categories' => ['E'], // Labels for the x-axis
            'mutu' => [0], // Dummy values
            'mutu2' => [0], // Dummy values
            'hari_giling' => ['No Data'], // Dummy value
        ];
    } else {
        $chartData = [
            'categories' => ['E'], // Labels for the x-axis
            'mutu' => [

                (float) $data[0]->mutu_e,
            ],
            'mutu2' => [
                (float) $data4[0]->mutu_e,
            ],
            'hari_giling' => [
                $hari_giling
            ],
        ];
    }



    // Return the data formatted for the line charts
    return response()->json([
        'status' => 'success',
        'data' => $chartData,
    ]);

}

public function getRendVsMutuPerhari24vs25Terbakartotal(Request $request){
    $tgl1 = $request->input('tgl1');
    $rayonId = $request->input('nama_rayon');

   $data = DB::select('call sp_get_mutu_total(?,?,?)', [urldecode($rayonId), $this->tahun, $tgl1]);

    $tanggalStopGiling = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('tahun_giling', $this->tahun)
        ->value('tanggal_stop_giling');

    $tanggalStopGiling2 = DB::table('master_tanggal_awalgiling_kebun_kso')
        ->where('tahun_giling', $this->tahun_sebelumnya)
        ->value('tanggal_stop_giling');    
        

        // if ($tanggalStopGiling) {
        //     $tanggalStopGiling = date('Y-m-d', strtotime($tanggalStopGiling));
        // } else {
            $tanggalStopGiling = ''; // Set to null if not found
        // }
        // if ($tanggalStopGiling2) {
        //     $tanggalStopGiling2 = date('Y-m-d', strtotime($tanggalStopGiling2));
        // } else {
            $tanggalStopGiling2 = ''; // Set to null if not found
        // }
    $data2 = DB::select('CALL sp_get_filtered_date_range_total(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun,
        $tanggalStopGiling,
        $tgl1
    ]);

    $data2 = collect($data2)->filter(function ($item) use ($tgl1) {
        return strtotime($item->tanggal) >= strtotime($tgl1);
    });

    $urut = collect($data2)->map(function ($item) {
        return $item->urut;
    })->toArray();

    $data3 = DB::select('CALL sp_get_filtered_date_range_total(?, ?, ?, ?)', [
        urldecode($rayonId),
        $this->tahun_sebelumnya,
        $tanggalStopGiling2,
        null
    ]);


    $data3 = collect($data3)->filter(function ($item) use ($urut) {
        return in_array($item->urut, $urut);
    });
    

    $tgl24 = collect($data3)->map(function ($item) {
        return $item->tanggal;
    })->toArray();

            // dd($data2);
    $firstKey = array_key_first($tgl24);
    $firstValue = isset($tgl24[$firstKey]) ? $tgl24[$firstKey] : null;

    $hg = array_key_first($urut);
    $hari_giling = isset($urut[$hg]) ? $urut[$hg] : null;

        $data4 = DB::select('call sp_get_mutu_total2(?, ?, ?)', [urldecode($rayonId), $this->tahun_sebelumnya, $tgl1]);
    // dd($data4);

    if (empty($data)) {
        return response()->json(['status' => 'error', 'message' => 'No data found'], 404);
    }

    

    if (empty($data)) {
        // Provide dummy data if $data is empty
        $chartData = [
            'categories' => ['E'], // Labels for the x-axis
            'mutu' => [0], // Dummy values
            'mutu2' => [0], // Dummy values
            'hari_giling' => ['No Data'], // Dummy value
        ];
    } else {
        $chartData = [
            'categories' => ['E'], // Labels for the x-axis
            'mutu' => [

                (float) $data[0]->mutu_e,
            ],
            'mutu2' => [
                (float) $data4[0]->mutu_e,
            ],
            'hari_giling' => [
                $hari_giling
            ],
        ];
    }



    // Return the data formatted for the line charts
    return response()->json([
        'status' => 'success',
        'data' => $chartData,
    ]);

}



public function getRendVsMutuPerhariKebun(Request $request){
    $tgl1 = $request->input('tgl1');
    $tgl2 = $request->input('tgl2');
    $rayonId = $request->input('nama_rayon');
    $mutu = $request->input('mutu'); // Filter by 'a', 'b', 'c', 'd', or 'e'

    $data = DB::select('call GetRendemenVsMutuPerhariKebun(?,?,?)', [urldecode($rayonId), $tgl1, $tgl2]);

    // Prepare data for the line charts filtered by the selected mutu
    $categories = collect($data)->pluck('tgl_giling')->map(function ($date) {
        return date('d M', strtotime($date));
    })->toArray();
    $rendKey = 'rend_' . strtolower($mutu);
    $mutuKey = 'mutu_' . strtolower($mutu);

    $chartData = [
        'categories' => $categories, // Dates for the x-axis
        'rend' => collect($data)->pluck($rendKey)->map(function ($value) {
            return (float) $value;
        })->toArray(),
        'mutu' => collect($data)->pluck($mutuKey)->map(function ($value) {
            return (float) $value;
        })->toArray(),
    ];

    // Return the data formatted for the line charts
    return response()->json([
        'status' => 'success',
        'data' => $chartData,
    ]);

}

public function getLkpPerRayon(Request $request)
{
    $tgl1 = $request->input('tgl1');
    $tgl2 = $request->input('tgl2');
    $rayonId = $request->input('rayon_id');
       $periode = $request->input('periode'); 
       $kategori = $request->input('kategori'); // Tambahkan input kategori jika diperlukan




// if(\Session::get('gid')<3)
//         {
// 		// Memanggil stored procedure
// 		$data = DB::table('q_lkp_rekap_dashboard')
//             ->select('pekerjaan', 'hektar')
//             ->get();
//                     $data = $data->map(function($item) {
//     // Replace commas with dots and convert hektar to float
//     $item->hektar = (float) str_replace(',', '.', $item->hektar);
//     return $item;
    
// });
// } else {
    	$data = DB::select('call GetRealisasiLKPPerRayon(?,?,?,?)', [$tgl1,$tgl2,urldecode($rayonId),urldecode($kategori)]);
    	$data = collect($data)->map(function($item) {
    // Replace commas with dots and convert hektar to float
    $item->pekerjaan = $item->pekerjaan;
    $item->hektar = (float) str_replace(',', '.', round($item->hektar,0));
    return $item;
});
// }

// var_dump($data);

   // Ambil data sasaran LKP dari stored procedure
    $data_sasaran_lkp = collect(DB::select("CALL sp_sum_sasaran_lkp_rayon(?, ?,?)", [urldecode($periode),urldecode($rayonId),urldecode($kategori)]));
    // Siapkan data untuk chart
    // Gabungkan data dan data_sasaran_lkp berdasarkan pekerjaan
      $serahTanah = $data->first(function ($item) {
        return $item->pekerjaan == 'serah_tanah';
    });
    $serahTanahHektar = $serahTanah ? $serahTanah->hektar : null;

    $tanamKepras = $data->first(function ($item) {
        return $item->pekerjaan == 'tanam_kepras';
    });
    $tanamKeprasHektar = $tanamKepras ? $tanamKepras->hektar : null;

        $pupuk1 = $data->first(function ($item) {
        return $item->pekerjaan == 'pupuk_1';
    });
    $pupuk1Hektar = $pupuk1 ? $pupuk1->hektar : null;

    $pupuk2 = $data->first(function ($item) {
        return $item->pekerjaan == 'pupuk_2';
    });
    $pupuk2Hektar = $pupuk2 ? $pupuk2->hektar : null;

    $combinedData = $data->map(function ($item) use ($data_sasaran_lkp, $serahTanahHektar, $tanamKeprasHektar, $pupuk1Hektar, $pupuk2Hektar) {
        $matchingSasaran = $data_sasaran_lkp->first(function ($sasaran) use ($item) {
            return $sasaran->pekerjaan == $item->pekerjaan;
        });

        // Jika pekerjaan tanam_kepras, gunakan serah_tanah sebagai sasaran_hektar
        $sasaran_hektar = $matchingSasaran ? (float) str_replace(',', '.', round($matchingSasaran->total_sasaran_ha, 0)) : null;
        if ($item->pekerjaan == 'tanam_kepras') {
            $sasaran_hektar = $serahTanahHektar;
        }
        if ($item->pekerjaan == 'pupuk_1') {
            $sasaran_hektar = $tanamKeprasHektar;
        }
        if (in_array($item->pekerjaan, ['pupuk_2', 'bumbun_1'])) {
            $sasaran_hektar = $pupuk1Hektar;
        }
        if ($item->pekerjaan == 'bumbun_2') {
            $sasaran_hektar = $pupuk2Hektar;
        }


        return [
            'pekerjaan' => $item->pekerjaan,
            'hektar' => $item->hektar,
            'sasaran_hektar' => $sasaran_hektar,
        ];
    });

     $data_sasaran_lkp_thnlalu = collect(DB::select("CALL sp_sum_sasaran_lkp_rayon_thnlalu2(?, ?,?)", [urldecode($periode), urldecode($rayonId), urldecode($kategori)]));
    $combinedData = $combinedData->map(function ($item) use ($data_sasaran_lkp_thnlalu) {
        $matchingThnLalu = $data_sasaran_lkp_thnlalu->first(function ($sasaran) use ($item) {
            return $sasaran->pekerjaan == $item['pekerjaan'];
        });
        $item['hektar_thn_lalu'] = $matchingThnLalu ? (float) str_replace(',', '.', round($matchingThnLalu->total_sasaran_ha, 0)) : null;
        return $item;
    });

    
    $chartData = [
        'pekerjaan' => $combinedData->pluck('pekerjaan')->toArray(),
        'hektar' => $combinedData->pluck('hektar')->toArray(),
        'sasaran_hektar' => $combinedData->pluck('sasaran_hektar')->toArray(),
        'hektar_thn_lalu' => $combinedData->pluck('hektar_thn_lalu')->toArray(),
    ];

    return response()->json(['status' => 'success', 'data' => $chartData]);
}

public function getLkpPerRayonKlentek(Request $request)
{
    $tgl1 = $request->input('tgl1');
    $tgl2 = $request->input('tgl2');
    $rayonId = $request->input('rayon_id');
    
    // Mengambil data utama dari stored procedure
    $data = DB::select('call GetMonitoringLKPRayon(?,?,?)', [urldecode($rayonId), $tgl1, $tgl2]);
    $data = collect($data)->map(function($item) {
        $item->pekerjaan = $item->pekerjaan;
        $item->hektar = (float) str_replace(',', '.', $item->hektar);
        return $item;
    });
    
    // Mengambil data sasaran dari stored procedure
    $data2 = DB::select('call GetMonitoringKlentekRayon(?,?)', [urldecode($rayonId),$tgl2]);
    $data2 = collect($data2)->map(function($item2) {
        $item2->pekerjaan = $item2->pekerjaan;
        $item2->hektar = (float) str_replace(',', '.', $item2->hektar);
        return $item2;
    });



    
    // Pastikan hektar selalu memiliki 3 item (klentek_1, klentek_2, klentek_3)
    $pekerjaan_default = ['klentek_1' => 0, 'klentek_2' => 0, 'klentek_3' => 0];
    
    $data_map = $pekerjaan_default;
    foreach ($data as $item) {
        $data_map[$item->pekerjaan] = $item->hektar;
    }
    $data_final = collect($data_map)->map(function ($hektar, $pekerjaan) {
        return ['pekerjaan' => $pekerjaan, 'hektar' => $hektar];
    })->values();
    
    // Pastikan sasaran juga memiliki 3 item
    $data2_map = $pekerjaan_default;
    foreach ($data2 as $item2) {
        $data2_map[$item2->pekerjaan] = $item2->hektar;
    }
    // Hitung Klentek 2 dan Klentek 3

    $dataklentek1 = DB::select('call GetKlentekRayonSasaran(?,?,?)', [urldecode($rayonId), $tgl2, 150]);
    $dataklentek2 = DB::select('call GetKlentekRayonSasaran(?,?,?)', [urldecode($rayonId), $tgl2, 210]);
    $dataklentek3 = DB::select('call GetKlentekRayonSasaran(?,?,?)', [urldecode($rayonId), $tgl2, 240]);

    $data2_map['klentek_1'] = collect($dataklentek1)->map(function ($item) {
        return (float) str_replace(',', '.', $item->hektar);
    })->sum();

    $data2_map['klentek_2'] = collect($dataklentek2)->map(function ($item) {
        return (float) str_replace(',', '.', $item->hektar);
    })->sum();

    $data2_map['klentek_3'] = collect($dataklentek3)->map(function ($item) {
        return (float) str_replace(',', '.', $item->hektar);
    })->sum();

    $data2_final = collect($data2_map)->map(function ($hektar, $pekerjaan) {
        return ['pekerjaan' => $pekerjaan, 'hektar' => $hektar];
    })->values();
    // Siapkan data untuk chart
    $chartData = [
        'pekerjaan' => $data_final->pluck('pekerjaan')->toArray(),
        'hektar' => $data_final->pluck('hektar')->toArray(),
        'sasaran' => $data2_final->pluck('hektar')->toArray()
    ];
    
    return response()->json(['status' => 'success', 'data' => $chartData]);
    
}

public function getLkpPerKebunKlentek(Request $request)
{
    $tgl1 = $request->input('tgl1');
    $tgl2 = $request->input('tgl2');
    $rayonId = $request->input('rayon_id');
    
    // Mengambil data utama dari stored procedure
    $data = DB::select('call GetMonitoringLKPKebun(?,?,?)', [urldecode($rayonId), $tgl1, $tgl2]);
    $data = collect($data)->map(function($item) {
        $item->pekerjaan = $item->pekerjaan;
        $item->hektar = (float) str_replace(',', '.', $item->hektar);
        return $item;
    });
    
    // Mengambil data sasaran dari stored procedure
    $data2 = DB::select('call GetMonitoringKlentekKebun(?,?)', [urldecode($rayonId),$tgl2]);
    $data2 = collect($data2)->map(function($item2) {
        $item2->pekerjaan = $item2->pekerjaan;
        $item2->hektar = (float) str_replace(',', '.', $item2->hektar);
        return $item2;
    });
    
    // Pastikan hektar selalu memiliki 3 item (klentek_1, klentek_2, klentek_3)
    $pekerjaan_default = ['klentek_1' => 0, 'klentek_2' => 0, 'klentek_3' => 0];
    
    $data_map = $pekerjaan_default;
    foreach ($data as $item) {
        $data_map[$item->pekerjaan] = $item->hektar;
    }
    $data_final = collect($data_map)->map(function ($hektar, $pekerjaan) {
        return ['pekerjaan' => $pekerjaan, 'hektar' => $hektar];
    })->values();
    
    // Pastikan sasaran juga memiliki 3 item
    $data2_map = $pekerjaan_default;
    foreach ($data2 as $item2) {
        $data2_map[$item2->pekerjaan] = $item2->hektar;
    }

    $dataklentek1 = DB::select('call GetKlentekKebunSasaran(?,?,?)', [urldecode($rayonId), $tgl2, 150]);
    $dataklentek2 = DB::select('call GetKlentekKebunSasaran(?,?,?)', [urldecode($rayonId), $tgl2, 210]);
    $dataklentek3 = DB::select('call GetKlentekKebunSasaran(?,?,?)', [urldecode($rayonId), $tgl2, 240]);

    $data2_map['klentek_1'] = collect($dataklentek1)->map(function ($item) {
        return (float) str_replace(',', '.', $item->hektar);
    })->sum();

    $data2_map['klentek_2'] = collect($dataklentek2)->map(function ($item) {
        return (float) str_replace(',', '.', $item->hektar);
    })->sum();

    $data2_map['klentek_3'] = collect($dataklentek3)->map(function ($item) {
        return (float) str_replace(',', '.', $item->hektar);
    })->sum();

    $data2_final = collect($data2_map)->map(function ($hektar, $pekerjaan) {
        return ['pekerjaan' => $pekerjaan, 'hektar' => $hektar];
    })->values();


    // Siapkan data untuk chart
    $chartData = [
        'pekerjaan' => $data_final->pluck('pekerjaan')->toArray(),
        'hektar' => $data_final->pluck('hektar')->toArray(),
        'sasaran' => $data2_final->pluck('hektar')->toArray()
    ];
    
    return response()->json(['status' => 'success', 'data' => $chartData]);
    
}

public function getLkpPerTotalKlentek(Request $request)
{
    $tgl1 = $request->input('tgl1');
    $tgl2 = $request->input('tgl2');
    
    // Mengambil data utama dari stored procedure
    $data = DB::select('call GetMonitoringLKPTotal(?,?)', [ $tgl1, $tgl2]);
    $data = collect($data)->map(function($item) {
        $item->pekerjaan = $item->pekerjaan;
        $item->hektar = (float) str_replace(',', '.', $item->hektar);
        return $item;
    });
    
    // Mengambil data sasaran dari stored procedure
    $data2 = DB::select('call GetMonitoringKlentekTotal(?)', [$tgl2]);
    $data2 = collect($data2)->map(function($item2) {
        $item2->pekerjaan = $item2->pekerjaan;
        $item2->hektar = (float) str_replace(',', '.', $item2->hektar);
        return $item2;
    });
    
    // Pastikan hektar selalu memiliki 3 item (klentek_1, klentek_2, klentek_3)
    $pekerjaan_default = ['klentek_1' => 0, 'klentek_2' => 0, 'klentek_3' => 0];
    
    $data_map = $pekerjaan_default;
    foreach ($data as $item) {
        $data_map[$item->pekerjaan] = $item->hektar;
    }
    $data_final = collect($data_map)->map(function ($hektar, $pekerjaan) {
        return ['pekerjaan' => $pekerjaan, 'hektar' => $hektar];
    })->values();
    
    // Pastikan sasaran juga memiliki 3 item
    $data2_map = $pekerjaan_default;
    foreach ($data2 as $item2) {
        $data2_map[$item2->pekerjaan] = $item2->hektar;
    }

    $dataklentek1 = DB::select('call GetKlentekTotalSasaran(?,?)', [$tgl2, 150]);
    $dataklentek2 = DB::select('call GetKlentekTotalSasaran(?,?)', [$tgl2, 210]);
    $dataklentek3 = DB::select('call GetKlentekTotalSasaran(?,?)', [$tgl2, 240]);

    $data2_map['klentek_1'] = collect($dataklentek1)->map(function ($item) {
        return (float) str_replace(',', '.', $item->hektar);
    })->sum();

    $data2_map['klentek_2'] = collect($dataklentek2)->map(function ($item) {
        return (float) str_replace(',', '.', $item->hektar);
    })->sum();

    $data2_map['klentek_3'] = collect($dataklentek3)->map(function ($item) {
        return (float) str_replace(',', '.', $item->hektar);
    })->sum();

    $data2_final = collect($data2_map)->map(function ($hektar, $pekerjaan) {
        return ['pekerjaan' => $pekerjaan, 'hektar' => $hektar];
    })->values();


    // Siapkan data untuk chart
    $chartData = [
        'pekerjaan' => $data_final->pluck('pekerjaan')->toArray(),
        'hektar' => $data_final->pluck('hektar')->toArray(),
        'sasaran' => $data2_final->pluck('hektar')->toArray()
    ];
    
    return response()->json(['status' => 'success', 'data' => $chartData]);
    
}

public function getLkpPerKebun(Request $request)
{
    $tgl1 = $request->input('tgl1');
    $tgl2 = $request->input('tgl2');
    $rayonId = $request->input('rayon_id');
    $periode = $request->input('periode'); // Tambahkan input periode
    $kat = $request->input('kat'); // Tambahkan input periode
    $cluster = $request->input('cluster'); // Tambahkan input cluster




// if(\Session::get('gid')<3)
//         {
// 		// Memanggil stored procedure
// 		$data = DB::table('q_lkp_rekap_dashboard')
//             ->select('pekerjaan', 'hektar')
//             ->get();
//                     $data = $data->map(function($item) {
//     // Replace commas with dots and convert hektar to float
//     $item->hektar = (float) str_replace(',', '.', $item->hektar);
//     return $item;
    
// });
// } else {
    	$data = DB::select('call GetRealisasiLKPPerKebun(?,?,?,?,?)', [$tgl1,$tgl2,urldecode($rayonId), urldecode($kat), urldecode($cluster)]);
    	$data = collect($data)->map(function($item) {
    // Replace commas with dots and convert hektar to float
    $item->pekerjaan = $item->pekerjaan;
    $item->hektar = (float) str_replace(',', '.', round($item->hektar,0));
    return $item;
});
// }

// var_dump($data);
    // Ambil data sasaran LKP dari stored procedure
    $data_sasaran_lkp = collect(DB::select("CALL sp_sum_sasaran_lkp_kebun(?, ?, ?,?)", [urldecode($periode),urldecode($rayonId), urldecode($kat), urldecode($cluster)]));
    // Siapkan data untuk chart
    // Gabungkan data dan data_sasaran_lkp berdasarkan pekerjaan
    // Ambil data serah_tanah dari hasil GetRealisasiLKPPerKebun
    $serahTanah = $data->first(function ($item) {
        return $item->pekerjaan == 'serah_tanah';
    });
    $serahTanahHektar = $serahTanah ? $serahTanah->hektar : null;

    $tanamKepras = $data->first(function ($item) {
        return $item->pekerjaan == 'tanam_kepras';
    });
    $tanamKeprasHektar = $tanamKepras ? $tanamKepras->hektar : null;

    $pupuk1 = $data->first(function ($item) {
        return $item->pekerjaan == 'pupuk_1';
    });
    $pupuk1Hektar = $pupuk1 ? $pupuk1->hektar : null;

    $pupuk2 = $data->first(function ($item) {
        return $item->pekerjaan == 'pupuk_2';
    });
    $pupuk2Hektar = $pupuk2 ? $pupuk2->hektar : null;

    $combinedData = $data->map(function ($item) use ($data_sasaran_lkp, $serahTanahHektar, $tanamKeprasHektar, $pupuk1Hektar, $pupuk2Hektar) {
        $matchingSasaran = $data_sasaran_lkp->first(function ($sasaran) use ($item) {
            return $sasaran->pekerjaan == $item->pekerjaan;
        });

        // Jika pekerjaan tanam_kepras, gunakan serah_tanah sebagai sasaran_hektar
        $sasaran_hektar = $matchingSasaran ? (float) str_replace(',', '.', round($matchingSasaran->total_sasaran_ha, 0)) : null;
        if ($item->pekerjaan == 'tanam_kepras') {
            $sasaran_hektar = $serahTanahHektar;
        }
        if ($item->pekerjaan == 'pupuk_1') {
            $sasaran_hektar = $tanamKeprasHektar;
        }
        if (in_array($item->pekerjaan, ['pupuk_2', 'bumbun_1'])) {
            $sasaran_hektar = $pupuk1Hektar;
        }
        if ($item->pekerjaan == 'bumbun_2') {
            $sasaran_hektar = $pupuk2Hektar;
        }



        return [
            'pekerjaan' => $item->pekerjaan,
            'hektar' => $item->hektar,
            'sasaran_hektar' => $sasaran_hektar,
        ];
    });

    

    $data_sasaran_lkp_thnlalu = collect(DB::select("CALL sp_sum_sasaran_lkp_rayon_thnlalu(?, ?, ?,?)", [urldecode($periode), urldecode($rayonId), urldecode($kat), urldecode($cluster)]));
    $combinedData = $combinedData->map(function ($item) use ($data_sasaran_lkp_thnlalu) {
        $matchingThnLalu = $data_sasaran_lkp_thnlalu->first(function ($sasaran) use ($item) {
            return $sasaran->pekerjaan == $item['pekerjaan'];
        });
        $item['hektar_thn_lalu'] = $matchingThnLalu ? (float) str_replace(',', '.', round($matchingThnLalu->total_sasaran_ha, 0)) : null;
        return $item;
    });

    $chartData = [
        'pekerjaan' => $combinedData->pluck('pekerjaan')->toArray(),
        'hektar' => $combinedData->pluck('hektar')->toArray(),
        'sasaran_hektar' => $combinedData->pluck('sasaran_hektar')->toArray(),
        'hektar_thn_lalu' => $combinedData->pluck('hektar_thn_lalu')->toArray(),
    ];

    return response()->json(['status' => 'success', 'data' => $chartData]);
}

public function getLkpTebu(Request $request)
{
    $tgl1 = $request->input('tgl1');
    $tgl2 = $request->input('tgl2');
    $rayonId = $request->input('rayon_id');
    $periode = $request->input('periode'); // Tambahkan input periode
    $kat = $request->input('kat'); // Tambahkan input periode

    	$data = DB::select('call GetRealisasiLKPPerKebun(?,?,?,?,?)', [$tgl1,$tgl2,urldecode($rayonId), urldecode($kat),'']);
    	$data = collect($data)->map(function($item) {
    // Replace commas with dots and convert hektar to float
    $item->pekerjaan = $item->pekerjaan;
    $item->hektar = (float) str_replace(',', '.', round($item->hektar,0));
    return $item;
});


    // Ambil data sasaran LKP dari stored procedure
    $data_sasaran_lkp = collect(DB::select("CALL sp_sum_sasaran_lkp_kebun(?, ?, ?,?)", [urldecode($periode),urldecode($rayonId), urldecode($kat),'']));
    // Siapkan data untuk chart
    $serahTanah = $data->first(function ($item) {
        return $item->pekerjaan == 'serah_tanah';
    });
    $serahTanahHektar = $serahTanah ? $serahTanah->hektar : null;

    $tanamKepras = $data->first(function ($item) {
        return $item->pekerjaan == 'tanam_kepras';
    });
    $tanamKeprasHektar = $tanamKepras ? $tanamKepras->hektar : null;

    $pupuk1 = $data->first(function ($item) {
        return $item->pekerjaan == 'pupuk_1';
    });
    $pupuk1Hektar = $pupuk1 ? $pupuk1->hektar : null;

    $pupuk2 = $data->first(function ($item) {
        return $item->pekerjaan == 'pupuk_2';
    });
    $pupuk2Hektar = $pupuk2 ? $pupuk2->hektar : null;

    $combinedData = $data->map(function ($item) use ($data_sasaran_lkp, $serahTanahHektar, $tanamKeprasHektar, $pupuk1Hektar, $pupuk2Hektar) {
        $matchingSasaran = $data_sasaran_lkp->first(function ($sasaran) use ($item) {
            return $sasaran->pekerjaan == $item->pekerjaan;
        });

        // Jika pekerjaan tanam_kepras, gunakan serah_tanah sebagai sasaran_hektar
        $sasaran_hektar = $matchingSasaran ? (float) str_replace(',', '.', round($matchingSasaran->total_sasaran_ha, 0)) : null;
        if ($item->pekerjaan == 'tanam_kepras') {
            $sasaran_hektar = $serahTanahHektar;
        }
        if ($item->pekerjaan == 'pupuk_1') {
            $sasaran_hektar = $tanamKeprasHektar;
        }
        if (in_array($item->pekerjaan, ['pupuk_2', 'bumbun_1'])) {
            $sasaran_hektar = $pupuk1Hektar;
        }
        if ($item->pekerjaan == 'bumbun_2') {
            $sasaran_hektar = $pupuk2Hektar;
        }



        return [
            'pekerjaan' => $item->pekerjaan,
            'hektar' => $item->hektar,
            'sasaran_hektar' => $sasaran_hektar,
        ];
    });

    $data_sasaran_lkp_thnlalu = collect(DB::select("CALL sp_sum_sasaran_lkp_rayon_thnlalu(?, ?, ?,?)", [urldecode($periode), urldecode($rayonId), urldecode($kat),'']));
    $combinedData = $combinedData->map(function ($item) use ($data_sasaran_lkp_thnlalu) {
        $matchingThnLalu = $data_sasaran_lkp_thnlalu->first(function ($sasaran) use ($item) {
            return $sasaran->pekerjaan == $item['pekerjaan'];
        });
        $item['hektar_thn_lalu'] = $matchingThnLalu ? (float) str_replace(',', '.', round($matchingThnLalu->total_sasaran_ha, 0)) : null;
        return $item;
    });

    $data_jawa = DB::select('call GetRealisasiLKPPerJawa(?,?,?,?)', [$tgl1, $tgl2,urldecode($rayonId), urldecode($kat)]);
    $data_jawa = collect($data_jawa)->map(function($item) {
        $item->jawa_nonjawa = $item->jawa_nonjawa;
        $item->hektar = (float) str_replace(',', '.', round($item->hektar,0));
        return $item;
    });

    // Filter data untuk JAWA dan LUAR JAWA
    $jawa_data = $data_jawa->where('jawa_nonjawa', 'JAWA')->values();
    $luar_jawa_data = $data_jawa->where('jawa_nonjawa', 'LUAR JAWA')->values();

    // Jika ingin menambahkan ke chartData, misal:

    $chartData = [
        'pekerjaan' => $combinedData->pluck('pekerjaan')->toArray(),
        'hektar' => $combinedData->pluck('hektar')->toArray(),
        'sasaran_hektar' => $combinedData->pluck('sasaran_hektar')->toArray(),
        'hektar_thn_lalu' => $combinedData->pluck('hektar_thn_lalu')->toArray(),
        'jawa' => $jawa_data->pluck('hektar')->toArray(),
        'luar_jawa' => $luar_jawa_data->pluck('hektar')->toArray(),
    ];

    return response()->json(['status' => 'success', 'data' => $chartData]);
}

public function lkptebu(Request $request)
{
    return view('dashboard.lkp_tebu');
}
	
	
public function grafikmutu(Request $request)
{
    $tgl_giling = $request->input('tgl_giling');
        $rayon = $request->input('rayon');

        // Ambil data dari database
        $data = DB::table('q_prod_rekap_mutu_rayon_tgl')
                  ->select('nama_rayon', 'mutu_A', 'mutu_B', 'mutu_C', 'mutu_D', 'mutu_E')
                  ->where('tgl_giling', $tgl_giling)
                  ->where('nama_rayon', $rayon)
                  ->first();

        // Pastikan data tersedia
        if (!$data) {
            return response()->json([]);
        }

        // Format data untuk Highcharts Pie
        $chartData = [
            ['name' => 'Mutu A', 'y' => $data->mutu_A,'color'=> '#28a745'],
            ['name' => 'Mutu B', 'y' => $data->mutu_B,'color'=> '#007bff'],
            ['name' => 'Mutu C', 'y' => $data->mutu_C,'color'=> '#ffc107'],
            ['name' => 'Mutu D', 'y' => $data->mutu_D,'color'=> '#dc3545'],
            ['name' => 'Mutu E', 'y' => $data->mutu_E,'color'=> '#000000'],
        ];

        // Ambil data dari database
        $data2 = DB::table('q_prod_rekap_mutu_rayon_tgl')
                  ->select(
                      'nama_rayon',
                      DB::raw('SUM(mutu_A) as mutu_A'),
                      DB::raw('SUM(mutu_B) as mutu_B'),
                      DB::raw('SUM(mutu_C) as mutu_C'),
                      DB::raw('SUM(mutu_D) as mutu_D'),
                      DB::raw('SUM(mutu_E) as mutu_E')
                  )
                  ->whereBetween('tgl_giling', [date('Y').'-01-16', $tgl_giling])
                  ->where('nama_rayon', $rayon)
                  ->groupBy('nama_rayon')
                  ->first();

        // Pastikan data tersedia
        if (!$data) {
            return response()->json([]);
        }

        // Format data untuk Highcharts Pie
        $chartData = [
            ['name' => 'Mutu A', 'y' => $data->mutu_A,'color'=> '#28a745'],
            ['name' => 'Mutu B', 'y' => $data->mutu_B,'color'=> '#007bff'],
            ['name' => 'Mutu C', 'y' => $data->mutu_C,'color'=> '#ffc107'],
            ['name' => 'Mutu D', 'y' => $data->mutu_D,'color'=> '#dc3545'],
            ['name' => 'Mutu E', 'y' => $data->mutu_E,'color'=> '#000000'],
        ];

        // Format data untuk Highcharts Pie
        $chartData2= [
            ['name' => 'Mutu A', 'y' => $data2->mutu_A,'color'=> '#28a745'],
            ['name' => 'Mutu B', 'y' => $data2->mutu_B,'color'=> '#007bff'],
            ['name' => 'Mutu C', 'y' => $data2->mutu_C,'color'=> '#ffc107'],
            ['name' => 'Mutu D', 'y' => $data2->mutu_D,'color'=> '#dc3545'],
            ['name' => 'Mutu E', 'y' => $data2->mutu_E,'color'=> '#000000'],
        ];

        $dataarr = array(
            'data_hi' => $chartData,
            'data_sd' =>$chartData2
        );

        return response()->json($dataarr);
}
	
public function protasperrayon(Request $request)
{
            $filter = $request->input('filter', 'kebun');
            $customfilter = $request->input('customfilter', '');

            if ($filter == 'kebun') {

                $data4 = DB::table('q_prod_protas_timbangan_kebun_dashboard')
                ->select('nama_kebun as nama_rayon', 'protas')
                ->when(!empty($customfilter), function ($query) use ($customfilter) {
                    return $query->where('nama_cluster', $customfilter);
                })
                ->get();  
               
                $data5 = DB::table('q_protas_takmar_kebun')
                ->select('nama_kebun as nama_rayon', 'protas')
                ->when(!empty($customfilter), function ($query) use ($customfilter) {
                    return $query->where('nama_cluster', $customfilter);
                })
                ->get();  

                $data6 = DB::table('q_2024_protas_kebun')
                ->select('nama_kebun as nama_rayon', 'Protas as protas')
                ->when(!empty($customfilter), function ($query) use ($customfilter) {
                    return $query->where('nama_cluster', $customfilter);
                })
                ->get();  

            }else if($filter == 'cluster'){
                $data4 = DB::table('q_prod_protas_timbangan_cluster_dashboard')
                ->select('nama_cluster as nama_rayon', 'protas')
                ->get();

                $data5 = DB::table('q_protas_takmar_cluster')
                ->select('nama_cluster as nama_rayon', 'protas')
                ->get();

                $data6 = DB::table('q_2024_protas_cluster')
                ->select('nama_cluster as nama_rayon', 'Protas as protas')
                ->get();  
            }else if($filter == 'jawa'){
                $data4 = DB::table('q_prod_protas_timbangan_jawa_dashboard')
                ->select('jawa_nonjawa as nama_rayon', 'protas')
                ->get();

                $data5 = DB::table('q_protas_takmar_jawa')
                ->select('jawa_nonjawa as nama_rayon', 'protas')
                ->get();

                $data6 = DB::table('q_2024_protas_jawa')
                ->select('jawa_nonjawa as nama_rayon', 'Protas as protas')
                ->get();  
            } else{
                $data4 = DB::table('q_prod_protas_timbangan_rayon_dashboard')
                ->select('nama_rayon', 'protas')
                ->when(!empty($customfilter), function ($query) use ($customfilter) {
                    return $query->where('nama_kebun', $customfilter);
                })
                ->get();
                
                $data5 = DB::table('q_protas_takmar_rayon')
                ->select('nama_rayon', 'protas')
                ->when(!empty($customfilter), function ($query) use ($customfilter) {
                    return $query->where('nama_kebun', $customfilter);
                })
                ->get();

                $data6 = DB::table('q_2024_protas_rayon')
                ->select('nama_rayon', 'Protas as protas')
                ->when(!empty($customfilter), function ($query) use ($customfilter) {
                    return $query->where('nama_kebun', $customfilter);
                })
                ->get();  

            }



            // Gabungkan data4 dan data5 berdasarkan nama_rayon
            $nama_rayon = array_map('strtoupper', $data4->pluck('nama_rayon')->toArray());
            $protas2 = $data4->pluck('protas')->toArray();

            // Buat array asosiatif dari data5 untuk pencarian cepat
            $data5_map = $data5->keyBy(function($item) { return strtoupper($item->nama_rayon); });
            $data6_map = $data6->keyBy(function($item) { return strtoupper($item->nama_rayon); });

            // Isi protas_takmar sesuai urutan nama_rayon di data4
            $protas_takmar = [];
            foreach ($nama_rayon as $nr) {
                $protas_takmar[] = isset($data5_map[$nr]) ? $data5_map[$nr]->protas : null;
            }
            $protas_takmar2 = [];
            foreach ($nama_rayon as $nr) {
                $protas_takmar2[] = isset($data6_map[$nr]) ? (float) $data6_map[$nr]->protas : null;
            }

            $data = array(
                'nama_rayon' => $nama_rayon,
                'protas2' => $protas2,
                'protas_takmar' => $protas_takmar,
                'protas_2024' => $protas_takmar2,

            );


        return $data;
}

public function mutuperrayon(Request $request)
{
            $filter = $request->input('filter', 'kebun');
            $tgl = $request->input('tgl', date('Y-m-d'));
            $customfilter = $request->input('customfilter', '');
            $tglbefore = date('Y-m-d', strtotime($tgl . ' -1 year'));


                $data4 = collect(DB::select('CALL sp_get_mutu_by_category(?, ?, ?)', [
                    $tgl,
                    $filter,
                    $customfilter ?: null
                ]))->map(function($item) {
                    return $item;
                });
               

                $data6 = collect(DB::select('CALL sp_mutu_report(?, ?, ?)', [
                    $filter,
                    $tglbefore,
                    $customfilter ?: null
                ]))->map(function($item) {
                    return $item;
                });


            // Gabungkan data4 dan data5 berdasarkan nama_rayon
            $nama_rayon = array_map('strtoupper', $data4->pluck('nama_rayon')->toArray());
            $mutu = $data4->pluck('mutu')->map(function($v) {
                return is_numeric($v) ? round($v, 1) : $v;
            })->toArray();

            // Buat array asosiatif dari data5 untuk pencarian cepat
            $data6_map = $data6->keyBy(function($item) { return strtoupper($item->nama_rayon); });

            // Isi protas_takmar sesuai urutan nama_rayon di data4

            $mutu_2024 = [];
            foreach ($nama_rayon as $nr) {
                $mutu_2024[] = isset($data6_map[$nr]) ? (float) $data6_map[$nr]->mutu : null;
            }

            $data = array(
                'nama_rayon' => $nama_rayon,
                'mutu' => $mutu,
                'mutu_2024' => $mutu_2024,

            );


        return $data;
}

public function mutuperrayonhi(Request $request)
{
            $filter = $request->input('filter', 'kebun');
            $tgl = $request->input('tgl', date('Y-m-d'));
            $customfilter = $request->input('customfilter', '');
            $tglbefore = date('Y-m-d', strtotime($tgl . ' -1 year'));


                $data4 = collect(DB::select('CALL sp_get_mutu_by_category_hi(?, ?, ?)', [
                    $tgl,
                    $filter,
                    $customfilter ?: null
                ]))->map(function($item) {
                    return $item;
                });
               

                $data6 = collect(DB::select('CALL sp_mutu_report_hi(?, ?, ?)', [
                    $filter,
                    $tglbefore,
                    $customfilter ?: null
                ]))->map(function($item) {
                    return $item;
                });


            // Gabungkan data4 dan data5 berdasarkan nama_rayon
            $nama_rayon = array_map('strtoupper', $data4->pluck('nama_rayon')->toArray());
            $mutu = $data4->pluck('mutu')->map(function($v) {
                return is_numeric($v) ? round($v, 1) : $v;
            })->toArray();

            // Buat array asosiatif dari data5 untuk pencarian cepat
            $data6_map = $data6->keyBy(function($item) { return strtoupper($item->nama_rayon); });

            // Isi protas_takmar sesuai urutan nama_rayon di data4

            $mutu_2024 = [];
            foreach ($nama_rayon as $nr) {
                $mutu_2024[] = isset($data6_map[$nr]) ? (float) $data6_map[$nr]->mutu : null;
            }

            $data = array(
                'nama_rayon' => $nama_rayon,
                'mutu' => $mutu,
                'mutu_2024' => $mutu_2024,

            );


        return $data;
}

public function getprotasharian(Request $request)
{
    $nama_rayon = $request->input('nama_rayon');
    $tgl_awal = $request->input('start_date');
    $tgl_akhir = $request->input('end_date');

    // Panggil stored procedure untuk mendapatkan data protas harian
    $data = DB::select('call sp_get_protas_rayon(?, ?, ?)', [
        urldecode($nama_rayon),
        $tgl_awal,
        $tgl_akhir
    ]);

    // Format data untuk response
    $result = collect($data)->map(function ($item) {
        return [
            'tgl_timbang' => date_format(date_create($item->tgl_timbang), "d M"),
            'protas' => (float) str_replace(',', '.', $item->protas),
            'protas_takmar' => (float) str_replace(',', '.', $item->protas_takmar),
        ];
    });

    return response()->json([
        'status' => 'success',
        'data' => $result
    ]);
}

public function getprotashariankebun(Request $request)
{
    $cluster = $request->input('cluster');
    $nama_rayon = $request->input('nama_rayon');
    $tgl_awal = $request->input('start_date');
    $tgl_akhir = $request->input('end_date');

    if($cluster !='' && $cluster != null && $nama_rayon == ''){
            $data = DB::select('call sp_get_protas_cluster(?, ?, ?)', [
                urldecode($cluster),
                $tgl_awal,
                $tgl_akhir
            ]);
    }else{
        $data = DB::select('call sp_get_protas_kebun(?, ?, ?)', [
            urldecode($nama_rayon),
            $tgl_awal,
            $tgl_akhir
        ]);
    }
    // Panggil stored procedure untuk mendapatkan data protas harian


    // Format data untuk response
    $result = collect($data)->map(function ($item) {
        return [
            'tgl_timbang' => date_format(date_create($item->tgl_timbang), "d M"),
            'protas' => (float) str_replace(',', '.', $item->protas),
            'protas_takmar' => (float) str_replace(',', '.', $item->protas_takmar),
        ];
    });

    return response()->json([
        'status' => 'success',
        'data' => $result
    ]);
}

public function getprotasranking(Request $request){
        // Data
        config(['app.debug' => true]);
        $tgl = $request->input('tgl');

        // Ambil data dari stored procedure dengan filter tanggal
        $data1 = DB::select('call sp_rangking_protas_kebun2(?)', [$tgl]);
        $data2 = DB::select('call sp_rangking_protas_cluster2(?)', [$tgl]);
        $data3 = DB::select('call sp_rangking_protas_rayon2(?)', [$tgl]);
        $data4 = DB::select('call sp_rangking_protas_jawanonjawa(?)', [$tgl]);      
        $data5 = DB::select('call sp_rangking_protas_total(?)', [$tgl]);  

        $data11 = DB::select('call sp_rangking_protas_kebun_hi(?)', [$tgl]);
        $data22 = DB::select('call sp_rangking_protas_cluster_hi(?)', [$tgl]);
        $data33 = DB::select('call sp_rangking_protas_rayon_hi(?)', [$tgl]);
        $data44 = DB::select('call sp_rangking_protas_jawanonjawa_hi(?)', [$tgl]);
        $data55 = DB::select('call sp_rangking_protas_total_hi(?)', [$tgl]);

        // Generate Bootstrap horizontal tables as HTML with Ranking column
        
        // Helper function to get color class based on ranking
        function getRankClass($rank) {
            if ($rank == 1) return 'table-success font-weight-bold';
            if ($rank == 2) return 'table-info font-weight-bold';
            if ($rank == 3) return 'table-warning font-weight-bold';
            return '';
        }

        // Table 1: Kebun
        $html1 = '
        <div class="col-lg-4"><h5>Ranking Produktivitas Kebun (Laporan Timbang)</h5>    
        <table class="table table-bordered table-striped table-hover table-sm table-responsive">
            <thead class="thead-dark">
            <tr>
            <th>No</th>
            <th>Nama Kebun</th>
            <th>takmar</th>
            <th>Hi</th>
            <th>Sd</th>
            <th>%Hi</th>
            <th>%Sd</th>
            <th></th>
            </tr>
            </thead>
            <tbody>';
        $rank = 1;
        foreach ($data1 as $row) {
            $class = getRankClass($rank);
            $html1 .= '<tr class="' . $class . '">
            <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
            <td>' . htmlspecialchars($row->nama_kebun) . '</td>';
            $html1 .='<td style="background:#FFF;">' . htmlspecialchars($row->protas_takmar ?? '') . '</td>';
            $html1 .= '<td style="background:#FFF;">';
            $protas_hi1 = 0;
            foreach ($data11 as $row2) {                
                
                if (strtoupper($row->nama_kebun) == strtoupper($row2->nama_kebun)) {
                    $protas_hi1 = htmlspecialchars($row2->protas);
                    break;
                }
                
            }
            $html1 .= $protas_hi1;
            $html1 .= '</td>';
            $html1 .='<td>' . htmlspecialchars($row->protas) . '</td>';


            // Hitung persentase dan tentukan warna latar belakang
            $protas_takmar_val = is_numeric($row->protas_takmar) ? (float)$row->protas_takmar : 0;
            $protas_hi1_val = is_numeric($protas_hi1) ? (float)$protas_hi1 : 0;
            $percent = ($protas_takmar_val != 0 && $protas_takmar_val != null) ? ($protas_hi1_val / $protas_takmar_val) * 100 : 0;
            $percentFormatted = htmlspecialchars(number_format($percent, 2));
            if ($percent >= 100) {
                $bgcolor = '#28a745'; // hijau
                $color = '#fff';
            } elseif ($percent >= 90) {
                $bgcolor = '#ffc107'; // kuning
                $color = '#000';
            } else {
                $bgcolor = '#dc3545'; // merah
                $color = '#fff';
            }
            $html1 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';

            $percent = ($row->protas_takmar != 0 && $row->protas_takmar != null) ? ($row->protas / $row->protas_takmar) * 100 : 0;
            $percentFormatted = htmlspecialchars(number_format($percent, 2));
            if ($percent >= 100) {
                $bgcolor = '#28a745'; // hijau
                $color = '#fff';
            } elseif ($percent >= 90) {
                $bgcolor = '#ffc107'; // kuning
                $color = '#000';
            } else {
                $bgcolor = '#dc3545'; // merah
                $color = '#fff';
            }
            $html1 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';
            $html1 .= '<td><button class="btn btn-sm btn-primary" onclick="showAsmanRanking(`' . urlencode($tgl) . '`,`' . urlencode($row->kode_kebun) . '`)"><i class="fa fa-eye"></i></button></td>';
            '</tr>';
            $rank++;
        }
        $html1 .= '</tbody></table></div>';

        // Table 2: Cluster
        $html2 = '<div class="col-lg-4"><h5>Ranking Produktivitas Cluster (Laporan Timbang)</h5>  
        <table class="table table-bordered table-striped table-hover table-sm table-responsive">
            <thead class="thead-dark">
            <tr>
            <th>No</th>
            <th>Nama Cluster</th>
            <th>takmar</th>
            <th>Hi</th>
            <th>Sd</th>
            <th>%Hi</th>
            <th>%Sd</th>
            </tr>
            </thead>
            <tbody>';
        $rank = 1;
        foreach ($data2 as $row) {
            $class = getRankClass($rank);
            $html2 .= '<tr class="' . $class . '">
            <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
            <td>' . htmlspecialchars($row->nama_cluster ?? $row->nama_rayon ?? '') . '</td>';
            $html2 .= '<td style="background:#FFF;">' . htmlspecialchars($row->protas_takmar ?? '') . '</td>';
            $html2 .= '<td style="background:#FFF;">';
            $protas_hi2 = 0;
            foreach ($data22 as $row2) {
                if (strtoupper($row->nama_cluster ?? $row->nama_rayon ?? '') == strtoupper($row2->nama_cluster ?? $row2->nama_rayon ?? '')) {
                    $protas_hi2 = $row2->protas;
                    break;
                }
            }
            $html2 .= $protas_hi2;
            $html2 .= '</td>';
            $html2 .= '<td>' . htmlspecialchars($row->protas) . '</td>';
            

            // Hitung persentase dan tentukan warna latar belakang
            $percent = ($row->protas_takmar != 0 && $row->protas_takmar != null) ? ($protas_hi2 / $row->protas_takmar) * 100 : 0;
            $percentFormatted = htmlspecialchars(number_format($percent, 2));
            if ($percent >= 100) {
                $bgcolor = '#28a745'; // hijau
                $color = '#fff';
            } elseif ($percent >= 90) {
                $bgcolor = '#ffc107'; // kuning
                $color = '#000';
            } else {
                $bgcolor = '#dc3545'; // merah
                $color = '#fff';
            }
            $html2 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';

            $percent = ($row->protas_takmar != 0 && $row->protas_takmar != null) ? ($row->protas / $row->protas_takmar) * 100 : 0;
            $percentFormatted = htmlspecialchars(number_format($percent, 2));
            if ($percent >= 100) {
                $bgcolor = '#28a745'; // hijau
                $color = '#fff';
            } elseif ($percent >= 90) {
                $bgcolor = '#ffc107'; // kuning
                $color = '#000';
            } else {
                $bgcolor = '#dc3545'; // merah
                $color = '#fff';
            }
            $html2 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';
            '</tr>';
            $rank++;
        }
        $html2 .= '</tbody></table>';

        $html2 .= '<br><h5>Ranking Produktivitas Jawa Non Jawa (Laporan Timbang)</h5> 
        <table class="table table-bordered table-striped table-hover table-sm table-responsive">
            <thead class="thead-dark">
            <tr>
            <th>No</th>
            <th>Nama Cluster</th>
            <th>takmar</th>
            <th>Hi</th>
            <th>Sd</th>
            <th>%Hi</th>
            <th>%Sd</th>
            </tr>
            </thead>
            <tbody>';
        $rank = 1;
        foreach ($data4 as $row) {
            $class = getRankClass($rank);
            $html2 .= '<tr class="' . $class . '">
            <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
            <td>' . htmlspecialchars($row->jawa_nonjawa ?? $row->nama_rayon ?? '') . '</td>';
            $html2 .= '<td style="background:#FFF;">' . htmlspecialchars($row->protas_takmar ?? '') . '</td>';
            $html2 .= '<td style="background:#FFF;">';
            $protas_hi2 = 0;
            foreach ($data44 as $row2) {
                if (strtoupper($row->jawa_nonjawa ?? $row->nama_rayon ?? '') == strtoupper($row2->jawa_nonjawa ?? $row2->nama_rayon ?? '')) {
                    $protas_hi2 = $row2->protas;
                    break;
                }
            }
            $html2 .= $protas_hi2;
            $html2 .= '</td>';
            $html2 .= '<td>' . htmlspecialchars($row->protas) . '</td>';
            

            // Hitung persentase dan tentukan warna latar belakang
            $percent = ($row->protas_takmar != 0 && $row->protas_takmar != null) ? ($protas_hi2 / $row->protas_takmar) * 100 : 0;
            $percentFormatted = htmlspecialchars(number_format($percent, 2));
            if ($percent >= 100) {
                $bgcolor = '#28a745'; // hijau
                $color = '#fff';
            } elseif ($percent >= 90) {
                $bgcolor = '#ffc107'; // kuning
                $color = '#000';
            } else {
                $bgcolor = '#dc3545'; // merah
                $color = '#fff';
            }
            $html2 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';

            $percent = ($row->protas_takmar != 0 && $row->protas_takmar != null) ? ($row->protas / $row->protas_takmar) * 100 : 0;
            $percentFormatted = htmlspecialchars(number_format($percent, 2));
            if ($percent >= 100) {
                $bgcolor = '#28a745'; // hijau
                $color = '#fff';
            } elseif ($percent >= 90) {
                $bgcolor = '#ffc107'; // kuning
                $color = '#000';
            } else {
                $bgcolor = '#dc3545'; // merah
                $color = '#fff';
            }
            $html2 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';
            '</tr>';
            $rank++;
        }
        $html2 .= '<tr>
            <td colspan="2" class="font-weight-bold">Total</td>
            <td style="background:#FFF;">' . htmlspecialchars($data5[0]->protas_takmar ?? '') . '</td>
            <td style="background:#FFF;">';
        $protas_hi2 = 0;
        foreach ($data55 as $row2) {
            if (strtoupper($data5[0]->total) == strtoupper($row2->total)) {
                $protas_hi2 = $row2->protas;
                break;
            }
        }
        $html2 .= $protas_hi2;
        $html2 .= '</td>';
        $html2 .= '<td>' . htmlspecialchars($data5[0]->protas) . '</td>';
        // Hitung persentase dan tentukan warna latar belakang
        $percent = ($data5[0]->protas_takmar != 0 && $data5[0]->protas_takmar != null) ? ($protas_hi2 / $data5[0]->protas_takmar) * 100 : 0;
        $percentFormatted = htmlspecialchars(number_format($percent, 2));
        if ($percent >= 100) {
            $bgcolor = '#28a745'; // hijau
            $color = '#fff';
        } elseif ($percent >= 90) {
            $bgcolor = '#ffc107'; // kuning
            $color = '#000';
        } else {
            $bgcolor = '#dc3545'; // merah
            $color = '#fff';
        }
        $html2 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';
        $percent = ($data5[0]->protas_takmar != 0 && $data5[0]->protas_takmar != null) ? ($data5[0]->protas / $data5[0]->protas_takmar) * 100 : 0;
        $percentFormatted = htmlspecialchars(number_format($percent, 2));
        if ($percent >= 100) {
            $bgcolor = '#28a745'; // hijau
            $color = '#fff';
        } elseif ($percent >= 90) {
            $bgcolor = '#ffc107'; // kuning
            $color = '#000';
        } else {
            $bgcolor = '#dc3545'; // merah
            $color = '#fff';
        }
        $html2 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';
        $html2 .= '<td><button class="btn btn-sm btn-primary" onclick="showAsmanRanking(`' . urlencode($tgl) . '`,``)"><i class="fa fa-eye"></i></button></td>';

        $html2 .= '</tr>';
        $html2 .= '</tbody></table>';

        $html2 .= '</div>';

        // Table 3: Rayon
        $html3 = '<div class="col-lg-4"><h5>Ranking Produktivitas Rayon (Laporan Timbang)</h5>    
        <table class="table table-bordered table-striped table-hover table-sm table-responsive">
            <thead class="thead-dark">
            <tr>
            <th>No</th>
            <th>Nama Rayon</th>
            <th>takmar</th>
            <th>Hi</th>
            <th>Sd</th>
            <th>%Hi</th>
            <th>%Sd</th>
            </tr>
            </thead>
            <tbody>';
        $rank = 1;
        foreach ($data3 as $row) {
            $class = getRankClass($rank);
            $html3 .= '<tr class="' . $class . '">
            <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
            <td>' . htmlspecialchars($row->nama_rayon ?? '') . '</td>';
            $html3 .= '<td style="background:#FFF;">' . htmlspecialchars($row->protas_takmar ?? '') . '</td>';
            $html3 .= '<td style="background:#FFF;">';
            $protas_hi3 = 0;
            foreach ($data33 as $row2) {
                if (strtoupper($row->nama_rayon ?? '') == strtoupper($row2->nama_rayon ?? '')) {
                    $protas_hi3 = $row2->protas;
                    break;
                }
            }
            $html3 .= $protas_hi3;
            $html3 .= '</td>';
            $html3 .= '<td>' . htmlspecialchars($row->protas) . '</td>';


            // Hitung persentase dan tentukan warna latar belakang
            $percent = ($row->protas_takmar != 0 && $row->protas_takmar != null) ? ($protas_hi3 / $row->protas_takmar) * 100 : 0;
            $percentFormatted = htmlspecialchars(number_format($percent, 2));
            if ($percent >= 100) {
                $bgcolor = '#28a745'; // hijau
                $color = '#fff';
            } elseif ($percent >= 90) {
                $bgcolor = '#ffc107'; // kuning
                $color = '#000';
            } else {
                $bgcolor = '#dc3545'; // merah
                $color = '#fff';
            }
            $html3 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';

            $percent = ($row->protas_takmar != 0 && $row->protas_takmar != null) ? ($row->protas / $row->protas_takmar) * 100 : 0;
            $percentFormatted = htmlspecialchars(number_format($percent, 2));
            if ($percent >= 100) {
                $bgcolor = '#28a745'; // hijau
                $color = '#fff';
            } elseif ($percent >= 90) {
                $bgcolor = '#ffc107'; // kuning
                $color = '#000';
            } else {
                $bgcolor = '#dc3545'; // merah
                $color = '#fff';
            }
            $html3 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';
            '</tr>';
            $rank++;
        }
        $html3 .= '</tbody></table></div>';

        // Optional: Add a little CSS for better highlight if not already present
        $html1 .= '<style>
        .table-success { background-color: #d4edda !important; }
        .table-info { background-color: #d1ecf1 !important; }
        .table-warning { background-color: #fff3cd !important; }
        .font-weight-bold { font-weight: bold; }
        </style>';


        $html1 .= '<script>
        function showAsmanRanking(tgl, kebun) {
            Swal.fire({
                title: "Loading...",
                html: "Mengambil data ranking asman...",
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                    fetch("dashboard/getprotasrankingasman?tgl=" + encodeURIComponent(tgl) + "&kebun=" + encodeURIComponent(kebun))
                        .then(response => response.text())
                        .then(html => {
                            Swal.fire({
                                title: "Ranking Protas Asman",
                                html: html,
                                width: "916px",
                                position: "center",
                                showCloseButton: true,
                                showConfirmButton: false
                            });
                        })
                        .catch(() => {
                            Swal.fire("Error", "Gagal mengambil data.", "error");
                        });
                }
            });
        }
        </script>';

        // Gabungkan semua tabel
        $html = $html3 . $html1 . $html2;

        // Return HTML response
        return response($html);

        
}

public function getprotasrankingasman(Request $request){
        // Data
        config(['app.debug' => true]);
        $tgl = $request->input('tgl');
        $kebun = urldecode($request->input('kebun'));

        // Ambil data dari stored procedure dengan filter tanggal
        $data1 = DB::select('call sp_rangking_protas_afd(?,?)', [$tgl, $kebun]);
        $data11 = DB::select('call sp_rangking_protas_afd_hi(?,?)', [$tgl, $kebun]);
        // Generate Bootstrap horizontal tables as HTML with Ranking column
        
        // Helper function to get color class based on ranking
        function getRankClass($rank) {
            if ($rank == 1) return 'table-success font-weight-bold';
            if ($rank == 2) return 'table-info font-weight-bold';
            if ($rank == 3) return 'table-warning font-weight-bold';
            return '';
        }

        // Table 1: Kebun
        $html1 = '<h5>Ranking Produktivitas Afdeling (Laporan Timbang)</h5>    
        <table class="table table-bordered table-striped table-hover table-sm table-responsive">
            <thead class="thead-dark">
            <tr>
            <th>No</th>
            <th>Afdeling</th>
            <th>Asman</th>
            <th>takmar</th>
            <th>Hi</th>
            <th>Sd</th>
            <th>%Hi</th>
            <th>%Sd</th>
            </tr>
            </thead>
            <tbody>';
        $rank = 1;
        foreach ($data1 as $row) {
            $class = getRankClass($rank);
            $html1 .= '<tr class="' . $class . '">
            <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
            <td>' . htmlspecialchars($row->kode_afd) . '</td>';
            $html1 .= '<td>' . htmlspecialchars($row->asman_new ?? '') . '</td>';
            $html1 .='<td style="background:#FFF;">' . htmlspecialchars($row->protas_takmar ?? '') . '</td>';
            $html1 .= '<td style="background:#FFF;">';
            $protas_hi1 = 0;
            foreach ($data11 as $row2) {                
                
                if (strtoupper($row->kode_afd) == strtoupper($row2->kode_afd)) {
                    $protas_hi1 = htmlspecialchars($row2->protas);
                    break;
                }
                
            }
            $html1 .= $protas_hi1;
            $html1 .= '</td>';
            $html1 .='<td>' . htmlspecialchars($row->protas) . '</td>';


            // Hitung persentase dan tentukan warna latar belakang
            $protas_hi1_val = is_numeric($protas_hi1) ? (float)$protas_hi1 : 0;
            $protas_takmar_val = is_numeric($row->protas_takmar) ? (float)$row->protas_takmar : 0;
            $percent = ($protas_takmar_val != 0 && $protas_takmar_val != null) ? ($protas_hi1_val / $protas_takmar_val) * 100 : 0;
            $percentFormatted = htmlspecialchars(number_format($percent, 2));
            if ($percent >= 100) {
                $bgcolor = '#28a745'; // hijau
                $color = '#fff';
            } elseif ($percent >= 90) {
                $bgcolor = '#ffc107'; // kuning
                $color = '#000';
            } else {
                $bgcolor = '#dc3545'; // merah
                $color = '#fff';
            }
            $html1 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';

            $percent = ($row->protas_takmar != 0 && $row->protas_takmar != null) ? ($row->protas / $row->protas_takmar) * 100 : 0;
            $percentFormatted = htmlspecialchars(number_format($percent, 2));
            if ($percent >= 100) {
                $bgcolor = '#28a745'; // hijau
                $color = '#fff';
            } elseif ($percent >= 90) {
                $bgcolor = '#ffc107'; // kuning
                $color = '#000';
            } else {
                $bgcolor = '#dc3545'; // merah
                $color = '#fff';
            }
            $html1 .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . $percentFormatted . '%</td>';
            '</tr>';
            $rank++;
        }
        $html1 .= '</tbody></table>';

       

        // Optional: Add a little CSS for better highlight if not already present
        $html1 .= '<style>
        .table-success { background-color: #d4edda !important; }
        .table-info { background-color: #d1ecf1 !important; }
        .table-warning { background-color: #fff3cd !important; }
        .font-weight-bold { font-weight: bold; }
        </style>';

        // Gabungkan semua tabel
        $html = $html1;

        // Return HTML response
        return response($html);

        
}

public function getprotastoptenasman(Request $request){
        // Data
        $tgl = $request->input('tgl');

        // Ambil data dari stored procedure dengan filter tanggal
        $data1 = DB::select('call sp_rangking_klasemen_protas_afd(?)', [$tgl]);
        $data2 = DB::select('call sp_rangking_klasemen_protas_afd_jawa(?, ?)', [$tgl,'JAWA']);
        $data3 = DB::select('call sp_rangking_klasemen_protas_afd_jawa(?, ?)', [$tgl,'LUAR JAWA']);
        // Generate Bootstrap horizontal tables as HTML with Ranking column
        

        // Card view for TOP 10 KLASEMEN PROTAS 2025
        // Card view for TOP 10 KLASEMEN PROTAS 2025
        // Card view for TOP 10 KLASEMEN PROTAS 2025 dengan list geser ke kanan (horizontal scroll)
        $html1 = '<div class="row justify-content-center"><div class="col-12 text-center">'
            . '<h5 style="color:#3345a1;font-weight:bold;">🏆 10 BESAR JUARA PROTAS NASIONAL '.$this->tahun.'<br><span style="font-size:15px;color:#28a745;">Afdeling Terproduktif Tahun Ini!</span></h5>'
            . '</div></div>';
        // Tambahkan wrapper untuk animasi scroll otomatis
        $html1 .= '
        <div id="autoscroll-container" style="overflow-x:auto; white-space:nowrap; position:relative;">
            <div id="autoscroll-list" class="d-flex flex-row" style="gap:18px; padding-bottom:10px; transition:transform 0.5s;">
        ';
        $rank = 1;
        foreach ($data1 as $row) {
            // Icon for top ten (trophy for top 3, star for 4-10)
            if ($rank == 1) {
            $icon = '<i class="fas fa-trophy animate-trophy" style="color:#ffd700;font-size:28px;"></i>';
            } elseif ($rank == 2) {
            $icon = '<i class="fas fa-trophy animate-trophy" style="color:#c0c0c0;font-size:28px;"></i>';
            } elseif ($rank == 3) {
            $icon = '<i class="fas fa-trophy animate-trophy" style="color:#cd7f32;font-size:28px;"></i>';
            } else {
            $icon = '<i class="fas fa-star animate-star" style="color:#007bff;font-size:22px;"></i>';
            }
            $foto = '/uploads/foto_asman/' . (empty($row->nik) || !file_exists(public_path('uploads/foto_asman/' . $row->nik . '.jpg')) ? 'avatar.png' : htmlspecialchars($row->nik) . '.jpg');
            $html1 .= '
            <div class="card shadow-sm animate-card" style="min-width:260px; max-width:260px; margin-right:8px; border-radius:12px; display:inline-block;">
            <div class="card-body text-center">
            <div style="margin-bottom:8px;">' . $icon . '</div>
            <img src="' . $foto . '" alt="Foto Asman" class="animate-img" style="max-width:60px;max-height:60px;border-radius:50%;box-shadow:0 2px 8px #bbb;">
            <h6 class="mt-2 mb-1" style="font-weight:bold;color:#3345a1;">' . htmlspecialchars($row->asman_new ?? '-') . '</h6>
            <div style="font-size:13px;color:#888;">Afdeling: <span style="color:#007bff;">' . htmlspecialchars($row->kode_afd) . '</span></div>
            <div style="font-size:13px;color:#888;">Rayon: <span style="color:#007bff;">' . htmlspecialchars($row->rayon ?? '-') . '</span></div>
            <div style="font-size:13px;color:#444;margin-top:8px;">
            <strong>Total Luas:</strong> ' . number_format($row->total_luas, 2) . ' Ha<br>
            <strong>Total Tebu:</strong> ' . number_format($row->total_tebu, 2) . ' Ton
            </div>
            <div style="font-size:15px;font-weight:bold;color:#28a745;margin-top:6px;">' . htmlspecialchars($row->protas) . ' <span style="font-size:12px;color:#555;">ton/ha</span></div>
            <div style="font-size:13px;color:#555;margin-top:4px;">Ranking: <span style="font-weight:bold;">' . $rank . '</span></div>
            </div>
            </div>';
            $rank++;
        }
        $html1 .= '</div></div>';
        // Tambahkan script untuk auto scroll kekiri dan kembali ke awal
        $html1 .= '
        <script>
        (function(){
            var container = document.getElementById("autoscroll-container");
            var list = document.getElementById("autoscroll-list");
            var scrollAmount = 0;
            var maxScroll = list.scrollWidth - container.clientWidth;
            var direction = 1;
            var paused = false;
            function autoScroll() {
            if (paused || maxScroll <= 0) return;
            scrollAmount += direction * 2;
            if (scrollAmount >= maxScroll) {
                direction = -1;
                scrollAmount = maxScroll;
            } else if (scrollAmount <= 0) {
                direction = 1;
                scrollAmount = 0;
            }
            container.scrollLeft = scrollAmount;
            }
            setInterval(autoScroll, 30);
            window.addEventListener("resize", function(){
            maxScroll = list.scrollWidth - container.clientWidth;
            });
            container.addEventListener("mouseenter", function() {
            paused = true;
            });
            container.addEventListener("mouseleave", function() {
            paused = false;
            });
        })();
        </script>
        ';

        // Card view for Jawa
        $html1 .= '<div class="row justify-content-center mt-4"><div class="col-12 text-center">'
            . '<h5 style="color:#3345a1;font-weight:bold;">🏆 10 BESAR JUARA PROTAS JAWA '.$this->tahun.'<br><span style="font-size:15px;color:#28a745;">Afdeling Terproduktif di Jawa!</span></h5>'
            . '</div></div>';
        $html1 .= '<div class="d-flex flex-row overflow-auto" style="gap:18px; padding-bottom:10px;">';
        $rank = 1;  
        foreach ($data2 as $row) {
            // Icon for top ten (trophy for top 3, star for 4-10)
            if ($rank == 1) {
                $icon = '<i class="fas fa-trophy animate-trophy" style="color:#ffd700;font-size:28px;"></i>';
            } elseif ($rank == 2) {
                $icon = '<i class="fas fa-trophy animate-trophy" style="color:#c0c0c0;font-size:28px;"></i>';
            } elseif ($rank == 3) {
                $icon = '<i class="fas fa-trophy animate-trophy" style="color:#cd7f32;font-size:28px;"></i>';
            } else {
                $icon = '<i class="fas fa-star animate-star" style="color:#007bff;font-size:22px;"></i>';
            }
            $foto = '/uploads/foto_asman/' . (empty($row->nik) || !file_exists(public_path('uploads/foto_asman/' . $row->nik . '.jpg')) ? 'avatar.png' : htmlspecialchars($row->nik) . '.jpg');
            $html1 .= '
            <div class="card shadow-sm animate-card" style="min-width:260px; max-width:260px; margin-right:8px; border-radius:12px;">
            <div class="card-body text-center">
                <div style="margin-bottom:8px;">' . $icon . '</div>
                <img src="' . $foto . '" alt="Foto Asman" class="animate-img" style="max-width:60px;max-height:60px;border-radius:50%;box-shadow:0 2px 8px #bbb;">
                <h6 class="mt-2 mb-1" style="font-weight:bold;color:#3345a1;">' . htmlspecialchars($row->asman_new ?? '-') . '</h6>
                <div style="font-size:13px;color:#888;">Afdeling: <span style="color:#007bff;">' . htmlspecialchars($row->kode_afd) . '</span></div>
                <div style="font-size:13px;color:#888;">Rayon: <span style="color:#007bff;">' . htmlspecialchars($row->rayon ?? '-') . '</span></div>
                <div style="font-size:13px;color:#444;margin-top:8px;">
                <strong>Total Luas:</strong> ' . number_format($row->total_luas, 2) . ' Ha<br>
                <strong>Total Tebu:</strong> ' . number_format($row->total_tebu, 2) . ' Ton
                </div>
                <div style="font-size:15px;font-weight:bold;color:#28a745;margin-top:6px;">' . htmlspecialchars($row->protas) . ' <span style="font-size:12px;color:#555;">ton/ha</span></div>
                <div style="font-size:13px;color:#555;margin-top:4px;">
                Ranking: <span style="font-weight:bold;">' . $rank . '</span></div>
            </div>
            </div>';
            $rank++;
        }
        $html1 .= '</div>';
        
        // Card view for Luar Jawa
        $html1 .= '<div class="row justify-content-center mt-4"><div class="col-12 text-center">'
            . '<h5 style="color:#3345a1;font-weight:bold;">🏆 10 BESAR JUARA PROTAS LUAR JAWA '.$this->tahun.'<br><span style="font-size:15px;color:#28a745;">Afdeling Terproduktif di Luar Jawa!</span></h5>'
            . '</div></div>';
        $html1 .= '<div class="d-flex flex-row overflow-auto" style="gap:18px; padding-bottom:10px;">';
        $rank = 1;
        foreach ($data3 as $row) {
            // Icon for top ten (trophy for top 3, star for 4-10)
            if ($rank == 1) {
                $icon = '<i class="fas fa-trophy animate-trophy" style="color:#ffd700;font-size:28px;"></i>';
            } elseif ($rank == 2) {
                $icon = '<i class="fas fa-trophy animate-trophy" style="color:#c0c0c0;font-size:28px;"></i>';
            } elseif ($rank == 3) {
                $icon = '<i class="fas fa-trophy animate-trophy" style="color:#cd7f32;font-size:28px;"></i>';
            } else {
                $icon = '<i class="fas fa-star animate-star" style="color:#007bff;font-size:22px;"></i>';
            }
            $foto = '/uploads/foto_asman/' . (empty($row->nik) || !file_exists(public_path('uploads/foto_asman/' . $row->nik . '.jpg')) ? 'avatar.png' : htmlspecialchars($row->nik) . '.jpg');
            $html1 .= '
            <div class="card shadow-sm animate-card" style="min-width:260px; max-width:260px; margin-right:8px; border-radius:12px;">
            <div class="card-body text-center">
                <div style="margin-bottom:8px;">' . $icon . '</div>
                <img src="' . $foto . '" alt="Foto Asman" class="animate-img" style="max-width:60px;max-height:60px;border-radius:50%;box-shadow:0 2px 8px #bbb;">
                <h6 class="mt-2 mb-1" style="font-weight:bold;color:#3345a1;">' . htmlspecialchars($row->asman_new ?? '-') . '</h6>
                <div style="font-size:13px;color:#888;">Afdeling: <span style="color:#007bff;">' . htmlspecialchars($row->kode_afd) . '</span></div>
                <div style="font-size:13px;color:#888;">Rayon: <span style="color:#007bff;">' . htmlspecialchars($row->rayon ?? '-') . '</span></div>
                <div style="font-size:13px;color:#444;margin-top:8px;">
                <strong>Total Luas:</strong> ' . number_format($row->total_luas, 2) . ' Ha<br>
                <strong>Total Tebu:</strong> ' . number_format($row->total_tebu, 2) . ' Ton
                </div>
                <div style="font-size:15px;font-weight:bold;color:#28a745;margin-top:6px;">' . htmlspecialchars($row->protas) . ' <span style="font-size:12px;color:#555;">ton/ha</span></div>
                <div style="font-size:13px;color:#555;margin-top:4px;">
                Ranking: <span style="font-weight:bold;">' . $rank . '</span></div>
            </div>
            </div>';
            $rank++;
        }
        $html1 .= '</div>';

        // Optional: Add a little CSS for better highlight if not already present
        $html1 .= '<style>
        .card.shadow-sm.animate-card { transition: box-shadow 0.2s; }
        .card.shadow-sm.animate-card:hover { box-shadow:0 4px 16px #bbb; transform: scale(1.04); }
        .fa-trophy, .fa-star { vertical-align:middle; }
        .animate-trophy {
            animation: bounceTrophy 1.2s infinite alternate;
        }
        .animate-star {
            animation: pulseStar 1.5s infinite;
        }
        .animate-card {
            animation: fadeInUp 0.7s;
        }
        .animate-img {
            animation: popImg 1.2s;
        }
        @keyframes bounceTrophy {
            0% { transform: translateY(0) scale(1); }
            60% { transform: translateY(-8px) scale(1.1); }
            100% { transform: translateY(0) scale(1); }
        }
        @keyframes pulseStar {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.2); opacity: 0.7; }
            100% { transform: scale(1); opacity: 1; }
        }
        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        @keyframes popImg {
            0% { transform: scale(0.8); opacity: 0; }
            60% { transform: scale(1.1); opacity: 1; }
            100% { transform: scale(1); opacity: 1; }
        }
        </style>';

        // Gabungkan semua tabel
        $html = $html1;

        // Return HTML response
        return response($html);

        
}

public function getrendemenrangking(Request $request)
{
    $tgl = $request->input('tgl');

    // Ambil data dari stored procedure dengan filter tanggal
    $dataRayon = DB::select('call sp_rangking_rendemen_rayon(?)', [$tgl]);
    $dataKebun = DB::select('call sp_rangking_rendemen_kebun(?)', [$tgl]);
    $dataCluster = DB::select('call sp_rangking_rendemen_cluster(?)', [$tgl]);
    $dataJawa = DB::select('call sp_rangking_rendemen_jawanonjawa(?)', [$tgl]);

    $dataRayonHi = DB::select('call sp_rangking_rendemen_rayon_hi(?)', [$tgl]);
    $dataKebunHi = DB::select('call sp_rangking_rendemen_kebun_hi(?)', [$tgl]);
    $dataClusterHi = DB::select('call sp_rangking_rendemen_cluster_hi(?)', [$tgl]);
    $dataJawaHi = DB::select('call sp_rangking_rendemen_jawanonjawa_hi(?)', [$tgl]);

    // Helper function to get color class based on ranking
    $getRankClass = function($rank) {
        if ($rank == 1) return 'table-success font-weight-bold';
        if ($rank == 2) return 'table-info font-weight-bold';
        if ($rank == 3) return 'table-warning font-weight-bold';
        return '';
    };

    // Table: Rayon
    $htmlRayon = '<div class="col-lg-4"><h5>Ranking Rendemen Rayon</h5>
    <table class="table table-bordered table-striped table-hover table-sm table-responsive">
        <thead class="thead-dark">
        <tr>
        <th>No</th>
        <th>Nama Rayon</th>
        <th>Takmar</th>
        <th>Hi</th>
        <th>Sd</th>
        </tr>
        </thead>
        <tbody>';
    $rank = 1;
    foreach ($dataRayon as $row) {
        $class = $getRankClass($rank);
        $htmlRayon .= '<tr class="' . $class . '">
        <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
        <td>' . htmlspecialchars($row->nama_rayon ?? '') . '</td>
        <td style="background:#FFF;">' . htmlspecialchars($row->rendemen_takmar ?? '') . '</td>';
        $htmlRayon .= '<td style="font-size: 15px;">';
        $rendhi = '-';
        foreach ($dataRayonHi as $row2) {
            if (strtoupper($row->nama_rayon) == strtoupper($row2->nama_rayon)) {
                $rendhi = '<span class="badge badge-secondary">' . htmlspecialchars($row2->rendemen) . '</span> <span class="badge badge-success">PG '.$row2->nama_pg.'</span>';
                   
                break;
            }
        }
        $htmlRayon .= $rendhi;
        $htmlRayon .= '</td>';
        $htmlRayon .= '<td style="font-size: 15px;"><span class="badge badge-secondary">' . htmlspecialchars($row->rendemen) . '</span> <span class="badge badge-info">PG '.$row->nama_pg.'</span></td>';
        $htmlRayon .= '</tr>';
        $rank++;
    }
    $htmlRayon .= '</tbody></table></div>';

    // Table: Kebun
    $htmlKebun = '<div class="col-lg-4"><h5>Ranking Rendemen Kebun</h5>
    <table class="table table-bordered table-striped table-hover table-sm table-responsive">
        <thead class="thead-dark">
        <tr>
        <th>No</th>
        <th>Nama Kebun</th>
        <th>Takmar</th>
        <th>Hi</th>
        <th>Sd</th>
        </tr>
        </thead>
        <tbody>';
    $rank = 1;
    foreach ($dataKebun as $row) {
        $class = $getRankClass($rank);
        $htmlKebun .= '<tr class="' . $class . '">
        <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
        <td>' . htmlspecialchars($row->nama_kebun ?? '') . '</td>
        <td style="background:#FFF;">' . htmlspecialchars($row->rendemen_takmar ?? '') . '</td>';
        $htmlKebun .= '<td style="font-size: 15px;">';
         $rendhi = '-';
        foreach ($dataKebunHi as $row2) {
            if (strtoupper($row->nama_kebun) == strtoupper($row2->nama_kebun)) {
                $rendhi = '<span class="badge badge-secondary">' . htmlspecialchars($row2->rendemen) . '</span> <span class="badge badge-success">PG '.$row2->nama_pg.'</span>';
                   
                break;
            }
        }
        $htmlKebun .= $rendhi;
        $htmlKebun .= '</td>';
        $htmlKebun .= '<td style="font-size: 15px;"><span class="badge badge-secondary">' . htmlspecialchars($row->rendemen) . '</span> <span class="badge badge-info">PG '.$row->nama_pg.'</span></td>';
        $htmlKebun .= '</tr>';
        $rank++;
    }
    $htmlKebun .= '</tbody></table></div>';

    // Table: Cluster
    $htmlCluster = '<div class="col-lg-4"><h5>Ranking Rendemen Cluster</h5>
    <table class="table table-bordered table-striped table-hover table-sm table-responsive">
        <thead class="thead-dark">
        <tr>
        <th>No</th>
        <th>Nama Cluster</th>
        <th>Takmar</th>
        <th>Hi</th>
        <th>Sd</th>
        </tr>
        </thead>
        <tbody>';
    $rank = 1;
    foreach ($dataCluster as $row) {
        $class = $getRankClass($rank);
        $htmlCluster .= '<tr class="' . $class . '">
        <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
        <td>' . htmlspecialchars($row->nama_cluster ?? '') . '</td>
        <td style="background:#FFF;">' . htmlspecialchars($row->rendemen_takmar ?? '') . '</td>';
        $htmlCluster .= '<td style="font-size: 15px;">';
                 $rendhi = '-';
        foreach ($dataClusterHi as $row2) {
            if (strtoupper($row->nama_cluster) == strtoupper($row2->nama_cluster)) {
                $rendhi = '<span class="badge badge-secondary">' . htmlspecialchars($row2->rendemen) . '</span> <span class="badge badge-success">PG '.$row2->nama_pg.'</span>';
                   
                break;
            }
        }
        $htmlCluster .= $rendhi;
        $htmlCluster .= '</td>';
        $htmlCluster .= '<td style="font-size: 15px;"><span class="badge badge-secondary">' . htmlspecialchars($row->rendemen) . '</span> <span class="badge badge-info">PG '.$row->nama_pg.'</span></td>';
        $htmlCluster .= '</tr>';
        $rank++;
    }
    $htmlCluster .= '</tbody></table>';
    $htmlCluster .= '<br><h5>Ranking Rendemen Cluster</h5>
    <table class="table table-bordered table-striped table-hover table-sm table-responsive">
        <thead class="thead-dark">
        <tr>
        <th>No</th>
        <th>Nama Cluster</th>
        <th>Takmar</th>
        <th>Hi</th>
        <th>Sd</th>
        </tr>
        </thead>
        <tbody>';
    $rank = 1;
    foreach ($dataJawa as $row) {
        $class = $getRankClass($rank);
        $htmlCluster .= '<tr class="' . $class . '">
        <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
        <td>' . htmlspecialchars($row->jawa_nonjawa ?? '') . '</td>
        <td style="background:#FFF;">' . htmlspecialchars($row->rendemen_takmar ?? '') . '</td>';
        $htmlCluster .= '<td style="font-size: 15px;">';
        $rendhi = '-';
        foreach ($dataJawaHi as $row2) {
            if (strtoupper($row->jawa_nonjawa) == strtoupper($row2->jawa_nonjawa)) {
                $rendhi = '<span class="badge badge-secondary">' . htmlspecialchars($row2->rendemen) . '</span> <span class="badge badge-success">PG '.$row2->nama_pg.'</span>';
                   
                break;
            }
        }
        $htmlCluster .= $rendhi;
        $htmlCluster .= '</td>';
        $htmlCluster .= '<td style="font-size: 15px;"><span class="badge badge-secondary">' . htmlspecialchars($row->rendemen) . '</span> <span class="badge badge-info">PG '.$row->nama_pg.'</span></td>';
        $htmlCluster .= '</tr>';
        $rank++;
    }
    $htmlCluster .= '</tbody></table>';
    $htmlCluster .= '</div>';

    // CSS highlight
    $htmlRayon .= '<style>
    .table-success { background-color:rgb(108, 141, 116) !important; }
    .table-info { background-color: #d1ecf1 !important; }
    .table-warning { background-color: #fff3cd !important; }
    .font-weight-bold { font-weight: bold; }
    </style>';

    // Gabungkan semua tabel
    $html = $htmlRayon . $htmlKebun . $htmlCluster;

    return response($html);
}

public function getmuturangking(Request $request)
{
    $tgl = $request->input('tgl');

    // Ambil data dari stored procedure dengan filter tanggal
    $dataRayon = DB::select('call sp_rangking_mutu_rayon(?)', [$tgl]);
    $dataKebun = DB::select('call sp_rangking_mutu_kebun(?)', [$tgl]);
    $dataCluster = DB::select('call sp_rangking_mutu_cluster(?)', [$tgl]);
    $dataJawa = DB::select('call sp_rangking_mutu_jawanonjawa(?)', [$tgl]);

    $dataRayon2 = DB::select('call sp_rangking_mutu_rayon_hi(?)', [$tgl]);
    $dataKebun2 = DB::select('call sp_rangking_mutu_kebun_hi(?)', [$tgl]);
    $dataCluster2 = DB::select('call sp_rangking_mutu_cluster_hi(?)', [$tgl]);
    $dataJawa2 = DB::select('call sp_rangking_mutu_jawanonjawa_hi(?)', [$tgl]);

    // Helper function to get color class based on ranking
    $getRankClass = function($rank) {
        if ($rank == 1) return 'table-success font-weight-bold';
        if ($rank == 2) return 'table-info font-weight-bold';
        if ($rank == 3) return 'table-warning font-weight-bold';
        return '';
    };

    // Table: Rayon
    $htmlRayon = '<div class="col-lg-4"><h5>Ranking Mutu Rayon</h5>
    <table class="table table-bordered table-striped table-hover table-sm table-responsive">
        <thead class="thead-dark">
        <tr>
        <th>No</th>
        <th>Nama Rayon</th>
        <th>A+B Hi</th>
        <th>A+B sd</th>
        <th>Asman</th>
        </tr>
        </thead>
        <tbody>';
    $rank = 1;
    foreach ($dataRayon as $row) {
        $class = $getRankClass($rank);
        $htmlRayon .= '<tr class="' . $class . '">
        <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
        <td>' . htmlspecialchars($row->nama_rayon ?? '') . '</td>';
        $htmlRayon .= '<td style="background:#FFF;">';
        foreach ($dataRayon2 as $row2) {
            if (strtoupper($row->nama_rayon ?? '') == strtoupper($row2->nama_rayon ?? '')) {
                $htmlRayon .= htmlspecialchars(number_format($row2->mutu)) . '%';
                break;
            }
        }
        $htmlRayon .= '</td>';

        $percent = (float) $row->mutu;
        if ($percent > 90) {
            $bgcolor = '#28a745'; // hijau
            $color = '#fff';
        } elseif ($percent >= 70 && $percent <= 90) {
            $bgcolor = '#ffc107'; // kuning
            $color = '#000';
        } else {
            $bgcolor = '#dc3545'; // merah
            $color = '#fff';
        }
        $htmlRayon .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . htmlspecialchars(number_format($row->mutu)) . '%</td>';
        $htmlRayon .= '<td><button class="btn btn-sm btn-primary" onclick="loadChartMutuAsman2(`'.$tgl.'`,`'.$row->nama_rayon.'`)"><i class="fa fa-eye"></i></button></td>';            

        $htmlRayon .= '</tr>';
        $rank++;
    }
    $htmlRayon .= '</tbody></table></div>';

    // Table: Kebun
    $htmlKebun = '<div class="col-lg-4"><h5>Ranking Mutu Kebun</h5>
    <table class="table table-bordered table-striped table-hover table-sm table-responsive">
        <thead class="thead-dark">
        <tr>
        <th>No</th>
        <th>Nama Kebun</th>
        <th>A+B Hi</th>
        <th>A+B sd</th>
        </tr>
        </thead>
        <tbody>';
    $rank = 1;
    foreach ($dataKebun as $row) {
        $class = $getRankClass($rank);
        $htmlKebun .= '<tr class="' . $class . '">
        <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
        <td>' . htmlspecialchars($row->nama_kebun ?? '') . '</td>';
        // Hitung persentase dan tentukan warna latar belakang
        $htmlKebun .= '<td style="background:#FFF;">';
        foreach ($dataKebun2 as $row2) {
            if (strtoupper($row->nama_kebun ?? '') == strtoupper($row2->nama_kebun ?? '')) {
                $htmlKebun .= htmlspecialchars(number_format($row2->mutu)) . '%';
                break;
            }
        }
        $htmlKebun .= '</td>';
        $percent = (float) $row->mutu;
         if ($percent > 90) {
            $bgcolor = '#28a745'; // hijau
            $color = '#fff';
        } elseif ($percent >= 70 && $percent <= 90) {
            $bgcolor = '#ffc107'; // kuning
            $color = '#000';
        } else {
            $bgcolor = '#dc3545'; // merah
            $color = '#fff';
        }
        $htmlKebun .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . htmlspecialchars(number_format($row->mutu)) . '%</td>';

        $htmlKebun .= '</tr>';
        $rank++;
    }
    $htmlKebun .= '</tbody></table></div>';

    // Table: Cluster
    $htmlCluster = '<div class="col-lg-4"><h5>Ranking Mutu Cluster</h5>
    <table class="table table-bordered table-striped table-hover table-sm table-responsive">
        <thead class="thead-dark">
        <tr>
        <th>No</th>
        <th>Nama Cluster</th>
        <th>A+B Hi</th>
        <th>A+B sd</th>
        </tr>
        </thead>
        <tbody>';
    $rank = 1;
    foreach ($dataCluster as $row) {
        $class = $getRankClass($rank);
        $htmlCluster .= '<tr class="' . $class . '">
        <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
        <td>' . htmlspecialchars($row->nama_cluster ?? '') . '</td>';
        $htmlCluster .= '<td style="background:#FFF;">'; 
        // Hitung persentase dan tentukan warna latar belakang
        foreach ($dataCluster2 as $row2) {
            if (strtoupper($row->nama_cluster ?? '') == strtoupper($row2->nama_cluster ?? '')) {
                $htmlCluster .= htmlspecialchars(number_format($row2->mutu)). '%';
                break;
            }
        }
        $htmlCluster .= '</td>'; 
        $percent = (float) $row->mutu;
         if ($percent > 90) {
            $bgcolor = '#28a745'; // hijau
            $color = '#fff';
        } elseif ($percent >= 70 && $percent <= 90) {
            $bgcolor = '#ffc107'; // kuning
            $color = '#000';
        } else {
            $bgcolor = '#dc3545'; // merah
            $color = '#fff';
        }
        $htmlCluster .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . htmlspecialchars(number_format($row->mutu)) . '%</td>';

        $htmlCluster .= '</tr>';
        $rank++;
    }
    $htmlCluster .= '</tbody></table>';
    $htmlCluster .= '<br><h5>Ranking Mutu Cluster</h5>
    <table class="table table-bordered table-striped table-hover table-sm table-responsive">
        <thead class="thead-dark">
        <tr>
        <th>No</th>
        <th>Nama Cluster</th>
        <th>A+B Hi</th>
        <th>A+B sd</th>
        </tr>
        </thead>
        <tbody>';
    $rank = 1;
    foreach ($dataJawa as $row) {
        $class = $getRankClass($rank);
        $htmlCluster .= '<tr class="' . $class . '">
        <td>' . $rank . ($rank <= 3 ? ' ' : '') . '</td>
        <td>' . htmlspecialchars($row->jawa_nonjawa ?? '') . '</td>';
        $htmlCluster .= '<td style="background:#FFF;">'; 
        // Hitung persentase dan tentukan warna latar belakang
        foreach ($dataJawa2 as $row2) {
            if (strtoupper($row->jawa_nonjawa ?? '') == strtoupper($row2->jawa_nonjawa ?? '')) {
                $htmlCluster .= htmlspecialchars(number_format($row2->mutu)). '%';
                break;
            }
        }
        $htmlCluster .= '</td>'; 
        $percent = (float) $row->mutu;
         if ($percent > 90) {
            $bgcolor = '#28a745'; // hijau
            $color = '#fff';
        } elseif ($percent >= 70 && $percent <= 90) {
            $bgcolor = '#ffc107'; // kuning
            $color = '#000';
        } else {
            $bgcolor = '#dc3545'; // merah
            $color = '#fff';
        }
        $htmlCluster .= '<td style="background:' . $bgcolor . ';color:' . $color . ';">' . htmlspecialchars(number_format($row->mutu)) . '%</td>';

        $htmlCluster .= '</tr>';
        $rank++;
    }
    $htmlCluster .= '</tbody></table>';
    $htmlCluster .= '</div>';

    // CSS highlight
    $htmlRayon .= '<style>
    .table-success { background-color: #d4edda !important; }
    .table-info { background-color: #d1ecf1 !important; }
    .table-warning { background-color: #fff3cd !important; }
    .font-weight-bold { font-weight: bold; }
    </style>';



    // Gabungkan semua tabel
    $html = $htmlRayon . $htmlKebun . $htmlCluster;

    return response($html);
}

public function getlabarugi(Request $request)
{
    // Ambil data dari view vew_lr_margin
    $data = DB::table('view_lr_margin_new3')
        ->select(
           '*')
        ->get();

    $html = '<style>
            .table th, .table thead th{
                    border: solid 1px #d1cbcb;
                }
         
            .tablr th:nth-child(1), .tablr td:nth-child(1) {
                position: sticky;
                left: 0;
                background: #FFF;
                z-index: 11;
            }

            .tablr th:nth-child(2), .tablr td:nth-child(2) {
                position: sticky;
                left: 5.7%;
                background: #FFF;
                z-index: 11;
            }

            .tablr th:nth-child(3), .tablr td:nth-child(3) {
                position: sticky;
                left: 13.1%;
                background: #FFF;
                z-index: 11;
            }

            </style>';    
    $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-hover table-sm table-responsive tablr">';
$html .= '<thead>';

// Baris 1
$html .= '<tr>
    <th rowspan="3" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">JAWA/LUAR</th>
    <th rowspan="3" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">CLUSTER</th>
    <th rowspan="3" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">KEBUN / RAYON</th>
    <th colspan="2" rowspan="2" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">SASARAN RKAP 2025</th>
    <th colspan="2" rowspan="2" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">SASARAN RKO 2025</th>
    <th rowspan="3" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">BEP RKO<br>Rendemen<br>(%)</th>
    <th colspan="2" rowspan="2" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">REALISASI GILING SD</th>
    <th rowspan="3" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Tebu Digiling<br>SD<br>(Ton)</th>
    <th rowspan="3" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">RKAP 2025<br>Ton</th>
    <th colspan="2" rowspan="2" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">SASARAN RKAP</th>
    <th colspan="2" rowspan="2" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">SASARAN RKO</th>
    <th colspan="2" rowspan="2" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">BEP RKO</th>
    <th colspan="2" rowspan="2" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">REAL SD</th>
    <th colspan="6" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">MARGIN REAL THD</th>
</tr>';

// Baris 3
$html .= '<tr>

    <th colspan="2" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Sasaran RKAP</th>
    <th colspan="2" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Sasaran RKO</th>
    <th colspan="2" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">BEP RKO</th>
</tr>';

// Baris 2
$html .= '<tr>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Produktivitas<br>(Ton / Ha)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Rendemen<br>(%)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Produktivitas<br>(Ton / Ha)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Rendemen<br>(%)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Produktivitas<br>(Ton / Ha)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Rendemen<br>(%)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">BH Gula<br>(Kg Gula / Ku Tebu)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Nilai tebu<br>(Rp/Ku)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">BH Gula<br>(Kg Gula / Ku Tebu)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Nilai tebu<br>(Rp/Ku)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">BH Gula<br>(Kg Gula / Ku Tebu)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Nilai tebu<br>(Rp/Ku)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">BH Gula<br>(Kg Gula / Ku Tebu)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Nilai tebu<br>(Rp/Ku)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">(Rp/Ku Tebu)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Rp.000</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">(Rp/Ku Tebu)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Rp.000</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">(Rp/Ku Tebu)</th>
    <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;z-index:0 !important;">Rp.000</th>
</tr>';



$html .= '</thead><tbody>';

    $headers = [
         'jawa_luar','cluster',  'kebun',
        'sasaran_rkap_protas', 'sasaran_rkap_rendemen', 'sasaran_rko_protas', 'sasaran_rko_rendemen', 'bep_rko_rendemen',
         'real_giling_protas', 'real_giling_rendemen', 'real_giling_tebu','rkap_ton',
        'sasaran_rkap_bhgula', 'sasaran_rkap_nilaitebu', 'sasaran_rko_bhgula', 'sasaran_rko_nilaitebu',
        'bep_rko_bhgula', 'bep_rko_nilaitebu', 'real_sd_bhgula', 'real_sd_nilaitebu',
        'margin_sasaran_rkap_rpperkui', 'margin_sasaran_rkap_ribuan',
        'margin_sasaran_rko_rpperkui', 'margin_sasaran_rko_ribuan',
        'margin_bep_rkap_rpperkui', 'margin_bep_rkap_ribuan'
    ];

// (Looping isi data tetap seperti sebelumnya)
foreach ($data as $row) {
    $html .= '<tr>';
    // $real_sd_nilaitebu = 0;
    // $bep_rko_nilaitebu = 0;
    // $sasaran_rkap_nilaitebu = 0;
    // $sasaran_rko_nilaitebu = 0;
    // $margin_sasaran_rkap_rpperkui = 0;
    // $margin_sasaran_rko_rpperkui = 0;
    // $margin_bep_rkap_rpperkui = 0;
    foreach ($headers as $header) {
        $value = isset($row->$header) ? $row->$header : '';
        // if (strpos($header, 'margin_') === 0 || strpos($header, 'nilaitebu') !== false || strpos($header, 'bhgula') !== false || strpos($header, 'tebu') !== false) {
        //     $value = is_numeric($value) ? number_format($value, 2, '.', '') : $value;
        // }

        // if($header == 'real_sd_nilaitebu'){
        //     if($row->real_giling_tebu > 0){
        //         $real_sd_nilaitebu = (round($row->real_sd_bhgula,2) * 14500) + (3 * 1800);  
        //         $value = (round($row->real_sd_bhgula,2) * 14500) + (3 * 1800);
        //     } else {
        //         $value = '-';
        //     }
        // }
        // if($header == 'bep_rko_nilaitebu'){
        //     if($row->real_giling_tebu > 0){
        //         $bep_rko_nilaitebu = (round($row->bep_rko_bhgula,2) * 14500) + (3 *  2288);  
        //         $value = (round($row->bep_rko_bhgula,2) * 14500) + (3 *  2288);
        //     } else {
        //         $value = '-';
        //     }
        // }
        // if($header == 'sasaran_rkap_nilaitebu'){
        //     if($row->real_giling_tebu > 0){
        //         $sasaran_rkap_nilaitebu = (round($row->sasaran_rkap_bhgula,2) * 14500) + (3 *  2288);  
        //         $value = (round($row->sasaran_rkap_bhgula,2) * 14500) + (3 *  2288);
        //     } else {
        //         $value = '-';
        //     }
        // }
        // if($header == 'sasaran_rko_nilaitebu'){
        //     if($row->real_giling_tebu > 0){
        //         $sasaran_rko_nilaitebu = (round($row->sasaran_rko_bhgula,2) * 14500) + (3 *  2288);  
        //         $value = (round($row->sasaran_rko_bhgula,2) * 14500) + (3 *  2288);
        //     } else {
        //         $value = '-';
        //     }
        // }

        // if($header == 'margin_sasaran_rkap_rpperkui'){
        //     if($row->real_giling_tebu > 0){
        //         $margin_sasaran_rkap_rpperkui = $real_sd_nilaitebu-$sasaran_rkap_nilaitebu;
        //         $value = $real_sd_nilaitebu-$sasaran_rkap_nilaitebu;
        //     } else {
        //         $value = '-';
        //     }
        // }

        // if($header == 'margin_sasaran_rko_rpperkui'){
        //     if($row->real_giling_tebu > 0){
        //         $margin_sasaran_rko_rpperkui = $real_sd_nilaitebu-$sasaran_rko_nilaitebu;
        //         $value = $real_sd_nilaitebu-$sasaran_rko_nilaitebu;
        //     } else {
        //         $value = '-';
        //     }
        // }
        // if($header == 'margin_bep_rkap_rpperkui'){
        //     if($row->real_giling_tebu > 0){
        //         $margin_bep_rkap_rpperkui = $real_sd_nilaitebu-$bep_rko_nilaitebu;
        //         $value = $real_sd_nilaitebu-$bep_rko_nilaitebu;
        //     } else {
        //         $value = '-';
        //     }
        // }

        // if($header == 'margin_sasaran_rkap_ribuan'){
        //         $value = ((round($row->real_giling_tebu,2)*10)*round($margin_sasaran_rkap_rpperkui,2))/1000;
        // }
        // if($header == 'margin_sasaran_rko_ribuan'){

        //         $value = ((round($row->real_giling_tebu,2)*10)*round($margin_sasaran_rko_rpperkui,2))/1000;
        // }
        // if($header == 'margin_bep_rkap_ribuan'){
        //         $value = ((round($row->real_giling_tebu,2)*10)*round($margin_bep_rkap_rpperkui,2))/1000;
        // }




        // Format khusus untuk field margin_sasaran_rkap_ribuan, margin_sasaran_rko_ribuan, margin_bep_rkap_ribuan
        if (in_array($header, [
            'margin_sasaran_rkap_ribuan',
            'margin_sasaran_rko_ribuan',
            'margin_bep_rkap_ribuan',
            'margin_sasaran_rkap_rpperkui',
            'margin_sasaran_rko_rpperkui',
            'margin_bep_rkap_rpperkui'
        ])) {
            $formattedValue = is_numeric($value) && $value < 0
            ? '(' . number_format(abs($value), 0) . ')'
            : (is_numeric($value) ? (number_format($value, 0) === '0' ? '-' : number_format($value, 0)) : $value);
        } else {
            $formattedValue = is_numeric($value) && $value < 0
            ? '(' . number_format(abs($value), 2) . ')'
            : (is_numeric($value) ? (number_format($value, 2) === '0.00' ? '-' : number_format($value, 2)) : $value);
        }

        $html .= '<td style="text-align:' . (is_numeric($value) ? 'right' : 'left') . ';' . (is_numeric($value) && $value < 0 ? 'color:red;' : '') . '">' .
            (strpos($row->kebun, 'TOTAL') !== false ? '<strong>' : '') .
            htmlspecialchars($formattedValue) .
            (strpos($row->kebun, 'TOTAL') !== false ? '</strong>' : '') .
        '</td>';
    }
    $html .= '</tr>';
}

$html .= '</tbody></table>
 <p style="font-size: 12px; color: red; margin-top: 10px;">
        <strong>Note:</strong> BEP RKO mengacu pada total biaya tebu giling, biaya TMA, dan NKM.
    </p>
    </div>';

return response($html);

}

public function getlabarugi2(Request $request)
{
    $data = DB::table('data_margin_lr')->get();
    $periode = DB::table('data_margin_lr_periode')->first();
    $html = '<style>
         .table th, .table thead th{
                    border: solid 1px #d1cbcb;
                }
         
            .tablr th:nth-child(1), .tablr td:nth-child(1) {
                position: sticky;
                left: 0;
                background: #FFF;
                z-index: 11;
            }

            .tablr th:nth-child(2), .tablr td:nth-child(2) {
                position: sticky;
                left: 5.5%;
                background: #FFF;
                z-index: 11;
            }

            .tablr th:nth-child(3), .tablr td:nth-child(3) {
                position: sticky;
                left: 10.1%;
                background: #FFF;
                z-index: 11;
            }

    </style>';
    $html .= '<div style="font-weight:bold;font-size:18px;color:#222;margin-bottom:8px;">PENCAPAIAN LABA RUGI TS 2025 - PER KEBUN</div>';
    // Format tanggal ke tgl/bln/thn
    $periode_str = '';
    if (!empty($periode->periode)) {
        $dt = date_create($periode->periode);
        $periode_str = date_format($dt, 'd/m/Y');
    }
    $html .= '<div style="font-style:italic;font-size:15px;color:#222;margin-bottom:12px;"><span style="font-weight:bold;">PERIODE SD</span> <span style="font-weight:bold;">' . htmlspecialchars($periode_str) . '</span></div>';
    $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-hover table-sm table-responsive tablr">';
    $html .= '<thead><tr>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">CLUSTER</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">KODE KEBUN</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">KEBUN / RAYON</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Sasaran Tebu Digiling<br>(Ton)</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Real Tebu Digiling<br>SD<br>(Ton)</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;" colspan="2">REALISASI GILING SD</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Harga Gula (real)</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Harga Tetes (real)</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Pendapatan Gula (Rp)</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Pendapatan Tetes (Rp)</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Real BDD</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Biaya Teralokasi</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">% Alokasi Bia</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">COGM Kinerja</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Margin Kinerja</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Real Margin/Ton Tebu</th>
        </tr>
        <tr>
        <th colspan="5" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;"></th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Gula</th>
        <th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">Tetes</th>
        <th colspan="10" style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;"></th>
        </tr>
    </tr></thead><tbody>';

    $subtotal = [];
    $grandtotal = [
        'sasaran_tebu_digiling' => 0,
        'real_tebu_digiling' => 0,
        'margin_per_rayon' => 0,
        'realisasi_giling_sd' => 0,
        'realisasi_giling_sd_ton' => 0,
        'harga_gula' => 0,
        'harga_tetes' => 0,
        'pendapatan_gula' => 0,
        'pendapatan_tetes' => 0,
        'real_bdd' => 0,
        'biaya_teralokasi' => 0,
        'persen_alokasi_bia' => 0,
        'cogm_kinerja' => 0,
        'margin_kinerja' => 0,
        'real_margin_per_ton' => 0,
        'count' => 0
    ];
    $prev_cluster = null;
    foreach ($data as $row) {
        // Inisialisasi subtotal jika cluster berubah
        if ($prev_cluster !== null && $row->cluster !== $prev_cluster) {
            // Tampilkan subtotal untuk cluster sebelumnya
            $html .= '<tr style="background:#eafaf1;font-weight:bold;">';
            $html .= '<td >Subtotal ' . htmlspecialchars($prev_cluster) . '</td>';
            $html .= '<td ></td>';
            $html .= '<td ></td>';
            $html .= '<td style="text-align:right;' . ($subtotal['sasaran_tebu_digiling'] < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['sasaran_tebu_digiling'], 2) . '</td>';
            $html .= '<td style="text-align:right;' . ($subtotal['real_tebu_digiling'] < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['real_tebu_digiling'], 2) . '</td>';
            $html .= '<td style="text-align:right;' . ($subtotal['realisasi_giling_sd'] < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['realisasi_giling_sd'], 3) . '</td>';
            $html .= '<td style="text-align:right;' . ($subtotal['realisasi_giling_sd_ton'] < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['realisasi_giling_sd_ton'], 3) . '</td>';
            $html .= '<td style="text-align:right;"></td>';
            $html .= '<td style="text-align:right;"></td>';
            $html .= '<td style="text-align:right;' . ($subtotal['pendapatan_gula'] < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['pendapatan_gula'], 0) . '</td>';
            $html .= '<td style="text-align:right;' . ($subtotal['pendapatan_tetes'] < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['pendapatan_tetes'], 0) . '</td>';
            $html .= '<td style="text-align:right;' . ($subtotal['real_bdd'] < 0 ? 'color:red;' : '') . '">' . ($subtotal['real_bdd'] ? number_format($subtotal['real_bdd'], 0) : '') . '</td>';
            $html .= '<td style="text-align:right;' . ($subtotal['biaya_teralokasi'] < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['biaya_teralokasi'], 0) . '</td>';
            $html .= '<td style="text-align:right;' . ($subtotal['persen_alokasi_bia'] / max($subtotal['count'], 1) < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['persen_alokasi_bia'] / max($subtotal['count'], 1), 2) . '</td>';
            $html .= '<td style="text-align:right;' . ($subtotal['cogm_kinerja'] < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['cogm_kinerja'], 0) . '</td>';
            $html .= '<td style="text-align:right;' . ($subtotal['margin_kinerja'] < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['margin_kinerja'], 0) . '</td>';
            $html .= '<td style="text-align:right;' . ($subtotal['margin_kinerja']/$subtotal['real_tebu_digiling'] < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['margin_kinerja']/$subtotal['real_tebu_digiling'], 0) . '</td>';
            $html .= '</tr>';
            $subtotal = [];
        }
        // Tampilkan baris data
        $html .= '<tr>';
        $html .= '<td>' . htmlspecialchars($row->cluster) . '</td>';
        $html .= '<td>' . htmlspecialchars($row->kode_kebun) . '</td>';
        $html .= '<td>' . htmlspecialchars($row->kebun_rayon) . '</td>';
        $html .= '<td style="text-align:right;">' . number_format($row->sasaran_tebu_digiling, 2) . '</td>';
        $html .= '<td style="text-align:right;">' . number_format($row->real_tebu_digiling, 2) . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->realisasi_giling_sd < 0 ? 'color:red;' : '') . '">' . number_format($row->realisasi_giling_sd, 3) . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->realisasi_giling_sd_ton < 0 ? 'color:red;' : '') . '">' . number_format($row->realisasi_giling_sd_ton, 3) . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->harga_gula < 0 ? 'color:red;' : '') . '">' . number_format($row->harga_gula, 0) . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->harga_tetes < 0 ? 'color:red;' : '') . '">' . number_format($row->harga_tetes, 0) . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->pendapatan_gula < 0 ? 'color:red;' : '') . '">' . number_format($row->pendapatan_gula, 0) . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->pendapatan_tetes < 0 ? 'color:red;' : '') . '">' . number_format($row->pendapatan_tetes, 0) . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->real_bdd < 0 ? 'color:red;' : '') . '">' . ($row->real_bdd ? number_format($row->real_bdd, 0) : '') . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->biaya_teralokasi < 0 ? 'color:red;' : '') . '">' . number_format($row->biaya_teralokasi, 0) . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->persen_alokasi_bia < 0 ? 'color:red;' : '') . '">' . number_format($row->persen_alokasi_bia, 2) . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->cogm_kinerja < 0 ? 'color:red;' : '') . '">' . number_format($row->cogm_kinerja, 0) . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->margin_kinerja < 0 ? 'color:red;' : '') . '">' . number_format($row->margin_kinerja, 0) . '</td>';
        $html .= '<td style="text-align:right;' . ((float)$row->real_margin_per_ton < 0 ? 'color:red;' : '') . '">' . number_format($row->real_margin_per_ton, 0) . '</td>';
        $html .= '</tr>';
        // Akumulasi subtotal
        if (!isset($subtotal['count'])) $subtotal['count'] = 0;
        foreach ($grandtotal as $key => $v) {
            if ($key == 'count') continue;
            $subtotal[$key] = ($subtotal[$key] ?? 0) + ($row->$key ?? 0);
            $grandtotal[$key] += ($row->$key ?? 0);
        }
        $subtotal['count']++;
        $grandtotal['count']++;
        $prev_cluster = $row->cluster;
    }
    // Tampilkan subtotal terakhir
    if ($prev_cluster !== null && $subtotal) {
        $html .= '<tr style="background:#eafaf1;font-weight:bold;">';
        $html .= '<td >Subtotal ' . htmlspecialchars($prev_cluster) . '</td>';
        $html .= '<td ></td>';
        $html .= '<td ></td>';
        $html .= '<td style="text-align:right;">' . number_format($subtotal['sasaran_tebu_digiling'], 2) . '</td>';
        $html .= '<td style="text-align:right;">' . number_format($subtotal['real_tebu_digiling'], 2) . '</td>';
        $html .= '<td style="text-align:right;">' . number_format($subtotal['realisasi_giling_sd'], 3) . '</td>';
        $html .= '<td style="text-align:right;">' . number_format($subtotal['realisasi_giling_sd_ton'], 3) . '</td>';
        $html .= '<td style="text-align:right;"></td>';
        $html .= '<td style="text-align:right;"></td>';
        $html .= '<td style="text-align:right;">' . number_format($subtotal['pendapatan_gula'], 0) . '</td>';
        $html .= '<td style="text-align:right;">' . number_format($subtotal['pendapatan_tetes'], 0) . '</td>';
        $html .= '<td style="text-align:right;">' . ($subtotal['real_bdd'] ? number_format($subtotal['real_bdd'], 0) : '') . '</td>';
        $html .= '<td style="text-align:right;">' . number_format($subtotal['biaya_teralokasi'], 0) . '</td>';
        $html .= '<td style="text-align:right;">' . number_format($subtotal['persen_alokasi_bia'] / max($subtotal['count'], 1), 2) . '</td>';
        $html .= '<td style="text-align:right;">' . number_format($subtotal['cogm_kinerja'], 0) . '</td>';
        $html .= '<td style="text-align:right;' . ($subtotal['margin_kinerja'] < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['margin_kinerja'], 0) . '</td>';
        $html .= '<td style="text-align:right;' . (($subtotal['margin_kinerja']/$subtotal['real_tebu_digiling']) < 0 ? 'color:red;' : '') . '">' . number_format($subtotal['margin_kinerja']/$subtotal['real_tebu_digiling'], 0) . '</td>';
        $html .= '</tr>';
    }

    $html .= '<tr style="background:#eafaf1;font-weight:bold;">';
    $html .= '<td >Grand Total</td>';
    $html .= '<td ></td>';
    $html .= '<td ></td>';
    $html .= '<td style="text-align:right;">' . number_format($grandtotal['sasaran_tebu_digiling'], 2) . '</td>';
    $html .= '<td style="text-align:right;">' . number_format($grandtotal['real_tebu_digiling'], 2) . '</td>';
    $html .= '<td style="text-align:right;">' . number_format($grandtotal['realisasi_giling_sd'], 3) . '</td>';
    $html .= '<td style="text-align:right;">' . number_format($grandtotal['realisasi_giling_sd_ton'], 3) . '</td>';
    $html .= '<td style="text-align:right;"></td>';
    $html .= '<td style="text-align:right;"></td>';
    $html .= '<td style="text-align:right;">' . number_format($grandtotal['pendapatan_gula'], 0) . '</td>';
    $html .= '<td style="text-align:right;">' . number_format($grandtotal['pendapatan_tetes'], 0) . '</td>';
    $html .= '<td style="text-align:right;">' . ($grandtotal['real_bdd'] ? number_format($grandtotal['real_bdd'], 0) : '') . '</td>';
    $html .= '<td style="text-align:right;">' . number_format($grandtotal['biaya_teralokasi'], 0) . '</td>';
    $html .= '<td style="text-align:right;">' . number_format($grandtotal['persen_alokasi_bia'] / max($grandtotal['count'], 1), 2) . '</td>';
    $html .= '<td style="text-align:right;">' . number_format($grandtotal['cogm_kinerja'], 0) . '</td>';
    $html .= '<td style="text-align:right;' . ($grandtotal['margin_kinerja'] < 0 ? 'color:red;' : '') . '">' . number_format($grandtotal['margin_kinerja'], 0) . '</td>';
    $html .= '<td style="text-align:right;' . (($grandtotal['margin_kinerja']/$grandtotal['real_tebu_digiling']) < 0 ? 'color:red;' : '') . '">' . ($grandtotal['real_tebu_digiling'] > 0 ? number_format($grandtotal['margin_kinerja']/$grandtotal['real_tebu_digiling'], 0) : '-') . '</td>';
    $html .= '</tr>';
    // Tampilkan grand total

    $html .= '</tbody></table></div>';
    $html .= '<div style="font-size:13px;color:#444;margin-top:12px;padding:10px 0 0 0;">
        <strong>Disclaimer:</strong>
        <ul style="font-size:13px;line-height:1.7;">
            <li>Perhitungan menggunakan pendekatan akuntansi manajemen</li>
            <li>Pendapatan dihitung berdasarkan total produksi gula dan tetes dengan asumsi terjual semua.</li>
            <li>BDD adalah Biaya yang ditangguhkan yang tercatat di SAP per 31 Juli 2025</li>
            <li>Biaya teralokasi adalah biaya COGM yang sudah diturunkan atau dialokasikan per periode closing Juli di SAP</li>
            <li>Perhitungan Margin kinerja tidak menghitung Persediaan awal dan Akhir</li>
            <li>% Alokasi Biaya Berdasarkan Tebu tergiling terhadap sasaran tebu (RKO)</li>
            <li>Pendapatan (gula dan tetes per ton dikali harga dibagi tebu tergiling)</li>
            <li>Biaya per ton tebu s/d dihitung berdasarkan realisasi biaya (BDD + Biaya teralokasi di SAP) x Realisasi Alokasi tebu (Tebu Tergiling / Tebu RKAP)</li>
            <li>Margin kinerja = Pendapatan dikurangi biaya</li>
        </ul>
    </div>';

    return response($html);
}

public function getRekapMonevPasok(Request $request)
{
    $tgl = $request->input('date');

    // Call the stored procedure to fetch data
    $data = DB::select('call sp_rekap_monev_pasok(?)', [$tgl]);

    // Process the data if needed
    $processedData = collect($data)->map(function ($item) {
        return [
            'nama_kebun' => $item->nama_kebun,
            'ton_takmar' => (float) $item->ton_takmar,
            'sasaran_harian' => (float) $item->sasaran_harian,
            'real_hi' => (float) $item->real_hi,
            'real_sd' => (float) $item->real_sd,
            'real_3' => (float) $item->real_3,
            'persen_sd' => round((float) $item->persen_sd, 2),
            'persen_hi' => round((float) $item->persen_hi, 2),
            'persen_3' => round((float) $item->persen_3, 2),
        ];
    });

    $html = '<style>
            .table th, .table thead th{
                    border: solid 1px #d1cbcb;
                }
            </style>';    
    // Generate HTML table
    $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-striped table-hover table-sm table-responsive">';
    $html .= '<thead>';
    $html .= '<tr>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;" rowspan="3">Nama Kebun</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;" rowspan="3">SASARAN<br>PASOK HARIAN<br>(Ton/Hari)</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;" colspan="5">REALISASI PASOK TS <br>(LAPORAN TIMBANG HARIAN) </th>';
    $html .= '<tr>';

    $html .= '<tr>';
    // $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">TAKSASI MARET<br>(Ton)</th>';
    // $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">SASARAN PASOK HARIAN<br>(Ton/Hari)</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">HI<br>(Ton)</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">SD<br>(Ton)</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">RERATA<br>PASOK 3 HARI<br>TERAKHIR<br>(Ton/Hari)</th>';
    // $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">% SD THD TOTAL<br>TAKSASI MARET</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">% HI THD<br>SASARAN<br>HARIAN TAKMAR</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">% RERATA 3<br>HARIAN THD<br>SASARAN<br>HARIAN</th>';
    $html .= '</tr>';
    $html .= '</thead>';
    $html .= '<tbody>';

    $headers = [
        'nama_kebun',	'sasaran_harian',	'real_hi',	'real_sd',	'real_3',	'persen_hi',	'persen_3'
    ];

// (Looping isi data tetap seperti sebelumnya)
foreach ($processedData as $row) {
    $html .= '<tr>';
    foreach ($headers as $header) {
        $value = isset($row[$header]) ? $row[$header] : '';
        
        $html .= '<td style="text-align:' . (is_numeric($value) ? 'right' : 'left') . ';' . (is_numeric($value) && $value < 0 ? 'color:red;' : '') . '">' . 
            (strpos($row['nama_kebun'], 'TOTAL') !== false || strpos($row['nama_kebun'], 'CLUSTER') !== false ? '<strong>' : '') . 
            htmlspecialchars(is_numeric($value) && $value < 0 ? '(' . number_format(abs($value), 2) . ')' : (is_numeric($value) ? (number_format($value, 2) === '0.00' ? '-' : number_format($value, 2)) : $value)) . 
            (strpos($row['nama_kebun'], 'TOTAL') !== false || strpos($row['nama_kebun'], 'CLUSTER') !== false ? '</strong>' : '') . 
            ($header === 'persen_sd' ? ($row['real_sd'] > $row['ton_takmar'] ? ' <i class="fas fa-caret-up" style="color:green;"></i>' : ' <i class="fas fa-caret-down" style="color:red;"></i>') : '') . 
            ($header === 'persen_hi' ? ($row['real_hi'] > $row['sasaran_harian'] ? ' <i class="fas fa-caret-up" style="color:green;"></i>' : ' <i class="fas fa-caret-down" style="color:red;"></i>') : '') . 
            ($header === 'persen_3' ? ($row['real_3'] > $row['sasaran_harian'] ? ' <i class="fas fa-caret-up" style="color:green;"></i>' : ' <i class="fas fa-caret-down" style="color:red;"></i>') : '') . 
        '</td>';
    }
    $html .= '</tr>';
}

    $html .= '</tbody>';
    $html .= '</table>
    </div>';
    $html .= '<p style="font-size: 12px; color: red; margin-top: 10px;">
        <strong>Note:</strong> Sasaran Pasok harian berdasarkan Sisa Tebu Prognosa Terakhir dan update estimasi akhir tebang/giling.
    </p>';



    // Return the HTML response
    return response($html);
}

public function getRekapMonevPasokRayon(Request $request)
{
    $tgl = $request->input('date');

    // Call the stored procedure to fetch data
    $data = DB::select('call sp_rekap_monev_pasok_rayon(?)', [$tgl]);

    // Process the data if needed
    $processedData = collect($data)->map(function ($item) {
        return [
            'nama_kebun' => $item->nama_kebun,
            'ton_takmar' => (float) $item->ton_takmar,
            'sasaran_harian' => (float) $item->sasaran_harian,
            'real_hi' => (float) $item->real_hi,
            'real_sd' => (float) $item->real_sd,
            'real_3' => (float) $item->real_3,
            'persen_sd' => round((float) $item->persen_sd, 2),
            'persen_hi' => round((float) $item->persen_hi, 2),
            'persen_3' => round((float) $item->persen_3, 2),
        ];
    });

    $html = '<style>
            .table th, .table thead th{
                    border: solid 1px #d1cbcb;
                }
            </style>';    
    // Generate HTML table
    $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-striped table-hover table-sm table-responsive">';
    $html .= '<thead>';
    $html .= '<tr>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;" rowspan="3">Nama Rayon</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;" rowspan="3">SASARAN<br>PASOK HARIAN<br>(Ton/Hari)</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;" colspan="6">REALISASI PASOK TS <br>(LAPORAN TIMBANG HARIAN) </th>';
    $html .= '<tr>';

    $html .= '<tr>';
    // $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">TAKSASI MARET<br>(Ton)</th>';
    // $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">HARIAN<br>(Ton/Hari)</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">HI<br>(Ton)</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">SD<br>(Ton)</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">RERATA<br>PASOK 3 HARI<br>TERAKHIR<br>(Ton/Hari)</th>';
    // $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">% SD THD TOTAL<br>TAKSASI MARET</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">% HI THD<br>SASARAN<br>HARIAN TAKMAR</th>';
    $html .= '<th style="background: #4c4c80;color: #FFF;font-size:12px;text-align:center;vertical-align:middle;">% RERATA 3<br>HARIAN THD<br>SASARAN<br>HARIAN</th>';
    $html .= '</tr>';
    $html .= '</thead>';
    $html .= '<tbody>';

    $headers = [
        'nama_kebun',		'sasaran_harian',	'real_hi',	'real_sd',	'real_3',		'persen_hi',	'persen_3'
    ];

// (Looping isi data tetap seperti sebelumnya)
foreach ($processedData as $row) {
    $html .= '<tr>';
    foreach ($headers as $header) {
        $value = isset($row[$header]) ? $row[$header] : '';
        
        $html .= '<td style="text-align:' . (is_numeric($value) ? 'right' : 'left') . ';' . (is_numeric($value) && $value < 0 ? 'color:red;' : '') . '">' . 
            (strpos($row['nama_kebun'], 'TOTAL') !== false || strpos($row['nama_kebun'], 'CLUSTER') !== false ? '<strong>' : '') . 
            htmlspecialchars(is_numeric($value) && $value < 0 ? '(' . number_format(abs($value), 2) . ')' : (is_numeric($value) ? (number_format($value, 2) === '0.00' ? '-' : number_format($value, 2)) : $value)) . 
            (strpos($row['nama_kebun'], 'TOTAL') !== false || strpos($row['nama_kebun'], 'CLUSTER') !== false ? '</strong>' : '') . 
            ($header === 'persen_sd' ? ($row['real_sd'] > $row['ton_takmar'] ? ' <i class="fas fa-caret-up" style="color:green;"></i>' : ' <i class="fas fa-caret-down" style="color:red;"></i>') : '') . 
            ($header === 'persen_hi' ? ($row['real_hi'] > $row['sasaran_harian'] ? ' <i class="fas fa-caret-up" style="color:green;"></i>' : ' <i class="fas fa-caret-down" style="color:red;"></i>') : '') . 
            ($header === 'persen_3' ? ($row['real_3'] > $row['sasaran_harian'] ? ' <i class="fas fa-caret-up" style="color:green;"></i>' : ' <i class="fas fa-caret-down" style="color:red;"></i>') : '') . 
        '</td>';
    }
    $html .= '</tr>';
}

    $html .= '</tbody>';
    $html .= '</table>
    </div>';

        $html .= '<p style="font-size: 12px; color: red; margin-top: 10px;">
        <strong>Note:</strong> Sasaran Pasok harian berdasarkan Sisa Tebu Prognosa Terakhir dan update estimasi akhir tebang/giling.
    </p>';



    // Return the HTML response
    return response($html);
}

public function getChartDataMutu(Request $request)
{
    $nama_rayon = $request->input('nama_rayon');
    $start_date = $request->input('start_date');
    $end_date = $request->input('end_date');

    // Fetch data from the database based on the date range
    $data = DB::table('q_prod_rekap_mutu_rayon_tgl')
        ->select(
            DB::raw("DATE_FORMAT(tgl_giling, '%d %b') as tgl_giling"),
            'mutu_A', 'mutu_B', 'mutu_C', 'mutu_D', 'mutu_E', 'mutu_F'
        )
        ->where('nama_rayon', $nama_rayon)
        ->whereBetween('tgl_giling', [$start_date, $end_date])
        ->get();

    // Return the data as JSON
    return response()->json($data);
}

public function getChartDataMutu2(Request $request)
{
    $cluster = $request->input('cluster');
    $nama_rayon = $request->input('nama_rayon');
    $start_date = $request->input('start_date');
    $end_date = $request->input('end_date');

    // Fetch data from the database based on the date range
    if(empty($cluster) && empty($nama_rayon)) {
        $data = DB::table('q_prod_rekap_mutu_total')
                ->select(DB::raw("DATE_FORMAT(tgl_giling, '%d %b') as tgl_giling"), 'mutu_A', 'mutu_B', 'mutu_C', 'mutu_D', 'mutu_E','mutu_F')
                ->whereBetween('tgl_giling', [$start_date, $end_date])
                ->get();
    }else if(!empty($cluster) && empty($nama_rayon)) {
            $data = DB::table('q_prod_rekap_mutu_cluster_tgl')
            ->select(DB::raw("DATE_FORMAT(tgl_giling, '%d %b') as tgl_giling"), 'mutu_A', 'mutu_B', 'mutu_C', 'mutu_D', 'mutu_E','mutu_F')
            ->where('nama_cluster', $cluster)
            ->whereBetween('tgl_giling', [$start_date, $end_date])
            ->get();
    }else{
            $data = DB::table('q_prod_rekap_mutu_kebun_tgl')
            ->select(DB::raw("DATE_FORMAT(tgl_giling, '%d %b') as tgl_giling"), 'mutu_A', 'mutu_B', 'mutu_C', 'mutu_D', 'mutu_E','mutu_F')
            ->where('nama_kebun', $nama_rayon)
            ->whereBetween('tgl_giling', [$start_date, $end_date])
            ->get();
    }
    
    

    // Return the data as JSON
    return response()->json($data);
}

public function getRekapMorfologiPerKategori(Request $request)
{
    $kode_kebun = $request->input('kebun');
    $kode_rayon = $request->input('rayon');
    $bulan = $request->input('bulan');

    // Penentuan tanggal berdasarkan kode bulan (1A = tgl 15, 1B = akhir bulan, dst sampai 12B)
    $tanggal = null;
    if (preg_match('/^(\d{1,2})([AB])$/', $bulan, $matches)) {
        $bulanAngka = (int)$matches[1];
        $jenis = $matches[2];
        $tahun = date('Y');
        if ($jenis === 'A') {
            $tanggal = $tahun.'-'.$bulanAngka.'-'.'15';
        } elseif ($jenis === 'B') {
            $tanggal = $tahun.'-'.$bulanAngka.'-'.date('t', strtotime("$tahun-$bulanAngka-01"));
        }
    }

            $getlevel = DB::table('tb_groups')
            ->select('level')
            ->where('group_id',\Session::get('gid'))
            ->first();

            if($getlevel->level == 3){
                $kode_kebun = \session::get('fid');
            }
    

    $data = DB::select('call sp_rekap_morfologi_per_kategori2(?, ?, ?)', [
        $kode_kebun,
        $kode_rayon,
        $tanggal
    ]);

    $html = '<style>
        .morfologi-table th, .morfologi-table td {
            text-align: center;
            vertical-align: middle;
        }
        .morfologi-table thead th {
            background: #3345a1;
            color: #fff;
            font-size: 13px;
        }
        .morfologi-table tbody tr:nth-child(even) {
            background: #f6f9fc;
        }
        .morfologi-table tbody tr:hover {
            background: #e3e8f0;
            transition: background 0.2s;
        }
        .morfologi-table td {
            font-size: 13px;
        }
        .morfologi-table tfoot tr {
            background: #e0e0e0;
            font-weight: bold;
        }
        .morfologi-table .total-row {
            background: linear-gradient(90deg, #e0eafc 0%, #cfdef3 100%);
            font-weight: bold;
        }
        .morfologi-table .percent-cell {
            background: #eafaf1;
            color: #1e7e34;
            font-weight: bold;
        }
        .table th, .table thead th {
            border: solid 1px #d1cbcb;
        }
    </style>';

    $html .= '<div style="overflow: auto;"><table class="table table-bordered morfologi-table" style="background: #f4f8ff; border-radius: 16px; box-shadow: 0 4px 24px #cfd8dc;">';
    $html .= '<thead>
    <tr style="background: linear-gradient(90deg, #1e3c72 0%, #2a5298 100%); color: #fff;">
        <th rowspan="2" style="vertical-align: middle; font-size:16px; letter-spacing:1px; border-right:2px solid #fff;">Kebun</th>
        <th rowspan="2" style="vertical-align: middle; font-size:16px; letter-spacing:1px; border-right:2px solid #fff;">Kategori</th>
        <th rowspan="2" style="vertical-align: middle; font-size:16px; letter-spacing:1px; border-right:2px solid #fff;">Luas Tanam / Kepras <br> <span style="font-size:13px;">(Petak/Ha)</span></th>
        <th rowspan="2" style="vertical-align: middle; font-size:16px; letter-spacing:1px; border-right:2px solid #fff;">Monitoring Morfologi <br> <span style="font-size:13px;">(Petak/Ha)</span></th>
        <th rowspan="2" style="vertical-align: middle; font-size:16px; letter-spacing:1px; border-right:2px solid #fff;">Belum Monitoring Morfologi <br> <span style="font-size:13px;">(Petak/Ha)</span></th>
        <th colspan="2" style="vertical-align: middle; font-size:16px; letter-spacing:1px;">% Pelaporan</th>
    </tr>
    <tr style="background: linear-gradient(90deg, #1e3c72 0%, #2a5298 100%); color: #fff;">
        <th style="font-size:15px;">Petak</th>
        <th style="font-size:15px;">Luas (Ha)</th>
    </tr>
    </thead>
    <tbody>';

    // Inisialisasi total
    $total_jml_petak = 0;
    $total_luas_tanam = 0;
    $total_jml_morfologi = 0;
    $total_luas_morfologi = 0;
    $total_belum_jml_petak = 0;
    $total_belum_luas_morfologi = 0;

    foreach ($data as $row) {
        $percent_petak = round(((int)$row->jml_morfologi / (int)$row->jml_petak) * 100, 2);
        $percent_luas = ($row->luas_morfologi ?? 0) > 0 && ($row->luas_tanam ?? 0) > 0 ? round(($row->luas_morfologi / $row->luas_tanam) * 100, 2) : 0;

        // Alternating row color and highlight
        if ($percent_petak >= 100) {
            $rowColor = 'background:linear-gradient(90deg,#e0f7fa 0%,#b2ebf2 100%);';
        } elseif ($percent_petak >= 90) {
            $rowColor = 'background:linear-gradient(90deg,#fffde7 0%,#fff9c4 100%);';
        } else {
            $rowColor = 'background:linear-gradient(90deg,#f8bbd0 0%,#fce4ec 100%);';
        }
        $html .= '<tr style="' . $rowColor . '">';
        $html .= '<td style="font-weight:bold;color:#1e3c72;font-size:15px;">' . htmlspecialchars($row->nama_kebun) . '</td>';
        $html .= '<td style="color:#2a5298;font-size:15px;">' . $row->kategori . '</td>';
        $html .= '<td style="text-align:right;font-size:15px;">' . $row->jml_petak . ' / <span style="color:#007bff;font-weight:bold;">' . number_format($row->luas_tanam,3) . '</span></td>';
        $html .= '<td style="text-align:right;font-size:15px;">';
        if (!empty($row->jml_morfologi)) {
            $url = url('dashboard/getRekapMorfologiPerKategoriDetail?plant=' . urlencode($row->kode_kebun) . '&rayon=' . urlencode($kode_rayon) . '&bulan=' . urlencode($bulan) . '&kategori=' . urlencode($row->kategori));
            $html .= '<a href="javascript:void(0);" onclick="SximoModal(\'' . $url . '\',\'Detail Morfologi\')" style="color:#43a047;font-weight:bold;">' . $row->jml_morfologi . '';
        } else {
            $html .= ($row->jml_morfologi ?? '-');
        }
        $html .= ' / <span style="color:#43a047;font-weight:bold;">' . (number_format($row->luas_morfologi,3).'</a>' ?? '-') . '</span></td>';

        $html .= '<td style="text-align:right;font-size:15px;">';
        if (!empty($row->belum_jml_petak)) {
            $url = url('dashboard/getRekapMorfologiPerKategoriDetail2?plant=' . urlencode($row->kode_kebun) . '&rayon=' . urlencode($kode_rayon) . '&kategori=' . urlencode($row->kategori));
            $html .= '<a href="javascript:void(0);" onclick="SximoModal(\'' . $url . '\',\'Detail Belum Morfologi\')" style="color:#e53935;font-weight:bold;">' . $row->belum_jml_petak . '';
        } else {
            $html .= ($row->belum_jml_petak ?? '-');
        }
        $html .= ' / <span style="color:#e53935;font-weight:bold;">' . (number_format($row->belum_luas_morfologi,3).'</a>' ?? '-') . '</span></td>';

        $html .= '<td class="percent-cell" style="background:#e3fcec;color:#388e3c;font-weight:bold;font-size:16px;">' . $percent_petak . '%</td>';
        $html .= '<td class="percent-cell" style="background:#e3fcec;color:#388e3c;font-weight:bold;font-size:16px;">' . $percent_luas . '%</td>';
        $html .= '</tr>';

        // Akumulasi total
        $total_jml_petak += $row->jml_petak;
        $total_luas_tanam += $row->luas_tanam;
        $total_jml_morfologi += $row->jml_morfologi;
        $total_luas_morfologi += $row->luas_morfologi;
        $total_belum_jml_petak += $row->belum_jml_petak;
        $total_belum_luas_morfologi += $row->belum_luas_morfologi;
    }

    // Baris total
    $total_percent_petak = $total_jml_petak > 0 ? round(($total_jml_morfologi / $total_jml_petak) * 100, 2) : 0;
    $total_percent_luas = $total_luas_tanam > 0 ? round(($total_luas_morfologi / $total_luas_tanam) * 100, 2) : 0;

    $html .= '<tr class="total-row" style="background:linear-gradient(90deg,#b2dfdb 0%,#e0f7fa 100%);font-weight:bold;">';
    $html .= '<td colspan="2" style="color:#1e3c72;font-size:16px;">Total</td>';
    $html .= '<td style="text-align:right;font-size:16px;">' . $total_jml_petak . ' / <span style="color:#007bff;font-weight:bold;">' . number_format($total_luas_tanam,3) . '</span></td>';
    $html .= '<td style="text-align:right;font-size:16px;">' . $total_jml_morfologi . ' / <span style="color:#43a047;font-weight:bold;">' . number_format($total_luas_morfologi,3) . '</span></td>';
    $html .= '<td style="text-align:right;font-size:16px;">' . $total_belum_jml_petak . ' / <span style="color:#e53935;font-weight:bold;">' . number_format($total_belum_luas_morfologi,3) . '</span></td>';
    $html .= '<td class="percent-cell" style="background:#e3fcec;color:#388e3c;font-weight:bold;font-size:16px;">' . $total_percent_petak . '%</td>';
    $html .= '<td class="percent-cell" style="background:#e3fcec;color:#388e3c;font-weight:bold;font-size:16px;">' . $total_percent_luas . '%</td>';
    $html .= '</tr>';

    $html .= '</tbody></table><div>';
    $html .= '<style>
        .morfologi-table {
            border-radius: 16px;
            overflow: hidden;
        }
        .morfologi-table th, .morfologi-table td {
            border: 1px solid #b0bec5;
            font-size: 15px;
            vertical-align: middle;
            transition: background 0.2s;
        }
        .morfologi-table thead th {
            font-weight: bold;
            letter-spacing: 0.5px;
            background: linear-gradient(90deg, #1e3c72 0%, #2a5298 100%) !important;
            color: #fff !important;
            border-bottom: 2px solid #fff;
        }
        .morfologi-table tbody tr:hover {
            background: #e3e8f0 !important;
            transition: background 0.2s;
        }
        .morfologi-table .percent-cell {
            font-size: 16px;
            border-left: 2px solid #b2dfdb;
            background: #e3fcec !important;
            color: #388e3c !important;
        }
        .morfologi-table .total-row td {
            font-size: 16px;
            background: linear-gradient(90deg,#b2dfdb 0%,#e0f7fa 100%) !important;
        }
        a {
            text-decoration: none;
            font-weight: bold;
            transition: color 0.2s;
        }
        a:hover {
            color: #1565c0 !important;
        }
    </style>';

    return response($html);
}

public function getRekapMorfologiKebun(Request $request)
    {
        $data = DB::table('q_rekap_morfologi_kebun')
            ->select('nama_kebun', 'jml_petak', 'jml_morfologi')
            ->get();

        $categories = $data->pluck('nama_kebun')->toArray();
        $jmlPetak = $data->pluck('jml_petak')->map(function($v){ return (int)$v; })->toArray();
        $jmlMorfologi = $data->pluck('jml_morfologi')->map(function($v){ return (int)$v; })->toArray();

        return response()->json([
            'status' => 'success',
            'categories' => $categories,
            'jml_petak' => $jmlPetak,
            'jml_morfologi' => $jmlMorfologi,
        ]);
    }


public function getRekapMorfologiRayon(Request $request)
    {
        $kebun = $request->input('kebun');
        $rayon = $request->input('rayon');

        $data = DB::table('q_rekap_morfologi_rayon')
            ->select('nama_rayon', 'jml_petak', 'jml_morfologi')
            ->when($kebun, function ($query) use ($kebun) {
                return $query->where('kode_kebun', $kebun);
            })
            ->when($rayon, function ($query) use ($rayon) {
                return $query->where('kode_rayon', $rayon);
            })
            ->get();

        $categories = $data->pluck('nama_rayon')->toArray();
        $jmlPetak = $data->pluck('jml_petak')->map(function($v){ return (int)$v; })->toArray();
        $jmlMorfologi = $data->pluck('jml_morfologi')->map(function($v){ return (int)$v; })->toArray();

        return response()->json([
            'status' => 'success',
            'categories' => $categories,
            'jml_petak' => $jmlPetak,
            'jml_morfologi' => $jmlMorfologi,
        ]);
    }

public function getRekapMorfologiPerKategoriDetail(Request $request)
{
    $plant = $request->input('plant');
    $rayon = $request->input('rayon');
    $bulan = $request->input('bulan');
    $kategori = $request->input('kategori');

     // Penentuan tanggal berdasarkan kode bulan (1A = tgl 15, 1B = akhir bulan, dst sampai 12B)
    $tanggal = null;
    if (preg_match('/^(\d{1,2})([AB])$/', $bulan, $matches)) {
        $bulanAngka = (int)$matches[1];
        $jenis = $matches[2];
        $tahun = date('Y');
        if ($jenis === 'A') {
            $tanggal = $tahun.'-'.$bulanAngka.'-'.'15';
        } elseif ($jenis === 'B') {
            $tanggal = $tahun.'-'.$bulanAngka.'-'.date('t', strtotime("$tahun-$bulanAngka-01"));
        }
    }

    // Panggil stored procedure
    $data = DB::select('call sp_rekap_morfologi_per_kategori_detail(?, ?, ?, ?)', [
        $plant,
        $rayon,
        $tanggal,
        $kategori
    ]);

    $html = '<style>
        .morfologi-detail-table th, .morfologi-detail-table td {
            text-align: center;
            vertical-align: middle;
            font-size: 13px;
        }
        .morfologi-detail-table thead th {
            background: #020273 !important;
            color: #fff;
        }
        .morfologi-detail-table tbody tr:nth-child(even) {
            background: #f6f9fc;
        }
        .morfologi-detail-table tbody tr:hover {
            background: #e3e8f0;
            transition: background 0.2s;
        }
        .morfologi-detail-table tfoot tr {
            background: #e0e0e0;
            font-weight: bold;
        }
            
    </style>';

    $html .= '<table class="table table-bordered morfologi-detail-table table-responsive">';
    $html .= '<thead>
        <tr>
            <th>No</th>
            <th>Petak</th>
            <th>Rayon</th>
            <th>Afd</th>
            <th>Kebun</th>
            <th>Luas (Ha)</th>
            <th>Jumlah Batang</th>
            <th>Tinggi Batang</th>
            <th>Diameter Batang</th>
            <th>Berat Batang</th>
            <th>Jumlah Ruas</th>
            <th>Protas Morfologi<br> Saat ini</th>
            <th>Foto</th>


            <th>Tanggal Akhir</th>
            <th>EntryBy</th>

        </tr>
    </thead>
    <tbody>';

    $no = 1;
    foreach ($data as $row) {
        $html .= '<tr>';
        $html .= '<td>' . $no++ . '</td>';
        $html .= '<td>' . htmlspecialchars($row->lahan_id ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->rayon ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->afd_new ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->nama_kebun ?? '-') . '</td>';
        $html .= '<td style="text-align:right;">' . number_format($row->ha ?? 0, 3) . '</td>';
        $html .= '<td>' . htmlspecialchars($row->jumlah_batang ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->tinggi_batang ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->diameter_batang ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->berat_batang_per_meter ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->jumlah_ruas ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->protas_morfologi ?? '-') . '</td>';


        if (!empty($row->foto)) {
            $html .= '<td>
            <a href="javascript:void(0);" onclick="showImageModal(\'/uploads/foto_morfologi/' . htmlspecialchars($row->foto) . '\')">
                <img src="/assets/images/showimage.png" alt="Foto" style="max-width:60px;max-height:60px;cursor:pointer;">
                <p>Lihat</p>
            </a>
            </td>';
            // Tambahkan modal hanya sekali di luar loop (bisa di bawah tabel)
            if (!isset($imageModalScriptAdded)) {
            $html .= '
            <div id="imageModalMorfologi" class="modal" tabindex="-1" role="dialog" style="display:none; background:rgba(0,0,0,0.7); position:fixed; top:0; left:0; width:100%; height:100%; z-index:9999; align-items:center; justify-content:center;">
                <span style="position:absolute;top:20px;right:40px;font-size:40px;color:#fff;cursor:pointer;" onclick="closeImageModal()">&times;</span>
                <img id="imageModalMorfologiImg" src="" style="max-width:90vw;max-height:90vh;display:block;margin:auto;box-shadow:0 0 20px #000;">
            </div>
            <script>
            function showImageModal(src) {
                document.getElementById("imageModalMorfologiImg").src = src;
                document.getElementById("imageModalMorfologi").style.display = "flex";
            }
            function closeImageModal() {
                document.getElementById("imageModalMorfologi").style.display = "none";
            }
            // Close modal on background click
            document.addEventListener("DOMContentLoaded", function() {
                var modal = document.getElementById("imageModalMorfologi");
                if(modal){
                modal.addEventListener("click", function(e) {
                    if (e.target === modal) closeImageModal();
                });
                }
            });
            </script>
            ';
            $imageModalScriptAdded = true;
            }
        } else {
            $html .= '<td>-</td>';
        }
        $html .= '<td>' . ($row->tanggal ? date('d-m-Y', strtotime($row->tanggal)) : '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->first_name ?? '-') . '</td>';

        $html .= '</tr>';
    }

    if (count($data) == 0) {
        $html .= '<tr><td colspan="9">Data tidak ditemukan.</td></tr>';
    }

    $html .= '</tbody></table>';
    $html .= '<script>
        $(document).ready(function() {
            $(".morfologi-detail-table").DataTable({
                "paging": true,
                "searching": true,
                "ordering": true,
            });
        }); </script>';

    return response($html);
}

public function getRekapMorfologiPerKategoriDetail2(Request $request)
{
    $plant = $request->input('plant');
    $rayon = $request->input('rayon');

    $kategori = $request->input('kategori');

     // Penentuan tanggal berdasarkan kode bulan (1A = tgl 15, 1B = akhir bulan, dst sampai 12B)

    // Panggil stored procedure
    $data = DB::select('call sp_rekap_morfologi_per_kategori_detail2(?, ?, ?)', [
        $plant,
        $rayon,
        $kategori
    ]);

    $html = '<style>
        .morfologi-detail-table th, .morfologi-detail-table td {
            text-align: center;
            vertical-align: middle;
            font-size: 13px;
        }
        .morfologi-detail-table thead th {
            background: #020273 !important;
            color: #fff;
        }
        .morfologi-detail-table tbody tr:nth-child(even) {
            background: #f6f9fc;
        }
        .morfologi-detail-table tbody tr:hover {
            background: #e3e8f0;
            transition: background 0.2s;
        }
        .morfologi-detail-table tfoot tr {
            background: #e0e0e0;
            font-weight: bold;
        }
            
    </style>';

    $html .= '<table class="table table-bordered morfologi-detail-table table-responsive">';
    $html .= '<thead>
        <tr>
            <th>No</th>
            <th>Petak</th>
            <th>Rayon</th>
            <th>Afd</th>
            <th>Kebun</th>
            <th>Asman</th>
            <th>Luas Tanam</th>
        </tr>
    </thead>
    <tbody>';

    $no = 1;
    foreach ($data as $row) {
        $html .= '<tr>';
        $html .= '<td>' . $no++ . '</td>';
        $html .= '<td>' . htmlspecialchars($row->lahan_id ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->rayon ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->afd_new ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->nama_kebun ?? '-') . '</td>';
        $html .= '<td>' . htmlspecialchars($row->asman_new ?? '-') . '</td>';
        $html .= '<td style="text-align:right;">' . number_format($row->luas_tanam ?? 0, 3) . '</td>';
        $html .= '</tr>';
    }

    if (count($data) == 0) {
        $html .= '<tr><td colspan="9">Data tidak ditemukan.</td></tr>';
    }

    $html .= '</tbody></table>';
    $html .= '<script>
        $(document).ready(function() {
            $(".morfologi-detail-table").DataTable({
                "paging": true,
                "searching": true,
                "ordering": true,
            });
        }); </script>';

    return response($html);
}

public function getChartDataMutuAsman(Request $request)
{
    $nama_rayon = $request->input('nama_rayon');
    $start_date = $request->input('start_date');
    $end_date = $request->input('end_date');
    $versi = $request->input('versi', '1'); // Default to v1 if not provided



    // Fetch data from the database based on the date range
    if ($versi == '1') {

            $data = DB::table('vw_mutu_asman')
        ->select('nama_rayon','kode_afd','nik','asman',DB::raw("DATE_FORMAT(tgl_giling, '%d %b') as tgl_giling"), 'mutu', 'sasaran')
        ->where('nama_rayon', $nama_rayon)
        ->where('mutu', '!=', 0.0)
        ->whereBetween('tgl_giling', [$start_date, $end_date])
        ->get();

        
                $mutuDetail = DB::select('call sp_mutu_rayon_detail(?, ?, ?)', [
            $nama_rayon,
            $start_date,
            $end_date
        ]);
            $grouped = $data->groupBy('kode_afd');
    } else if ($versi == '2') {

            $data = DB::table('vw_mutu_asman2')
        ->select('nama_rayon','kode_afd','nik','asman',DB::raw("DATE_FORMAT(tgl_giling, '%d %b') as tgl_giling"), 'mutu', 'sasaran')
        ->where('nama_rayon', $nama_rayon)
                ->where('mutu', '!=', 0.0)
        ->whereBetween('tgl_giling', [$start_date, $end_date])
        ->get();

        
                $mutuDetail = DB::select('call sp_mutu_rayon_detail2(?, ?, ?)', [
            $nama_rayon,
            $start_date,
            $end_date
        ]);
            $grouped = $data->groupBy('nik');
    }
 
        // Default to v1    

        $summary = DB::table('vw_mutu_asman')
            ->selectRaw('asman, min(mutu) as min_mutu, max(mutu) as max_mutu, round((POW(max(mutu) / min(mutu), 1/6) - 1) * 100) as growth')
            ->whereBetween('tgl_giling', [$start_date, $end_date])
            ->where('nama_rayon', $nama_rayon)
            ->where('asman', '!=', 'TOTAL')
            ->groupBy('kode_afd')
            ->orderByDesc('growth')
            ->get();        

        $this->data['mutu_detail'] = $mutuDetail;
        $this->data['growth'] = $summary;
    // Group data by asman


    $result = [];
    $growtharray = [];
    foreach ($grouped as $kode_afd => $items) {
        $categories = $items->pluck('tgl_giling')->map(function($date) {
            return date('d M', strtotime($date));
        })->unique()->toArray();
        $mutu = $items->pluck('mutu')->map(function($v) {
            return (float)$v;
        })->toArray();

        // Ambil data awal dan akhir dari data mutu
        $mutu_awal = count($mutu) > 0 ? $mutu[0] : null;
        $mutu_akhir = count($mutu) > 0 ? $mutu[count($mutu) - 1] : null;
        
        $countMutu = count($mutu) > 1 ? (count($mutu) - 1) : count($mutu);
        $growth = $countMutu > 0 && $mutu_awal > 0
            ? round((pow($mutu_akhir / $mutu_awal, 1 / $countMutu) - 1) * 100, 2)
            : 0;
        $growtharray[] = [
            'asman' => $items->first()->asman,
            'growth' => $growth
        ];

        $sasaran = $items->pluck('sasaran')->map(function($v) {
            return (float)$v;
        })->toArray();

        $chartOptions = [
            'chart' => [
                'zoomType' => 'xy'
            ],
            'title' => [
                'text' => $versi == '2'
                    ? ($items->first()->nama_rayon . '<br>' . $items->first()->asman)
                    : ($items->first()->nama_rayon . ' - ' . $kode_afd . '<br>' . $items->first()->asman)
            ],
            'xAxis' => [
                'categories' => $categories,
                'title' => [
                    'text' => 'Tanggal Giling'
                ]
            ],
            'yAxis' => [
                [
                    'title' => [
                        'text' => 'Sasaran'
                    ],
                    'max' => 120,
                    'tickPositions' => [0, 20, 40, 60, 80, 100, 120],
                    'opposite' => true
                ],
                [
                    'title' => [
                        'text' => 'Mutu'
                    ],
                    'max' => 120,
                    'tickPositions' => [0, 20, 40, 60, 80, 100, 120],
                    'opposite' => false
                ]
            ],
            'series' => [
                [
                    'name' => 'Sasaran',
                    'data' => $sasaran,
                    'color' => 'orange',
                    'dataLabels' => [
                        'enabled' => true,
                        'format' => '{y}',
                        'style' => [
                            'fontWeight' => 'bold',
                            'color' => '#000'
                        ]
                    ],
                    'yAxis' => 0
                ],
                [
                    'name' => 'Mutu',
                    'data' => $mutu,
                    'color' => '#007bff',
                    'dataLabels' => [
                        'enabled' => true,
                        'format' => '{y}',
                        'style' => [
                            'fontWeight' => 'bold',
                            'color' => '#000'
                        ]
                    ],
                    'yAxis' => 1
                ]
            ]
        ];

        $result[] = $chartOptions;
    }

    $this->data['grafik'] = $result;
    $this->data['growtharray'] = $growtharray;
    // return $this->data['grafik'];
    return view('dashboard.mututebuasman', $this->data);
}


public function getChartDataMutuAfdeling(Request $request)
{
    config(['app.debug' => true]);
    $nama_rayon = $request->input('nama_rayon');
    $start_date = $request->input('start_date');
    $end_date = $request->input('end_date');

    // Fetch data from the database based on the date range
    $data = DB::table('q_prod_rekap_mutu_afdeling_tgl')
        ->select(
            'kode_afd',
            DB::raw("DATE_FORMAT(tgl_giling, '%d %b') as tgl_giling2"),
            'mutu_A',
            'mutu_B',
            'mutu_C',
            'mutu_D',
            'mutu_E',
            'mutu_F'
        )
        ->where('nama_rayon', $nama_rayon)
        ->whereBetween('tgl_giling', [$start_date, $end_date])

        ->orderBy('tgl_giling', 'asc')
        ->get();

    if ($data->isEmpty()) {
        return response()->json([
            'status' => 'error',
            'message' => 'Data tidak ditemukan'
        ]);
    }

    // Group data by afdeling
    $grouped = $data->groupBy('kode_afd');
    $chartOptions = [];

    foreach ($grouped as $kode_afd => $items) {
        $categories = $items->pluck('tgl_giling2')->unique()->toArray();
        
        $mutuA = $items->pluck('mutu_A')->map(function($v) { return (float)$v; })->toArray();
        $mutuB = $items->pluck('mutu_B')->map(function($v) { return (float)$v; })->toArray();
        $mutuC = $items->pluck('mutu_C')->map(function($v) { return (float)$v; })->toArray();
        $mutuD = $items->pluck('mutu_D')->map(function($v) { return (float)$v; })->toArray();
        $mutuE = $items->pluck('mutu_E')->map(function($v) { return (float)$v; })->toArray();
        $mutuF = $items->pluck('mutu_F')->map(function($v) { return (float)$v; })->toArray();

        $chartOptions[] = [
            'chart' => ['type' => 'line'],
            'title' => ['text' => 'Mutu Tebu Afdeling ' . htmlspecialchars($kode_afd)],
            'xAxis' => [
                'categories' => $categories,
                'title' => ['text' => 'Tanggal Giling']
            ],
            'yAxis' => [
                'title' => ['text' => 'Persentase (%)'],
                'min' => 0,
                'max' => 100
            ],
            'series' => [
                ['name' => 'Mutu A', 'data' => $mutuA, 'color' => '#28a745'],
                ['name' => 'Mutu B', 'data' => $mutuB, 'color' => '#007bff'],
                ['name' => 'Mutu C', 'data' => $mutuC, 'color' => '#ffc107'],
                ['name' => 'Mutu D', 'data' => $mutuD, 'color' => '#dc3545'],
                ['name' => 'Mutu E', 'data' => $mutuE, 'color' => '#000000'],
                ['name' => 'Mutu F', 'data' => $mutuF, 'color' => '#6c757d']
            ],
            'plotOptions' => [
                'series' => [
                    'marker' => ['enabled' => true],
                    'dataLabels' => [
                        'enabled' => true,
                        'format' => '{y:.1f}%',
                        'style' => ['fontSize' => '11px']
                    ]
                ]
            ]
        ];
    }
    $this->data['grafik'] = $chartOptions;
    return view('dashboard.mututebuafdharian', $this->data);
}

public function getChartDataMutuAsman2(Request $request)
{
    config(['app.debug' => true]);
    $nama_rayon = $request->input('nama_rayon');
    $start_date = $request->input('start_date');
    $end_date = $request->input('end_date');

    // Fetch data from the database based on the date range
    $data = DB::table('q_prod_rekap_mutu_afdeling_tgl')
        ->select(
            'asman',
            'kode_afd',
            'nik',
            DB::raw("DATE_FORMAT(tgl_giling, '%d %b') as tgl_giling2"),
            'mutu_A',
            'mutu_B',
            'mutu_C',
            'mutu_D',
            'mutu_E',
            'mutu_F'
        )
        ->where('nama_rayon', $nama_rayon)
        ->whereBetween('tgl_giling', [$start_date, $end_date])
    
        ->orderBy('tgl_giling', 'asc')
        ->get();

    if ($data->isEmpty()) {
        return response()->json([
            'status' => 'error',
            'message' => 'Data tidak ditemukan'
        ]);
    }

    // Group data by afdeling
    $grouped = $data->groupBy('nik');
    $chartOptions = [];

    foreach ($grouped as $kode_afd => $items) {
        $categories = $items->pluck('tgl_giling2')->unique()->toArray();
        
        $mutuA = $items->pluck('mutu_A')->map(function($v) { return (float)$v; })->toArray();
        $mutuB = $items->pluck('mutu_B')->map(function($v) { return (float)$v; })->toArray();
        $mutuC = $items->pluck('mutu_C')->map(function($v) { return (float)$v; })->toArray();
        $mutuD = $items->pluck('mutu_D')->map(function($v) { return (float)$v; })->toArray();
        $mutuE = $items->pluck('mutu_E')->map(function($v) { return (float)$v; })->toArray();
        $mutuF = $items->pluck('mutu_F')->map(function($v) { return (float)$v; })->toArray();

        $chartOptions[] = [
            'chart' => ['type' => 'line'],
            'title' => ['text' => 'Mutu Tebu Afdeling ' . htmlspecialchars($items->first()->kode_afd).' <br> ' . htmlspecialchars($items->first()->asman)],
            'xAxis' => [
                'categories' => $categories,
                'title' => ['text' => 'Tanggal Giling']
            ],
            'yAxis' => [
                'title' => ['text' => 'Persentase (%)'],
                'min' => 0,
                'max' => 100
            ],
            'series' => [
                ['name' => 'Mutu A', 'data' => $mutuA, 'color' => '#28a745'],
                ['name' => 'Mutu B', 'data' => $mutuB, 'color' => '#007bff'],
                ['name' => 'Mutu C', 'data' => $mutuC, 'color' => '#ffc107'],
                ['name' => 'Mutu D', 'data' => $mutuD, 'color' => '#dc3545'],
                ['name' => 'Mutu E', 'data' => $mutuE, 'color' => '#000000'],
                ['name' => 'Mutu F', 'data' => $mutuF, 'color' => '#6c757d']
            ],
            'plotOptions' => [
                'series' => [
                    'marker' => ['enabled' => true],
                    'dataLabels' => [
                        'enabled' => true,
                        'format' => '{y:.1f}%',
                        'style' => ['fontSize' => '11px']
                    ]
                ]
            ]
        ];
    }
    $this->data['grafik'] = $chartOptions;
    return view('dashboard.mututebuafdharian', $this->data);
}

public function getChartDataProtasAsman(Request $request)
{
    $nama_rayon = $request->input('nama_rayon');
    $start_date = $request->input('start_date');
    $end_date = $request->input('end_date');
    $versi = $request->input('versi', '1'); // Default to v1 if not provided
    // Fetch data from the database based on the date range


    if ($versi == '1') {
            $data = collect(DB::select('call sp_rangking_protas_asman(?, ?, ?)', [
                $start_date,
                $end_date,
                $nama_rayon
            ]));

            $protasDetail = DB::select('call sp_rangking_protas_asman_detail(?, ?, ?)', [
                $start_date,
                $end_date,
                $nama_rayon
            ]);
    } else {
        // Default to v1
            $data = collect(DB::select('call sp_rangking_protas_asman2(?, ?, ?)', [
                $start_date,
                $end_date,
                $nama_rayon
            ]));

        $protasDetail = DB::select('call sp_rangking_protas_asman_detail2(?, ?, ?)', [
            $start_date,
            $end_date,
            $nama_rayon
        ]);
    }

    if ($versi == '1') {
            $grouped = $data->groupBy('kode_afd');
    } else {
            $grouped = $data->groupBy('nik');
    }

    
    $this->data['protas_detail'] = $protasDetail;

    // Group data by kode_afd

    $result = [];
    $growtharray = [];
    foreach ($grouped as $kode_afd => $items) {
        $categories = $items->pluck('tgl_timbang')->map(function($date) {
            return date('d M', strtotime($date));
        })->unique()->toArray();
        $protas = $items->pluck('protas')->map(function($v) {
            return (float)$v;
        })->toArray();

         $protas_awal = count($protas) > 0 ? $protas[0] : null;
        $protas_akhir = count($protas) > 0 ? $protas[count($protas) - 1] : null;

        $countProtas = count($protas) > 1 ? (count($protas) - 1) : count($protas);
        $growth = $countProtas > 0 && $protas_awal > 0
            ? round((pow($protas_akhir / $protas_awal, 1 / $countProtas) - 1) * 100, 2)
            : 0;
        $growtharray[] = [
            'asman' => $items->first()->asman,
            'growth' => $growth
        ];
        $sasaran = $items->pluck('protas_takmar')->map(function($v) {
            return (float)$v;
        })->toArray();

        $chartOptions = [
            'chart' => [
                'zoomType' => 'xy'
            ],
            'title' => [
                'text' => $versi == '2'
                    ? ($items->first()->nama_rayon . '<br>' . $items->first()->asman)
                    : ($items->first()->nama_rayon . ' - ' . $kode_afd . '<br>' . $items->first()->asman)
            ],
            'xAxis' => [
                'categories' => $categories,
                'title' => [
                    'text' => 'Tanggal Giling'
                ]
            ],
            'yAxis' => [
                [
                    'title' => [
                        'text' => 'Taksasi'
                    ],
                    'max' => 240,
                    'tickPositions' => [0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240],
                    'opposite' => true
                ],
                [
                    'title' => [
                        'text' => 'protas'
                    ],
                    'max' => 240,
                    'tickPositions' => [0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240],
                    'opposite' => false
                ]
            ],
            'series' => [
                [
                    'name' => 'Taksasi',
                    'data' => $sasaran,
                    'color' => 'orange',
                    'dataLabels' => [
                        'enabled' => true,
                        'format' => '{y}',
                        'style' => [
                            'fontWeight' => 'bold',
                            'color' => '#000'
                        ]
                    ],
                    'yAxis' => 0
                ],
                [
                    'name' => 'protas',
                    'data' => $protas,
                    'color' => '#007bff',
                    'dataLabels' => [
                        'enabled' => true,
                        'format' => '{y}',
                        'style' => [
                            'fontWeight' => 'bold',
                            'color' => '#000'
                        ]
                    ],
                    'yAxis' => 1
                ]
            ]
        ];

        $result[] = $chartOptions;
    }

    $this->data['grafik'] = $result;
    $this->data['growtharray'] = $growtharray;
    // return $this->data['grafik'];
    return view('dashboard.protastebuasman', $this->data);
}

public function getRekapMejaTebuMutuEvaluasi(Request $request)
{
    $plant = $request->input('plant', 'SK01');
    $tipeRekap = $request->input('tipe_rekap', 'afdeling');
    $tglAwal1 = $request->input('tgl_awal_1');
    $tglAkhir1 = $request->input('tgl_akhir_1');
    $tglAwal2 = $request->input('tgl_awal_2');
    $tglAkhir2 = $request->input('tgl_akhir_2');

    // Call the stored procedure
    $data = DB::select('call sp_rekap_mejatebu_mutu_evaluasi_2periode(?, ?, ?, ?, ?, ?)', [
        $plant,
        $tipeRekap,
        $tglAwal1,
        $tglAkhir1,
        $tglAwal2,
        $tglAkhir2
    ]);

    // Process the data
    $processedData = collect($data)->map(function ($item) {
        return $item;
    });

    $html = '<style>
        .table th, .table thead th {
            border: solid 1px #d1cbcb;
            background: #4c4c80;
            color: #FFF;
            font-size: 12px;
            text-align: center;
            vertical-align: middle;
        }
        .table td {
            font-size: 13px;
        }
        .table tbody tr:nth-child(even) {
            background: #f6f9fc;
        }
        .table tbody tr:hover {
            background: #e3e8f0;
        }
    </style>';

    // Separate total rows from non-total rows
    $totalRows = [];
    $nonTotalRows = [];
    
    foreach ($processedData as $row) {
                $isTotalRow = stripos($row->nama_rayon ?? '', 'TOTAL') !== false || stripos($row->nama_cluster ?? '', 'GRAND TOTAL') !== false;
        
        $mutu_ab_P1 = isset($row->mutu_ab_p1) ? (float)$row->mutu_ab_p1 : 0;
        $mutu_ab_P2 = isset($row->mutu_ab_p2) ? (float)$row->mutu_ab_p2 : 0;
        
        if ($mutu_ab_P1 > 0) {
            $trendPercent = (($mutu_ab_P2 - $mutu_ab_P1) / $mutu_ab_P1) * 100;
        } else {
            $trendPercent = null;
        }
        
        $row->trendPercent = $trendPercent;
        $row->isTotalRow = $isTotalRow;
        
        if ($isTotalRow) {
            $totalRows[] = $row;
        } else {
            $nonTotalRows[] = $row;
        }
    }
    
    // Sort only non-total rows by trendPercent descending, nulls last
    usort($nonTotalRows, function($a, $b) {
        if ($a->trendPercent === null) return 1;
        if ($b->trendPercent === null) return -1;
        return $b->trendPercent <=> $a->trendPercent;
    });
    
    // Combine sorted non-total rows with total rows at the end
    $processedDataWithTrend = array_merge($nonTotalRows, $totalRows);

    $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-striped table-hover table-sm table-responsive">';
    $html .= '<thead>';
    $html .= '<tr>';
    $html .= '<th rowspan="2">No</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Cluster</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Plant</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Kebun</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Rayon</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Manajer Tanaman</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Afdeling</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Asman</th>';
    $html .= '<th colspan="2" style="text-align:center;">Periode 1 (' . date('d M Y', strtotime($tglAwal1)) . ' - ' . date('d M Y', strtotime($tglAkhir1)) . ')</th>';
    $html .= '<th colspan="2" style="text-align:center;">Periode 2 (' . date('d M Y', strtotime($tglAwal2)) . ' - ' . date('d M Y', strtotime($tglAkhir2)) . ')</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Trend A+B</th>';
    $html .= '</tr>';
    $html .= '<tr>';

    $html .= '<th>Mutu A+B</th>';
    $html .= '<th>Mutu C+D+E+F</th>';
    $html .= '<th>Mutu A+B</th>';
    $html .= '<th>Mutu C+D+E+F</th>';
    $html .= '</tr>';
    $html .= '</thead>';
    $html .= '<tbody>';

    $no = 1;
    foreach ($processedDataWithTrend as $row) {
        $rowStyle = $row->isTotalRow ? 'style="background-color:#e3fcec;font-weight:bold;"' : '';
        
        $html .= '<tr ' . $rowStyle . '>';
        $html .= '<td>' . $no++ . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_cluster ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->plant ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_kebun ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_rayon ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_manajer_tanaman ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->kode_afd ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_asman ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        
        // Periode 1
        $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_ab_p1) ? number_format($row->mutu_ab_p1, 2) : '-') . '</td>';
        $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_cdef_p1) ? number_format($row->mutu_cdef_p1, 2) : '-') . '</td>';
        
        // Periode 2
        $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_ab_p2) ? number_format($row->mutu_ab_p2, 2) : '-') . '</td>';
        $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_cdef_p2) ? number_format($row->mutu_cdef_p2, 2) : '-') . '</td>';
        
        // Trend display
        if ($row->trendPercent !== null) {
            $trendIcon = $row->trendPercent > 0 ? '<i class="fas fa-arrow-up" style="color:green;"></i>' : '<i class="fas fa-arrow-down" style="color:red;"></i>';
            $html .= '<td style="text-align:center;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . $trendIcon . ' ' . number_format($row->trendPercent, 2) . '%</td>';
        } else {
            $html .= '<td style="text-align:center;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">-</td>';
        }
        
        $html .= '</tr>';
    }

    $html .= '</tbody>';
    $html .= '</table></div>';

    return response($html);
}

public function getRekapMejaTebuMutuEvaluasi2(Request $request)
{
    $plant = $request->input('plant', 'SK01');
    $tipeRekap = $request->input('tipe_rekap', 'afdeling');
    $tglAwal1 = $request->input('tgl_awal_1');
    $tglAkhir1 = $request->input('tgl_akhir_1');
    $tglAwal2 = $request->input('tgl_awal_2');
    $tglAkhir2 = $request->input('tgl_akhir_2');

    // Call the stored procedure
    $data = DB::select('call sp_rekap_mejatebu_mutu_evaluasi_2periode_2(?, ?, ?, ?, ?, ?)', [
        $plant,
        $tipeRekap,
        $tglAwal1,
        $tglAkhir1,
        $tglAwal2,
        $tglAkhir2
    ]);

    // Process the data
    $processedData = collect($data)->map(function ($item) {
        return $item;
    });

    $html = '<style>
        .table th, .table thead th {
            border: solid 1px #d1cbcb;
            background: #4c4c80;
            color: #FFF;
            font-size: 12px;
            text-align: center;
            vertical-align: middle;
        }
        .table td {
            font-size: 13px;
        }
        .table tbody tr:nth-child(even) {
            background: #f6f9fc;
        }
        .table tbody tr:hover {
            background: #e3e8f0;
        }
    </style>';

    // Separate total rows from non-total rows
    $totalRows = [];
    $nonTotalRows = [];
    
    foreach ($processedData as $row) {
//       $isTotalRow = stripos($row->nama_rayon ?? '', 'TOTAL') !== false;
        $isTotalRow = stripos($row->nama_rayon ?? '', 'TOTAL') !== false || stripos($row->nama_cluster ?? '', 'GRAND TOTAL') !== false;
        
        $protas_P1 = isset($row->protas_p1) ? (float)$row->protas_p1 : 0;
        $protas_P2 = isset($row->protas_p2) ? (float)$row->protas_p2 : 0;
        
        if ($protas_P1 > 0) {
            $trendPercent = (($protas_P2 - $protas_P1) / $protas_P1) * 100;
        } else {
            $trendPercent = null;
        }
        
        $row->trendPercent = $trendPercent;
        $row->isTotalRow = $isTotalRow;
        
        if ($isTotalRow) {
            $totalRows[] = $row;
        } else {
            $nonTotalRows[] = $row;
        }
    }
    
    // Sort only non-total rows by trendPercent descending, nulls last
    usort($nonTotalRows, function($a, $b) {
        if ($a->trendPercent === null) return 1;
        if ($b->trendPercent === null) return -1;
        return $b->trendPercent <=> $a->trendPercent;
    });
    
    // Combine sorted non-total rows with total rows at the end
    $processedDataWithTrend = array_merge($nonTotalRows, $totalRows);
    $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-striped table-hover table-sm table-responsive">';
        $html .= '<thead>';
        $html .= '<tr style="background: #4c4c80; color: #FFF;">';
        $html .= '<th rowspan="2">No</th>';
        $html .= '<th rowspan="2" style="vertical-align:middle;">Cluster</th>';
        $html .= '<th rowspan="2" style="vertical-align:middle;">Plant</th>';
        $html .= '<th rowspan="2" style="vertical-align:middle;">Kebun</th>';
        $html .= '<th rowspan="2" style="vertical-align:middle;">Kode Rayon</th>';
        $html .= '<th rowspan="2" style="vertical-align:middle;">Rayon</th>';
        $html .= '<th rowspan="2" style="vertical-align:middle;">Manajer Tanaman</th>';
        $html .= '<th rowspan="2" style="vertical-align:middle;">Kode Afd</th>';
        $html .= '<th rowspan="2" style="vertical-align:middle;">Nama Afd</th>';
        $html .= '<th rowspan="2" style="vertical-align:middle;">Asman</th>';
        $html .= '<th colspan="8" style="text-align:center;">Periode 1 (' . date('d M Y', strtotime($tglAwal1)) . ' - ' . date('d M Y', strtotime($tglAkhir1)) . ')</th>';
        $html .= '<th colspan="8" style="text-align:center;">Periode 2 (' . date('d M Y', strtotime($tglAwal2)) . ' - ' . date('d M Y', strtotime($tglAkhir2)) . ')</th>';
        $html .= '<th rowspan="2" style="vertical-align:middle;">Trend Protas</th>';
        $html .= '</tr>';
        $html .= '<tr style="background: #4c4c80; color: #FFF;">';
        $html .= '<th>Ha Tebang</th>';
        $html .= '<th>Netto Ton</th>';
        $html .= '<th>Protas</th>';
        $html .= '<th>Mutu A+B</th>';
        $html .= '<th>Mutu C</th>';
        $html .= '<th>Mutu D</th>';
        $html .= '<th>Mutu E</th>';
        $html .= '<th>Mutu F</th>';
        $html .= '<th>Ha Tebang</th>';
        $html .= '<th>Netto Ton</th>';
        $html .= '<th>Protas</th>';
        $html .= '<th>Mutu A+B</th>';
        $html .= '<th>Mutu C</th>';
        $html .= '<th>Mutu D</th>';
        $html .= '<th>Mutu E</th>';
        $html .= '<th>Mutu F</th>';
        $html .= '</tr>';
        $html .= '</thead>';
        $html .= '<tbody>';

        $no = 1;
        foreach ($processedDataWithTrend as $row) {
            $rowStyle = $row->isTotalRow ? 'style="background-color:#e3fcec;font-weight:bold;"' : '';
            
            $html .= '<tr ' . $rowStyle . '>';
            $html .= '<td>' . $no++ . '</td>';
            $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_cluster ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
            $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->plant ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
            $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_kebun ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
            $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->kode_rayon ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
            $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_rayon ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
            $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_manajer_tanaman ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
            $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->kode_afd ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
            $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_afd ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
            $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_asman ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
            
            // Periode 1
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->ha_tebang_p1) ? number_format($row->ha_tebang_p1, 2) : '-') . '</td>';
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->netto_ton_p1) ? number_format($row->netto_ton_p1, 2) : '-') . '</td>';
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->protas_p1) ? number_format($row->protas_p1, 2) : '-') . '</td>';
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_ab_p1) ? number_format($row->mutu_ab_p1, 2) : '-') . '</td>';
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_c_p1) ? number_format($row->mutu_c_p1, 2) : '-') . '</td>';
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_d_p1) ? number_format($row->mutu_d_p1, 2) : '-') . '</td>';
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_e_p1) ? number_format($row->mutu_e_p1, 2) : '-') . '</td>';
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_f_p1) ? number_format($row->mutu_f_p1, 2) : '-') . '</td>';
            
            // Periode 2
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->ha_tebang_p2) ? number_format($row->ha_tebang_p2, 2) : '-') . '</td>';
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->netto_ton_p2) ? number_format($row->netto_ton_p2, 2) : '-') . '</td>';
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->protas_p2) ? number_format($row->protas_p2, 2) : '-') . '</td>';
            
            // Mutu A+B dengan icon
            $mutu_ab_p1 = isset($row->mutu_ab_p1) ? (float)$row->mutu_ab_p1 : 0;
            $mutu_ab_p2 = isset($row->mutu_ab_p2) ? (float)$row->mutu_ab_p2 : 0;
            $icon_ab = '';
            if ($mutu_ab_p1 > 0 && $mutu_ab_p2 > 0) {
                $icon_ab = $mutu_ab_p2 > $mutu_ab_p1 ? ' <i class="fas fa-arrow-up" style="color:green;"></i>' : ' <i class="fas fa-arrow-down" style="color:red;"></i>';
            }
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_ab_p2) ? number_format($row->mutu_ab_p2, 2) : '-') . $icon_ab . '</td>';
            
            // Mutu C dengan icon
            $mutu_c_p1 = isset($row->mutu_c_p1) ? (float)$row->mutu_c_p1 : 0;
            $mutu_c_p2 = isset($row->mutu_c_p2) ? (float)$row->mutu_c_p2 : 0;
            $icon_c = '';
            if ($mutu_c_p1 > 0 && $mutu_c_p2 > 0) {
                $icon_c = $mutu_c_p2 > $mutu_c_p1 ? ' <i class="fas fa-arrow-up" style="color:green;"></i>' : ' <i class="fas fa-arrow-down" style="color:red;"></i>';
            }
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_c_p2) ? number_format($row->mutu_c_p2, 2) : '-') . $icon_c . '</td>';
            
            // Mutu D dengan icon
            $mutu_d_p1 = isset($row->mutu_d_p1) ? (float)$row->mutu_d_p1 : 0;
            $mutu_d_p2 = isset($row->mutu_d_p2) ? (float)$row->mutu_d_p2 : 0;
            $icon_d = '';
            if ($mutu_d_p1 > 0 && $mutu_d_p2 > 0) {
                $icon_d = $mutu_d_p2 > $mutu_d_p1 ? ' <i class="fas fa-arrow-up" style="color:green;"></i>' : ' <i class="fas fa-arrow-down" style="color:red;"></i>';
            }
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_d_p2) ? number_format($row->mutu_d_p2, 2) : '-') . $icon_d . '</td>';
            
            // Mutu E dengan icon
            $mutu_e_p1 = isset($row->mutu_e_p1) ? (float)$row->mutu_e_p1 : 0;
            $mutu_e_p2 = isset($row->mutu_e_p2) ? (float)$row->mutu_e_p2 : 0;
            $icon_e = '';
            if ($mutu_e_p1 > 0 && $mutu_e_p2 > 0) {
                $icon_e = $mutu_e_p2 > $mutu_e_p1 ? ' <i class="fas fa-arrow-up" style="color:green;"></i>' : ' <i class="fas fa-arrow-down" style="color:red;"></i>';
            }
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_e_p2) ? number_format($row->mutu_e_p2, 2) : '-') . $icon_e . '</td>';
            
            // Mutu F dengan icon
            $mutu_f_p1 = isset($row->mutu_f_p1) ? (float)$row->mutu_f_p1 : 0;
            $mutu_f_p2 = isset($row->mutu_f_p2) ? (float)$row->mutu_f_p2 : 0;
            $icon_f = '';
            if ($mutu_f_p1 > 0 && $mutu_f_p2 > 0) {
                $icon_f = $mutu_f_p2 > $mutu_f_p1 ? ' <i class="fas fa-arrow-up" style="color:green;"></i>' : ' <i class="fas fa-arrow-down" style="color:red;"></i>';
            }
            $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->mutu_f_p2) ? number_format($row->mutu_f_p2, 2) : '-') . $icon_f . '</td>';
            
            // Trend display
            if ($row->trendPercent !== null) {
                $trendIcon = $row->trendPercent > 0 ? '<i class="fas fa-arrow-up" style="color:green;"></i>' : '<i class="fas fa-arrow-down" style="color:red;"></i>';
                $html .= '<td style="text-align:center;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . $trendIcon . ' ' . number_format($row->trendPercent, 2) . '%</td>';
            } else {
                $html .= '<td style="text-align:center;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">-</td>';
            }
            
            $html .= '</tr>';
        }

        $html .= '</tbody>';
        $html .= '</table></div>';

    return response($html);
}

public function getRekapTimbanganProtasEvaluasi(Request $request)
{
    $plant = $request->input('plant', 'SK01');
    $tipeRekap = $request->input('tipe_rekap', 'rayon');
    $tglAwal1 = $request->input('tgl_awal_1');
    $tglAkhir1 = $request->input('tgl_akhir_1');
    $tglAwal2 = $request->input('tgl_awal_2');
    $tglAkhir2 = $request->input('tgl_akhir_2');

    // Call the stored procedure
    $data = DB::select('call sp_rekap_timbangan_protas_evaluasi_2periode(?, ?, ?, ?, ?, ?)', [
        $plant,
        $tipeRekap,
        $tglAwal1,
        $tglAkhir1,
        $tglAwal2,
        $tglAkhir2
    ]);

    // Process the data
    $processedData = collect($data)->map(function ($item) {
        return $item;
    });

    $html = '<style>
        .table th, .table thead th {
            border: solid 1px #d1cbcb;
            background: #4c4c80;
            color: #FFF;
            font-size: 12px;
            text-align: center;
            vertical-align: middle;
        }
        .table td {
            font-size: 13px;
        }
        .table tbody tr:nth-child(even) {
            background: #f6f9fc;
        }
        .table tbody tr:hover {
            background: #e3e8f0;
        }
    </style>';

    // Separate total rows from non-total rows
    $totalRows = [];
    $nonTotalRows = [];
    
    foreach ($processedData as $row) {
//        $isTotalRow = stripos($row->nama_rayon ?? '', 'TOTAL') !== false;
                $isTotalRow = stripos($row->nama_rayon ?? '', 'TOTAL') !== false || stripos($row->nama_cluster ?? '', 'GRAND TOTAL') !== false;
        
        $protas_P1 = isset($row->protas_p1) ? (float)$row->protas_p1 : 0;
        $protas_P2 = isset($row->protas_p2) ? (float)$row->protas_p2 : 0;
        
        if ($protas_P1 > 0) {
            $trendPercent = (($protas_P2 - $protas_P1) / $protas_P1) * 100;
        } else {
            $trendPercent = null;
        }
        
        $row->trendPercent = $trendPercent;
        $row->isTotalRow = $isTotalRow;
        
        if ($isTotalRow) {
            $totalRows[] = $row;
        } else {
            $nonTotalRows[] = $row;
        }
    }
    
    // Sort only non-total rows by trendPercent descending, nulls last
    usort($nonTotalRows, function($a, $b) {
        if ($a->trendPercent === null) return 1;
        if ($b->trendPercent === null) return -1;
        return $b->trendPercent <=> $a->trendPercent;
    });
    
    // Combine sorted non-total rows with total rows at the end
    $processedDataWithTrend = array_merge($nonTotalRows, $totalRows);

    $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-striped table-hover table-sm table-responsive">';
    $html .= '<thead>';
    $html .= '<tr>';
    $html .= '<th rowspan="2">No</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Cluster</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Plant</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Kebun</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Rayon</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Manajer Tanaman</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Afdeling</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Asman</th>';
    $html .= '<th colspan="3" style="text-align:center;">Periode 1 (' . date('d M Y', strtotime($tglAwal1)) . ' - ' . date('d M Y', strtotime($tglAkhir1)) . ')</th>';
    $html .= '<th colspan="3" style="text-align:center;">Periode 2 (' . date('d M Y', strtotime($tglAwal2)) . ' - ' . date('d M Y', strtotime($tglAkhir2)) . ')</th>';
    $html .= '<th rowspan="2" style="vertical-align:middle;">Trend Protas</th>';
    $html .= '</tr>';
    $html .= '<tr>';
    $html .= '<th>Ha Tebang</th>';
    $html .= '<th>Netto Ton</th>';
    $html .= '<th>Protas</th>';
    $html .= '<th>Ha Tebang</th>';
    $html .= '<th>Netto Ton</th>';
    $html .= '<th>Protas</th>';
    $html .= '</tr>';
    $html .= '</thead>';
    $html .= '<tbody>';

    $no = 1;
    foreach ($processedDataWithTrend as $row) {
        $rowStyle = $row->isTotalRow ? 'style="background-color:#e3fcec;font-weight:bold;"' : '';
        
        $html .= '<tr ' . $rowStyle . '>';
        $html .= '<td>' . $no++ . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_cluster ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->kode_kebun ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_kebun ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_rayon ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_manajer_tanaman ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->kode_afd ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        $html .= '<td>' . ($row->isTotalRow ? '<strong>' : '') . htmlspecialchars($row->nama_asman ?? '-') . ($row->isTotalRow ? '</strong>' : '') . '</td>';
        
        // Periode 1
        $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->ha_tebang_p1) ? number_format($row->ha_tebang_p1, 2) : '-') . '</td>';
        $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->netto_ton_p1) ? number_format($row->netto_ton_p1, 2) : '-') . '</td>';
        $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->protas_p1) ? number_format($row->protas_p1, 2) : '-') . '</td>';
        
        // Periode 2
        $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->ha_tebang_p2) ? number_format($row->ha_tebang_p2, 2) : '-') . '</td>';
        $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->netto_ton_p2) ? number_format($row->netto_ton_p2, 2) : '-') . '</td>';
        $html .= '<td style="text-align:right;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . (isset($row->protas_p2) ? number_format($row->protas_p2, 2) : '-') . '</td>';
        
        // Trend display
        if ($row->trendPercent !== null) {
            $trendIcon = $row->trendPercent > 0 ? '<i class="fas fa-arrow-up" style="color:green;"></i>' : '<i class="fas fa-arrow-down" style="color:red;"></i>';
            $html .= '<td style="text-align:center;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">' . $trendIcon . ' ' . number_format($row->trendPercent, 2) . '%</td>';
        } else {
            $html .= '<td style="text-align:center;' . ($row->isTotalRow ? 'font-weight:bold;' : '') . '">-</td>';
        }
        
        $html .= '</tr>';
    }

    $html .= '</tbody>';
    $html .= '</table></div>';

    return response($html);
}

public function getLkpPerAfd(Request $request)
{
    $tgl1 = $request->input('tgl1');
    $tgl2 = $request->input('tgl2');
    $kebunId = $request->input('kebun');
    
    // Ambil data dari stored procedure
    $data = DB::select('call GetRealisasiLKPPerAfd(?,?,?)', [$tgl1, $tgl2, urldecode($kebunId)]);
    $data = collect($data)->map(function($item) {
        $item->kode_afd = $item->kode_afd;
        $item->nama_asman = $item->nama_asman;
        $item->pekerjaan = $item->pekerjaan;
        $item->hektar = (float) str_replace(',', '.', round($item->hektar, 0));
        return $item;
    });

    // Group by kode_afd
    $grouped = $data->groupBy('kode_afd')->map(function ($items, $kode_afd) {
        return [
            'kode_afd' => $kode_afd,
            'nama_asman' => $items->first()->nama_asman,
            'pekerjaan' => $items->pluck('pekerjaan')->toArray(),
            'hektar' => $items->pluck('hektar')->toArray(),
        ];
    })->values();

    // Output chartOptions untuk setiap afd
    $chartOptions = [];
    foreach ($grouped as $afd) {
        $chartOptions[] = [
            'chart' => ['type' => 'column'],
            'title' => ['text' => 'Realisasi LKP Afdeling ' . $afd['kode_afd'] . ' <br> ' . $afd['nama_asman']],
            'xAxis' => [
                'categories' => $afd['pekerjaan'],
                'title' => ['text' => 'Pekerjaan']
            ],
            'yAxis' => [
                'min' => 0,
                'title' => ['text' => 'Hektar']
            ],
            'series' => [
                [
                    'name' => 'Realisasi',
                    'data' => $afd['hektar'],
                    'color' => '#007bff',
                    'dataLabels' => [
                        'enabled' => true,
                        'format' => '{y}',
                        'style' => [
                            'fontWeight' => 'bold',
                            'color' => '#000'
                        ]
                    ]
                ]
            ]
        ];
    }
    $this->data['grafik'] = $chartOptions;
    // return $this->data['grafik'];
    return view('dashboard.lkpafdeling', $this->data);
}

public function getLkpPerAsman(Request $request)
{
    $tgl1 = $request->input('tgl1');
    $tgl2 = $request->input('tgl2');
    $kebunId = $request->input('kebun');
    
    // Ambil data dari stored procedure
    $data = DB::select('call GetRealisasiLKPPerAsman(?,?,?)', [$tgl1, $tgl2, urldecode($kebunId)]);
    $data = collect($data)->map(function($item) {
        $item->kode_afd = $item->kode_afd;
        $item->nama_asman = $item->nama_asman;
        $item->pekerjaan = $item->pekerjaan;
        $item->hektar = (float) str_replace(',', '.', round($item->hektar, 0));
        return $item;
    });

    // Group by kode_afd
    $grouped = $data->groupBy('nama_asman')->map(function ($items, $kode_afd) {
        return [
            'kode_afd' => $kode_afd,
            'nama_asman' => $items->first()->nama_asman,
            'pekerjaan' => $items->pluck('pekerjaan')->toArray(),
            'hektar' => $items->pluck('hektar')->toArray(),
        ];
    })->values();

    // Output chartOptions untuk setiap afd
    $chartOptions = [];
    foreach ($grouped as $afd) {
        $chartOptions[] = [
            'chart' => ['type' => 'column'],
            'title' => ['text' => 'Realisasi LKP Asman <br> ' . $afd['nama_asman']],
            'xAxis' => [
                'categories' => $afd['pekerjaan'],
                'title' => ['text' => 'Pekerjaan']
            ],
            'yAxis' => [
                'min' => 0,
                'title' => ['text' => 'Hektar']
            ],
            'series' => [
                [
                    'name' => 'Realisasi',
                    'data' => $afd['hektar'],
                    'color' => '#007bff',
                    'dataLabels' => [
                        'enabled' => true,
                        'format' => '{y}',
                        'style' => [
                            'fontWeight' => 'bold',
                            'color' => '#000'
                        ]
                    ]
                ]
            ]
        ];
    }
    $this->data['grafik'] = $chartOptions;
    // return $this->data['grafik'];
    return view('dashboard.lkpafdeling', $this->data);
}




public function getListLKP(Request $request)
{
    $nama_kebun = $request->input('nama_kebun');

    // Fetch data from the database based on the date range
    if(empty($nama_kebun)){
        $data = DB::table('q_lkp_rekapvssasaran')
        ->select('*')
        ->whereNotNull('hektar_pekerjaan')  // Menambahkan kondisi pekerjaan tidak boleh null
        ->get();
    }else{
        $data = DB::select('call GetPekerjaanKSO(?)', [urldecode($nama_kebun)]);   
    }
    
    // Return the data as JSON
    return response()->json($data);
}

public function getChartBibit(Request $request)
    {
       // Ambil parameter filter dari request
            $plant = $request->input('plant', 'SK01');
            $rayon = $request->input('rayon', 'SK01');
            $masa_tanam = $request->input('masa_tanam', '24/25');
            $jenjang_bibitan = $request->input('jenjang_bibitan', 'KBI');

            // Query untuk mengambil data berdasarkan filter
            $data = DB::table('q_rekap_bibit_kso')
            ->select(
                DB::raw('CONCAT(jenjang_bibitan, "-", jenis_bibit) as jenis_bibit'),  // Menggunakan DB::raw untuk ekspresi SQL
                '1A', '1B', '2A', '2B', '3A', '3B', '4A', '4B', '5A', '5B',
                '6A', '6B', '7A', '7B', '8A', '8B', '9A', '9B', '10A', '10B',
                '11A', '11B', '12A', '12B'
            )
            ->where('plant', $plant)
            ->when(!empty($masa_tanam), function ($query) use ($masa_tanam) {
                return $query->where('masa_tanam', $masa_tanam);
            })
            ->when(!empty($rayon), function ($query) use ($rayon) {
                return $query->where('kode_rayon', $rayon);
            })
            // Menambahkan kondisi WHERE untuk jenjang_bibitan hanya jika tidak kosong
            ->when(!empty($jenjang_bibitan), function ($query) use ($jenjang_bibitan) {
                return $query->where('jenjang_bibitan', $jenjang_bibitan);
            })
            ->get();
        

            // Mengembalikan data sebagai response JSON
            return response()->json($data);

    }

    public function getChartMutuClusterisasi(Request $request)
    {
   // Ambil parameter filter dari request
$rayon = $request->input('rayon', 'SK01');

$data = DB::table('q_rekap_takmar_clusterisasi')
    ->select('nama_rayon', 'luas_a', 'luas_b', 'luas_c', 'luas_d', 'luas_e')
    ->where('kode_rayon', $rayon)
    ->first();

    $data2 = DB::table('q_rekap_takmar_clusterisasi')
    ->select(
        'nama_rayon',
        DB::raw('SUM(luas_a) as total_luas_a'),
        DB::raw('SUM(luas_b) as total_luas_b'),
        DB::raw('SUM(luas_c) as total_luas_c'),
        DB::raw('SUM(luas_d) as total_luas_d'),
        DB::raw('SUM(luas_e) as total_luas_e')
    )
    ->first();

// Pastikan data tersedia
if (!$data) {
    return response()->json([]);
}

// Format data untuk Highcharts Pie dengan 2 digit desimal
$chartData = [
    ['name' => 'A', 'y' => (float) number_format($data->luas_a, 2), 'color'=> '#28a745'],
    ['name' => 'B', 'y' => (float) number_format($data->luas_b, 2), 'color'=> '#007bff'],
    ['name' => 'C', 'y' => (float) number_format($data->luas_c, 2), 'color'=> '#ffc107'],
    ['name' => 'D', 'y' => (float) number_format($data->luas_d, 2), 'color'=> '#dc3545'],
    ['name' => 'E', 'y' => (float) number_format($data->luas_e, 2), 'color'=> '#000000'],
];

$chartData2 = [
    ['name' => 'A', 'y' => (float) $data2->total_luas_a, 'color'=> '#28a745'],
    ['name' => 'B', 'y' => (float) $data2->total_luas_b, 'color'=> '#007bff'],
    ['name' => 'C', 'y' => (float) $data2->total_luas_c, 'color'=> '#ffc107'],
    ['name' => 'D', 'y' => (float) $data2->total_luas_d, 'color'=> '#dc3545'],
    ['name' => 'E', 'y' => (float) $data2->total_luas_e, 'color'=> '#000000'],
];

$dataarr = array(
    'data' => $chartData,
    'nama_rayon' => $data->nama_rayon,
    'data2' => $chartData2
);


// Mengembalikan data sebagai response JSON
return response()->json($dataarr);


    }

    public function getrankinglkpkebun(Request $request){
    $data = DB::table('q_ranking_lkp_kebun')
        ->select('nama_kebun', 'luas_tanam', 'luas_morfologi', 'jml_morfologi', 'prosen_luas')
        ->where('kategori', 'PC')
        ->get();
    $data2 = DB::table('q_ranking_lkp_kebun')
        ->select('nama_kebun', 'luas_tanam', 'luas_morfologi', 'jml_morfologi', 'prosen_luas')
        ->where('kategori', 'RC')
        ->get();    
    $data3 = DB::table('q_ranking_lkp_kebun')
        ->select(
            'nama_kebun',
            DB::raw('SUM(luas_tanam) as total_luas_tanam'),
            DB::raw('SUM(luas_morfologi) as total_luas_morfologi'),
            DB::raw('SUM(jml_morfologi) as total_jml_morfologi'),
            DB::raw('SUM(luas_morfologi)/SUM(luas_tanam) as total_prosen_luas')
        )
        ->groupBy('kode_kebun')
        ->orderByDesc('total_prosen_luas')
        ->get();

    // Tab navigation for Total, PC, and RC
    $html = '
    <ul class="nav nav-tabs" id="lkpKebunTab" role="tablist">
        <li class="nav-item">
            <a class="nav-link active" id="morkebun-total-tab" data-toggle="tab" href="#morkebun-total" role="tab" aria-controls="total" aria-selected="true">Total</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="morkebun-pc-tab" data-toggle="tab" href="#morkebun-pc" role="tab" aria-controls="pc" aria-selected="false">PC</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="morkebun-rc-tab" data-toggle="tab" href="#morkebun-rc" role="tab" aria-controls="rc" aria-selected="false">RC</a>
        </li>
    </ul>
    <div class="tab-content" id="lkpKebunTabContent">
        <div class="tab-pane fade show active" id="morkebun-total" role="tabpanel" aria-labelledby="morkebun-total-tab">
            <div class=""><br>
                <strong>Total Morfologi Kebun</strong>
                <table class="table table-responsive table-sm table-bordered">
                    <thead>
                        <tr style="background: linear-gradient(90deg, #4c4c80 0%, #1e90ff 100%); color: #fff;">
                            <th style="background: #4c4c80; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #4c4c80; font-size:12px; color: #fff;">Nama Kebun</th>
                            <th style="background: #4c4c80; font-size:12px; color: #fff;">Luas Tanam (Ha)</th>
                            <th style="background: #4c4c80; font-size:12px; color: #fff;">Luas Morfologi (Ha)</th>
                            <th style="background: #4c4c80; font-size:12px; color: #fff;">Jumlah Petak</th>
                            <th style="background: #4c4c80; font-size:12px; color: #fff;">% Luas Morfologi</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data3 as $row) {
        $proses_luas = $row->total_luas_morfologi / $row->total_luas_tanam * 100; // Convert to percentage
        if ($proses_luas >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($proses_luas >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->nama_kebun) . '</td>
            <td style="text-align:right;">' . number_format($row->total_luas_tanam, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->total_luas_morfologi, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->total_jml_morfologi, 0) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($proses_luas, 2) . '%</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
        </div>
        <div class="tab-pane fade" id="morkebun-pc" role="tabpanel" aria-labelledby="morkebun-pc-tab">
            <div class=""><br>
                <strong>Ranking Morfologi Kebun (PC)</strong>
                <table class="table table-responsive table-sm table-bordered">
                    <thead style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                        <tr>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Kebun</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Tanam (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Morfologi (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Jumlah Petak</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">% Luas Morfologi</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data as $row) {
        if ($row->prosen_luas >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($row->prosen_luas >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->nama_kebun) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_tanam, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_morfologi, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->jml_morfologi, 0) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosen_luas, 2) . '%</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
        </div>
        <div class="tab-pane fade" id="morkebun-rc" role="tabpanel" aria-labelledby="morkebun-rc-tab">
            <div class=""><br>
                <strong>Ranking Morfologi Kebun (RC)</strong>
                <table class="table table-responsive table-sm table-bordered">
                    <thead style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                        <tr>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Kebun</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Tanam (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Morfologi (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Jumlah Petak</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">% Luas Morfologi</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data2 as $row) {
        if ($row->prosen_luas >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($row->prosen_luas >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->nama_kebun) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_tanam, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_morfologi, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->jml_morfologi, 0) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosen_luas, 2) . '%</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
    </div>
    <script>
        $(function(){
            $("#lkpKebunTab a").on("click", function(e){
                e.preventDefault();
                $(this).tab("show");
            });
        });
    </script>
    ';

    return response($html);
}

public function getrankinglkprayon(Request $request){
    $data = DB::table('q_ranking_lkp_rayon')
        ->select('nama_rayon', 'luas_tanam', 'luas_morfologi', 'jml_morfologi', 'prosen_luas')
        ->where('kategori', 'PC')
        ->get();
    $data2 = DB::table('q_ranking_lkp_rayon')
        ->select('nama_rayon', 'luas_tanam', 'luas_morfologi', 'jml_morfologi', 'prosen_luas')
        ->where('kategori', 'RC')
        ->get();    
    $data3 = DB::table('q_ranking_lkp_rayon')
        ->select(
            'nama_rayon',
            DB::raw('SUM(luas_tanam) as total_luas_tanam'),
            DB::raw('SUM(luas_morfologi) as total_luas_morfologi'),
            DB::raw('SUM(jml_morfologi) as total_jml_morfologi'),
            DB::raw('SUM(luas_morfologi)/SUM(luas_tanam) as total_prosen_luas')
        )
        ->groupBy('kode_rayon')
        ->orderByDesc('total_prosen_luas')
        ->get();

    // Tab navigation for Total, PC, and RC
    $html = '
    <ul class="nav nav-tabs" id="lkpRayonTab" role="tablist">
        <li class="nav-item">
            <a class="nav-link active" id="morforayon-total-tab" data-toggle="tab" href="#morforayon-total" role="tab" aria-controls="morfo-total" aria-selected="true">Total</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="morforayon-pc-tab" data-toggle="tab" href="#morforayon-pc" role="tab" aria-controls="morforayon-pc" aria-selected="false">PC</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="morforayon-rc-tab" data-toggle="tab" href="#morforayon-rc" role="tab" aria-controls="morforayon-rc" aria-selected="false">RC</a>
        </li>
    </ul>
    <div class="tab-content" id="lkpRayonTabContent">
        <div class="tab-pane fade show active" id="morforayon-total" role="tabpanel" aria-labelledby="morforayon-total-tab">
            <div class=""><br>
                <strong>Total Morfologi Rayon</strong>
                <table class="table table-responsive table-sm table-bordered">
                    <thead>
                        <tr style="background: linear-gradient(90deg, #3345a1 0%, #4c4c80 100%); color: #fff;">
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Rayon</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Tanam (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Morfologi (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Jumlah Petak</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">% Luas Morfologi</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data3 as $row) {
        $proses_luas = $row->total_luas_morfologi / $row->total_luas_tanam * 100; // Convert to percentage
        if ($proses_luas >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($proses_luas >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->nama_rayon) . '</td>
            <td style="text-align:right;">' . number_format($row->total_luas_tanam, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->total_luas_morfologi, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->total_jml_morfologi, 0) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($proses_luas, 2) . '%</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
        </div>
        <div class="tab-pane fade" id="morforayon-pc" role="tabpanel" aria-labelledby="morforayon-pc-tab">
            <div class=""><br>
                <strong>Ranking Morfologi Rayon (PC)</strong>
                <table class="table table-responsive table-sm table-bordered">
                    <thead style="background: linear-gradient(90deg, #3345a1 0%, #185a9d 100%); color: #fff;">
                        <tr>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Rayon</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Tanam (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Morfologi (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Jumlah Petak</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">% Luas Morfologi</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data as $row) {
        if ($row->prosen_luas >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($row->prosen_luas >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->nama_rayon) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_tanam, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_morfologi, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->jml_morfologi, 0) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosen_luas, 2) . '%</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
        </div>
        <div class="tab-pane fade" id="morforayon-rc" role="tabpanel" aria-labelledby="morforayon-rc-tab">
            <div class=""><br>
                <strong>Ranking Morfologi Rayon (RC)</strong>
                <table class="table table-responsive table-sm table-bordered">
                    <thead style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                        <tr>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Rayon</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Tanam (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Morfologi (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Jumlah Petak</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">% Luas Morfologi</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data2 as $row) {
        if ($row->prosen_luas >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($row->prosen_luas >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->nama_rayon) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_tanam, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_morfologi, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->jml_morfologi, 0) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosen_luas, 2) . '%</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
    </div>
    <script>
        $(function(){
            $("#lkpRayonTab a").on("click", function(e){
                e.preventDefault();
                $(this).tab("show");
            });
        });
    </script>
    ';

    return response($html);
}

public function getrankinglkpafdeling(Request $request){

       $getlevel = DB::table('tb_groups')
            ->select('level')
            ->where('group_id',\Session::get('gid'))
            ->first();

    $data = DB::table('q_ranking_lkp_afd')
        ->select('kode_afd','nama_asman', 'luas_tanam', 'luas_morfologi', 'jml_morfologi', 'prosen_luas')
        ->where('kategori', 'PC')
        ->when($getlevel->level == 3, function ($query) {
        return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 4));
        })
        ->when($getlevel->level == 4, function ($query) {
            return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 6));
        })
        ->get();
    $data2 = DB::table('q_ranking_lkp_afd')
        ->select('kode_afd','nama_asman', 'luas_tanam', 'luas_morfologi', 'jml_morfologi', 'prosen_luas')
        ->where('kategori', 'RC')
        ->when($getlevel->level == 3, function ($query) {
        return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 4));
        })
        ->when($getlevel->level == 4, function ($query) {
            return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 6));
        })
        ->get();
    $data3 = DB::table('q_ranking_lkp_afd')
        ->select(
            'kode_afd',
            'nama_asman',
            DB::raw('SUM(luas_tanam) as total_luas_tanam'),
            DB::raw('SUM(luas_morfologi) as total_luas_morfologi'),
            DB::raw('SUM(jml_morfologi) as total_jml_morfologi'),
            DB::raw('SUM(luas_morfologi)/SUM(luas_tanam) as total_prosen_luas')
        )
        ->when($getlevel->level == 3, function ($query) {
        return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 4));
        })
        ->when($getlevel->level == 4, function ($query) {
            return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 6));
        })
        ->groupBy('kode_afd')
        ->orderByDesc('total_prosen_luas')
        ->get();

    // Tab navigation for Total, PC, and RC
    $html = '
    <ul class="nav nav-tabs" id="lkpAfdelingTab" role="tablist">
        <li class="nav-item">
            <a class="nav-link active" id="morf-afd-total-tab" data-toggle="tab" href="#morf-afd-total" role="tab" aria-controls="morf-afd-total" aria-selected="true">Total</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="morf-afd-pc-tab" data-toggle="tab" href="#morf-afd-pc" role="tab" aria-controls="morf-afd-pc" aria-selected="false">PC</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="morf-afd-rc-tab" data-toggle="tab" href="#morf-afd-rc" role="tab" aria-controls="morf-afd-rc" aria-selected="false">RC</a>
        </li>
    </ul>
    <div class="tab-content" id="lkpAfdelingTabContent">
        <div class="tab-pane fade show active" id="morf-afd-total" role="tabpanel" aria-labelledby="morf-afd-total-tab">
            <div class=""><br>
                <strong>Total Morfologi Afdeling</strong>
                <table class="table table-responsive table-sm table-bordered">
                    <thead>
                        <tr style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Kode Afdeling</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Asman</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Tanam (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Morfologi (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Jumlah Petak</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">% Luas Morfologi</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data3 as $row) {
        $proses_luas = $row->total_luas_morfologi / $row->total_luas_tanam * 100; // Convert to percentage
        if ($proses_luas >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($proses_luas >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->kode_afd) . '</td>
            <td>' . htmlspecialchars($row->nama_asman) . '</td>
            <td style="text-align:right;">' . number_format($row->total_luas_tanam, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->total_luas_morfologi, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->total_jml_morfologi, 0) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($proses_luas, 2) . '%</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
        </div>
        <div class="tab-pane fade" id="morf-afd-pc" role="tabpanel" aria-labelledby="morf-afd-pc-tab">
            <div class=""><br>
                <strong>Ranking Morfologi Afdeling (PC)</strong>
                <table class="table table-responsive table-sm table-bordered">
                    <thead>
                        <tr style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Kode Afdeling</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Asman</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Tanam (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Morfologi (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Jumlah Petak</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">% Luas Morfologi</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data as $row) {
        if ($row->prosen_luas >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($row->prosen_luas >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->kode_afd) . '</td>
            <td>' . htmlspecialchars($row->nama_asman) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_tanam, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_morfologi, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->jml_morfologi, 0) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosen_luas, 2) . '%</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
        </div>
        <div class="tab-pane fade" id="morf-afd-rc" role="tabpanel" aria-labelledby="morf-afd-rc-tab">
            <div class=""><br>
                <strong>Ranking Morfologi Afdeling (RC)</strong>
                <table class="table table-responsive table-sm table-bordered">
                    <thead>
                        <tr style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Kode Afdeling</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Asman</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Tanam (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Luas Morfologi (Ha)</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Jumlah Petak</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">% Luas Morfologi</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data2 as $row) {
        if ($row->prosen_luas >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($row->prosen_luas >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->kode_afd) . '</td>
            <td>' . htmlspecialchars($row->nama_asman) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_tanam, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->luas_morfologi, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->jml_morfologi, 0) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosen_luas, 2) . '%</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
    </div>
    <script>
        $(function(){
            $("#lkpAfdelingTab a").on("click", function(e){
                e.preventDefault();
                $(this).tab("show");
            });
        });
    </script>
    ';

    return response($html);
}

public function getrankinglkp2kebun(Request $request){
    $data = DB::table('q_ranking_lkp2_kebun')
        ->select('kebun', 'ha_serah_tanah', 'ha_tanam_kepras', 
            DB::raw('CASE WHEN ha_serah_tanah > 0 THEN ROUND(ha_tanam_kepras / ha_serah_tanah * 100, 2) ELSE 0 END as prosentase'))
        ->orderByDesc('prosentase')
        ->where('jenis_kate', 'PC')
        ->get();

    $data2 = DB::table('q_ranking_lkp2_kebun')
        ->select('kebun', 'ha_serah_tanah', 'ha_tanam_kepras', 
            DB::raw('CASE WHEN ha_serah_tanah > 0 THEN ROUND(ha_tanam_kepras / ha_serah_tanah * 100, 2) ELSE 0 END as prosentase'))
        ->orderByDesc('prosentase')
        ->where('jenis_kate', 'RC')
        ->get();    
    $data3 = DB::table('q_ranking_lkp2_kebun')
        ->select(
            'kebun',
            DB::raw('SUM(ha_serah_tanah) as total_ha_serah_tanah'),
            DB::raw('SUM(ha_tanam_kepras) as total_ha_tanam_kepras'),
            DB::raw('CASE WHEN SUM(ha_serah_tanah) > 0 THEN ROUND(SUM(ha_tanam_kepras) / SUM(ha_serah_tanah) * 100, 2) ELSE 0 END as total_prosentase')
        )
        ->groupBy('kebun')
        ->orderByDesc('total_prosentase')
        ->get();
        
// Tab navigation for PC, RC, and Total
$html = '
<ul class="nav nav-tabs" id="lkpKebunTab" role="tablist">
    <li class="nav-item">
        <a class="nav-link active" id="lkpkebun-total-tab" data-toggle="tab" href="#lkpkebun-total" role="tab" aria-controls="total" aria-selected="false">Total</a>
    </li>
    <li class="nav-item">
        <a class="nav-link " id="lkpkebun-pc-tab" data-toggle="tab" href="#lkpkebun-pc" role="tab" aria-controls="pc" aria-selected="true">PC</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" id="lkpkebun-rc-tab" data-toggle="tab" href="#lkpkebun-rc" role="tab" aria-controls="rc" aria-selected="false">RC</a>
    </li>

</ul>
<div class="tab-content" id="lkpKebunTabContent">
    <div class="tab-pane fade" id="lkpkebun-pc" role="tabpanel" aria-labelledby="pc-tab">
        <div class="bg-white"><br>
            <strong>Ranking LKP Kebun (PC)</strong>
        <table class="table table-responsive table-sm table-bordered">
            <thead style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                <tr>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Kebun</th>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Sasaran</th>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Tanam/Kepras</th>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">% Tanam/Kepras</th>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">Keterangan</th>
                </tr>
            </thead>
            <tbody>';
$no = 1;
foreach ($data as $row) {
    $keterangan = '';
    if ($row->ha_tanam_kepras > $row->ha_serah_tanah) {
        $keterangan = '<span style="color:red;">Cek ulang inputan</span>';
    }
    if ($row->prosentase >= 100) {
        $bgcolor = '#28a745'; $color = '#fff';
    } elseif ($row->prosentase >= 90) {
        $bgcolor = '#ffc107'; $color = '#000';
    } else {
        $bgcolor = '#dc3545'; $color = '#fff';
    }
    $html .= '<tr>
        <td>' . $no++ . '</td>
        <td>' . htmlspecialchars($row->kebun) . '</td>
        <td style="text-align:right;">' . number_format($row->ha_serah_tanah, 2) . '</td>
        <td style="text-align:right;">' . number_format($row->ha_tanam_kepras, 2) . '</td>
        <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosentase, 2) . '%</td>
        <td>' . $keterangan . '</td>
    </tr>';
}
$html .= '</tbody></table></div>
    </div>
    <div class="tab-pane fade" id="lkpkebun-rc" role="tabpanel" aria-labelledby="rc-tab">
        <div class="bg-white"><br>
            <strong>Ranking LKP Kebun (RC)</strong>
        <table class="table table-responsive table-sm table-bordered">
            <thead style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                <tr>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Kebun</th>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Sasaran</th>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Tanam/Kepras</th>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">% Tanam/Kepras</th>
                    <th style="background: #3345a1; font-size:12px; color: #fff;">Keterangan</th>
                </tr>
            </thead>
            <tbody>';
$no = 1;
foreach ($data2 as $row) {
    $keterangan = '';
    if ($row->ha_tanam_kepras > $row->ha_serah_tanah) {
        $keterangan = '<span style="color:red;">Cek ulang inputan</span>';
    }
    if ($row->prosentase >= 100) {
        $bgcolor = '#28a745'; $color = '#fff';
    } elseif ($row->prosentase >= 90) {
        $bgcolor = '#ffc107'; $color = '#000';
    } else {
        $bgcolor = '#dc3545'; $color = '#fff';
    }
    $html .= '<tr>
        <td>' . $no++ . '</td>
        <td>' . htmlspecialchars($row->kebun) . '</td>
        <td style="text-align:right;">' . number_format($row->ha_serah_tanah, 2) . '</td>
        <td style="text-align:right;">' . number_format($row->ha_tanam_kepras, 2) . '</td>
        <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosentase, 2) . '%</td>
        <td>' . $keterangan . '</td>
    </tr>';
}
$html .= '</tbody></table></div>
    </div>
    <div class="tab-pane fade show active" id="lkpkebun-total" role="tabpanel" aria-labelledby="total-tab">
        <div class="bg-white"><br>
            <strong>Total LKP Kebun</strong>
        <table class="table table-responsive table-sm table-bordered">
            <thead>
                <tr style="background: linear-gradient(90deg, #4c4c80 0%, #1e90ff 100%); color: #fff;">
                    <th style="background: #4c4c80; font-size:12px;color: #fff;">Ranking</th>
                    <th style="background: #4c4c80; font-size:12px;color: #fff;">Kebun</th>
                    <th style="background: #4c4c80; font-size:12px;color: #fff;">Ha Sasaran</th>
                    <th style="background: #4c4c80; font-size:12px;color: #fff;">Ha Tanam/Kepras</th>
                    <th style="background: #4c4c80; font-size:12px;color: #fff;">% Tanam/Kepras</th>
                    <th style="background: #4c4c80; font-size:12px;color: #fff;">Keterangan</th>
                </tr>
            </thead>
            <tbody>';
$no = 1;
foreach ($data3 as $row) {
    $keterangan = '';
    if ($row->total_ha_tanam_kepras > $row->total_ha_serah_tanah) {
        $keterangan = '<span style="color:red;">Cek ulang inputan</span>';
    }
    if ($row->total_prosentase >= 100) {
        $bgcolor = '#28a745'; $color = '#fff';
    } elseif ($row->total_prosentase >= 90) {
        $bgcolor = '#ffc107'; $color = '#000';
    } else {
        $bgcolor = '#dc3545'; $color = '#fff';
    }
    $html .= '<tr>
        <td>' . $no++ . '</td>
        <td>' . htmlspecialchars($row->kebun) . '</td>
        <td style="text-align:right;">' . number_format($row->total_ha_serah_tanah, 2) . '</td>
        <td style="text-align:right;">' . number_format($row->total_ha_tanam_kepras, 2) . '</td>
        <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->total_prosentase, 2) . '%</td>
        <td>' . $keterangan . '</td>
    </tr>';
}
$html .= '</tbody></table></div>
    </div>
</div>
<script>
    $(function(){
        $("#lkpKebunTab a").on("click", function(e){
            e.preventDefault();
            $(this).tab("show");
        });
    });
</script>
';

    return response($html);
}

public function getrankinglkp2rayon(Request $request){
    $data = DB::table('q_ranking_lkp2_rayon')
        ->select('rayon', 'ha_serah_tanah', 'ha_tanam_kepras', 
            DB::raw('CASE WHEN ha_serah_tanah > 0 THEN ROUND(ha_tanam_kepras / ha_serah_tanah * 100, 2) ELSE 0 END as prosentase'))
        ->orderByDesc('prosentase')
        ->where('jenis_kate', 'PC')
        ->get();
    $data2 = DB::table('q_ranking_lkp2_rayon')
        ->select('rayon', 'ha_serah_tanah', 'ha_tanam_kepras', 
            DB::raw('CASE WHEN ha_serah_tanah > 0 THEN ROUND(ha_tanam_kepras / ha_serah_tanah * 100, 2) ELSE 0 END as prosentase')) 
        ->orderByDesc('prosentase')
        ->where('jenis_kate', 'RC')
        ->get();
    $data3 = DB::table('q_ranking_lkp2_rayon')
        ->select(
            'rayon',
            DB::raw('SUM(ha_serah_tanah) as total_ha_serah_tanah'),
            DB::raw('SUM(ha_tanam_kepras) as total_ha_tanam_kepras'),
            DB::raw('CASE WHEN SUM(ha_serah_tanah) > 0 THEN ROUND(SUM(ha_tanam_kepras) / SUM(ha_serah_tanah) * 100, 2) ELSE 0 END as total_prosentase')
        )
        ->groupBy('rayon')
        ->orderByDesc('total_prosentase')
        ->get();
// Tab navigation for Total, PC, and RC
$html = '
<ul class="nav nav-tabs" id="lkpRayonTab" role="tablist">
    <li class="nav-item">
        <a class="nav-link active" id="lkprayon-total-tab" data-toggle="tab" href="#lkprayon-total" role="tab" aria-controls="total" aria-selected="true">Total</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" id="lkprayon-pc-tab" data-toggle="tab" href="#lkprayon-pc" role="tab" aria-controls="pc" aria-selected="false">PC</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" id="lkprayon-rc-tab" data-toggle="tab" href="#lkprayon-rc" role="tab" aria-controls="rc" aria-selected="false">RC</a>
    </li>
</ul>
<div class="tab-content" id="lkpRayonTabContent">
    <div class="tab-pane fade show active" id="lkprayon-total" role="tabpanel" aria-labelledby="lkprayon-total-tab">
        <div class="bg-white"><br>
            <strong>Total LKP Rayon</strong>
            <table class="table table-responsive table-sm table-bordered">
                <thead>
                    <tr style="background: linear-gradient(90deg, #4c4c80 0%, #1e90ff 100%); color: #fff;">
                        <th style="background: #4c4c80; font-size:12px;color: #fff;">Ranking</th>
                        <th style="background: #4c4c80; font-size:12px;color: #fff;">Rayon</th>
                        <th style="background: #4c4c80; font-size:12px;color: #fff;">Ha Sasaran</th>
                        <th style="background: #4c4c80; font-size:12px;color: #fff;">Ha Tanam/Kepras</th>
                        <th style="background: #4c4c80; font-size:12px;color: #fff;">% Tanam/Kepras</th>
                    </tr>
                </thead>
                <tbody>';
$no = 1;
foreach ($data3 as $row) {
    if ($row->total_prosentase >= 100) {
        $bgcolor = '#28a745'; $color = '#fff';
    } elseif ($row->total_prosentase >= 90) {
        $bgcolor = '#ffc107'; $color = '#000';
    } else {
        $bgcolor = '#dc3545'; $color = '#fff';
    }
    $html .= '<tr>
        <td>' . $no++ . '</td>
        <td>' . htmlspecialchars($row->rayon) . '</td>
        <td style="text-align:right;">' . number_format($row->total_ha_serah_tanah, 2) . '</td>
        <td style="text-align:right;">' . number_format($row->total_ha_tanam_kepras, 2) . '</td>
        <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->total_prosentase, 2) . '%</td>
    </tr>';
}
$html .= '</tbody></table></div>
    </div>
    <div class="tab-pane fade" id="lkprayon-pc" role="tabpanel" aria-labelledby="lkprayon-pc-tab">
        <div class="bg-white"><br>
            <strong>Ranking LKP Rayon (PC)</strong>
            <table class="table table-responsive table-sm table-bordered">
                <thead style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                    <tr>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Rayon</th>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Sasaran</th>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Tanam/Kepras</th>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">% Tanam/Kepras</th>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">Keterangan</th>
                    </tr>
                </thead>
                <tbody>';
$no = 1;
foreach ($data as $row) {
    $keterangan = '';
    if ($row->ha_tanam_kepras > $row->ha_serah_tanah) {
        $keterangan = '<span style="color:red;">Cek ulang inputan</span>';
    }
    if ($row->prosentase >= 100) {
        $bgcolor = '#28a745'; $color = '#fff';
    } elseif ($row->prosentase >= 90) {
        $bgcolor = '#ffc107'; $color = '#000';
    } else {
        $bgcolor = '#dc3545'; $color = '#fff';
    }
    $html .= '<tr>
        <td>' . $no++ . '</td>
        <td>' . htmlspecialchars($row->rayon) . '</td>
        <td style="text-align:right;">' . number_format($row->ha_serah_tanah, 2) . '</td>
        <td style="text-align:right;">' . number_format($row->ha_tanam_kepras, 2) . '</td>
        <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosentase, 2) . '%</td>
        <td>' . $keterangan . '</td>
    </tr>';
}
$html .= '</tbody></table></div>
    </div>
    <div class="tab-pane fade" id="lkprayon-rc" role="tabpanel" aria-labelledby="lkprayon-rc-tab">
        <div class="bg-white"><br>
            <strong>Ranking LKP Rayon (RC)</strong>
            <table class="table table-responsive table-sm table-bordered">
                <thead style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                    <tr>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Rayon</th>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Sasaran</th>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Tanam/Kepras</th>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">% Tanam/Kepras</th>
                        <th style="background: #3345a1; font-size:12px; color: #fff;">Keterangan</th>
                    </tr>
                </thead>
                <tbody>';
$no = 1;
foreach ($data2 as $row) {
    $keterangan = '';
    if ($row->ha_tanam_kepras > $row->ha_serah_tanah) {
        $keterangan = '<span style="color:red;">Cek ulang inputan</span>';
    }
    if ($row->prosentase >= 100) {
        $bgcolor = '#28a745'; $color = '#fff';
    } elseif ($row->prosentase >= 90) {
        $bgcolor = '#ffc107'; $color = '#000';
    } else {
        $bgcolor = '#dc3545'; $color = '#fff';
    }
    $html .= '<tr>
        <td>' . $no++ . '</td>
        <td>' . htmlspecialchars($row->rayon) . '</td>
        <td style="text-align:right;">' . number_format($row->ha_serah_tanah, 2) . '</td>
        <td style="text-align:right;">' . number_format($row->ha_tanam_kepras, 2) . '</td>
        <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosentase, 2) . '%</td>
        <td>' . $keterangan . '</td>
    </tr>';
}
$html .= '</tbody></table></div>
    </div>
</div>
<script>
    $(function(){
        $("#lkpRayonTab a").on("click", function(e){
            e.preventDefault();
            $(this).tab("show");
        });
    });
</script>
';

return response($html);
    }

    public function getrankinglkp2afdeling(){   

                $getlevel = DB::table('tb_groups')
            ->select('level')
            ->where('group_id',\Session::get('gid'))
            ->first();


    $data = DB::table('q_ranking_lkp2_afd')
        ->select('kode_afd', 'nama_asman', 'ha_serah_tanah', 'ha_tanam_kepras', 
            DB::raw('CASE WHEN ha_serah_tanah > 0 THEN ROUND(ha_tanam_kepras / ha_serah_tanah * 100, 2) ELSE 0 END as prosentase'))
        ->orderByDesc('prosentase')
        ->where('jenis_kate', 'PC')
         ->when($getlevel->level == 3, function ($query) {
            return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 4));
        })
        ->when($getlevel->level == 4, function ($query) {
            return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 6));
        })
        ->get();
    $data2 = DB::table('q_ranking_lkp2_afd')
        ->select('kode_afd', 'nama_asman', 'ha_serah_tanah', 'ha_tanam_kepras', 
            DB::raw('CASE WHEN ha_serah_tanah > 0 THEN ROUND(ha_tanam_kepras / ha_serah_tanah * 100, 2) ELSE 0 END as prosentase'))
        ->orderByDesc('prosentase')
        ->where('jenis_kate', 'RC')
         ->when($getlevel->level == 3, function ($query) {
            return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 4));
        })
        ->when($getlevel->level == 4, function ($query) {
            return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 6));
        })
        ->get();
   
    $data4 = DB::table('q_ranking_lkp2_afd')
        ->select(
            'kode_afd',
            'nama_asman',
            DB::raw('SUM(ha_serah_tanah) as total_ha_serah_tanah'),
            DB::raw('SUM(ha_tanam_kepras) as total_ha_tanam_kepras'),
            DB::raw('CASE WHEN SUM(ha_serah_tanah) > 0 THEN ROUND(SUM(ha_tanam_kepras) / SUM(ha_serah_tanah) * 100, 2) ELSE 0 END as total_prosentase')
        )
        ->when($getlevel->level == 3, function ($query) {
            return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 4));
        })
        ->when($getlevel->level == 4, function ($query) {
            return $query->where('kode_kebun', substr(\Session::get('fid'), 0, 6));
        })
        ->groupBy('kode_afd')
        ->orderByDesc('total_prosentase')
        ->get();
    // Tab navigation for Total, PC, and RC
    $html = '
    <ul class="nav nav-tabs" id="lkpAfdelingTab" role="tablist">
        <li class="nav-item">
            <a class="nav-link active" id="lkpafd-total-tab" data-toggle="tab" href="#lkpafd-total" role="tab" aria-controls="total" aria-selected="true">Total</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="lkpafd-pc-tab" data-toggle="tab" href="#lkpafd-pc" role="tab" aria-controls="pc" aria-selected="false">PC</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="lkpafd-rc-tab" data-toggle="tab" href="#lkpafd-rc" role="tab" aria-controls="rc" aria-selected="false">RC</a>
        </li>
    </ul>
    <div class="tab-content" id="lkpAfdelingTabContent">
        <div class="tab-pane fade show active" id="lkpafd-total" role="tabpanel" aria-labelledby="lkpafd-total-tab">
            <div class="bg-white"><br>
                <strong>Total LKP Afdeling</strong>
                <table class="table table-responsive table-sm">
                    <thead>
                        <tr style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Asman</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Sasaran</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Tanam/Kepras</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">% Tanam/Kepras</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data4 as $row) {
        if ($row->total_prosentase >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($row->total_prosentase >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->nama_asman) . '</td>
            <td style="text-align:right;">' . number_format($row->total_ha_serah_tanah, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->total_ha_tanam_kepras, 2) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->total_prosentase, 2) . '%</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
        </div>
        <div class="tab-pane fade" id="lkpafd-pc" role="tabpanel" aria-labelledby="lkpafd-pc-tab">
            <div class=""><br>
                <strong>Ranking LKP Afdeling (PC)</strong>
                <table class="table table-responsive table-sm">
                    <thead style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                        <tr>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Kode Afdeling</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Asman</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Sasaran</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Tanam/Kepras</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">% Tanam/Kepras</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Keterangan</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data as $row) {
        $keterangan = '';
        if ($row->ha_tanam_kepras > $row->ha_serah_tanah) {
            $keterangan = '<span style="color:red;">Cek ulang inputan</span>';
        }
        if ($row->prosentase >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($row->prosentase >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->kode_afd) . '</td>
            <td>' . htmlspecialchars($row->nama_asman) . '</td>
            <td style="text-align:right;">' . number_format($row->ha_serah_tanah, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->ha_tanam_kepras, 2) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosentase, 2) . '%</td>
            <td>' . $keterangan . '</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
        </div>
        <div class="tab-pane fade" id="lkpafd-rc" role="tabpanel" aria-labelledby="lkpafd-rc-tab">
            <div class=""><br>
                <strong>Ranking LKP Afdeling (RC)</strong>
                <table class="table table-responsive table-sm">
                    <thead style="background: linear-gradient(90deg, #3345a1 0%, #1e90ff 100%); color: #fff;">
                        <tr>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ranking</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Kode Afdeling</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Nama Asman</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Sasaran</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Ha Tanam/Kepras</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">% Tanam/Kepras</th>
                            <th style="background: #3345a1; font-size:12px; color: #fff;">Keterangan</th>
                        </tr>
                    </thead>
                    <tbody>';
    $no = 1;
    foreach ($data2 as $row) {
        $keterangan = '';
        if ($row->ha_tanam_kepras > $row->ha_serah_tanah) {
            $keterangan = '<span style="color:red;">Cek ulang inputan</span>';
        }
        if ($row->prosentase >= 100) {
            $bgcolor = '#28a745'; $color = '#fff';
        } elseif ($row->prosentase >= 90) {
            $bgcolor = '#ffc107'; $color = '#000';
        } else {
            $bgcolor = '#dc3545'; $color = '#fff';
        }
        $html .= '<tr>
            <td>' . $no++ . '</td>
            <td>' . htmlspecialchars($row->kode_afd) . '</td>
            <td>' . htmlspecialchars($row->nama_asman) . '</td>
            <td style="text-align:right;">' . number_format($row->ha_serah_tanah, 2) . '</td>
            <td style="text-align:right;">' . number_format($row->ha_tanam_kepras, 2) . '</td>
            <td style="text-align:right;background:' . $bgcolor . ';color:' . $color . ';">' . number_format($row->prosentase, 2) . '%</td>
            <td>' . $keterangan . '</td>
        </tr>';
    }
    $html .= '</tbody></table></div>
    </div>
    <script>
        $(function(){
            $("#lkpAfdelingTab a").on("click", function(e){
                e.preventDefault();
                $(this).tab("show");
            });
        });
    </script>
    ';
    return response($html);
}

       

        public function getSasaran2526KebunPopmie()
        {
            $data = DB::table('TX_TOTAL_KSO')
                ->join('master_petak', 'TX_TOTAL_KSO.id_lahan', '=', 'master_petak.lahan_id')
                ->join('master_afd', 'master_petak.afd_new', '=', 'master_afd.kode_afd')
                ->join('master_rayon', 'master_afd.kode_rayon', '=', 'master_rayon.kode_rayon')
                ->join('master_kebun', 'master_rayon.kode_kebun', '=', 'master_kebun.kode_kebun')
                ->join('master_kategori', 'master_petak.kategori_n', '=', 'master_kategori.kat_lahan')
                ->join('master_sasaran2526_kebun_popmie as a', 'a.kode_kebun', '=', 'master_kebun.kode_kebun')
                ->select(
                    'master_kebun.nama_kebun',
                    'a.ha_luas_sasaran',
                    DB::raw('SUM(TX_TOTAL_KSO.ha) as luas_real'),
                    DB::raw('ROUND(SUM(TX_TOTAL_KSO.ha)/a.ha_luas_sasaran*100,2) as persen_luas'),
                    'a.ton_tebu_sasaran',
                    DB::raw("'' as real_ton_tebu"),
                    DB::raw("0. as persen_ton_tebu"),
                    'a.protas_sasaran',
                    DB::raw("'' as real_protas"),
                    DB::raw("0. as persen_protas")
                )
                ->where('TX_TOTAL_KSO.pekerjaan', 'serah_tanah')
                ->where('TX_TOTAL_KSO.tgl', '!=', '0000-00-00')
                ->whereBetween('TX_TOTAL_KSO.tgl', ['2024-12-01', date('Y-m-d')])
                ->groupBy('master_kebun.kode_kebun')
                ->get();

            $html = '<style>
                .table th, .table thead th {
                    border: solid 1px #d1cbcb;
                }
            </style>';
            $html .= '<div style="overflow-x:auto;">
                <table class="table table-bordered table-hover table-sm" style="background: #fff; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 12px rgba(44,62,80,0.08);">
                <thead>
                    <tr style="background: linear-gradient(90deg, #4c4c80 0%, #1e90ff 100%); color: #FFF;">
                        <th style="font-size: 15px; text-align:center; vertical-align:middle;color:#FFF;">Nama Kebun</th>
                        <th style="font-size: 15px; text-align:center; vertical-align:middle;color:#FFF;background: linear-gradient(90deg, #4c4c80 0%, #0f579e 100%);">Luas Sasaran (Ha)</th>
                        <th style="font-size: 15px; text-align:center; vertical-align:middle;color:#FFF;background: linear-gradient(90deg, #4c4c80 0%, #0f579e 100%);">Luas Realisasi (Ha)</th>
                        <th style="font-size: 15px; text-align:center; vertical-align:middle;color:#FFF;background: linear-gradient(90deg, #4c4c80 0%, #0f579e 100%);">% Luas</th>
                        <th style="font-size: 15px; text-align:center; vertical-align:middle;color:#FFF;background: linear-gradient(90deg, #4c4c80 0%, #0f579e 100%);">Tebu Sasaran (Ton)</th>
                        <th style="font-size: 15px; text-align:center; vertical-align:middle;color:#FFF;background: linear-gradient(90deg, #4c4c80 0%, #0f579e 100%);">Tebu Realisasi (Ton)</th>
                        <th style="font-size: 15px; text-align:center; vertical-align:middle;color:#FFF;background: linear-gradient(90deg, #4c4c80 0%, #0f579e 100%);">% Tebu</th>
                        <th style="font-size: 15px; text-align:center; vertical-align:middle;color:#FFF;background: linear-gradient(90deg, #4c4c80 0%, #0f579e 100%);">Protas Sasaran (Ton/Ha)</th>
                        <th style="font-size: 15px; text-align:center; vertical-align:middle;color:#FFF;background: linear-gradient(90deg, #4c4c80 0%, #0f579e 100%);">Protas Realisasi (Ton/Ha)</th>
                        <th style="font-size: 15px; text-align:center; vertical-align:middle;color:#FFF;background: linear-gradient(90deg, #4c4c80 0%, #0f579e 100%);">% Protas</th>
                    </tr>
                </thead>
                <tbody>';

            $total_luas = 0;
            $total_luas_real = 0;
            $total_tebu = 0;
            $total_protas = 0;
            $count = 0;

            foreach ($data as $row) {
                $html .= '<tr style="background:' . ($count % 2 == 0 ? '#f6f9fc' : '#eaf1fb') . ';">';
                $html .= '<td style="font-weight:500;">' . htmlspecialchars($row->nama_kebun) . '</td>';
                // Luas columns
                $html .= '<td style="text-align:right; font-weight:500; color:#3345a1; background:#eafaf1;">' . number_format($row->ha_luas_sasaran, 2) . '</td>';
                $html .= '<td style="text-align:right; font-weight:500; color:#3345a1; background:#eafaf1;">' . number_format($row->luas_real, 2) . '</td>';

                // Tambahan progress bar persen_tebu_real
                $persen_tebu_real = isset($row->persen_luas) ? (float)$row->persen_luas : 0;
                $bar_color = $persen_tebu_real < 50 ? '#dc3545' : '#28a745';
                $html .= '<td style="text-align: right;background-color:#ffd2bb;">
                    <div style="display: flex; align-items: center; justify-content: flex-end;">
                        <span>' . number_format($persen_tebu_real, 2) . '%</span>
                        <div style="width: 50px; height: 10px; margin-left: 10px; background-color: #ccc; border-radius: 5px; overflow: hidden;">
                            <div style="width: ' . $persen_tebu_real . '%; height: 100%; background-color: ' . $bar_color . ';"></div>
                        </div>
                    </div>
                </td>';
                // Tebu columns
                $html .= '<td style="text-align:right; font-weight:500; color:#1e90ff; background:#f9f2e6;">' . number_format($row->ton_tebu_sasaran, 2) . '</td>';
                $html .= '<td style="text-align:right; font-weight:500; color:#1e90ff; background:#f9f2e6;">' . $row->real_ton_tebu . '</td>';
                // Tambahan progress bar persen_ton_tebu
                $persen_ton_tebu = isset($row->persen_ton_tebu) ? (float)$row->persen_ton_tebu : 0;
                $bar_color_tebu = $persen_ton_tebu < 50 ? '#dc3545' : '#28a745';
                $html .= '<td style="text-align: right; font-weight:500; color:#1e90ff; background:#f9f2e6;">
                    <div style="display: flex; align-items: center; justify-content: flex-end;">
                        <span>' . number_format($persen_ton_tebu, 2) . '%</span>
                        <div style="width: 50px; height: 10px; margin-left: 10px; background-color: #ccc; border-radius: 5px; overflow: hidden;">
                            <div style="width: ' . $persen_ton_tebu . '%; height: 100%; background-color: ' . $bar_color_tebu . ';"></div>
                        </div>
                    </div>
                </td>';
                // Protas columns
                $html .= '<td style="text-align:right; font-weight:500; color:#28a745; background:#e6f0ff;">' . number_format($row->protas_sasaran, 2) . '</td>';
                $html .= '<td style="text-align:right; font-weight:500; color:#28a745; background:#e6f0ff;">' . $row->real_protas . '</td>';
                // Tambahan progress bar persen_protas
                $persen_protas = isset($row->persen_protas) ? (float)$row->persen_protas : 0;
                $bar_color_protas = $persen_protas < 50 ? '#dc3545' : '#28a745';
                $html .= '<td style="text-align: right; font-weight:500; color:#28a745; background:#e6f0ff;">
                    <div style="display: flex; align-items: center; justify-content: flex-end;">
                        <span>' . number_format($persen_protas, 2) . '%</span>
                        <div style="width: 50px; height: 10px; margin-left: 10px; background-color: #ccc; border-radius: 5px; overflow: hidden;">
                            <div style="width: ' . $persen_protas . '%; height: 100%; background-color: ' . $bar_color_protas . ';"></div>
                        </div>
                    </div>
                </td>';
                $html .= '</tr>';

                $total_luas += $row->ha_luas_sasaran;
                $total_luas_real += $row->luas_real;
                $total_tebu += $row->ton_tebu_sasaran;
                $total_protas += $row->protas_sasaran;
                $count++;
            }

            if ($count > 0) {
                $avg_protas = $total_luas > 0 ? $total_tebu / $total_luas : 0;
                $avg_persen_luas = $total_luas > 0 ? $total_luas_real / $total_luas * 100 : 0;
                $html .= '<tr style="font-weight:bold;background:linear-gradient(90deg,#e0eafc 0%,#cfdef3 100%);color:#222;">';
                $html .= '<td>Total</td>';
                $html .= '<td style="text-align:right; background:#eafaf1;">' . number_format($total_luas, 2) . '</td>';
                $html .= '<td style="text-align:right; background:#eafaf1;">' . number_format($total_luas_real, 2) . '</td>';
                $html .= '<td style="text-align: right; background-color:#ffd2bb;">
                    <div style="display: flex; align-items: center; justify-content: flex-end;">
                        <span>' . number_format($avg_persen_luas, 2) . '%</span>
                        <div style="width: 50px; height: 10px; margin-left: 10px; background-color: #ccc; border-radius: 5px; overflow: hidden;">
                            <div style="width: ' . $avg_persen_luas . '%; height: 100%; background-color: ' . ($avg_persen_luas < 50 ? '#dc3545' : '#28a745') . ';"></div>
                        </div>
                    </div>
                </td>';
                $html .= '<td style="text-align:right; background:#f9f2e6;">' . number_format($total_tebu, 2) . '</td>';
                $html .= '<td style="text-align:right; background:#f9f2e6;">-</td>';
                $html .= '<td style="text-align:right; background:#f9f2e6;">-</td>';
                $html .= '<td style="text-align:right; background:#e6f0ff;">' . number_format($avg_protas, 2) . '</td>';
                $html .= '<td style="text-align:right; background:#e6f0ff;">-</td>';
                $html .= '<td style="text-align:right; background:#e6f0ff;">-</td>';
                $html .= '</tr>';
            }

            if (count($data) == 0) {
                $html .= '<tr><td colspan="10" style="text-align:center;">Data tidak ditemukan.</td></tr>';
            }

            $html .= '</tbody></table></div>
            <style>
                .table thead th {
                    border: 1px solid #d1cbcb;
                    font-size: 15px;
                    text-align: center;
                    vertical-align: middle;
                }
                .table tbody td {
                    font-size: 14px;
                    vertical-align: middle;
                }
                .table tbody tr:hover {
                    background: #d1ecf1 !important;
                    transition: background 0.2s;
                }
            </style>';

            return response($html);
        }


        public function getGrafikTanamBulananKebun(Request $request)
        {
            $kode_kebun = $request->input('kode_kebun', 'SK09');
            $kode_kat = $request->input('kode_kat', 'PC');
            $tgl_awal = $request->input('tgl_awal', '2024-09-01');
            $tgl_akhir = $request->input('tgl_akhir', '2025-09-10');
            if (empty($kode_kebun)) {
                $total = 1;
            }else{
                $total = 1;
            }

            // Ambil data dari stored procedure
            $data = DB::select('call sp_rekap_tanam_bulantanam_grafik_kebun(?,?,?,?,?)', [
                $kode_kebun, $kode_kat, $tgl_awal, $tgl_akhir, $total
            ]);

            // Proses data untuk grafik Highcharts
            $categories = [];
            $ha_serah_tanah = [];
            $ha_tanam_kepras = [];

            foreach ($data as $row) {
                $categories[] = $row->bulan_tanam;
                $ha_serah_tanah[] = round((float) $row->ha_serah_tanah, 0);
                $ha_tanam_kepras[] = round((float) $row->ha_tanam_kepras, 0);
            }

            // Format data untuk Highcharts
            // Pisahkan TOTAL KSO dari data, tampilkan di text sendiri
            $filtered = [];
            $totalKsoIndex = null;
            foreach ($categories as $idx => $cat) {
                if (strtoupper(trim($cat)) === 'TOTAL') {
                    $totalKsoIndex = $idx;
                } else {
                    $filtered['categories'][] = $cat;
                    $filtered['ha_serah_tanah'][] = $ha_serah_tanah[$idx];
                    $filtered['ha_tanam_kepras'][] = $ha_tanam_kepras[$idx];
                }
            }

            $chartOptions = [
                'chart' => [
                    'type' => 'column',
                    'backgroundColor' => [
                        'linearGradient' => [0, 0, 0, 400],
                        'stops' => [
                            [0, '#f4f8ff'],
                            [1, '#eaf1fb']
                        ]
                    ],
                    'style' => [
                        'fontFamily' => 'Segoe UI, Arial, sans-serif'
                    ]
                ],
                'title' => [
                    'text' => 'Realisasi Berdasarkan Bulan Tanam (Kebun)',
                    'style' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold',
                        'fontSize' => '20px',
                        'textShadow' => '0 2px 8px #d1ecf1'
                    ]
                ],
                'xAxis' => [
                    'categories' => $filtered['categories'] ?? [],
                    'title' => ['text' => 'Bulan Tanam'],
                    'labels' => [
                        'style' => [
                            'color' => '#1e3c72',
                            'fontWeight' => 'bold',
                            'fontSize' => '13px'
                        ]
                    ],
                    'lineColor' => '#1e90ff',
                    'tickColor' => '#1e90ff'
                ],
                'yAxis' => [
                    'min' => 0,
                    'title' => [
                        'text' => 'Hektar',
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ],
                    'gridLineColor' => '#e0eafc',
                    'labels' => [
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ]
                ],
                'legend' => [
                    'backgroundColor' => '#fff',
                    'borderColor' => '#d1ecf1',
                    'borderWidth' => 1,
                    'itemStyle' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold'
                    ]
                ],
                'tooltip' => [
                    'backgroundColor' => 'rgba(50,70,150,0.95)',
                    'style' => [
                        'color' => '#fff',
                        'fontSize' => '13px'
                    ],
                    'borderRadius' => 10,
                    'borderWidth' => 2,
                    'shadow' => true,
                    'headerFormat' => '<span style="font-size:14px;font-weight:bold">{point.key}</span><br/>',
                    'pointFormat' => ' {series.name}: <b>{point.y}</b><br/>'
                ],
                'plotOptions' => [
                    'column' => [
                        'borderRadius' => 6,
                        'pointPadding' => 0.15,
                        'groupPadding' => 0.08,
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#222',
                                'textOutline' => 'none'
                            ],
                            'backgroundColor' => 'rgba(255,255,255,0.7)',
                            'borderRadius' => 4,
                            'padding' => 2
                        ]
                    ]
                ],
                'colors' => [
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#43e97b'], [1, '#38f9d7']]],
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#f7971e'], [1, '#ffd200']]]
                ],
                'series' => [
                    [
                        'name' => 'Ha Serah Tanah',
                        'data' => $filtered['ha_serah_tanah'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#43e97b'],
                                [1, '#38f9d7']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#28a745'
                            ]
                        ]
                    ],
                    [
                        'name' => 'Ha Tanam/Kepras',
                        'data' => $filtered['ha_tanam_kepras'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#f7971e'],
                                [1, '#ffd200']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#ffc107'
                            ]
                        ]
                    ]
                ]
            ];

            // Tambahkan info TOTAL KSO sebagai text HTML yang menarik
            $totalKsoHtml = '';
            if ($totalKsoIndex !== null) {
                $totalKsoHtml = '
                <div style="
                    margin: 24px 0 8px 0;
                    padding: 18px 24px;
                    background: linear-gradient(90deg, #4c4c80 0%, #1e90ff 100%);
                    color: #fff;
                    border-radius: 12px;
                    box-shadow: 0 2px 12px rgba(44,62,80,0.08);
                    font-size: 18px;
                    font-weight: bold;
                    text-align: center;
                    letter-spacing: 1px;
                ">
                    TOTAL &mdash; 
                    <span style="font-size:15px;font-weight:normal;">
                        Ha Serah Tanah: <span style="font-weight:bold;">' . number_format($ha_serah_tanah[$totalKsoIndex]) . '</span> | 
                        Ha Tanam/Kepras: <span style="font-weight:bold;">' . number_format($ha_tanam_kepras[$totalKsoIndex]) . '</span>
                    </span>
                </div>
                ';
            }

            // Kirim juga totalKsoHtml jika ingin dipakai di frontend
            $this->data['total_kso_html'] = $totalKsoHtml;

            return response()->json([
                'status' => 'success',
                'totalKsoHtml' => $this->data['total_kso_html'],
                'chartOptions' => $chartOptions
            ]);
        }

        public function getGrafikTanamBulananRayon(Request $request)
        {
            $kode_rayon = $request->input('kode_rayon', 'SK09K1');
            $kode_kat = $request->input('kode_kat', 'PC');
            $tgl_awal = $request->input('tgl_awal', '2024-09-01');
            $tgl_akhir = $request->input('tgl_akhir', '2025-09-10');

            // Ambil data dari stored procedure
            $data = DB::select('call sp_rekap_tanam_bulantanam_grafik_rayon(?,?,?,?)', [
                $kode_rayon, $kode_kat, $tgl_awal, $tgl_akhir
            ]);

            // Proses data untuk grafik Highcharts
            $categories = [];
            $ha_serah_tanah = [];
            $ha_tanam_kepras = [];

            foreach ($data as $row) {
                $categories[] = $row->bulan_tanam;
                $ha_serah_tanah[] = round((float) $row->ha_serah_tanah, 0);
                $ha_tanam_kepras[] = round((float) $row->ha_tanam_kepras, 0);
            }

            // Format data untuk Highcharts
            // Pisahkan TOTAL KSO dari data, tampilkan di text sendiri
            $filtered = [];
            $totalKsoIndex = null;
            foreach ($categories as $idx => $cat) {
                if (strtoupper(trim($cat)) === 'TOTAL') {
                    $totalKsoIndex = $idx;
                } else {
                    $filtered['categories'][] = $cat;
                    $filtered['ha_serah_tanah'][] = $ha_serah_tanah[$idx];
                    $filtered['ha_tanam_kepras'][] = $ha_tanam_kepras[$idx];
                }
            }

            $chartOptions = [
                'chart' => [
                    'type' => 'column',
                    'backgroundColor' => [
                        'linearGradient' => [0, 0, 0, 400],
                        'stops' => [
                            [0, '#f4f8ff'],
                            [1, '#eaf1fb']
                        ]
                    ],
                    'style' => [
                        'fontFamily' => 'Segoe UI, Arial, sans-serif'
                    ]
                ],
                'title' => [
                    'text' => 'Realisasi Berdasarkan Bulan Tanam (Rayon)',
                    'style' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold',
                        'fontSize' => '20px',
                        'textShadow' => '0 2px 8px #d1ecf1'
                    ]
                ],
                'xAxis' => [
                    'categories' => $filtered['categories'] ?? [],
                    'title' => ['text' => 'Bulan Tanam'],
                    'labels' => [
                        'style' => [
                            'color' => '#1e3c72',
                            'fontWeight' => 'bold',
                            'fontSize' => '13px'
                        ]
                    ],
                    'lineColor' => '#1e90ff',
                    'tickColor' => '#1e90ff'
                ],
                'yAxis' => [
                    'min' => 0,
                    'title' => [
                        'text' => 'Hektar',
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ],
                    'gridLineColor' => '#e0eafc',
                    'labels' => [
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ]
                ],
                'legend' => [
                    'backgroundColor' => '#fff',
                    'borderColor' => '#d1ecf1',
                    'borderWidth' => 1,
                    'itemStyle' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold'
                    ]
                ],
                'tooltip' => [
                    'backgroundColor' => 'rgba(50,70,150,0.95)',
                    'style' => [
                        'color' => '#fff',
                        'fontSize' => '13px'
                    ],
                    'borderRadius' => 10,
                    'borderWidth' => 2,
                    'shadow' => true,
                    'headerFormat' => '<span style="font-size:14px;font-weight:bold">{point.key}</span><br/>',
                    'pointFormat' => ' {series.name}: <b>{point.y}</b><br/>'
                ],
                'plotOptions' => [
                    'column' => [
                        'borderRadius' => 6,
                        'pointPadding' => 0.15,
                        'groupPadding' => 0.08,
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#222',
                                'textOutline' => 'none'
                            ],
                            'backgroundColor' => 'rgba(255,255,255,0.7)',
                            'borderRadius' => 4,
                            'padding' => 2
                        ]
                    ]
                ],
                'colors' => [
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#43e97b'], [1, '#38f9d7']]],
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#f7971e'], [1, '#ffd200']]]
                ],
                'series' => [
                    [
                        'name' => 'Ha Serah Tanah',
                        'data' => $filtered['ha_serah_tanah'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#43e97b'],
                                [1, '#38f9d7']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#28a745'
                            ]
                        ]
                    ],
                    [
                        'name' => 'Ha Tanam/Kepras',
                        'data' => $filtered['ha_tanam_kepras'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#f7971e'],
                                [1, '#ffd200']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#ffc107'
                            ]
                        ]
                    ]
                ]
            ];

            // Tambahkan info TOTAL KSO sebagai text HTML yang menarik
            $totalKsoHtml = '';
            if ($totalKsoIndex !== null) {
                $totalKsoHtml = '
                <div style="
                    margin: 24px 0 8px 0;
                    padding: 18px 24px;
                    background: linear-gradient(90deg, #4c4c80 0%, #1e90ff 100%);
                    color: #fff;
                    border-radius: 12px;
                    box-shadow: 0 2px 12px rgba(44,62,80,0.08);
                    font-size: 18px;
                    font-weight: bold;
                    text-align: center;
                    letter-spacing: 1px;
                ">
                    TOTAL &mdash; 
                    <span style="font-size:15px;font-weight:normal;">
                        Ha Serah Tanah: <span style="font-weight:bold;">' . number_format($ha_serah_tanah[$totalKsoIndex]) . '</span> | 
                        Ha Tanam/Kepras: <span style="font-weight:bold;">' . number_format($ha_tanam_kepras[$totalKsoIndex]) . '</span>
                    </span>
                </div>
                ';
            }

            // Kirim juga totalKsoHtml jika ingin dipakai di frontend
            $this->data['total_kso_html'] = $totalKsoHtml;

            return response()->json([
                'status' => 'success',
                'totalKsoHtml' => $this->data['total_kso_html'],
                'chartOptions' => $chartOptions
            ]);
        }

        public function getGrafikDroneKebunPeriode(Request $request)
        {
            $tahun = $request->input('tahun', 2025);
            $periode = $request->input('periode', '10A');

            $data = DB::select('call sp_rekap_drone_kebun_periode_dinamis(?, ?)', [$tahun, $periode]);

            $categories = [];
            $jumlah_petak = [];
            $jumlah_petak_sd = [];
            $drone = [];

            foreach ($data as $row) {
                $categories[] = $row->nama_kebun;
                $jumlah_petak[] = (int) $row->jumlah_petak_tanamkepras;
                $jumlah_petak_sd[] = (int) $row->{'jumlah_petak_tanamkepras_sd_' . $periode};
                $drone[] = (int) $row->{'drone_' . $periode};
            }

            // Filter out "TOTAL KSO" from categories and corresponding data, but keep its values for display
            $filtered = [];
            $totalKsoIndex = null;
            foreach ($categories as $idx => $cat) {
                if (strtoupper(trim($cat)) === 'TOTAL KSO') {
                    $totalKsoIndex = $idx;
                } else {
                    $filtered['categories'][] = $cat;
                    $filtered['jumlah_petak'][] = $jumlah_petak[$idx];
                    $filtered['jumlah_petak_sd'][] = $jumlah_petak_sd[$idx];
                    $filtered['drone'][] = $drone[$idx];
                }
            }

            $chartOptions = [
                'chart' => [
                    'type' => 'column',
                    'backgroundColor' => [
                        'linearGradient' => [0, 0, 0, 400],
                        'stops' => [
                            [0, '#f4f8ff'],
                            [1, '#eaf1fb']
                        ]
                    ],
                    'style' => [
                        'fontFamily' => 'Segoe UI, Arial, sans-serif'
                    ]
                ],
                'title' => [
                    'text' => 'Grafik Monitoring Foto Drone Periodik - Kebun',
                    'style' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold',
                        'fontSize' => '20px',
                        'textShadow' => '0 2px 8px #d1ecf1'
                    ]
                ],
                'xAxis' => [
                    'categories' => $filtered['categories'] ?? [],
                    'title' => ['text' => 'Nama Kebun'],
                    'labels' => [
                        'style' => [
                            'color' => '#1e3c72',
                            'fontWeight' => 'bold',
                            'fontSize' => '13px'
                        ]
                    ],
                    'lineColor' => '#1e90ff',
                    'tickColor' => '#1e90ff'
                ],
                'yAxis' => [
                    'min' => 0,
                    'title' => [
                        'text' => 'Jumlah',
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ],
                    'gridLineColor' => '#e0eafc',
                    'labels' => [
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ]
                ],
                'legend' => [
                    'backgroundColor' => '#fff',
                    'borderColor' => '#d1ecf1',
                    'borderWidth' => 1,
                    'itemStyle' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold'
                    ]
                ],
                'tooltip' => [
                    'backgroundColor' => 'rgba(50,70,150,0.95)',
                    'style' => [
                        'color' => '#fff',
                        'fontSize' => '13px'
                    ],
                    'borderRadius' => 10,
                    'borderWidth' => 2,
                    'shadow' => true,
                    'headerFormat' => '<span style="font-size:14px;font-weight:bold">{point.key}</span><br/>',
                    'pointFormat' => ' {series.name}: <b>{point.y}</b><br/>'
                ],
                'plotOptions' => [
                    'column' => [
                        'borderRadius' => 6,
                        'pointPadding' => 0.15,
                        'groupPadding' => 0.08,
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#222',
                                'textOutline' => 'none'
                            ],
                            'backgroundColor' => 'rgba(255,255,255,0.7)',
                            'borderRadius' => 4,
                            'padding' => 2
                        ]
                    ]
                ],
                'colors' => [
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#43e97b'], [1, '#38f9d7']]],
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#f7971e'], [1, '#ffd200']]],
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#f857a6'], [1, '#ff5858']]]
                ],
                'series' => [
                    [
                        'name' => 'Jml Petak Tanam/Kepras',
                        'data' => $filtered['jumlah_petak'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#43e97b'],
                                [1, '#38f9d7']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#28a745'
                            ]
                        ]
                    ],
                    [
                        'name' => 'Jml Petak Tanam/Kepras SD ' . $periode,
                        'data' => $filtered['jumlah_petak_sd'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#f7971e'],
                                [1, '#ffd200']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#ffc107'
                            ]
                        ]
                    ],
                    [
                        'name' => 'Drone ' . $periode,
                        'data' => $filtered['drone'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#f857a6'],
                                [1, '#ff5858']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#dc3545'
                            ]
                        ]
                    ]
                ]
            ];

            // Tambahkan info TOTAL KSO sebagai text HTML yang menarik
            $totalKsoHtml = '';
            if ($totalKsoIndex !== null) {
                $totalKsoHtml = '
                <div style="
                    margin: 24px 0 8px 0;
                    padding: 18px 24px;
                    background: linear-gradient(90deg, #4c4c80 0%, #1e90ff 100%);
                    color: #fff;
                    border-radius: 12px;
                    box-shadow: 0 2px 12px rgba(44,62,80,0.08);
                    font-size: 18px;
                    font-weight: bold;
                    text-align: center;
                    letter-spacing: 1px;
                ">
                    TOTAL &mdash; 
                    <span style="font-size:15px;font-weight:normal;">
                        Jml Petak: <span style="font-weight:bold;">' . number_format($jumlah_petak[$totalKsoIndex]) . '</span> | 
                        Jml Petak SD ' . htmlspecialchars($periode) . ': <span style="font-weight:bold;">' . number_format($jumlah_petak_sd[$totalKsoIndex]) . '</span> | 
                        Drone ' . htmlspecialchars($periode) . ': <span style="font-weight:bold;">' . number_format($drone[$totalKsoIndex]) . '</span>
                    </span>
                </div>
                ';
            }

            // Kirim juga totalKsoHtml jika ingin dipakai di frontend
            $this->data['total_kso_html'] = $totalKsoHtml;

            return response()->json([
                'status' => 'success',
                'total_kso_html' => $totalKsoHtml,
                'chartOptions' => $chartOptions
            ]);
        }

         public function getGrafikDroneRayonPeriode(Request $request)
        {
            $tahun = $request->input('tahun', 2025);
            $periode = $request->input('periode', '10A');
            $kebun = $request->input('kebun', 'NULL');

            $data = DB::select('call sp_rekap_drone_rayon_periode_dinamis(?, ?, ?)', [$tahun, $periode, $kebun]);

            $categories = [];
            $jumlah_petak = [];
            $jumlah_petak_sd = [];
            $drone = [];

            foreach ($data as $row) {
                $categories[] = $row->nama_rayon;
                $jumlah_petak[] = (int) $row->jumlah_petak_tanamkepras;
                $jumlah_petak_sd[] = (int) $row->{'jumlah_petak_tanamkepras_sd_' . $periode};
                $drone[] = (int) $row->{'drone_' . $periode};
            }

            // Filter out "TOTAL KSO" from categories and corresponding data, but keep its values for display
            $filtered = [];
            $totalKsoIndex = null;
            foreach ($categories as $idx => $cat) {
                if (strtoupper(trim($cat)) === 'TOTAL') {
                    $totalKsoIndex = $idx;
                } else {
                    $filtered['categories'][] = $cat;
                    $filtered['jumlah_petak'][] = $jumlah_petak[$idx];
                    $filtered['jumlah_petak_sd'][] = $jumlah_petak_sd[$idx];
                    $filtered['drone'][] = $drone[$idx];
                }
            }

            $chartOptions = [
                'chart' => [
                    'type' => 'column',
                    'backgroundColor' => [
                        'linearGradient' => [0, 0, 0, 400],
                        'stops' => [
                            [0, '#f4f8ff'],
                            [1, '#eaf1fb']
                        ]
                    ],
                    'style' => [
                        'fontFamily' => 'Segoe UI, Arial, sans-serif'
                    ]
                ],
                'title' => [
                    'text' => 'Grafik Monitoring Foto Drone Periodik - Rayon',
                    'style' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold',
                        'fontSize' => '20px',
                        'textShadow' => '0 2px 8px #d1ecf1'
                    ]
                ],
                'xAxis' => [
                    'categories' => $filtered['categories'] ?? [],
                    'title' => ['text' => 'Nama Rayon'],
                    'labels' => [
                        'style' => [
                            'color' => '#1e3c72',
                            'fontWeight' => 'bold',
                            'fontSize' => '13px'
                        ]
                    ],
                    'lineColor' => '#1e90ff',
                    'tickColor' => '#1e90ff'
                ],
                'yAxis' => [
                    'min' => 0,
                    'title' => [
                        'text' => 'Jumlah',
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ],
                    'gridLineColor' => '#e0eafc',
                    'labels' => [
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ]
                ],
                'legend' => [
                    'backgroundColor' => '#fff',
                    'borderColor' => '#d1ecf1',
                    'borderWidth' => 1,
                    'itemStyle' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold'
                    ]
                ],
                'tooltip' => [
                    'backgroundColor' => 'rgba(50,70,150,0.95)',
                    'style' => [
                        'color' => '#fff',
                        'fontSize' => '13px'
                    ],
                    'borderRadius' => 10,
                    'borderWidth' => 2,
                    'shadow' => true,
                    'headerFormat' => '<span style="font-size:14px;font-weight:bold">{point.key}</span><br/>',
                    'pointFormat' => ' {series.name}: <b>{point.y}</b><br/>'
                ],
                'plotOptions' => [
                    'column' => [
                        'borderRadius' => 6,
                        'pointPadding' => 0.15,
                        'groupPadding' => 0.08,
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#222',
                                'textOutline' => 'none'
                            ],
                            'backgroundColor' => 'rgba(255,255,255,0.7)',
                            'borderRadius' => 4,
                            'padding' => 2
                        ]
                    ]
                ],
                'colors' => ['#28a745', '#ffc107', '#1e90ff', '#dc3545', '#17a2b8'],
                'series' => [
                    [
                        'name' => 'Jml Petak Tanam/Kepras',
                        'data' => $filtered['jumlah_petak'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#43e97b'],
                                [1, '#38f9d7']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#28a745'
                            ]
                        ]
                    ],
                    [
                        'name' => 'Jml Petak Tanam/Kepras SD ' . $periode,
                        'data' => $filtered['jumlah_petak_sd'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#f7971e'],
                                [1, '#ffd200']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#ffc107'
                            ]
                        ]
                    ],
                    [
                        'name' => 'Drone ' . $periode,
                        'data' => $filtered['drone'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#f857a6'],
                                [1, '#ff5858']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#dc3545'
                            ]
                        ]
                    ]
                ]
            ];

            // Tambahkan info TOTAL KSO/TOTAL sebagai text HTML yang menarik
            $totalKsoHtml = '';
            if ($totalKsoIndex !== null) {
                $totalKsoHtml = '
                <div style="
                    margin: 24px 0 8px 0;
                    padding: 18px 24px;
                    background: linear-gradient(90deg, #4c4c80 0%, #1e90ff 100%);
                    color: #fff;
                    border-radius: 12px;
                    box-shadow: 0 2px 12px rgba(44,62,80,0.08);
                    font-size: 18px;
                    font-weight: bold;
                    text-align: center;
                    letter-spacing: 1px;
                ">
                    TOTAL &mdash; 
                    <span style="font-size:15px;font-weight:normal;">
                        Jml Petak: <span style="font-weight:bold;">' . number_format($jumlah_petak[$totalKsoIndex]) . '</span> | 
                        Jml Petak SD ' . htmlspecialchars($periode) . ': <span style="font-weight:bold;">' . number_format($jumlah_petak_sd[$totalKsoIndex]) . '</span> | 
                        Drone ' . htmlspecialchars($periode) . ': <span style="font-weight:bold;">' . number_format($drone[$totalKsoIndex]) . '</span>
                    </span>
                </div>
                ';
            }

            $this->data['total_kso_html'] = $totalKsoHtml;

            return response()->json([
                'status' => 'success',
                'total_kso_html' => $totalKsoHtml,
                'chartOptions' => $chartOptions
            ]);
        }

        public function getGrafikMorfKebunPeriode(Request $request)
        {
            config(['app.debug' => true]);
            $tahun = $request->input('tahun', 2025);
            $periode = $request->input('periode', '10A');

            $data = DB::select('call sp_rekap_morfologi_kebun_periode_dinamis(?, ?)', [$tahun, $periode]);

            $categories = [];
            $jumlah_petak = [];
            $jumlah_petak_sd = [];
            $drone = [];

            foreach ($data as $row) {
                $categories[] = $row->nama_kebun;
                $jumlah_petak[] = (int) $row->jumlah_petak_tanamkepras;
                $jumlah_petak_sd[] = (int) $row->{'jumlah_petak_tanamkepras_sd_' . $periode};
                $drone[] = (int) $row->{'morfologi_' . $periode};
            }

            // Pisahkan TOTAL KSO dari data, tampilkan di text sendiri
            $filtered = [];
            $totalKsoIndex = null;
            foreach ($categories as $idx => $cat) {
                if (strtoupper(trim($cat)) === 'TOTAL KSO') {
                    $totalKsoIndex = $idx;
                } else {
                    $filtered['categories'][] = $cat;
                    $filtered['jumlah_petak'][] = $jumlah_petak[$idx];
                    $filtered['jumlah_petak_sd'][] = $jumlah_petak_sd[$idx];
                    $filtered['drone'][] = $drone[$idx];
                }
            }

            $chartOptions = [
                'chart' => [
                    'type' => 'column',
                    'backgroundColor' => [
                        'linearGradient' => [0, 0, 0, 400],
                        'stops' => [
                            [0, '#f4f8ff'],
                            [1, '#eaf1fb']
                        ]
                    ],
                    'style' => [
                        'fontFamily' => 'Segoe UI, Arial, sans-serif'
                    ]
                ],
                'title' => [
                    'text' => 'Grafik Monitoring Morfologi Periodik - Kebun',
                    'style' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold',
                        'fontSize' => '20px',
                        'textShadow' => '0 2px 8px #d1ecf1'
                    ]
                ],
                'xAxis' => [
                    'categories' => $filtered['categories'] ?? [],
                    'title' => ['text' => 'Nama Kebun'],
                    'labels' => [
                        'style' => [
                            'color' => '#1e3c72',
                            'fontWeight' => 'bold',
                            'fontSize' => '13px'
                        ]
                    ],
                    'lineColor' => '#1e90ff',
                    'tickColor' => '#1e90ff'
                ],
                'yAxis' => [
                    'min' => 0,
                    'title' => [
                        'text' => 'Jumlah',
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ],
                    'gridLineColor' => '#e0eafc',
                    'labels' => [
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ]
                ],
                'legend' => [
                    'backgroundColor' => '#fff',
                    'borderColor' => '#d1ecf1',
                    'borderWidth' => 1,
                    'itemStyle' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold'
                    ]
                ],
                'tooltip' => [
                    'backgroundColor' => 'rgba(50,70,150,0.95)',
                    'style' => [
                        'color' => '#fff',
                        'fontSize' => '13px'
                    ],
                    'borderRadius' => 10,
                    'borderWidth' => 2,
                    'shadow' => true,
                    'headerFormat' => '<span style="font-size:14px;font-weight:bold">{point.key}</span><br/>',
                    'pointFormat' => ' {series.name}: <b>{point.y}</b><br/>'
                ],
                'plotOptions' => [
                    'column' => [
                        'borderRadius' => 6,
                        'pointPadding' => 0.15,
                        'groupPadding' => 0.08,
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#222',
                                'textOutline' => 'none'
                            ],
                            'backgroundColor' => 'rgba(255,255,255,0.7)',
                            'borderRadius' => 4,
                            'padding' => 2
                        ]
                    ]
                ],
                'colors' => [
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#43e97b'], [1, '#38f9d7']]],
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#f7971e'], [1, '#ffd200']]],
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#f857a6'], [1, '#ff5858']]]
                ],
                'series' => [
                    [
                        'name' => 'Jml Petak Tanam/Kepras',
                        'data' => $filtered['jumlah_petak'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#43e97b'],
                                [1, '#38f9d7']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#28a745'
                            ]
                        ]
                    ],
                    [
                        'name' => 'Jml Petak Tanam/Kepras SD ' . $periode,
                        'data' => $filtered['jumlah_petak_sd'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#f7971e'],
                                [1, '#ffd200']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#ffc107'
                            ]
                        ]
                    ],
                    [
                        'name' => 'Morfologi ' . $periode,
                        'data' => $filtered['drone'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#f857a6'],
                                [1, '#ff5858']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#dc3545'
                            ]
                        ]
                    ]
                ]
            ];

            // Tambahkan info TOTAL KSO sebagai text HTML yang menarik
            $totalKsoHtml = '';
            if ($totalKsoIndex !== null) {
                $totalKsoHtml = '
                <div style="
                    margin: 24px 0 8px 0;
                    padding: 18px 24px;
                    background: linear-gradient(90deg, #4c4c80 0%, #1e90ff 100%);
                    color: #fff;
                    border-radius: 12px;
                    box-shadow: 0 2px 12px rgba(44,62,80,0.08);
                    font-size: 18px;
                    font-weight: bold;
                    text-align: center;
                    letter-spacing: 1px;
                ">
                    TOTAL &mdash; 
                    <span style="font-size:15px;font-weight:normal;">
                        Jml Petak: <span style="font-weight:bold;">' . number_format($jumlah_petak[$totalKsoIndex]) . '</span> | 
                        Jml Petak SD ' . htmlspecialchars($periode) . ': <span style="font-weight:bold;">' . number_format($jumlah_petak_sd[$totalKsoIndex]) . '</span> | 
                        Morfologi ' . htmlspecialchars($periode) . ': <span style="font-weight:bold;">' . number_format($drone[$totalKsoIndex]) . '</span>
                    </span>
                </div>
                ';
            }

            $this->data['total_kso_html'] = $totalKsoHtml;

            return response()->json([
                'status' => 'success',
                'total_kso_html' => $totalKsoHtml,
                'chartOptions' => $chartOptions
            ]);
        }

         public function getGrafikMorfRayonPeriode(Request $request)
        {
            config(['app.debug' => true]);
            $tahun = $request->input('tahun', 2025);
            $periode = $request->input('periode', '10A');
            $kebun = $request->input('kebun', 'NULL');

            $data = DB::select('call sp_rekap_morfologi_rayon_periode_dinamis(?, ?, ?, ?)', [$tahun, $periode, $kebun,0]);

            $categories = [];
            $jumlah_petak = [];
            $jumlah_petak_sd = [];
            $drone = [];

            foreach ($data as $row) {
                $categories[] = $row->nama_rayon;
                $jumlah_petak[] = (int) $row->jumlah_petak_tanamkepras;
                $jumlah_petak_sd[] = (int) $row->{'jumlah_petak_tanamkepras_sd_' . $periode};
                $drone[] = (int) $row->{'morfologi_' . $periode};
            }

            // Pisahkan TOTAL KSO dari data, tampilkan di text sendiri
            $filtered = [];
            $totalKsoIndex = null;
            foreach ($categories as $idx => $cat) {
                if (strtoupper(trim($cat)) === 'TOTAL') {
                    $totalKsoIndex = $idx;
                } else {
                    $filtered['categories'][] = $cat;
                    $filtered['jumlah_petak'][] = $jumlah_petak[$idx];
                    $filtered['jumlah_petak_sd'][] = $jumlah_petak_sd[$idx];
                    $filtered['drone'][] = $drone[$idx];
                }
            }

            $chartOptions = [
                'chart' => [
                    'type' => 'column',
                    'backgroundColor' => [
                        'linearGradient' => [0, 0, 0, 400],
                        'stops' => [
                            [0, '#f4f8ff'],
                            [1, '#eaf1fb']
                        ]
                    ],
                    'style' => [
                        'fontFamily' => 'Segoe UI, Arial, sans-serif'
                    ]
                ],
                'title' => [
                    'text' => 'Grafik Monitoring Morfologi Periodik - Rayon',
                    'style' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold',
                        'fontSize' => '20px',
                        'textShadow' => '0 2px 8px #d1ecf1'
                    ]
                ],
                'xAxis' => [
                    'categories' => $filtered['categories'] ?? [],
                    'title' => ['text' => 'Nama Rayon'],
                    'labels' => [
                        'style' => [
                            'color' => '#1e3c72',
                            'fontWeight' => 'bold',
                            'fontSize' => '13px'
                        ]
                    ],
                    'lineColor' => '#1e90ff',
                    'tickColor' => '#1e90ff'
                ],
                'yAxis' => [
                    'min' => 0,
                    'title' => [
                        'text' => 'Jumlah',
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ],
                    'gridLineColor' => '#e0eafc',
                    'labels' => [
                        'style' => [
                            'color' => '#3345a1',
                            'fontWeight' => 'bold'
                        ]
                    ]
                ],
                'legend' => [
                    'backgroundColor' => '#fff',
                    'borderColor' => '#d1ecf1',
                    'borderWidth' => 1,
                    'itemStyle' => [
                        'color' => '#3345a1',
                        'fontWeight' => 'bold'
                    ]
                ],
                'tooltip' => [
                    'backgroundColor' => 'rgba(50,70,150,0.95)',
                    'style' => [
                        'color' => '#fff',
                        'fontSize' => '13px'
                    ],
                    'borderRadius' => 10,
                    'borderWidth' => 2,
                    'shadow' => true,
                    'headerFormat' => '<span style="font-size:14px;font-weight:bold">{point.key}</span><br/>',
                    'pointFormat' => ' {series.name}: <b>{point.y}</b><br/>'
                ],
                'plotOptions' => [
                    
                    'column' => [
                        'borderRadius' => 6,
                        'pointPadding' => 0.15,
                        'groupPadding' => 0.08,
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#222',
                                'textOutline' => 'none'
                            ],
                            'backgroundColor' => 'rgba(255,255,255,0.7)',
                            'borderRadius' => 4,
                            'padding' => 2
                        ]
                    ]
                ],
                'colors' => [
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#43e97b'], [1, '#38f9d7']]],
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#f7971e'], [1, '#ffd200']]],
                    ['linearGradient' => [0, 0, 0, 300], 'stops' => [[0, '#f857a6'], [1, '#ff5858']]]
                ],
                'series' => [
                    [
                        'name' => 'Jml Petak Tanam/Kepras',
                        'data' => $filtered['jumlah_petak'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#43e97b'],
                                [1, '#38f9d7']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#28a745'
                            ]
                        ]
                    ],
                    [
                        'name' => 'Jml Petak Tanam/Kepras SD ' . $periode,
                        'data' => $filtered['jumlah_petak_sd'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#f7971e'],
                                [1, '#ffd200']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#ffc107'
                            ]
                        ]
                    ],
                    [
                        'name' => 'Morfologi ' . $periode,
                        'data' => $filtered['drone'] ?? [],
                        'color' => [
                            'linearGradient' => [0, 0, 0, 300],
                            'stops' => [
                                [0, '#f857a6'],
                                [1, '#ff5858']
                            ]
                        ],
                        'dataLabels' => [
                            'enabled' => true,
                            'style' => [
                                'fontWeight' => 'bold',
                                'color' => '#dc3545'
                            ]
                        ]
                    ]
                ]
            ];

            // Tambahkan info TOTAL KSO sebagai text HTML yang menarik
            $totalKsoHtml = '';
            if ($totalKsoIndex !== null) {
                $totalKsoHtml = '
                <div style="
                    margin: 24px 0 8px 0;
                    padding: 18px 24px;
                    background: linear-gradient(90deg, #4c4c80 0%, #1e90ff 100%);
                    color: #fff;
                    border-radius: 12px;
                    box-shadow: 0 2px 12px rgba(44,62,80,0.08);
                    font-size: 18px;
                    font-weight: bold;
                    text-align: center;
                    letter-spacing: 1px;
                ">
                    TOTAL &mdash; 
                    <span style="font-size:15px;font-weight:normal;">
                        Jml Petak: <span style="font-weight:bold;">' . number_format($jumlah_petak[$totalKsoIndex]) . '</span> | 
                        Jml Petak SD ' . htmlspecialchars($periode) . ': <span style="font-weight:bold;">' . number_format($jumlah_petak_sd[$totalKsoIndex]) . '</span> | 
                        Morfologi ' . htmlspecialchars($periode) . ': <span style="font-weight:bold;">' . number_format($drone[$totalKsoIndex]) . '</span>
                    </span>
                </div>
                ';
            }

            // Kirim juga totalKsoHtml jika ingin dipakai di frontend
            $this->data['total_kso_html'] = $totalKsoHtml;

            return response()->json([
                'status' => 'success',
                'total_kso_html' => $totalKsoHtml,
                'chartOptions' => $chartOptions
            ]);
        }

        public function getRankingDroneRayon(Request $request)
        {
            config(['app.debug' => true]);
            $tahun = $request->input('tahun', 2025);
            $periode = $request->input('periode', '10A');
            $kebun = $request->input('kebun', 'NULL');

            $data = DB::select('call sp_rekap_drone_rayon_periode_dinamis(?, ?, ?)', [$tahun, $periode, $kebun]);

            // Sort descending by drone_10A
            $sorted = collect($data)->sortByDesc(function($item) use ($periode) {
                $jumlah_petak = (float)($item->{'jumlah_petak_tanamkepras_sd_' . $periode} ?? 0);
                $drone = (float)($item->{'drone_' . $periode} ?? 0);
                return $jumlah_petak > 0 ? $drone / $jumlah_petak : 0;
            })->values();

            $html = '<style>
                .table th, .table td { text-align:center; vertical-align:middle; }
                .table thead th { background: #3345a1; color: #fff; font-size: 12px; }
                .table tbody tr:nth-child(even) { background: #f6f9fc; }
                .table tbody tr:hover { background: #e3e8f0; transition: background 0.2s; }
            </style>';
            $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-sm table-responsive">';
            $html .= '<thead>
                <tr>
                    <th>Ranking</th>
                    <th>Rayon</th>
                    <th>Luas (Ha)</th>
                    <th>Petak Total<br> Tanam & Kepras</th>
                    <th>Petak SD ' . $periode . '<br> Tanam & Kepras </th>
                    <th>Petak Foto<br> Drone ' . $periode . '</th>
                    <th>% Drone/' . $periode . '</th>
                </tr>
            </thead>
            <tbody>';
            $no = 1;
            foreach ($sorted as $row) {
                if ($row->nama_rayon === 'TOTAL') continue;
                $jumlah_petak = (float)($row->{'jumlah_petak_tanamkepras_sd_' . $periode} ?? 0);
                $drone = (float)($row->{'drone_' . $periode} ?? 0);
                $percent_drone = $jumlah_petak > 0 ? round($drone / $jumlah_petak * 100, 2) : 0;
                // Tentukan warna bar berdasarkan prosentase
                if ($percent_drone >= 100) {
                    $bar_color = '#28a745'; // hijau
                } elseif ($percent_drone >= 75) {
                    $bar_color = '#ffc107'; // kuning
                } else {
                    $bar_color = '#dc3545'; // merah
                }
                $html .= '<tr>
                    <td>' . $no++ . '</td>
                    <td>' . htmlspecialchars($row->nama_rayon) . '</td>
                    <td style="text-align:right;">' . number_format($row->luas_polig, 2) . '</td>
                    <td style="text-align:right;">' . number_format($row->jumlah_petak_tanamkepras) . '</td>
                    <td style="text-align:right;">' . number_format($jumlah_petak) . '</td>
                    <td style="text-align:right;font-weight:bold;color:' . ($drone > 0 ? '#28a745' : '#dc3545') . ';">' . number_format($drone) . '</td>
                    <td style="text-align:right;">
                        <div style="display:flex;align-items:center;justify-content:flex-end;">
                            <span>' . number_format($percent_drone, 2) . '%</span>
                            <div style="width:60px;height:10px;margin-left:8px;background:#eee;border-radius:5px;overflow:hidden;">
                                <div style="width:' . min($percent_drone,100) . '%;height:100%;background:' . $bar_color . ';"></div>
                            </div>
                        </div>
                    </td>
                </tr>';
            }
            $html .= '</tbody></table></div>';

            return response($html);
        }

        public function getRankingMorfRayon(Request $request)
        {
            config(['app.debug' => true]);
            $tahun = $request->input('tahun', 2025);
            $periode = $request->input('periode', '10A');
            $kebun = $request->input('kebun', 'NULL');

            $data = DB::select('call sp_rekap_morfologi_rayon_periode_dinamis(?, ?, ?,?)', [$tahun, $periode, $kebun,0]);

            // Sort descending by drone_10A
            $sorted = collect($data)->sortByDesc(function($item) use ($periode) {
                $jumlah_petak = (float)($item->{'jumlah_petak_tanamkepras_sd_' . $periode} ?? 0);
                $drone = (float)($item->{'morfologi_' . $periode} ?? 0);
                return $jumlah_petak > 0 ? $drone / $jumlah_petak : 0;
            })->values();

            $html = '<style>
                .table th, .table td { vertical-align:middle; }
                .table thead th { background: #3345a1; color: #fff; font-size: 12px; }
                .table tbody tr:nth-child(even) { background: #f6f9fc; }
                .table tbody tr:hover { background: #e3e8f0; transition: background 0.2s; }
            </style>';
            $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-sm table-responsive">';
            $html .= '<thead>
                <tr>
                    <th>Ranking</th>
                    <th>Rayon</th>
                    <th>Luas (Ha)</th>
                    <th>Petak Total<br> Tanam & Kepras</th>
                    <th>Petak SD ' . $periode . '<br> Tanam & Kepras </th>
                    <th>Petak Foto<br> Morfologi ' . $periode . '</th>
                    <th>% Morfologi/' . $periode . '</th>
                </tr>
            </thead>
            <tbody>';
            $no = 1;
            foreach ($sorted as $row) {
                if ($row->nama_rayon === 'TOTAL') continue;
                $jumlah_petak = (float)($row->{'jumlah_petak_tanamkepras_sd_' . $periode} ?? 0);
                $drone = (float)($row->{'morfologi_' . $periode} ?? 0);
                $percent_drone = $jumlah_petak > 0 ? round($drone / $jumlah_petak * 100, 2) : 0;

                // Warna bar prosentase
                if ($percent_drone >= 100) {
                    $bar_color = '#28a745'; // hijau
                } elseif ($percent_drone >= 75) {
                    $bar_color = '#f1ff65'; // kuning
                } else {
                    $bar_color = '#dc3545'; // merah
                }

               
                    $tr_bg = 'background:color:#222;';
             

                $html .= '<tr style="' . $tr_bg . '">
                    <td style="font-weight:bold;">' . $no . '</td>
                    <td style="font-weight:bold;">' . htmlspecialchars($row->nama_rayon) . '</td>
                    <td style="text-align:right;">' . number_format($row->luas_polig, 2) . '</td>
                    <td style="text-align:right;">' . number_format($row->jumlah_petak_tanamkepras) . '</td>
                    <td style="text-align:right;">' . number_format($jumlah_petak) . '</td>
                    <td style="text-align:right;font-weight:bold;color:' . ($drone > 0 ? '#00a125' : '#dc3545') . ';">' . number_format($drone) . '</td>
                    <td style="text-align:right;">
                        <div style="display:flex;align-items:center;justify-content:flex-end;font-weight:bold;">
                            <span>' . number_format($percent_drone, 2) . '%</span>
                            <div style="width:60px;height:10px;margin-left:8px;background:#eee;border-radius:5px;overflow:hidden;">
                                <div style="width:' . min($percent_drone,100) . '%;height:100%;background:' . $bar_color . ';"></div>
                            </div>
                        </div>
                    </td>
                </tr>';
                $no++;
            }
            $html .= '</tbody></table></div>';

            return response($html);
        }

public function getRekapCurahHujanPerRayon(Request $request)
        {
                    // config(['app.debug' => true]);
            $tahun = $request->input('tahun', 2025);
            $data = DB::select('call get_rekap_curah_hujan_per_rayon(?)', [$tahun]);

            $bulan = [
                'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
                'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
            ];

            $html = '<style>
                .ch-rendah { background:#e3fcec; color:#388e3c; }
                .ch-menengah { background:#fffde7; color:#bfa900; }
                .ch-tinggi { background:#ffe0e0; color:#d35400; }
                .ch-sangattinggi { background:#f8bbd0; color:#c2185b; }
                .hh-cell { background:#eaf1fb; color:#3345a1; }
                .table th, .table td { font-size:13px; text-align:center; vertical-align:middle; }
                .table thead th { background: #4c4c80; color: #fff; }
                .sticky-col {
                    position: sticky;
                    left: 0;
                    background: #fff;
                    z-index: 2;
                }
                .sticky-col-1 {
                    left: 0;
                    z-index: 3;
                }
                .sticky-col-2 {
                    left: 120px;
                    z-index: 3;
                }
            </style>';
            $html .= '<div style="overflow-x:auto;"><table id="table-curahhujan" class="table table-bordered table-hover table-sm table table-responsive" style="height: 650px;display: block;">';
            $html .= '<thead style="position: sticky; top: 0; z-index: 10; background: #fff;">
                <tr>
                    <th rowspan="2" class="sticky-col sticky-col-1">Nama Kebun</th>
                    <th rowspan="2" class="sticky-col sticky-col-2">Nama Rayon</th>';
            foreach ($bulan as $b) {
                $html .= '<th colspan="2">' . $b . '</th>';
            }
            $html .= '<th colspan="2">Rata-rata</th>';
            $html .= '</tr><tr>';
            foreach ($bulan as $b) {
                $html .= '<th>Curah Hujan (mm)</th><th>Hari Hujan</th>';
            }
            $html .= '<th>Curah Hujan (mm)</th><th>Hari Hujan</th>';
            $html .= '</tr></thead><tbody>';

            // Kelompokkan data per nama kebun
            $grouped = [];
            foreach ($data as $row) {
                $grouped[$row->nama_kebun][] = $row;
            }

            foreach ($grouped as $nama_kebun => $rows) {
                // Hitung total rata-rata per kebun
                $total_ch_per_bulan = array_fill(0, count($bulan), 0);
                $total_hh_per_bulan = array_fill(0, count($bulan), 0);
                $count_ch_per_bulan = array_fill(0, count($bulan), 0);
                $count_hh_per_bulan = array_fill(0, count($bulan), 0);

                foreach ($rows as $row) {
                    foreach ($bulan as $idx => $b) {
                        $ch = $row->{$b . '_ch'};
                        $hh = $row->{$b . '_hh'};
                        if ($ch !== null && $ch !== '') {
                            $total_ch_per_bulan[$idx] += $ch;
                            $count_ch_per_bulan[$idx]++;
                        }
                        if ($hh !== null && $hh !== '') {
                            $total_hh_per_bulan[$idx] += $hh;
                            $count_hh_per_bulan[$idx]++;
                        }
                    }
                }

                // Baris per rayon
                foreach ($rows as $row) {
                    $html .= '<tr>';
                    $html .= '<td class="sticky-col sticky-col-1">' . htmlspecialchars($row->nama_kebun) . '</td>';
                    $html .= '<td class="sticky-col sticky-col-2">' . htmlspecialchars($row->nama_rayon) . '</td>';
                    $total_ch = 0;
                    $total_hh = 0;
                    $count_ch = 0;
                    $count_hh = 0;
                    foreach ($bulan as $idx => $b) {
                        $ch = $row->{$b . '_ch'};
                        $hh = $row->{$b . '_hh'};
                        // Penentuan warna
                        if ($ch === null || $ch === '') {
                            $warna = '';
                        } elseif ($ch <= 100) {
                            $warna = 'ch-rendah';
                        } elseif ($ch <= 300) {
                            $warna = 'ch-menengah';
                        } elseif ($ch <= 500) {
                            $warna = 'ch-tinggi';
                        } else {
                            $warna = 'ch-sangattinggi';
                        }
                        $html .= '<td class="' . $warna . '">' . ($ch !== null && $ch !== '' ? number_format($ch, 0) : '-') . '</td>';
                        $html .= '<td class="hh-cell">' . ($hh !== null && $hh !== '' ? $hh : '-') . '</td>';
                        if ($ch !== null && $ch !== '') {
                            $total_ch += $ch;
                            $count_ch++;
                        }
                        if ($hh !== null && $hh !== '') {
                            $total_hh += $hh;
                            $count_hh++;
                        }
                    }
                    // Tambahkan kolom rata-rata di akhir baris
                    $avg_ch = $count_ch > 0 ? round($total_ch / $count_ch, 1) : 0;
                    $avg_hh = $count_hh > 0 ? round($total_hh / $count_hh, 0) : 0;
                    $html .= '<td style="font-weight:bold;" class="'.$this->getWarnaCurahHujan($avg_ch).'">' . ($count_ch > 0 ? number_format($avg_ch, 1) : '-') . '</td>';
                    $html .= '<td style="background:#eaf1fb;font-weight:bold;">' . ($count_hh > 0 ? number_format($avg_hh, 0) : '-') . '</td>';
                    $html .= '</tr>';
                }

                // Baris total rata-rata per kebun
                $html .= '<tr style="background:#f6f9fc;font-weight:bold;">';
                $html .= '<td class="sticky-col sticky-col-1" colspan="2">Total Rata-rata ' . htmlspecialchars($nama_kebun) . '</td>';
                $sum_avg_ch = 0;
                $sum_avg_hh = 0;
                $bulan_valid = 0;
                foreach ($bulan as $idx => $b) {
                    $avg_ch_bulan = $count_ch_per_bulan[$idx] > 0 ? round($total_ch_per_bulan[$idx] / $count_ch_per_bulan[$idx], 1) : 0;
                    $avg_hh_bulan = $count_hh_per_bulan[$idx] > 0 ? round($total_hh_per_bulan[$idx] / $count_hh_per_bulan[$idx], 0) : 0;
                    $html .= '<td class="'.$this->getWarnaCurahHujan($avg_ch_bulan).'">' . ($count_ch_per_bulan[$idx] > 0 ? number_format($avg_ch_bulan, 1) : '-') . '</td>';
                    $html .= '<td style="background:#eaf1fb;">' . ($count_hh_per_bulan[$idx] > 0 ? number_format($avg_hh_bulan, 0) : '-') . '</td>';
                    if ($count_ch_per_bulan[$idx] > 0) {
                        $sum_avg_ch += $avg_ch_bulan;
                        $bulan_valid++;
                    }
                    if ($count_hh_per_bulan[$idx] > 0) {
                        $sum_avg_hh += $avg_hh_bulan;
                    }
                }
                // Rata-rata dari rata-rata bulanan
                $final_avg_ch = $bulan_valid > 0 ? round($sum_avg_ch / $bulan_valid, 1) : 0;
                $final_avg_hh = $bulan_valid > 0 ? round($sum_avg_hh / $bulan_valid, 0) : 0;
                $html .= '<td style="font-weight:bold;" class="'.$this->getWarnaCurahHujan($final_avg_ch).'">' . ($bulan_valid > 0 ? number_format($final_avg_ch, 1) : '-') . '</td>';
                $html .= '<td style="background:#b2d7f2;font-weight:bold;">' . ($bulan_valid > 0 ? number_format($final_avg_hh, 0) : '-') . '</td>';
                $html .= '</tr>';
            }

            $html .= '</tbody></table></div>
            <div style="margin-top:10px;font-size:13px;">
                <span style="background:#e3fcec;color:#388e3c;padding:2px 8px;border-radius:4px;">Rendah: 0-100 mm</span>
                <span style="background:#fffde7;color:#bfa900;padding:2px 8px;border-radius:4px;">Menengah: 101-300 mm</span>
                <span style="background:#ffe0e0;color:#d35400;padding:2px 8px;border-radius:4px;">Tinggi: 301-500 mm</span>
                <span style="background:#f8bbd0;color:#c2185b;padding:2px 8px;border-radius:4px;">Sangat Tinggi: >500 mm</span>
            </div>';

            return response($html);
        }

        protected function getWarnaCurahHujan($ch)
        {
            if ($ch === null || $ch === '') {
                return '';
            } elseif ($ch <= 100) {
                return 'ch-rendah';
            } elseif ($ch <= 300) {
                return 'ch-menengah';
            } elseif ($ch <= 500) {
                return 'ch-tinggi';
            } else {
                return 'ch-sangattinggi';
            }
        }

        public function getRekapCurahHujanTahunanKebun(Request $request)
        {
            $kebun = $request->input('kebun', 'Kwala Madu');
            $rayon = $request->input('rayon', 'Kwala Madu A');
            $mode = $request->input('mode', 'column'); // 'kebun' atau 'rayon'

            // Jika jenis = rayon, dan nama_kebun mengandung spasi, ambil hanya bagian sebelum spasi terakhir (misal: "Kwala Madu A" -> "Kwala Madu A")
            // Jika parameter rayon kosong, gunakan data kebun, jika ada gunakan data rayon
            if (empty($rayon)) {
                $jenis = 'kebun';
                $nama_kebun = $kebun;
            } else {
                $jenis = 'rayon';
                $nama_kebun = $rayon;
            }
            $data = DB::select('call get_rekap_curah_hujan_tahunan(?, ?)', [$jenis, $nama_kebun]);

            // Daftar bulan
            $bulan = [
                'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
                'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
            ];

            // Siapkan data untuk grafik Highcharts
            $categories = [];
            $series_ch = [];
            $series_hh = [];

            // Ambil tahun-tahun yang ada
            foreach ($data as $row) {
                $categories[] = $row->tahun;
            }

            // Untuk setiap bulan, buat data series curah hujan (ch) dan hari hujan (hh)
            // Siapkan data curah hujan per bulan per tahun (kategori: bulan, series: tahun)
            $tahun_list = array_unique(array_map(function($row) { return $row->tahun; }, $data));
            sort($tahun_list);

            // Kategori: bulan
            $categories = $bulan;

            // Series: tiap tahun, data: curah hujan per bulan
            $series = [];
            foreach ($tahun_list as $tahun) {
                $data_ch = [];
                foreach ($bulan as $b) {
                    // Cari row dengan tahun dan ambil curah hujan bulan tsb
                    $row = collect($data)->first(function($item) use ($tahun) { return $item->tahun == $tahun; });
                    $data_ch[] = $row ? (float)($row->{$b . '_ch'} ?? 0) : 0;
                }
                $series[] = [
                    'name' => (string)$tahun,
                    'data' => $data_ch,
                    'type' => $mode
                ];
            }

            
            // Format untuk Highcharts
            $chartOptions = [
                'chart' => [
                    'type' => $mode,
                    'backgroundColor' => '#fff'
                ],
                'title' => [
                    'text' => 'Grafik Curah Hujan Bulanan'
                ],
                'xAxis' => [
                    'categories' => $categories,
                    'title' => ['text' => 'Bulan']
                ],
                'yAxis' => [
                    [
                        'title' => ['text' => 'Curah Hujan (mm)'],
                        'min' => 0
                    ]
                ],
                'tooltip' => [
                    'shared' => true
                ],
                'legend' => [
                    'layout' => 'vertical',
                    'align' => 'right',
                    'verticalAlign' => 'middle'
                ],
                'series' => array_map(function($s) {
                    $s['dataLabels'] = [
                        'enabled' => true,
                        'style' => [
                            'fontSize' => '11px'
                        ]
                    ];
                    return $s;
                }, $series)
            ];

            // Tambahkan legend keterangan warna curah hujan
            $chartOptions['customLegendHtml'] = '
                <div style="margin-top:10px;font-size:13px;">
                    <span style="background:#e3fcec;color:#388e3c;padding:2px 8px;border-radius:4px;">Rendah: 0-100 mm</span>
                    <span style="background:#fffde7;color:#bfa900;padding:2px 8px;border-radius:4px;">Menengah: 101-300 mm</span>
                    <span style="background:#ffe0e0;color:#d35400;padding:2px 8px;border-radius:4px;">Tinggi: 301-500 mm</span>
                    <span style="background:#f8bbd0;color:#c2185b;padding:2px 8px;border-radius:4px;">Sangat Tinggi: &gt;500 mm</span>
                </div>
            ';

            return response()->json([
                'status' => 'success',
                'chartOptions' => $chartOptions
            ]);
        }

        public function getChartMutuTakdesPerCluster(Request $request)
        {
            config(['app.debug' => true]);
            // Ambil parameter filter dari request
            $kode_kebun = $request->input('kode_kebun', '');
            $kode_rayon = $request->input('kode_rayon', '');
            $afdeling = $request->input('afdeling', '');

            // Query untuk mengambil data berdasarkan filter
            $data = DB::table('q_takdes_petak')
                ->select(
                    'clusterisasi_protas',
                    DB::raw('COUNT(*) as jumlah_baris'),
                    DB::raw('ROUND(SUM(takdes_ton)/SUM(luas_poligon), 2) as rata_protas'),
                    DB::raw('ROUND(SUM(luas_poligon), 3) as total_luas_poligon')
                )
                ->whereNotNull('lahan_id')
                ->when(!empty($kode_kebun), function ($query) use ($kode_kebun) {
                    return $query->where('kode_kebun', $kode_kebun);
                })
                ->when(!empty($kode_rayon), function ($query) use ($kode_rayon) {
                    return $query->where('kode_rayon', $kode_rayon);
                })
                ->when(!empty($afdeling), function ($query) use ($afdeling) {
                    return $query->where('afdeling', $afdeling);
                })
                ->groupBy('clusterisasi_protas')
                ->orderBy(DB::raw("CASE 
                    WHEN clusterisasi_protas COLLATE utf8mb4_unicode_ci = 'EMAS' THEN 1
                    WHEN clusterisasi_protas COLLATE utf8mb4_unicode_ci = 'HIJAU' THEN 2  
                    WHEN clusterisasi_protas COLLATE utf8mb4_unicode_ci = 'KUNING' THEN 3
                    WHEN clusterisasi_protas COLLATE utf8mb4_unicode_ci = 'MERAH' THEN 4
                    WHEN clusterisasi_protas COLLATE utf8mb4_unicode_ci = 'HITAM' THEN 5
                    ELSE 6 END"))
                ->get();

                // Ambil data kebun untuk mengetahui total petak dan luas per kebun
                $dataKebun = DB::table('q_takdes_rekap_kebun')
                    ->select(
                            '*'
                    )                  

                    ->groupBy('kode_kebun')
                    ->get();

            // Proses data untuk Highcharts
            $categories = $data->pluck('clusterisasi_protas')->toArray();
            $jumlah_baris = $data->pluck('jumlah_baris')->map(function($v) { return (int)$v; })->toArray();
            $total_luas = $data->pluck('total_luas_poligon')->map(function($v) { return round((float)$v, 2); })->toArray();
            $rata_protas = $data->pluck('rata_protas')->map(function($v) { return round((float)$v, 2); })->toArray();
            
            // Warna untuk tiap cluster berdasarkan tingkat produktivitas
            $colors = [
                'EMAS' => '#ffc107', // emas/gold
                'HIJAU' => '#28a745', // hijau                
                'KUNING' => '#FFD700', // kuning
                'MERAH' => '#dc3545',  // merah
                'HITAM' => '#343a40', // hitam
            ];

            // Format data untuk Highcharts
            $chartDataLuas = [];
            $chartDataJumlah = [];
            foreach ($data as $item) {
                $chartDataLuas[] = [
                    'name' => $item->clusterisasi_protas,
                    'y' => (float) $item->total_luas_poligon,
                    'color' => $colors[$item->clusterisasi_protas] ?? '#6c757d'
                ];
                $chartDataJumlah[] = [
                    'name' => $item->clusterisasi_protas,
                    'y' => (int) $item->jumlah_baris,
                    'color' => $colors[$item->clusterisasi_protas] ?? '#6c757d'
                ];
                $chartDataRataProtas[] = [
                    'name' => $item->clusterisasi_protas,
                    'y' => (float) $item->rata_protas,
                    'color' => $colors[$item->clusterisasi_protas] ?? '#6c757d'
                ];
            }

            // Return the data as JSON
            return response()->json([
                'status' => 'success',
                'data' => $chartDataLuas,
                'categories' => $categories,
                'jumlah_baris' => $chartDataJumlah,
                'total_luas' => $total_luas,
                'rata_protas' => $chartDataRataProtas,
                'dataKebun' => $dataKebun
            ]);
        }

        public function getTakdesDataByCluster(Request $request)
        {
            $kode_kebun = $request->input('kode_kebun', '');
            $kode_rayon = $request->input('kode_rayon', '');
            $afdeling = $request->input('afdeling', '');
            $clusterisasi_protas = $request->input('clusterisasi_protas', '');

            // Query to get data from q_takdes_petak with foto drone count
            $data = DB::table('q_takdes_petak')
                ->leftJoin('tx_foto_drone', function($join) {
                    $join->on('q_takdes_petak.lahan_id', '=', 'tx_foto_drone.lahan_id')
                         ->whereMonth('tx_foto_drone.tanggal', 12)
                         ->whereYear('tx_foto_drone.tanggal', 2025);
                })
                ->select('q_takdes_petak.*', DB::raw('COUNT(tx_foto_drone.lahan_id) as jumlah_foto_drone'))
                ->where(function ($query) use ($kode_kebun, $kode_rayon, $afdeling) {
                    if (!empty($kode_kebun)) {
                        $query->where('q_takdes_petak.kode_kebun', $kode_kebun);
                    }
                    if (!empty($kode_rayon)) {
                        $query->where('q_takdes_petak.kode_rayon', $kode_rayon);
                    }
                    if (!empty($afdeling)) {
                        $query->where('q_takdes_petak.afdeling', $afdeling);
                    }
                })
                ->when(!empty($clusterisasi_protas), function ($query) use ($clusterisasi_protas) {
                    return $query->whereRaw('q_takdes_petak.clusterisasi_protas COLLATE utf8mb4_unicode_ci = ?', [$clusterisasi_protas]);
                })
                ->groupBy('q_takdes_petak.lahan_id')
                ->get();

            $html = '<style>
                .table th, .table td { text-align:center; vertical-align:middle; font-size:13px; }
                .table thead th { background: #4c4c80; color: #fff; font-weight:bold; }
                .table tbody tr:nth-child(even) { background: #f6f9fc; }
                .table tbody tr:hover { background: #e3e8f0; transition: background 0.2s; }
                .cluster-emas { background: #fff3cd; color: #856404; }
                .cluster-hijau { background: #d4edda; color: #155724; }
                .cluster-kuning { background: #fff3cd; color: #856404; }
                .cluster-merah { background: #f8d7da; color: #721c24; }
                .cluster-hitam { background: #f1f1f1; color: #495057; }
                .table-container {
                    overflow-x: auto;
                    max-height: 70vh;
                    border: 1px solid #ddd;
                }
                .table thead th {
                    position: sticky;
                    top: 0;
                    z-index: 10;
                    background: #4c4c80 !important;
                    color: #fff !important;
                    font-weight: bold;
                    border-bottom: 2px solid #fff;
                }
            </style>';
            
            $html .= '<div class="table-container"><table class="table table-sm table-bordered table-hover table-sm table-responsive" style="height: 600px;">';
            $html .= '<thead>
                <tr>
                    <th>No</th>
                    <th>Foto Drone</th>
                    <th>Jawa/Luar Jawa</th>
                    <th>Cluster</th>
                    <th>Kode Kebun</th>
                    <th>Nama Kebun</th>
                    <th>GM</th>
                    <th>Kode Rayon</th>
                    <th>Nama Rayon</th>
                    <th>Manajer Tanaman</th>
                    <th>Afdeling</th>
                    <th>Asman</th>
                    <th>Asmud</th>
                    <th>Kode Petak SAP</th>
                    <th>Project Def SAP</th>
                    <th>No Kontrak eFarming</th>
                    <th>Lahan ID</th>
                    <th>Group Lahan ID</th>
                    <th>Deskripsi Petak</th>
                    <th>Desa</th>
                    <th>Kecamatan</th>
                    <th>Kabupaten</th>
                    <th>Luas Poligon (Ha)</th>
                    <th>Tahun Tanam</th>
                    <th>Masa Tanam</th>
                    <th>Bulan Tanam</th>
                    <th>Jenis Kategori 1</th>
                    <th>Jenis Kategori 2</th>
                    <th>Kategori Lahan 1</th>
                    <th>Kategori Lahan 2</th>
                    <th>Kepemilikan</th>
                    <th>Jenis Tanah</th>
                    <th>Tipologi Lahan</th>
                    <th>Varietas</th>
                    <th>Kemasakan</th>
                    <th>Tinggi Batang Sekarang</th>
                    <th>Tinggi Batang Akhir</th>
                    <th>Berat Batang Sekarang</th>
                    <th>Berat Batang Akhir</th>
                    <th>Jumlah Juring Per Ha</th>
                    <th>Jumlah Juring Total</th>
                    <th>Jumlah Batang Per Juring Sekarang</th>
                    <th>Jumlah Batang Per Juring Akhir</th>
                    <th>Panjang Juring</th>
                    <th>Panjang Juring Per Ha</th>
                    <th>PKP Meter</th>
                    <th>Diameter Batang Sekarang</th>
                    <th>Diameter Batang Akhir</th>
                    <th>Jumlah Batang Per Meter Sekarang</th>
                    <th>Jumlah Batang Per Meter Akhir</th>
                    <th>Taksasi Pandang (Ton/Ha)</th>
                    <th>Taksasi Hitung (Ton/Ha)</th>
                    <th>Takdes (Ton/Ha)</th>
                    <th>Takdes (Ton)</th>
                    <th>Rendemen Takdes</th>
                    <th>Rendemen Bagi Hasil</th>
                    <th>Hablur</th>
                    <th>Hablur Per Ha</th>
                    <th>Hablur Milik</th>
                    <th>Gula Milik</th>
                    <th>Tetes Milik</th>
                    <th>Clusterisasi Protas</th>
                    <th>Kode PG Penggiling</th>
                    <th>Nama PG Penggiling</th>
                    <th>Jarak Petak ke PG</th>
                    <th>Angkutan</th>
                    <th>Jenis Muat</th>
                    <th>Periode Tebang Rencana</th>
                    <th>Kelompok HGU</th>
                    <th>Ex Regional</th>
                </tr>
            </thead>
            <tbody>';

            $no = 1;
            $total_luas = 0;

            foreach ($data as $row) {
                // Tentukan class berdasarkan clusterisasi
                $clusterClass = '';
                switch (strtoupper($row->clusterisasi_protas ?? '')) {
                    case 'EMAS':
                        $clusterClass = 'cluster-emas';
                        break;
                    case 'HIJAU':
                        $clusterClass = 'cluster-hijau';
                        break;
                    case 'KUNING':
                        $clusterClass = 'cluster-kuning';
                        break;
                    case 'MERAH':
                        $clusterClass = 'cluster-merah';
                        break;
                    case 'HITAM':
                        $clusterClass = 'cluster-hitam';
                        break;
                }

                $html .= '<tr>';
                $html .= '<td>' . $no++ . '</td>';
                $html .= '<td>';
                if ($row->jumlah_foto_drone > 0) {
                    $html .= '<a href="javascript:void(0);" onclick="SximoModal2(\'dashboard/getFotoDrone?lahan_id=' . urlencode($row->lahan_id) . '\',\'Foto Drone - ' . htmlspecialchars($row->lahan_id) . '\')" style="color:#007bff;font-weight:bold;">' . number_format($row->jumlah_foto_drone, 0) . ' Foto</a>';
                } else {
                    $html .= '<span style="color:#6c757d;">0</span>';
                }
                $html .= '</td>';
                $html .= '<td>' . htmlspecialchars($row->jawa_luarjawa ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->cluster ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kode_kebun ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->nama_kebun ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->nama_general_manager ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kode_rayon ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->nama_rayon ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->nama_manajer_tanaman ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->afdeling ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->asman ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->asmud ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kode_petak_sap ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->project_def_sap ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->no_kontrak_efarming ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->lahan_id ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->group_lahan_id ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->deskripsi_petak ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->desa ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kecamatan ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kabupaten ?? '-') . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->luas_poligon ?? 0, 3) . '</td>';
                $html .= '<td>' . htmlspecialchars($row->tahun_tanam ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->masa_tanam ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->bulan_tanam ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->jenis_kategori_1 ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->jenis_kategori_2 ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kategori_lahan_1 ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kategori_lahan_2 ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kepemilikan ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->jenis_tanah ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->tipologi_lahan ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->varietas ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kemasakan ?? '-') . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->tinggi_batang_sekarang ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->tinggi_batang_akhir ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->berat_batang_sekarang ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->berat_batang_akhir ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->jumlah_juring_perha ?? 0, 0) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->jumlah_juring_total ?? 0, 0) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->jumlah_batang_perjuring_sekarang ?? 0, 0) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->jumlah_batang_perjuring_akhir ?? 0, 0) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->panjang_juring ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->panjang_juring_perha ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->pkp_meter ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->diameter_batang_sekarang ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->diameter_batang_akhir ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->jumlah_batang_permeter_sekarang ?? 0, 0) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->jumlah_batang_permeter_akhir ?? 0, 0) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->taksasi_pandang_tonperha ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->taksasi_hitung_tonperha ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->takdes_tonperha ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->takdes_ton ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->rendemen_takdes ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->rendemen_bagihasil ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->hablur ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->hablur_perha ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->hablur_milik ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->gula_milik ?? 0, 2) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->tetes_milik ?? 0, 2) . '</td>';
                $html .= '<td class="' . $clusterClass . '" style="font-weight:bold;">' . htmlspecialchars($row->clusterisasi_protas ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kode_pg_penggiling ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->nama_pg_penggiling ?? '-') . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->jarak_petak_kepg ?? 0, 2) . '</td>';
                $html .= '<td>' . htmlspecialchars($row->angkutan ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->jenis_muat ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->periode_tebng_rencana ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kelompok_hgu ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->ex_regional ?? '-') . '</td>';
                $html .= '</tr>';

                $total_luas += $row->luas_poligon ?? 0;
            }

            // Baris total
            if (count($data) > 0) {
                $html .= '<tr style="font-weight:bold;background:linear-gradient(90deg,#e0eafc 0%,#cfdef3 100%);color:#222;">';
                $html .= '<td colspan="21">Total</td>';
                $html .= '<td style="text-align:right;">' . number_format($total_luas, 3) . '</td>';
                $html .= '<td colspan="46">' . count($data) . ' Petak</td>';
                $html .= '</tr>';
            }

            if (count($data) == 0) {
                $html .= '<tr><td colspan="68" style="text-align:center;">Data tidak ditemukan.</td></tr>';
            }

            $html .= '</tbody></table></div>';
            
            $html .= '<div style="margin-top:10px;font-size:13px;">
                <span style="background:#fff3cd;color:#856404;padding:2px 8px;border-radius:4px;">EMAS</span>
                <span style="background:#d4edda;color:#155724;padding:2px 8px;border-radius:4px;">HIJAU</span>
                <span style="background:#fff3cd;color:#856404;padding:2px 8px;border-radius:4px;">KUNING</span>
                <span style="background:#f8d7da;color:#721c24;padding:2px 8px;border-radius:4px;">MERAH</span>
                <span style="background:#f1f1f1;color:#495057;padding:2px 8px;border-radius:4px;">HITAM</span>
            </div>';

            return response($html);
        }

        public function getTakmarRekapKebun(Request $request)
        {
            $kodeKebun = $request->input('kode_kebun', '');
            $cluster = $request->input('cluster', '');
            $jawa = $request->input('jawa_luarjawa', '');

            $rows = DB::table('q_takmar_rekap_kebun')
                ->when($kodeKebun !== '', function ($q) use ($kodeKebun) {
                    return $q->where('kode_kebun', $kodeKebun);
                })
                ->when($cluster !== '', function ($q) use ($cluster) {
                    return $q->where(function ($qq) use ($cluster) {
                        $qq->where('cluster', $cluster)->orWhere('nama_cluster', $cluster);
                    });
                })
                ->when($jawa !== '', function ($q) use ($jawa) {
                    return $q->where(function ($qq) use ($jawa) {
                        $qq->where('jawa_luarjawa', $jawa)->orWhere('jawa_nonjawa', $jawa);
                    });
                })
                ->orderBy('row_type', 'desc')
                ->get();

            $pick = function ($row, array $keys, $default = null) {
                foreach ($keys as $k) {
                    if (isset($row->$k)) {
                        return $row->$k;
                    }
                }
                return $default;
            };

            $html = '<style>
                .takmar-table th, .takmar-table td { font-size:12px; text-align:center; vertical-align:middle; }
                .takmar-table thead th { background:#4c4c80; color:#fff; position:sticky; top:0; z-index:2; }
                .takmar-table tbody tr:nth-child(even) { background:#f6f9fc; }
                .takmar-table tbody tr:hover { background:#e3e8f0; }
            </style>';

            $html .= '<div style="overflow:auto;max-height:650px">';
            $html .= '<table class="table table-sm table-striped table-bordered" style="font-size:10px;">';
            $html .= '<thead class="thead-dark"><tr>
                <th>Jawa/Luar Jawa</th>
                <th>Cluster</th>
                <th>Kode Kebun</th>
                <th>Nama Kebun</th>
                <th>Jml Petak</th>
                <th>Luas Polig (Ha)</th>
                <th>Takmar (Ton)</th>
                <th>Protas (Ton/Ha)</th>
                <th>Rendemen</th>
                <th>Rendemen BH</th>
                <th>Hablur (Ton)</th>
                <th>Hablur/Ha</th>
                <th>Hablur Milik</th>
                <th>Gula Milik</th>
                <th>Tetes Milik</th>
            </tr></thead><tbody>';

            $tot = [
                'jml_petak' => 0, 'luas' => 0, 'takdes' => 0, 'protas' => 0,
                'rend' => 0, 'rend_bh' => 0, 'hablur' => 0, 'hablur_ha' => 0,
                'hablur_milik' => 0, 'gula_milik' => 0, 'tetes_milik' => 0, 'count' => 0
            ];

            $no = 1;
            foreach ($rows as $r) {
                $jmlPetak = (float) $pick($r, ['jml_petak'], 0);
                $luas = (float) $pick($r, ['luas_polig', 'luas_poligon'], 0);
                $takdes = (float) $pick($r, ['takmar_ton', 'takmar_tor'], 0);
                $protas = (float) $pick($r, ['protas', 'takmar_tonperha', 'takmar_tonha'], 0);
                $rend = (float) $pick($r, ['rendemen_takmar'], 0);
                $rendBh = (float) $pick($r, ['rendemen_bagihasil', 'rendemen_bagi_hasil'], 0);
                $hablur = (float) $pick($r, ['hablur', 'hablur_ton'], 0);
                $hablurHa = (float) $pick($r, ['hablur_per_ha', 'hablur_per'], 0);
                $hablurMilik = (float) $pick($r, ['hablur_milik', 'hablur_mili'], 0);
                $gulaMilik = (float) $pick($r, ['gula_milik'], 0);
                $tetesMilik = (float) $pick($r, ['tetes_milik'], 0);

                $html .= '<tr>
                    <td>'.htmlspecialchars((string) $pick($r, ['jawa_luarjawa', 'jawa_luarja', 'jawa_nonjawa'], '-')).'</td>
                    <td>'.htmlspecialchars((string) $pick($r, ['cluster', 'nama_cluster'], '-')).'</td>
                    <td>'.htmlspecialchars((string) $pick($r, ['kode_kebun', 'kode_kebu'], '-')).'</td>
                    <td>'.htmlspecialchars((string) $pick($r, ['nama_kebun', 'nama_keb'], '-')).'</td>
                    <td style="text-align:right">'.number_format($jmlPetak, 0).'</td>
                    <td style="text-align:right">'.number_format($luas, 3).'</td>
                    <td style="text-align:right">'.number_format($takdes, 2).'</td>
                    <td style="text-align:right">'.number_format($protas, 2).'</td>
                    <td style="text-align:right">'.number_format($rend, 2).'</td>
                    <td style="text-align:right">'.number_format($rendBh, 2).'</td>
                    <td style="text-align:right">'.number_format($hablur, 2).'</td>
                    <td style="text-align:right">'.number_format($hablurHa, 2).'</td>
                    <td style="text-align:right">'.number_format($hablurMilik, 2).'</td>
                    <td style="text-align:right">'.number_format($gulaMilik, 2).'</td>
                    <td style="text-align:right">'.number_format($tetesMilik, 2).'</td>
                </tr>';

                $tot['jml_petak'] += $jmlPetak;
                $tot['luas'] += $luas;
                $tot['takdes'] += $takdes;
                $tot['protas'] += $protas;
                $tot['rend'] += $rend;
                $tot['rend_bh'] += $rendBh;
                $tot['hablur'] += $hablur;
                $tot['hablur_ha'] += $hablurHa;
                $tot['hablur_milik'] += $hablurMilik;
                $tot['gula_milik'] += $gulaMilik;
                $tot['tetes_milik'] += $tetesMilik;
                $tot['count']++;
            }

         

            $html .= '</tbody></table></div>';

            return response($html);
        }

        public function getFotoDrone(Request $request)
        {
            $lahan_id = $request->input('lahan_id');
            
            if (empty($lahan_id)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Parameter lahan_id is required'
                ]);
            }

            // Query untuk mengambil data foto drone berdasarkan lahan_id
            $data = DB::select('SELECT lahan_id, tanggal, foto FROM tx_foto_drone WHERE lahan_id = ? AND MONTH(tanggal) = 12 AND YEAR(tanggal) = 2025 ORDER BY tanggal DESC', [$lahan_id]);

            $html = '<style>
                .foto-drone-table th, .foto-drone-table td {
                    text-align: center;
                    vertical-align: middle;
                    font-size: 13px;
                }
                .foto-drone-table thead th {
                    background: #4c4c80;
                    color: #fff;
                    font-weight: bold;
                }
                .foto-drone-table tbody tr:nth-child(even) {
                    background: #f6f9fc;
                }
                .foto-drone-table tbody tr:hover {
                    background: #e3e8f0;
                    transition: background 0.2s;
                }
                .foto-thumbnail {
                    max-width: 100px;
                    max-height: 80px;
                    border-radius: 8px;
                    box-shadow: 0 2px 8px rgba(0,0,0,0.2);
                    cursor: pointer;
                }
                .foto-thumbnail:hover {
                    transform: scale(1.05);
                    transition: transform 0.2s;
                }
            </style>';
            
            $html .= '<div style="overflow-x:auto;">
                <table class="table table-bordered table-hover table-sm foto-drone-table">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Lahan ID</th>
                            <th>Tanggal</th>
                            <th>Foto</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>';

            $no = 1;
            foreach ($data as $row) {
                $html .= '<tr>';
                $html .= '<td>' . $no++ . '</td>';
                $html .= '<td>' . htmlspecialchars($row->lahan_id) . '</td>';
                $html .= '<td>' . date('d-m-Y', strtotime($row->tanggal)) . '</td>';
                
                // Kolom foto
                if (!empty($row->foto)) {
                    $html .= '<td>
                        <img src="uploads/foto_drone/' . htmlspecialchars($row->foto) . '" 
                             alt="Foto Drone" 
                             class="foto-thumbnail"
                             onerror="this.src=\'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjgwIiB2aWV3Qm94PSIwIDAgMTAwIDgwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxyZWN0IHdpZHRoPSIxMDAiIGhlaWdodD0iODAiIGZpbGw9IiNmOGY5ZmEiLz48dGV4dCB4PSI1MCIgeT0iNDAiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZpbGw9IiM2Yzc1N2QiIGZvbnQtc2l6ZT0iMTIiPkdhbWJhcjwvdGV4dD48dGV4dCB4PSI1MCIgeT0iNTUiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZpbGw9IiM2Yzc1N2QiIGZvbnQtc2l6ZT0iMTIiPnRpZGFrIGFkYTwvdGV4dD48L3N2Zz4=\'; this.alt=\'Gambar tidak tersedia\';"/>
                    </td>';
                } else {
                    $html .= '<td><span style="color: #6c757d; font-style: italic;">Tidak ada foto</span></td>';
                }
                
                // Kolom aksi
                $html .= '<td>';
                if (!empty($row->foto)) {
                    $html .= '<a href="uploads/foto_drone/' . htmlspecialchars($row->foto) . '" target="_blank" class="btn btn-sm btn-primary" title="Lihat Foto">
                        <i class="fas fa-eye"></i>
                    </a><a href="uploads/foto_drone/' . htmlspecialchars($row->foto) . '" download="' . htmlspecialchars($row->lahan_id) . '_' . date('Y-m-d', strtotime($row->tanggal)) . '.jpg" class="btn btn-sm btn-success ml-1" title="Download Foto">
                    <i class="fas fa-download"></i>
                </a>';
                } else {
                    $html .= '<span class="text-muted">-</span>';
                }
                
                $html .= '</td>';

                
                $html .= '</tr>';
            }

            if (count($data) == 0) {
                $html .= '<tr><td colspan="5" style="text-align:center; color: #6c757d;">Data foto drone tidak ditemukan untuk lahan ID: ' . htmlspecialchars($lahan_id) . '</td></tr>';
            }

            $html .= '</tbody></table></div>';
            
            // Modal untuk menampilkan gambar
          

            return response($html);
        
        }

        public function getGrafikKlentekTotal(Request $request)
        {
  
            $tanggal = $request->input('tanggal', date('Y-m-d'));
            $kode_kebun = NULL;
            // Ambil data dari stored procedure
            $data = DB::select('call sp_monitoring_klentek_kebun(?, ?)', [$kode_kebun,$tanggal]);

            $pekerjaan = ['klentek_1', 'klentek_2', 'klentek_3'];
            $hektar = [];
            $sasaran = [];

            foreach ($pekerjaan as $idx => $pekerjaan_name) {
                $hektar[] = isset($data[0]->{"klentek_" . ($idx + 1)}) ? (float)$data[0]->{"klentek_" . ($idx + 1)} : 0;
                $sasaran[] = isset($data[0]->{"sasaran_klentek_" . ($idx + 1)}) ? (float)$data[0]->{"sasaran_klentek_" . ($idx + 1)} : 0;
            }

            return response()->json([
                'status' => 'success',
                'data' => [
                    'pekerjaan' => $pekerjaan,
                    'hektar' => $hektar,
                    'sasaran' => $sasaran
                ]
            ]);
        
        }

        public function getGrafikKlentekKebun(Request $request)
        {
  
            $tanggal = $request->input('tanggal', date('Y-m-d'));
            $kode_kebun = $request->input('kode_kebun');
            
            if (empty($kode_kebun)) {
                $kode_kebun = NULL;
            }
            // Ambil data dari stored procedure
            $data = DB::select('call sp_monitoring_klentek_kebun(?, ?)', [$kode_kebun,$tanggal]);

            $pekerjaan = ['klentek_1', 'klentek_2', 'klentek_3'];
            $hektar = [];
            $sasaran = [];

            foreach ($pekerjaan as $idx => $pekerjaan_name) {
                $hektar[] = isset($data[0]->{"klentek_" . ($idx + 1)}) ? (float)$data[0]->{"klentek_" . ($idx + 1)} : 0;
                $sasaran[] = isset($data[0]->{"sasaran_klentek_" . ($idx + 1)}) ? (float)$data[0]->{"sasaran_klentek_" . ($idx + 1)} : 0;
            }

            return response()->json([
                'status' => 'success',
                'data' => [
                    'pekerjaan' => $pekerjaan,
                    'hektar' => $hektar,
                    'sasaran' => $sasaran
                ]
            ]);
        
        }

         public function getGrafikKlentekRayon(Request $request)
        {
       
            $tanggal = $request->input('tanggal', date('Y-m-d'));
            $kode_rayon = $request->input('kode_rayon');
            
            // Ambil data dari stored procedure
            $data = DB::select('call sp_monitoring_klentek_rayon(?, ?)', [$kode_rayon,$tanggal]);

            $pekerjaan = ['klentek_1', 'klentek_2', 'klentek_3'];
            $hektar = [];
            $sasaran = [];

            foreach ($pekerjaan as $idx => $pekerjaan_name) {
                $hektar[] = isset($data[0]->{"klentek_" . ($idx + 1)}) ? (float)$data[0]->{"klentek_" . ($idx + 1)} : 0;
                $sasaran[] = isset($data[0]->{"sasaran_klentek_" . ($idx + 1)}) ? (float)$data[0]->{"sasaran_klentek_" . ($idx + 1)} : 0;
            }

            return response()->json([
                'status' => 'success',
                'data' => [
                    'pekerjaan' => $pekerjaan,
                    'hektar' => $hektar,
                    'sasaran' => $sasaran
                ]
            ]);
        
        }

        public function getRekapDronePetakPeriodeDinamis(Request $request)
        {
            $tahun = $request->input('tahun');
            $periode = $request->input('periode');
            $kode_rayon = $request->input('kode_rayon');

            // Ambil data dari stored procedure
            $data = DB::select('call sp_rekap_drone_petak_periode_dinamis(?, ?, ?)', [
            $tahun, $periode, $kode_rayon
            ]);

            // Kelompokkan data berdasarkan nama_rayon
            $grouped = collect($data)->groupBy('nama_rayon');

            // Buat tab navigation
            $html = '<style>
            .table th, .table td { text-align:center; vertical-align:middle; font-size:13px; }
            .table thead th { background: #4c4c80; color: #fff; font-weight:bold; }
            .table tbody tr:nth-child(even) { background: #f6f9fc; }
            .table tbody tr:hover { background: #e3e8f0; transition: background 0.2s; }
            .nav-tabs .nav-link.active { background: #4c4c80; color: #fff !important; }
            .nav-tabs .nav-link { color: #4c4c80; }
            </style>';

            // Tombol download Excel (menggunakan SheetJS/xlsx)
            $html .= '<div style="margin:10px 0;">
            <button id="btn-download-excel" class="btn btn-success btn-sm">
                <i class="fa fa-file-excel"></i> Download Excel
            </button>
            </div>';

            $html .= '<ul class="nav nav-tabs" id="dronePetakTab" role="tablist">';
            $tabIdx = 0;
            foreach ($grouped as $nama_rayon => $rows) {
            $active = $tabIdx === 0 ? 'active' : '';
            $html .= '<li class="nav-item">
                <a class="nav-link '.$active.'" id="tab-'.$tabIdx.'" data-toggle="tab" href="#tab-content-'.$tabIdx.'" role="tab" aria-controls="tab-content-'.$tabIdx.'" aria-selected="'.($active ? 'true' : 'false').'">'.htmlspecialchars($nama_rayon).'</a>
            </li>';
            $tabIdx++;
            }
            $html .= '</ul>';

            $html .= '<div class="tab-content" id="dronePetakTabContent">';
            $tabIdx = 0;
            foreach ($grouped as $nama_rayon => $rows) {
            $active = $tabIdx === 0 ? 'show active' : '';
            $html .= '<div class="tab-pane fade '.$active.'" id="tab-content-'.$tabIdx.'" role="tabpanel" aria-labelledby="tab-'.$tabIdx.'">';
            $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-sm table-responsive drone-petak-table" id="drone-petak-table-'.$tabIdx.'">';
            $html .= '<thead>
                <tr>
                <th>No</th>
                <th>Lahan ID</th>
                <th>Kode Kebun</th>
                <th>Kode Rayon</th>
                <th>Nama Rayon</th>
                <th>Afdeling</th>
                <th>Luas Poligon (Ha)</th>
                <th>Petak Tanam & Kepras</th>
                <th>Petak SD '.$periode.'</th>
                <th>Foto Drone '.$periode.'</th>
                </tr>
            </thead>
            <tbody>';
            $no = 1;
            foreach ($rows as $row) {
                $drone_val = (int)($row->{'drone_' . $periode} ?? 0);
                $drone_status = $drone_val > 0
                ? '<span style="color:#28a745;font-weight:bold;">Sudah Input</span>'
                : '<span style="color:#dc3545;font-weight:bold;">Belum Input</span>';
                $html .= '<tr>';
                $html .= '<td>' . $no++ . '</td>';
                $html .= '<td>' . htmlspecialchars($row->lahan_id ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kode_kebun ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kode_rayon ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->nama_rayon ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->afd_new ?? '-') . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->luas_polig ?? 0, 3) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->petak_tanamkepras ?? 0) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->{'jumlah_petak_tanamkepras_sd_' . $periode} ?? 0) . '</td>';
                $html .= '<td>' . $drone_status . '</td>';
                $html .= '</tr>';
            }
            if (count($rows) == 0) {
                $html .= '<tr><td colspan="11" style="text-align:center;">Data tidak ditemukan.</td></tr>';
            }
            $html .= '</tbody></table></div>';
            $html .= '</div>';
            $tabIdx++;
            }
            $html .= '</div>';
            $html .= '<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>';
            $html .= '<script>
            $(function(){
                $("#dronePetakTab a").on("click", function(e){
                e.preventDefault();
                $(this).tab("show");
                });

                $("#btn-download-excel").off("click").on("click", function() {
                // Ambil tab aktif
                var activeTab = $("#dronePetakTab .nav-link.active").attr("href");
                var table = $(activeTab).find("table.drone-petak-table")[0];
                if (!table) {
                    alert("Tabel tidak ditemukan!");
                    return;
                }
                var wb = XLSX.utils.table_to_book(table, {sheet: "Data"});
                XLSX.writeFile(wb, "rekap_drone_petak_'.$periode.'_'.$tahun.'.xlsx");
                });
            });
            </script>';

            return response($html);
        
        }

        public function getRekapMorfPetakPeriodeDinamis(Request $request)
        {
            $tahun = $request->input('tahun');
            $periode = $request->input('periode');
            $kode_rayon = $request->input('kode_rayon');

            // Ambil data dari stored procedure
            $data = DB::select('call sp_rekap_morfologi_petak_periode_dinamis(?, ?, ?, ?)', [
            $tahun, $periode, $kode_rayon, 0
            ]);

            // Kelompokkan data berdasarkan nama_rayon
            $grouped = collect($data)->groupBy('nama_rayon');

            // Buat tab navigation
            $html = '<style>
            .table th, .table td { text-align:center; vertical-align:middle; font-size:13px; }
            .table thead th { background: #4c4c80; color: #fff; font-weight:bold; }
            .table tbody tr:nth-child(even) { background: #f6f9fc; }
            .table tbody tr:hover { background: #e3e8f0; transition: background 0.2s; }
            .nav-tabs .nav-link.active { background: #4c4c80; color: #fff !important; }
            .nav-tabs .nav-link { color: #4c4c80; }
            </style>';

            // Tombol download Excel (menggunakan SheetJS/xlsx)
            $html .= '<div style="margin:10px 0;">
            <button id="btn-download-excel" class="btn btn-success btn-sm">
                <i class="fa fa-file-excel"></i> Download Excel
            </button>
            </div>';

            $html .= '<ul class="nav nav-tabs" id="dronePetakTab" role="tablist">';
            $tabIdx = 0;
            foreach ($grouped as $nama_rayon => $rows) {
            $active = $tabIdx === 0 ? 'active' : '';
            $html .= '<li class="nav-item">
                <a class="nav-link '.$active.'" id="tab-'.$tabIdx.'" data-toggle="tab" href="#tab-content-'.$tabIdx.'" role="tab" aria-controls="tab-content-'.$tabIdx.'" aria-selected="'.($active ? 'true' : 'false').'">'.htmlspecialchars($nama_rayon).'</a>
            </li>';
            $tabIdx++;
            }
            $html .= '</ul>';

            $html .= '<div class="tab-content" id="dronePetakTabContent">';
            $tabIdx = 0;
            foreach ($grouped as $nama_rayon => $rows) {
            $active = $tabIdx === 0 ? 'show active' : '';
            $html .= '<div class="tab-pane fade '.$active.'" id="tab-content-'.$tabIdx.'" role="tabpanel" aria-labelledby="tab-'.$tabIdx.'">';
            $html .= '<div style="overflow-x:auto;"><table class="table table-bordered table-sm table-responsive drone-petak-table" id="drone-petak-table-'.$tabIdx.'">';
            $html .= '<thead>
                <tr>
                <th>No</th>
                <th>Kode Kebun</th>
                <th>Nama Kebun</th>
                <th>Kode Rayon</th>
                <th>Nama Rayon</th>
                <th>Afdeling</th>
                <th>Lahan ID</th>
                <th>Luas Poligon (Ha)</th>
                <th>Petak Tanam & Kepras</th>
                <th>Petak SD '.$periode.'</th>
                <th>Morfologi '.$periode.'</th>
                </tr>
            </thead>
            <tbody>';
            $no = 1;
            foreach ($rows as $row) {
                $morfologi_val = (int)($row->{'morfologi_' . $periode} ?? 0);
                $morfologi_status = $morfologi_val > 0
                ? '<span style="color:#28a745;font-weight:bold;">Sudah Input</span>'
                : '<span style="color:#dc3545;font-weight:bold;">Belum Input</span>';
                $html .= '<tr>';
                $html .= '<td>' . $no++ . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kode_kebun ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->nama_kebun ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->kode_rayon ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->nama_rayon ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->afd_new ?? '-') . '</td>';
                $html .= '<td>' . htmlspecialchars($row->lahan_id ?? '-') . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->luas_polig ?? 0, 3) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->jumlah_petak_tanamkepras ?? 0) . '</td>';
                $html .= '<td style="text-align:right;">' . number_format($row->{'jumlah_petak_tanamkepras_sd_' . $periode} ?? 0) . '</td>';
                $html .= '<td>' . $morfologi_status . '</td>';
                $html .= '</tr>';
            }
            if (count($rows) == 0) {
                $html .= '<tr><td colspan="11" style="text-align:center;">Data tidak ditemukan.</td></tr>';
            }
            $html .= '</tbody></table></div>';
            $html .= '</div>';
            $tabIdx++;
            }
            $html .= '</div>';
            $html .= '<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>';
            $html .= '<script>
            $(function(){
                $("#dronePetakTab a").on("click", function(e){
                e.preventDefault();
                $(this).tab("show");
                });

                $("#btn-download-excel").off("click").on("click", function() {
                // Ambil tab aktif
                var activeTab = $("#dronePetakTab .nav-link.active").attr("href");
                var table = $(activeTab).find("table.drone-petak-table")[0];
                if (!table) {
                    alert("Tabel tidak ditemukan!");
                    return;
                }
                var wb = XLSX.utils.table_to_book(table, {sheet: "Data"});
                XLSX.writeFile(wb, "rekap_drone_petak_'.$periode.'_'.$tahun.'.xlsx");
                });
            });
            </script>';

            return response($html);
        
        }

        public function getChartDataKesegaranAfd(Request $request)
        {
            $kode_kebun = $request->input('kebun');
            $kode_rayon = $request->input('rayon');
            $cluster = $request->input('cluster');
            $tanggal = $request->input('tanggal', date('Y-m-d', strtotime('-1 day')));

            if($cluster !='' && $cluster != null && $kode_kebun == ''){
                $dataHI = DB::select('CALL sp_kesegaran_kebun_hi(?, ?)', [
                    $cluster,
                    $tanggal
                ]);
                $dataSD = DB::select('CALL sp_kesegaran_kebun_sd(?, ?)', [
                    $cluster,
                    $tanggal
                ]);
            }else{
                  // Fetch data HI (Hari Ini)
                    $dataHI = DB::select('CALL sp_kesegaran_afd_grafik_hi(?, ?, ?)', [
                    $kode_kebun,
                    $kode_rayon,
                    $tanggal
                    ]);

                    // Fetch data SD (Sampai Dengan)
                    $dataSD = DB::select('CALL sp_kesegaran_afd_grafik_sd(?, ?, ?)', [
                    $kode_kebun,
                    $kode_rayon,
                    $tanggal
                    ]);      
            }

            

            // Process data HI
            $processedHI = collect($dataHI)->map(function ($row) {
            return [
                'grouping_label' => $row->grouping_label,
                'label_24jam' => (int) $row->{'<24jam'},
                'label_48jam' => (int) $row->{'24sd48jam'},
                'label_lebih_48jam' => (int) $row->{'>48jam'}
            ];
            });

            // Process data SD
            $processedSD = collect($dataSD)->map(function ($row) {
            return [
                'grouping_label' => $row->grouping_label,
                'label_24jam' => (int) $row->{'<24jam'},
                'label_48jam' => (int) $row->{'24sd48jam'},
                'label_lebih_48jam' => (int) $row->{'>48jam'}
            ];
            });

            return response()->json([
            'status' => 'success',
            'tanggal' => date('d-m-Y', strtotime($tanggal)),
            'data_hi' => $processedHI,
            'data_sd' => $processedSD
            ]);
        }



         public function grafikbiayasdm(){

            $this->data['unit'] =  DB::table('master_unit_sdm')
                        ->select('kode_unit', 'unit')
                        ->get();     

            return view('dashboard.biayasdm', $this->data);
        }

        public function gettotkaryawan(Request $request){
            $p_unit = $request->input('unit', '');

            $this->data['jml_kary'] = DB::table('data_jk_sdm')
                            ->selectRaw('SUM(L) + SUM(P) as jml')
                            ->when(!empty($p_unit), function ($query) use ($p_unit) {
                                return $query->where('unit', $p_unit);
                            })
                            ->groupBy('bulan')
                            ->orderByDesc('bulan')
                            ->limit(1)
                            ->value('jml');
            return response()->json([
                'status' => 'success',
                'data' => [
                    'jml_kary' => $this->data['jml_kary'],
                ],
            ]);
        }

        public function getrataumurkaryawan(Request $request){
            $p_unit = $request->input('unit', '');

            $this->data['rata_umur'] = DB::table('data_umur_sdm')
                ->selectRaw('ROUND((
                    (`17_25` * 21) +
                    (`26_35` * 30.5) +
                    (`36_45` * 40.5) +
                    (`46_50` * 48) +
                    (`50_>` * 55)
                ) / NULLIF((`17_25` + `26_35` + `36_45` + `46_50` + `50_>`), 0), 2) AS rata_rata_usia')
                ->when(!empty($p_unit), function ($query) use ($p_unit) {
                    return $query->where('unit', $p_unit);
                })
                ->groupBy('bulan')
                ->orderByDesc('bulan')
                ->limit(1)
                ->value('rata_rata_usia');
            return response()->json([
                'status' => 'success',
                'data' => [
                    'rata_umur' => round($this->data['rata_umur']),
                ],
            ]);
        }

        public function getratabiayakaryawan(Request $request)
        {
            $p_tahun = date('Y');
            $p_unit = $request->input('unit', '');

            // Call the stored procedure to fetch data
            $totalkary = DB::table('data_jk_sdm')
                            ->selectRaw('SUM(L) + SUM(P) as jml')
                            ->when(!empty($p_unit), function ($query) use ($p_unit) {
                                return $query->where('unit', $p_unit);
                            })
                            ->groupBy('bulan')
                            ->orderByDesc('bulan')
                            ->limit(1)
                            ->value('jml');

             // Call the stored procedure to fetch data
                $data = DB::select('call sp_rekap_biaya_sdm(?,?)', [$p_tahun, $p_unit]);

                // Process the data if needed
                $processedData = collect($data)->map(function ($item, $key) use ($totalkary) {
                    return [
                    'rata_biaya_sdm' => round(((float) $item->total_kary_tetap_real + (float) $item->total_kary_non_tetap_real + (float) $item->total_kary_os_real) / max($totalkary, 1), 0),
                    ];
                });                

            // Return the data as JSON
            return response()->json([
                'status' => 'success',
                'data' => $processedData,
            ]);
        }

        public function getbiayasdm(Request $request)
        {
                $p_tahun = date('Y');

                $p_unit = $request->input('unit', '');
                // Call the stored procedure to fetch data
                $data = DB::select('call sp_rekap_biaya_sdm(?,?)', [$p_tahun, $p_unit]);

                // Process the data if needed
                $processedData = collect($data)->map(function ($item) {
                    return [
                        'bulan' => date('F', mktime(0, 0, 0, $item->bulan, 1)),
                        'tahun' => $item->tahun,
                    'total_kary_tetap_real' => number_format((float) $item->total_kary_tetap_real/1000, 0, ',', '.'),
                    'total_kary_tetap_rkap' => number_format((float) $item->total_kary_tetap_rkap/1000, 0, ',', '.'),
                    'persen_kary_tetap' => round((float) $item->total_kary_tetap_real/1000 / max((float) $item->total_kary_tetap_rkap/1000, 1) * 100, 2),

                    'total_kary_non_tetap_real' => number_format((float) $item->total_kary_non_tetap_real/1000, 0, ',', '.'),
                    'total_kary_non_tetap_rkap' => number_format((float) $item->total_kary_non_tetap_rkap/1000, 0, ',', '.'),
                    'persen_kary_non_tetap' => round((float) $item->total_kary_non_tetap_real/1000 / max((float) $item->total_kary_non_tetap_rkap/1000, 1) * 100, 2),

                    'total_kary_os_real' => number_format((float) $item->total_kary_os_real/1000, 0, ',', '.'),
                    'total_kary_os_rkap' => number_format((float) $item->total_kary_os_rkap/1000, 0, ',', '.'),
                    'persen_kary_os' => round((float) $item->total_kary_os_real/1000 / max((float) $item->total_kary_os_rkap/1000, 1) * 100, 2),
                    ];
                });

                // Return the data as JSON
                return response()->json([
                    'status' => 'success',
                    'data' => $processedData,
                ]);
        }
        public function getbiayasdmunit(Request $request)
        {
            $p_tahun = $request->input('tahun', date('Y'));
            $p_unit = $request->input('unit', '');

            // Call the stored procedure to fetch data
            if(empty($p_unit)){
                $data = DB::select('call sp_rekap_biaya_sdm_total(?)', [$p_tahun]);
            }else{
                $data = DB::select('call sp_rekap_biaya_sdm_per_unit(?, ?)', [$p_tahun, $p_unit]);
            }
            // Process the data if needed
            
                $chartData = collect($data)->map(function ($item) {
                return [
                            'categori' => date('F', mktime(0, 0, 0, $item->bulan, 1)),
                            'real_tetap' => round(((float) $item->total_kary_tetap_real)/1000,0),
                            'real_non_tetap' => round(((float) $item->total_kary_non_tetap_real)/1000,0),
                            'real_os' => round(((float) $item->total_kary_os_real)/1000,0),
                            'rkap_tetap' => round(((float) $item->total_kary_tetap_rkap)/1000,0),
                        ];
                });

                $categories = $chartData->pluck('categori')->toArray();
                $real_tetap = $chartData->pluck('real_tetap')->toArray();
                $real_non_tetap = $chartData->pluck('real_non_tetap')->toArray();
                $real_os = $chartData->pluck('real_os')->toArray();
                $rkap_tetap = $chartData->pluck('rkap_tetap')->toArray();

                // Return the data formatted for Highcharts
                return response()->json([
                    'status' => 'success',
                    'categori' => $categories,
                    'real_tetap' => $real_tetap,
                    'real_non_tetap' => $real_non_tetap,
                    'real_os' => $real_os,
                    'rkap_tetap' => $rkap_tetap,
                ]);


        }

        public function getRendemenHarianPgGrafik(Request $request)
        {
            $tanggal = $request->input('tanggal', date('Y-m-d'));
            $data = DB::select('CALL sp_real_2026_rendemen_harian_pg_grafik(?)', [$tanggal]);

            $categories = collect($data)->map(function ($item) {
                return $item->nama_pg ?? $item->kode_pg ?? '';
            })->toArray();

            $kodePg = collect($data)->pluck('kode_pg')->toArray();

            $rendemenHi = collect($data)->map(function ($item) {
                return is_null($item->rendemen_hi) || $item->rendemen_hi === '' ? null : (float) $item->rendemen_hi;
            })->toArray();

            $rendemenSd = collect($data)->map(function ($item) {
                return is_null($item->rendemen_sd) || $item->rendemen_sd === '' ? null : (float) $item->rendemen_sd;
            })->toArray();

            $tanggalLabel = !empty($data) ? ($data[0]->tanggal ?? date('d/m/Y', strtotime($tanggal))) : date('d/m/Y', strtotime($tanggal));

            return response()->json([
                'status' => 'success',
                'tanggal' => $tanggalLabel,
                'categories' => $categories,
                'kode_pg' => $kodePg,
                'series' => [
                    [
                        'name' => 'Rendemen HI',
                        'data' => $rendemenHi,
                    ],
                    [
                        'name' => 'Rendemen SD',
                        'data' => $rendemenSd,
                    ],
                ],
            ]);
        }

        public function getgendersdmunit(Request $request)
        {
            // $p_tahun = $request->input('tahun', date('Y'));
            $p_unit = $request->input('unit', '');
            // Call the stored procedure to fetch data
            
            $data = DB::table('data_jk_sdm')
                ->select(
                    'bulan',
                    'tahun',
                    DB::raw('SUM(L) as L'),
                    DB::raw('SUM(P) as P')
                )
                ->when(!empty($p_unit), function ($query) use ($p_unit) {
                    return $query->where('unit', $p_unit);
                })
                ->groupBy('bulan', 'tahun')
                ->orderByDesc('bulan')
                ->limit(1)
                ->get();

            // Format data untuk Highcharts Pie
            $chartData = [
                [
                    'name' => 'Laki-laki',
                    'y' => (int) ($data[0]->L ?? 0),
                    'color' => '#007bff'
                ],
                [
                    'name' => 'Perempuan',
                    'y' => (int) ($data[0]->P ?? 0),
                    'color' => '#e83e8c'
                ]
            ];

            return response()->json([
                'status' => 'success', 
                'data' => $chartData,
                'bulan' => $data[0]->bulan ?? '',
                'tahun' => $data[0]->tahun ?? ''
            ]);
        }

        public function geteducationsdmunit(Request $request)
        {
            $p_unit = $request->input('unit', '');
            $data = DB::table('data_pendidikan_sdm')
                ->select(
                    'bulan',
                    'tahun',
                    DB::raw('SUM(sd) as SD'),
                    DB::raw('SUM(smp) as SMP'),
                    DB::raw('SUM(sma) as SMA'),
                    DB::raw('SUM(d1_d3) as D1_D3'),
                    DB::raw('SUM(s1) as S1'),
                    DB::raw('SUM(s2) as S2')
                )
                ->when(!empty($p_unit), function ($query) use ($p_unit) {
                    return $query->where('unit', $p_unit);
                })
                ->groupBy('bulan', 'tahun')
                ->orderByDesc('bulan')
                ->limit(1)
                ->get();

            $result = [
                [
                    'name' => 'SD',
                    'y' => (int) ($data[0]->SD ?? 0),
                    'color' => '#f39c12'
                ],
                [
                    'name' => 'SMP',
                    'y' => (int) ($data[0]->SMP ?? 0),
                    'color' => '#27ae60'
                ],
                [
                    'name' => 'SMA',
                    'y' => (int) ($data[0]->SMA ?? 0),
                    'color' => '#2980b9'
                ],
                [
                    'name' => 'D1-D3',
                    'y' => (int) ($data[0]->D1_D3 ?? 0),
                    'color' => '#8e44ad'
                ],
                [
                    'name' => 'S1',
                    'y' => (int) ($data[0]->S1 ?? 0),
                    'color' => '#e67e22'
                ],
                [
                    'name' => 'S2',
                    'y' => (int) ($data[0]->S2 ?? 0),
                    'color' => '#c0392b'
                ]
            ];

            return response()->json([
                'status' => 'success',
                'data' => $result,
                'bulan' => $data[0]->bulan ?? '',
                'tahun' => $data[0]->tahun ?? ''
            ]);
        }

        public function getjabatansdmunit(Request $request)
        {
            $p_unit = $request->input('unit', '');
            $data = DB::table('data_status_kary_sdm')
                ->select(
                    'bulan',
                    'tahun',
                    DB::raw('SUM(os) as OS'),
                    DB::raw('SUM(non_tetap) as NON_TETAP'),
                    DB::raw('SUM(karpel_tetap) as KARPEL_TETAP'),
                    DB::raw('SUM(bod_3) as BOD_3'),
                    DB::raw('SUM(bod_2) as BOD_2'),
                    DB::raw('SUM(bod_1) as BOD_1'),
                    DB::raw('SUM(sevp) as SEVP')
                )
                ->when(!empty($p_unit), function ($query) use ($p_unit) {
                    return $query->where('unit', $p_unit);
                })
                ->groupBy('bulan', 'tahun')
                ->orderByDesc('bulan')
                ->limit(1)
                ->get();

            $result = [
                [
                    'name' => 'OS',
                    'y' => (int) ($data[0]->OS ?? 0),
                    'color' => '#007bff'
                ],
                [
                    'name' => 'NON TETAP',
                    'y' => (int) ($data[0]->NON_TETAP ?? 0),
                    'color' => '#ffc107'
                ],
                [
                    'name' => 'KARPEL TETAP',
                    'y' => (int) ($data[0]->KARPEL_TETAP ?? 0),
                    'color' => '#28a745'
                ],
                [
                    'name' => 'BOD 3',
                    'y' => (int) ($data[0]->BOD_3 ?? 0),
                    'color' => '#17a2b8'
                ],
                [
                    'name' => 'BOD 2',
                    'y' => (int) ($data[0]->BOD_2 ?? 0),
                    'color' => '#6f42c1'
                ],
                [
                    'name' => 'BOD 1',
                    'y' => (int) ($data[0]->BOD_1 ?? 0),
                    'color' => '#e83e8c'
                ],
                [
                    'name' => 'SEVP',
                    'y' => (int) ($data[0]->SEVP ?? 0),
                    'color' => '#fd7e14'
                ]
            ];

            return response()->json([
                'status' => 'success',
                'data' => $result,
                'bulan' => $data[0]->bulan ?? '',
                'tahun' => $data[0]->tahun ?? ''
            ]);
        }

        public function getumursdmunit(Request $request)
        {
            $p_unit = $request->input('unit', '');
            $data = DB::table('data_umur_sdm')
                ->select(
                    'bulan',
                    'tahun',
                    DB::raw('SUM(`17_25`) as `17_25`'),
                    DB::raw('SUM(`26_35`) as `26_35`'),
                    DB::raw('SUM(`36_45`) as `36_45`'),
                    DB::raw('SUM(`46_50`) as `46_50`'),
                    DB::raw('SUM(`50_>`) as `50_>`')
                )
                ->when(!empty($p_unit), function ($query) use ($p_unit) {
                    return $query->where('unit', $p_unit);
                })
                ->groupBy('bulan', 'tahun')
                ->orderByDesc('bulan')
                ->limit(1)
                ->get();

            $result = [
                [
                    'name' => '17-25',
                    'y' => (int) ($data[0]->{'17_25'} ?? 0),
                    'color' => '#007bff'
                ],
                [
                    'name' => '26-35',
                    'y' => (int) ($data[0]->{'26_35'} ?? 0),
                    'color' => '#28a745'
                ],
                [
                    'name' => '36-45',
                    'y' => (int) ($data[0]->{'36_45'} ?? 0),
                    'color' => '#ffc107'
                ],
                [
                    'name' => '46-50',
                    'y' => (int) ($data[0]->{'46_50'} ?? 0),
                    'color' => '#fd7e14'
                ],
                [
                    'name' => '50+',
                    'y' => (int) ($data[0]->{'50_>'} ?? 0),
                    'color' => '#dc3545'
                ]
            ];

            return response()->json([
                'status' => 'success',
                'data' => $result,
                'bulan' => $data[0]->bulan ?? '',
                'tahun' => $data[0]->tahun ?? ''
            ]);
        }
      
        public function getstatussdmunit(Request $request)
        {
            $p_unit = $request->input('unit', '');
            $data = DB::table('data_golongan_sdm')
                ->select(
                    'bulan',
                    'tahun',
                    DB::raw('SUM(os) as OS'),
                    DB::raw('SUM(pkwt) as PKWT'),
                    DB::raw('SUM(ktng) as KTNG'),
                    DB::raw('SUM(karpel) as KARPEL'),
                    DB::raw('SUM(karpim) as KARPIM')
                )
                ->when(!empty($p_unit), function ($query) use ($p_unit) {
                    return $query->where('unit', $p_unit);
                })
                ->groupBy('bulan', 'tahun')
                ->orderByDesc('bulan')
                ->limit(1)
                ->get();

            $result = [
                [
                    'name' => 'OS',
                    'y' => (int) ($data[0]->OS ?? 0),
                    'color' => '#007bff'
                ],
                [
                    'name' => 'PKWT',
                    'y' => (int) ($data[0]->PKWT ?? 0),
                    'color' => '#ffc107'
                ],
                [
                    'name' => 'KTNG',
                    'y' => (int) ($data[0]->KTNG ?? 0),
                    'color' => '#28a745'
                ],
                [
                    'name' => 'KARPEL',
                    'y' => (int) ($data[0]->KARPEL ?? 0),
                    'color' => '#17a2b8'
                ],
                [
                    'name' => 'KARPIM',
                    'y' => (int) ($data[0]->KARPIM ?? 0),
                    'color' => '#e83e8c'
                ]
            ];

            return response()->json([
                'status' => 'success',
                'data' => $result,
                'bulan' => $data[0]->bulan ?? '',
                'tahun' => $data[0]->tahun ?? ''
            ]);
        }

        public function getgolongansdmunit(Request $request)
        {
            $p_unit = $request->input('unit', '');
            $data = DB::table('data_jabatan_sdm')
                ->select(
                    'bulan',
                    'tahun',
                    DB::raw('SUM(NG) as NG'),
                    DB::raw('SUM(`6A_7B`) as `6A_7B`'),
                    DB::raw('SUM(`8A_10`) as `8A_10`'),
                    DB::raw('SUM(`11_14`) as `11_14`'),
                    DB::raw('SUM(`15_16`) as `15_16`'),
                    DB::raw('SUM(`17_18`) as `17_18`')
                )
                ->when(!empty($p_unit), function ($query) use ($p_unit) {
                    return $query->where('unit', $p_unit);
                })
                ->groupBy('bulan', 'tahun')
                ->orderByDesc('bulan')
                ->limit(1)
                ->get();

            $result = [
                [
                    'name' => 'NG',
                    'y' => (int) ($data[0]->NG ?? 0),
                    'color' => '#007bff'
                ],
                [
                    'name' => '6A-7B',
                    'y' => (int) ($data[0]->{'6A_7B'} ?? 0),
                    'color' => '#28a745'
                ],
                [
                    'name' => '8A-10',
                    'y' => (int) ($data[0]->{'8A_10'} ?? 0),
                    'color' => '#ffc107'
                ],
                [
                    'name' => '11-14',
                    'y' => (int) ($data[0]->{'11_14'} ?? 0),
                    'color' => '#fd7e14'
                ],
                [
                    'name' => '15-16',
                    'y' => (int) ($data[0]->{'15_16'} ?? 0),
                    'color' => '#dc3545'
                ],
                [
                    'name' => '17-18',
                    'y' => (int) ($data[0]->{'17_18'} ?? 0),
                    'color' => '#6f42c1'
                ]
            ];

            return response()->json([
                'status' => 'success',
                'data' => $result,
                'bulan' => $data[0]->bulan ?? '',
                'tahun' => $data[0]->tahun ?? ''
            ]);
        }

    public function getLoginHistory() {
		if(!\Auth::check()) return redirect('user/login');

		$history = \DB::table('tb_users as a')
			->leftJoin('tb_groups as b', 'a.group_id', '=', 'b.group_id')
			->leftJoin('master_kebun as c', 'c.kode_kebun', '=', 'a.first_name')
            ->leftJoin('master_rayon as d', 'd.kode_rayon', '=', 'a.first_name')
			->select('a.email', \DB::raw('IFNULL(c.nama_kebun, IFNULL(d.nama_rayon, a.first_name)) as unit'), 'b.name as group_name', 'a.last_login')
			->orderBy('a.last_login', 'desc')
			->get();

        //rangking history berasal dari tb_login_history
        $topten = \DB::table('tb_login_history as a')
            ->leftJoin('tb_users as b', 'a.user_id', '=', 'b.id')
            ->leftJoin('tb_groups as c', 'b.group_id', '=', 'c.group_id')
            ->leftJoin('master_kebun as d', 'd.kode_kebun', '=', 'b.first_name')
            ->leftJoin('master_rayon as e', 'e.kode_rayon', '=', 'b.first_name')
            ->select('b.email', \DB::raw('IFNULL(d.nama_kebun, IFNULL(e.nama_rayon, b.first_name)) as unit'), 'c.name as group_name', \DB::raw('COUNT(a.id) as login_count'))
            ->where('b.group_id', '!=', 1)
            ->groupBy('a.user_id')
            ->orderBy('login_count', 'desc')
            ->limit(10)
            ->get();    

		$this->data = array(
			'pageTitle' => 'User Login History',
			'pageNote' => 'Riwayat login user',
			'history' => $history,
			'topten' => $topten,
		);

		return view('user.loginhistory', $this->data);
	}
}