<?php namespace App\Http\Controllers\Services;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
use Validator, Input, Redirect ; 
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

use Config;


/**
 * API Endpoint: POST /api/reset-password
 *
 * Deskripsi: Reset password user.
 *
 * Parameter POST:
 *   - id           (string)   : User ID (nomor telepon)
 *   - new_password (string)   : Password baru (min 6 karakter)
 *
 * Response sukses:
 *   {
 *     "success": true,
 *     "message": "Password berhasil direset"
 *   }
 *
 * Response gagal:
 *   {
 *     "success": false,
 *     "message": "..."
 *   }
 *
 * Contoh request:
 *   POST /api/reset-password
 *   Body: { "id": "08123456789", "new_password": "passwordbaru" }
 */
class ModuleMobileController extends Controller {

	public function __construct()
	{		
		parent::__construct();
        
	}

	public function index( Request $request )
	{
		// Make Sure users Logged 			
		// $this->grabApi( $request , 'api') ;		
		// if($this->access['is_view'] ==0) 
		// 	 return response()->json(array('status'=>'error' , 'data' =>  __('core.note_restric') ));
		// // Render into json 
		//  return response()->json(array('status'=>'success' , 'data' => (array) $this->data ));
	}	

    public function uploadpetaktebang(Request $request)
    {
        
            $validator = Validator::make($request->all(), [
                // 'id_petak' => 'required',
                // 'tanggal' => 'required|date',
                // 'jam' => 'required',
                // 'vendor_gl' => 'string',
                // 'luas_tebang' => 'required|numeric',
                // 'jenis_tebang' => 'required|string',
                // 'nomor_gl' => 'string',
                // 'nomor_ch' => 'string',
                // 'jenis_kendaraan' => 'required|string',
                // 'nomor_kendaraan' => 'required|string',
                // 'brix_kebun' => 'numeric',
                // 'pg_penggiling' => 'string',
                // 'nomor_booking' => 'required|string',
                // 'user_id' => 'required',
                // 'thntnm' => 'required',
                // 'foto_kendaraan' => 'required|image|mimes:jpeg,png,jpg'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 400);
            }

            try {
                // Check if booking number already exists
                $existingRecord = \DB::table('tx_petak_tebang')
                    ->where('nomor_booking', $request->nomor_booking)
                    ->first();
                if ($existingRecord) {
                    return response()->json([
                        'success' => true,
                        'status' => 'success',
                        'message' => 'Nomer Kode Booking sudah ada sebelumnya',
                        'id' => $existingRecord->id
                    ]);
                }

                $fotoKendaraanPath = null;
                
                // Handle photo upload
                if ($request->hasFile('foto_kendaraan')) {
                    $file = $request->file('foto_kendaraan');
                    $fileName = time() . '_' . $file->getClientOriginalName();
                    
                    // Create directory if not exists
                    $uploadPath = public_path('uploads/foto_kendaraan_tma');
                    if (!file_exists($uploadPath)) {
                        mkdir($uploadPath, 0777, true);
                    }
                    
                    // Compress image if larger than 1MB
                    $tempPath = $file->getPathname();
                    $compressedImage = $this->compressImage($tempPath, 1024 * 1024); // 1MB limit
                    
                    file_put_contents($uploadPath . '/' . $fileName, $compressedImage);
                    $fotoKendaraanPath = 'uploads/foto_kendaraan_tma/' . $fileName;
                }
                
                // Insert data into database
                \DB::table('tx_petak_tebang')->insert([
                    'id_petak' => $request->id_petak,
                    'tanggal' => $request->tanggal,
                    'jam' => $request->jam,
                    'vendor_gl' => $this->extractString($request->nama_vendor),
                    'luas_tebang' => $request->luas_tebang,
                    'jenis_tebang' => $request->jenis_tebang,
                    'mandor_tebang' => $this->extractString($request->mandor_tebang),
                    'vendor_angkutan' => $this->extractString($request->vendor_angkutan),
                    'vendor_mekanis' => $this->extractString($request->vendor_mekanis),
                    'range_jarak' => $this->extractString2($request->range_jarak),
                    'nomor_gl' => $request->nomor_gl,
                    'nomor_ch' => $request->nomor_ch,
                    'jenis_kendaraan' => $request->jenis_kendaraan,
                    'nomor_kendaraan' => $request->nomor_kendaraan,
                    'brix_kebun' => $request->brix_kebun,
                    'pg_penggiling' => $this->extractString($request->pg_penggiling),
                    'antar_jemput' => $request->antar_jemput,
                    'nomor_booking' => $request->nomor_booking,
                    'keterangan' => $request->keterangan,
                    'user_id' => $request->user_id,
                    'thntnm' => $request->thntnm,
                    'foto_kendaraan' => $fotoKendaraanPath,
                    'createdOn' => now(),
                    'updatedOn' => now()
                ]);
                
                return response()->json([
                    'success' => true,
                    'status' => 'success',
                    'message' => 'Data petaktebang berhasil disimpan',
                    'id' => \DB::getPdo()->lastInsertId()
                ]);
            } catch (\Exception $e) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Gagal menyimpan data: ' . $e->getMessage()
                ], 500);
            }
    }
    
    public function extractString($input)
    {
        $stringarr = explode(' - ', $input);
        return trim($stringarr[0]);
    }

    public function extractString2($input)
    {
        $stringarr = explode('-', $input);
        return trim($stringarr[0]);
    }

    public function getPetakTebangByUser(Request $request)
    {
        $userId = $request->input('user_id');
        if (!$userId) {
            return response()->json([
                'success' => false,
                'message' => 'user_id is required'
            ], 400);
        }

        try {
            $data = \DB::table('tx_petak_tebang')
                ->where('user_id', $userId)
                ->orderBy('createdOn', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to load data: ' . $e->getMessage()
            ], 500);
        }
    }

    public function getPetakTebangByPetak(Request $request)
    {
        $idPetak = $request->input('id_petak');
        if (!$idPetak) {
            return response()->json([
                'success' => false,
                'message' => 'id_petak is required'
            ], 400);
        }

        try {
            $data = \DB::table('tx_petak_tebang')
                ->where('id_petak', $idPetak)
                ->orderBy('createdOn', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to load data: ' . $e->getMessage()
            ], 500);
        }
    }

    public function getPetakTebangByBooking(Request $request)
    {
        $idBooking = $request->input('id_booking');
        if (!$idBooking) {
            return response()->json([
                'success' => false,
                'message' => 'id_booking is required'
            ], 400);
        }

        try {
            $data = \DB::table('tx_petak_tebang')
                ->leftJoin('tx_pos_keluar', 'tx_petak_tebang.nomor_booking', '=', 'tx_pos_keluar.kode_booking')
                ->leftJoin('master_pg', 'tx_petak_tebang.pg_penggiling', '=', 'master_pg.kode_pg')
                ->select('tx_petak_tebang.*', 'tx_pos_keluar.kode_booking as pos_keluar_kode_booking', 'tx_pos_keluar.spta as pos_keluar_spta', 'master_pg.nama_pg as pg_penggiling_nama')
                ->where('tx_petak_tebang.nomor_booking', $idBooking)
                ->orderBy('tx_petak_tebang.createdOn', 'desc')
                ->first();

            if ($data && $data->pos_keluar_kode_booking !== null) {
                return response()->json([
                    'success' => false,
                    'message' => 'Data sudah ada dengan nomor SPTA ' . ($data->pos_keluar_spta ?: '-')
                ]);
            }

            return response()->json([
                'success' => true,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to load data: ' . $e->getMessage()
            ], 500);
        }
    }

    public function getPosKeluarByUser(Request $request)
    {
        $userId = $request->input('user_id');
        if (!$userId) {
            return response()->json([
                'success' => false,
                'message' => 'user_id is required'
            ], 400);
        }

        try {
            $data = \DB::table('tx_pos_keluar')
                ->where('user_id', $userId)
                ->orderBy('createdOn', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to load data: ' . $e->getMessage()
            ], 500);
        }
    }

    public function uploadposkeluar(Request $request)
    {
        $validator = Validator::make($request->all(), [
          //  'kode_booking' => 'required|string',
       //     'spta' => 'required|string',
         //   'tanggal' => 'required|date',
            //'jam' => 'required',
        //    'sopir' => 'required|string',
      //      'user_id' => 'required',
      //      'thntnm' => 'required',
         //   'nomor_kendaraan' => 'required',
       //     'foto_kendaraan' => 'required|image|mimes:jpeg,png,jpg'
        ]);

        if ($validator->fails()) {
            return response()->json([
            'status' => 'error',
            'message' => 'Validation failed',
            'errors' => $validator->errors()
            ], 400);
        }

        try {

            // Check if booking code already exists
            $existingRecord = \DB::table('tx_pos_keluar')
                ->where('kode_booking', $request->kode_booking)
                ->first();

            // Check if booking code already exists
            $existingRecordSpta = \DB::table('tx_pos_keluar')
                ->where('spta', $request->spta)
                ->first();

            if ($existingRecord) {
                return response()->json([
                    'success' => true,
                    'status' => 'success',
                    'message' => 'Nomer Kode Booking sudah ada sebelumnya',
                    'id' => $existingRecord->id
                ]);
            }

            if ($existingRecordSpta) {
                return response()->json([
                    'success' => true,
                    'status' => 'success',
                    'message' => 'Nomer SPTA sudah ada sebelumnya',
                    'id' => $existingRecordSpta->id
                ]);
            }


            $fotoKendaraanPath = null;
            
            // Handle photo upload
            if ($request->hasFile('foto_kendaraan')) {
            $file = $request->file('foto_kendaraan');
            $fileName = time() . '_' . $file->getClientOriginalName();
            
            // Create directory if not exists
            $uploadPath = public_path('uploads/foto_kendaraan_poskeluar');
            if (!file_exists($uploadPath)) {
                mkdir($uploadPath, 0777, true);
            }
            
            // Compress image if larger than 1MB
            $tempPath = $file->getPathname();
            $compressedImage = $this->compressImage($tempPath, 1024 * 1024); // 1MB limit
            
            file_put_contents($uploadPath . '/' . $fileName, $compressedImage);
            $fotoKendaraanPath = 'uploads/foto_kendaraan_poskeluar/' . $fileName;
            }
            

            // Insert data into database
            \DB::table('tx_pos_keluar')->insert([
            'kode_booking' => $request->kode_booking,
            'spta' => $request->spta,
            'tanggal' => $request->tanggal,
            'jam' => $request->jam,
            'sopir' => $request->sopir,
            'lokasi' => $request->lokasi,
            'user_id' => $request->user_id,
            'thntnm' => $request->thntnm,
            'nomor_kendaraan' => $request->nomor_kendaraan,
            'foto_kendaraan' => $fotoKendaraanPath,
            'createdOn' => now(),
            'updatedOn' => now()
            ]);
            
            return response()->json([
            'success' => true,
            'status' => 'success',
            'message' => 'Data pos keluar berhasil disimpan',
            'id' => \DB::getPdo()->lastInsertId()
            ]);
        } catch (\Exception $e) {
            return response()->json([
            'status' => 'error',
            'message' => 'Gagal menyimpan data: ' . $e->getMessage()
            ], 500);
        }
    }

    public function uploadposselektor(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'spta' => 'required|string',
            'tanggal' => 'required|date',
            'jam' => 'required',
            'user_id' => 'required',
            'thntnm' => 'required',
            'foto_kendaraan' => 'required|image|mimes:jpeg,png,jpg'
        ]);

        if ($validator->fails()) {
            return response()->json([
            'status' => 'error',
            'message' => 'Validation failed',
            'errors' => $validator->errors()
            ], 400);
        }

        try {
            $fotoKendaraanPath = null;
            
            // Handle photo upload
            if ($request->hasFile('foto_kendaraan')) {
            $file = $request->file('foto_kendaraan');
            $fileName = time() . '_' . $file->getClientOriginalName();
            
            // Create directory if not exists
            $uploadPath = public_path('uploads/foto_kendaraan_posselektor');
            if (!file_exists($uploadPath)) {
                mkdir($uploadPath, 0777, true);
            }
            
            // Compress image if larger than 1MB
            $tempPath = $file->getPathname();
            $compressedImage = $this->compressImage($tempPath, 1024 * 1024); // 1MB limit
            
            file_put_contents($uploadPath . '/' . $fileName, $compressedImage);
            $fotoKendaraanPath = 'uploads/foto_kendaraan_posselektor/' . $fileName;
            }
            
            // Insert data into database
            \DB::table('tx_pos_selektor')->insert([ 
            'spta' => $request->spta,
            'tanggal' => $request->tanggal,
            'jam' => $request->jam,
            'user_id' => $request->user_id,
            'thntnm' => $request->thntnm,
            'foto_kendaraan' => $fotoKendaraanPath,
            'createdOn' => now(),
            'updatedOn' => now()
            ]);
            
            return response()->json([
            'success' => true,
            'status' => 'success',
            'message' => 'Data pos Selektor berhasil disimpan',
            'id' => \DB::getPdo()->lastInsertId()
            ]);
        } catch (\Exception $e) {
            return response()->json([
            'status' => 'error',
            'message' => 'Gagal menyimpan data: ' . $e->getMessage()
            ], 500);
        }
    }



    public function getPetakData(Request $request)
    {

        try {
            // Get data from q_takdes_petak table where afdeling is specified
            $userId = $request->input('user_id');

            $user = \DB::table('master_user_mobile')->where('id', $userId)->first();
            
            $query1 = \DB::table('q_takdes_petak as qtp')
                ->join('master_mapping_afd_pg as mmap', function($join) {
                    $join->whereRaw('FIND_IN_SET(qtp.afdeling, mmap.kode_afd)');
                })
                ->join('tx_ajuan_tebang as tat', function($join) {
                    $join->on('qtp.afdeling', '=', 'tat.afdeling')
                         ->on('tat.lahan_id', '=', 'qtp.lahan_id')
                         ->where('tat.status_ajuan', '=', 2);
                })
                ->selectRaw("qtp.lahan_id, qtp.afdeling, qtp.deskripsi_petak, qtp.luas_poligon, qtp.nama_kebun, qtp.kode_kebun, ROUND(tat.luas_poligon/ROUND((tat.taksasi_ton/(select bobot from master_bobot_pertruk where kode_kebun = qtp.kode_kebun and jenis_angkutan = tat.jenis_kendaraan_angkutan))),3) as luas_per_spta");
            
            if ($userId) {
                $query1->where('mmap.user_id', $userId);
            }

            $query2 = \DB::table('master_mandor_tebang as qtp')
                ->join('master_mapping_afd_pg as mmap', function($join) {
                    $join->whereRaw('FIND_IN_SET(qtp.afdeling, mmap.kode_afd)');
                })
                ->select('qtp.nik', 'qtp.nama');
            
            if ($userId) {
                $query2->where('mmap.user_id', $userId);
            }

            $query3 = \DB::table('master_tarif_vendor_gl as a')
                ->join('master_vendor_gl as b', 'a.id_vendor', '=', 'b.kode_vendor')
                ->select('b.kode_vendor', 'b.nama_vendor')
                ->where('a.kode_kebun', $user->kebun)
                ->groupBy('b.id')
                ->orderBy('b.id', 'asc');

            $query4 = \DB::table('master_tarif_vendor_angkutan as a')
                ->join('master_vendor_angkutan as b', 'a.id_vendor', '=', 'b.kode_vendor')
                ->select('b.kode_vendor', 'b.nama_vendor')
                ->where('a.kode_kebun', $user->kebun)
                ->groupBy('b.id')
                ->orderBy('b.id', 'asc');
            

            $query5 = \DB::table('master_vendor_mekanis as qtp')
                ->select('qtp.kode_vendor', 'qtp.nama_vendor');


            $query6 = \DB::table('master_tarif_vendor_angkutan as a')
                ->join('master_tarif as b', 'a.id_range', '=', 'b.id')
                ->select('b.id', 'b.deskripsi')
                ->where('a.kode_kebun', $user->kebun)
                ->groupBy('b.id')
                ->orderBy('b.id', 'asc');
            
            
            $data['petak'] = $query1->get();
            $data['mandor'] = $query2->get();
            $data['vendor'] = $query3->get();
            $data['vendorangkutan'] = $query4->get();
            $data['vendormekanis'] = $query5->get();
            $data['tarifvendorangkutan'] = $query6->get();
            
            return response()->json([
                'status' => 'success',
                'data' => $data
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to retrieve data: ' . $e->getMessage()
            ]);
        }
    }

    public function trackPetakTebang(Request $request, $nomorTruk)
    {
        try {
            $data = \DB::table(\DB::raw('(
                SELECT *
                FROM tx_petak_tebang
                WHERE nomor_kendaraan = ?
                   OR nomor_booking = ?
                ORDER BY createdOn DESC
                LIMIT 5
            ) a'), [])->setBindings([trim($nomorTruk), trim($nomorTruk)])
                ->join('q_takdes_petak as b', 'a.id_petak', '=', 'b.lahan_id')
                ->leftJoin('tx_pos_keluar as c', function($join) {
                    $join->on('a.nomor_booking', '=', 'c.kode_booking')
                         ->on('a.tanggal', '=', 'c.tanggal');
                })
                ->leftJoin('master_pg as d', 'a.pg_penggiling', '=', 'd.kode_pg')
                ->leftJoin('master_mandor_tebang as mmt', 'mmt.nik', '=', 'a.mandor_tebang')
                ->leftJoin('master_vendor_gl as v', 'v.kode_vendor', '=', 'a.vendor_gl')
                ->leftJoin('data_selektor as ds', 'c.spta', '=', 'ds.no_spta')
                ->leftJoin('data_timbangan as dt', 'c.spta', '=', 'dt.no_spta')
                ->leftJoin('data_meja_tebu as dm', 'c.spta', '=', 'dm.no_spta')
                ->leftJoin('tx_pos_selektor as ps', 'c.spta', '=', 'ps.spta')
                ->select('a.*', 'b.nama_kebun', 'b.afdeling', 'b.asman', 'c.spta', 
                         'c.foto_kendaraan as foto_poskeluar', 'ps.foto_kendaraan as foto_posselektor',
                         'c.sopir', 'd.nama_pg as pg_penggiling', 'mmt.nama as mandor_tebang',
                         'v.nama_vendor', 'ds.selektor as tgl_selektor', 'dt.tgl_netto as tgl_timbangan',
                         'dm.meja_tebu as tgl_giling')
                ->orderBy('a.createdOn', 'desc')
                ->get();

            $formattedData = $data->map(function ($item) {
                return [
                    'nomor_booking' => $item->nomor_booking,
                    'id_petak' => $item->id_petak,
                    'tanggal' => $this->formatDate($item->tanggal),
                    'jam' => $item->jam,
                    'nama_vendor' => $item->nama_vendor,
                    'luas_tebang' => (float) $item->luas_tebang,
                    'jenis_tebang' => $item->jenis_tebang,
                    'pg_penggiling' => $item->pg_penggiling,
                    'mandor_tebang' => $item->mandor_tebang ?? null,
                    'jenis_kendaraan' => $item->jenis_kendaraan,
                    'nomor_gl' => $item->nomor_gl,
                    'nomor_ch' => $item->nomor_ch,
                    'brix_kebun' => (float) $item->brix_kebun,
                    'spta' => $item->spta ?? null,
                    'nama_kebun' => $item->nama_kebun,
                    'afdeling' => $item->afdeling,
                    'asman' => $item->asman,
                    'foto_kendaraan' => $item->foto_kendaraan,
                    'foto_poskeluar' => $item->foto_poskeluar ?? null,
                    'foto_posselektor' => $item->foto_posselektor ?? null,
                    'link_foto_kendaraan' => "https://difa.ksotebu.com/".$item->foto_kendaraan,
                    'link_foto_poskeluar' => $item->foto_poskeluar ? "https://difa.ksotebu.com/".$item->foto_poskeluar : null,
                    'link_foto_posselektor' => $item->foto_posselektor ? "https://difa.ksotebu.com/".$item->foto_posselektor : null,
                    'sopir' => $item->sopir ?? null,
                    'status' => $item->status ?? 'completed',
                    'tgl_selektor' => $item->tgl_selektor ?? null,
                    'tgl_timbangan' => $item->tgl_timbangan ?? null,
                    'tgl_giling' => $item->tgl_giling ?? null,
                    'created_at' => $item->createdOn

                ];
            });

            return response()->json([
                'status' => 'success',
                'data' => $formattedData
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to retrieve tracking data: ' . $e->getMessage()
            ], 500);
        }
    }

    public function resetPassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|string',
            'new_password' => 'required|string|min:6'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 400);
        }

        $id = $request->input('id');
        $newPassword = $request->input('new_password');

        $user = \DB::table('master_user_mobile')->where('id', $id)->first();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'Id tidak ditemukan'
            ], 404);
        }

        try {
            \DB::table('master_user_mobile')
                ->where('id', $id)
                ->update([
                    'password' => \Hash::make($newPassword),
                    'updatedOn' => now()
                ]);

            return response()->json([
                'success' => true,
                'message' => 'Password berhasil direset'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal reset password: ' . $e->getMessage()
            ], 500);
        }
    }

    private function formatDate($date)
    {
        if (!$date) {
            return null;
        }

        try {
            // Check if date is in d/m/Y format (e.g., 13/01/2026)
            if (preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $date)) {
                $dateTime = \DateTime::createFromFormat('d/m/Y', $date);
                if ($dateTime) {
                    return $dateTime->format('Y-m-d');
                }
            }
            
            // Return original date if not in expected format
            return $date;
        } catch (\Exception $e) {
            return $date;
        }
    }

    public function health(Request $request)
    {
        try {
            // Check database connection
            \DB::connection()->getPdo();
            
            return response()->json([
                'status' => 'success',
                'message' => 'Service is healthy',
                'timestamp' => now()->toISOString()
            ]);
            
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Service unhealthy: ' . $e->getMessage(),
                'timestamp' => now()->toISOString()
            ], 500);
        }
    }
    public function assetsDownload( Request $request)
    {
        // Get all files from resources/views/masterkonten/mobile directory
        $mobileViewsPath = resource_path('views/masterkonten/mobile');
        
        if (!is_dir($mobileViewsPath)) {
            return response()->json(['status' => 'error', 'message' => 'Mobile views directory not found']);
        }
        
        $files = [];
        $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($mobileViewsPath));
        
        foreach ($iterator as $file) {
            if ($file->isFile()) {
            $relativePath = str_replace($mobileViewsPath . '/', '', $file->getPathname());
            $content = file_get_contents($file->getPathname());
            
            $files[] = [
                'name' => $relativePath,
                'content' => $content
            ];
            }
        }
        
        return response()->json([
            'status' => 'success',
            'files' => $files
        ]);
    }

   

    private function compressImage($filePath, $maxFileSize)
    {
        $imageInfo = getimagesize($filePath);
        $mimeType = $imageInfo['mime'];
        
        switch ($mimeType) {
            case 'image/jpeg':
                $image = imagecreatefromjpeg($filePath);
                break;
            case 'image/png':
                $image = imagecreatefrompng($filePath);
                break;
            case 'image/gif':
                $image = imagecreatefromgif($filePath);
                break;
            default:
                throw new \Exception('Unsupported image type: ' . $mimeType);
        }
        
        $quality = 90; // Start with high quality
        ob_start();
        imagejpeg($image, null, $quality);
        $compressedImage = ob_get_clean();
        
        while (strlen($compressedImage) > $maxFileSize && $quality > 10) {
            $quality -= 10;
            ob_start();
            imagejpeg($image, null, $quality);
            $compressedImage = ob_get_clean();
        }
        
        imagedestroy($image);
        
        return $compressedImage;
    }

    public function DashboardView( Request $request )
    {
        $id = 39;
		$getdata = \DB::table('master_konten')->where('id', $id)->first();
		if(!$getdata)
		{
			return response()->json(array(
				'status'=>'error',
				'message'=> 'Record Not Found'
			));
		}
       $content = '';
		$moduleFolder = base_path('resources/views/masterkonten/module');
		$filePath = $moduleFolder . '/' . $getdata->filename;
		if (is_file($filePath)) {
			$content = file_get_contents($filePath);
		} else {
			$content = 'File not found.';
		}

        $bladeFile = str_replace('.blade.php', '', $getdata->filename);
        $this->data['mobile'] = '1';
		$this->data['content'] = view('masterkonten.module.'.$bladeFile, $this->data)->with('content', $content)->render();
		return view('masterkonten.page',$this->data);
    }

    public function DashboardDigifarm( Request $request )
    {
         $id = 53;
		$getdata = \DB::table('master_konten')->where('id', $id)->first();
		if(!$getdata)
		{
			return response()->json(array(
				'status'=>'error',
				'message'=> 'Record Not Found'
			));
		}
       $content = '';
		$moduleFolder = base_path('resources/views/masterkonten/module');
		$filePath = $moduleFolder . '/' . $getdata->filename;
		if (is_file($filePath)) {
			$content = file_get_contents($filePath);
		} else {
			$content = 'File not found.';
		}

        $bladeFile = str_replace('.blade.php', '', $getdata->filename);
        $this->data['mobile'] = '1';
        if ($request->hasHeader('Authorization')) {
            $authHeader = $request->header('Authorization');
            if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
                $token = $matches[1];
                $this->data['token'] = $token;
            }
        }
        if ($request->has('thntnm')) {
            $thntnm = $request->input('thntnm');
            if ($thntnm == '2526') {
                Config::set('database.default', session('database_name', 'mysql_2526'));
            }
        }
		$this->data['content'] = view('masterkonten.module.'.$bladeFile, $this->data)->with('content', $content)->render();
		return view('masterkonten.page',$this->data);
    }

        /**
         * Helper: resolve filter parameters dari request + token user.
         * Mengembalikan array [tgl, kode_kebun, kode_rayon, afdeling, namakebun, namarayon].
         */
        private function resolveFilterFromRequest(Request $request): array
        {
            $tgl        = $request->input('tanggal');
            $kode_kebun = $request->input('kebun');
            $kode_rayon = $request->input('rayon');
            $afdeling   = $request->input('afdeling');
            $namakebun  = '';
            $namarayon  = '';

            $getuser = \DB::table('master_user_mobile')
                ->join('tb_token', 'tb_token.userId', '=', 'master_user_mobile.id')
                ->join('master_kebun', 'master_kebun.kode_kebun', '=', 'master_user_mobile.kebun')
                ->join('master_rayon', 'master_rayon.kode_rayon', '=', 'master_user_mobile.rayon')
                ->where('tb_token.token', $request->input('token'))
                ->where('master_user_mobile.group_id', '>', 8)
                ->first();

            if ($getuser) {
                if ($getuser->kebun) {
                    $kode_kebun = $getuser->kebun;
                    $namakebun  = $getuser->nama_kebun;
                }
                if ($getuser->rayon) {
                    $kode_rayon = $getuser->rayon;
                    $namarayon  = $getuser->nama_rayon;
                }
            }

            return compact('tgl', 'kode_kebun', 'kode_rayon', 'afdeling', 'namakebun', 'namarayon');
        }

        /**
         * Fungsi 1: Hitung jumlah petak_tebang, pos_keluar, dan pos_selektor
         * (s.d. tanggal & hari ini).
         */
        public function getPetakCountData(Request $request)
        {
            [
                'tgl'        => $tgl,
                'kode_kebun' => $kode_kebun,
                'kode_rayon' => $kode_rayon,
                'afdeling'   => $afdeling,
                'namakebun'  => $namakebun,
                'namarayon'  => $namarayon,
            ] = $this->resolveFilterFromRequest($request);

            try {
                // --- Query 1: Petak Tebang s.d. tanggal ---
                $query1 = \DB::table('tx_petak_tebang as a')
                    ->join('q_takdes_petak as b', 'b.lahan_id', '=', 'a.id_petak')
                    ->selectRaw('count(*) as jml_petak');
                if ($tgl)        $query1->where('a.tanggal', '<=', $tgl);
                if ($kode_kebun) $query1->where('b.kode_kebun', $kode_kebun);
                if ($kode_rayon) $query1->where('b.kode_rayon', $kode_rayon);
                if ($afdeling)   $query1->where('b.afdeling', $afdeling);
                $result1 = $query1->first();

                // --- Query 1hi: Petak Tebang hari ini ---
                $query1hi = \DB::table('tx_petak_tebang as a')
                    ->join('q_takdes_petak as b', 'b.lahan_id', '=', 'a.id_petak')
                    ->selectRaw('count(*) as jml_petak');
                if ($tgl)        $query1hi->where('a.tanggal', $tgl);
                if ($kode_kebun) $query1hi->where('b.kode_kebun', $kode_kebun);
                if ($kode_rayon) $query1hi->where('b.kode_rayon', $kode_rayon);
                if ($afdeling)   $query1hi->where('b.afdeling', $afdeling);
                $result1hi = $query1hi->first();

                // --- Query 2: Pos Keluar s.d. tanggal ---
                $query2 = \DB::table(\DB::raw('(
                    select count(*) as jml_petak
                    from tx_pos_keluar as a
                    join tx_petak_tebang as c on a.kode_booking = c.nomor_booking
                    join q_takdes_petak as b on b.lahan_id = c.id_petak
                    ' .
                    ($tgl        ? "where a.tanggal <= '" . addslashes($tgl) . "'" : "") .
                    ($kode_kebun ? ($tgl ? " and " : "where ") . "b.kode_kebun = '" . addslashes($kode_kebun) . "'" : "") .
                    ($kode_rayon ? (($tgl || $kode_kebun) ? " and " : "where ") . "b.kode_rayon = '" . addslashes($kode_rayon) . "'" : "") .
                    ($afdeling   ? (($tgl || $kode_kebun || $kode_rayon) ? " and " : "where ") . "b.afdeling = '" . addslashes($afdeling) . "'" : "") .
                    ' group by a.spta
                ) as z'));
                $result2 = $query2->selectRaw('sum(z.jml_petak) as jml_petak')->first();

                // --- Query 2hi: Pos Keluar hari ini ---
                $query2hi = \DB::table(\DB::raw('(
                    select count(*) as jml_petak
                    from tx_pos_keluar as a
                    join tx_petak_tebang as c on a.kode_booking = c.nomor_booking
                    join q_takdes_petak as b on b.lahan_id = c.id_petak
                    ' .
                    ($tgl        ? "where a.tanggal = '" . addslashes($tgl) . "'" : "") .
                    ($kode_kebun ? ($tgl ? " and " : "where ") . "b.kode_kebun = '" . addslashes($kode_kebun) . "'" : "") .
                    ($kode_rayon ? (($tgl || $kode_kebun) ? " and " : "where ") . "b.kode_rayon = '" . addslashes($kode_rayon) . "'" : "") .
                    ($afdeling   ? (($tgl || $kode_kebun || $kode_rayon) ? " and " : "where ") . "b.afdeling = '" . addslashes($afdeling) . "'" : "") .
                    ' group by a.spta
                ) as z'));
                $result2hi = $query2hi->selectRaw('sum(z.jml_petak) as jml_petak')->first();

                // --- Query 3: Pos Selektor s.d. tanggal ---
                $query3 = \DB::table(\DB::raw('(
                    SELECT COUNT(*) AS jml_petak
                    FROM data_selektor a
                    join tx_pos_keluar as b on b.spta = a.no_spta
                    join tx_petak_tebang as c on b.kode_booking = c.nomor_booking
                    JOIN tx_ajuan_tebang d ON d.lahan_id = a.no_petak
                    ' .
                    ($tgl        ? "WHERE a.tgl_selektor <= '" . addslashes($tgl) . "'" : "") .
                    ($kode_kebun ? ($tgl ? " AND " : "WHERE ") . "left(d.rayon,4) = '" . addslashes($kode_kebun) . "'" : "") .
                    ($kode_rayon ? (($tgl || $kode_kebun) ? " AND " : "WHERE ") . "d.rayon = '" . addslashes($kode_rayon) . "'" : "") .
                    ($afdeling   ? (($tgl || $kode_kebun || $kode_rayon) ? " AND " : "WHERE ") . "d.afdeling = '" . addslashes($afdeling) . "'" : "") .
                    ' GROUP BY a.no_spta
                ) as g'));
                $query3->selectRaw('sum(g.jml_petak) as jml_petak');
                $result3 = $query3->first();

                // --- Query 3hi: Pos Selektor hari ini ---
                $query3hi = \DB::table(\DB::raw('(
                    SELECT COUNT(*) AS jml_petak
                    FROM data_selektor a
                    join tx_pos_keluar as b on b.spta = a.no_spta
                    join tx_petak_tebang as c on b.kode_booking = c.nomor_booking
                    JOIN tx_ajuan_tebang d ON d.lahan_id = a.no_petak
                    ' .
                    ($tgl        ? "WHERE a.tgl_selektor = '" . addslashes($tgl) . "'" : "") .
                    ($kode_kebun ? ($tgl ? " AND " : "WHERE ") . "left(d.rayon,4) = '" . addslashes($kode_kebun) . "'" : "") .
                    ($kode_rayon ? (($tgl || $kode_kebun) ? " AND " : "WHERE ") . "d.rayon = '" . addslashes($kode_rayon) . "'" : "") .
                    ($afdeling   ? (($tgl || $kode_kebun || $kode_rayon) ? " AND " : "WHERE ") . "d.afdeling = '" . addslashes($afdeling) . "'" : "") .
                    ' GROUP BY a.no_spta
                ) as g'));
                $query3hi->selectRaw('sum(g.jml_petak) as jml_petak');
                $result3hi = $query3hi->first();

                return response()->json([
                    'success' => true,
                    'data'    => [
                        'petak_tebang'          => $result1->jml_petak   ?? 0,
                        'pos_keluar'            => $result2->jml_petak   ?? 0,
                        'petak_tebang_hari_ini' => $result1hi->jml_petak ?? 0,
                        'pos_keluar_hari_ini'   => $result2hi->jml_petak ?? 0,
                        'pos_selektor'          => $result3->jml_petak   ?? 0,
                        'pos_selektor_hari_ini' => $result3hi->jml_petak ?? 0,
                        'kebun'                 => $namakebun ?? null,
                        'kode_kebun'            => $kode_kebun ?? null,
                        'rayon'                 => $namarayon ?? null,
                        'kode_rayon'            => $kode_rayon ?? null,
                        'afdeling'              => $afdeling   ?? null,
                    ],
                ]);
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'message' => 'Query failed: ' . $e->getMessage()]);
            }
        }

        /**
         * Fungsi 2: Analisis waktu tempuh (s.d. tanggal & hari ini).
         */
        public function getAnalisisWaktuTempuh(Request $request)
        {
            [
                'tgl'        => $tgl,
                'kode_kebun' => $kode_kebun,
                'kode_rayon' => $kode_rayon,
                'afdeling'   => $afdeling,
                'namakebun'  => $namakebun,
                'namarayon'  => $namarayon,
            ] = $this->resolveFilterFromRequest($request);

            try {
                $baseFrom = '
                    FROM data_selektor AS a
                    JOIN tx_pos_keluar AS b ON b.spta = a.no_spta
                    JOIN tx_petak_tebang AS c ON b.kode_booking = c.nomor_booking
                    JOIN q_takdes_petak as d ON d.lahan_id = c.id_petak
                    JOIN master_pos_keluar e ON e.id = b.lokasi
                    JOIN master_pos_keluar_detail f
                        ON f.id_pos = e.kode_pos
                        AND f.pg_penggiling = c.pg_penggiling
                ';

                $baseSelect = '
                    TIMESTAMPDIFF(MINUTE, CONCAT(b.tanggal, " ", b.jam), a.selektor) AS selisih_menit,
                    f.waktu_tempuh_normal,
                    CASE
                        WHEN TIMESTAMPDIFF(MINUTE, CONCAT(b.tanggal, " ", b.jam), a.selektor) > f.waktu_tempuh_normal THEN "Terlalu Lambat"
                        WHEN TIMESTAMPDIFF(MINUTE, CONCAT(b.tanggal, " ", b.jam), a.selektor) < f.waktu_tempuh_normal THEN "Terlalu Cepat"
                        ELSE "Wajar"
                    END AS kategori,
                    COUNT(*) as jml_spta
                ';

                $outerSelect = '
                    kategori,
                    AVG(selisih_menit) AS rata_rata_menit,
                    SUM(jml_spta) AS jumlah_data,
                    ROUND(SUM(jml_spta) / SUM(SUM(jml_spta)) OVER () * 100, 2) AS prosentase
                ';

                // S.d. tanggal
                $whereSD = ($tgl        ? "WHERE b.tanggal <= '" . addslashes($tgl) . "'"                                                    : "")
                         . ($kode_kebun ? (($tgl                                 ? " AND " : "WHERE ") . "d.kode_kebun = '" . addslashes($kode_kebun) . "'") : "")
                         . ($kode_rayon ? ((($tgl || $kode_kebun)                ? " AND " : "WHERE ") . "d.kode_rayon = '" . addslashes($kode_rayon) . "'") : "")
                         . ($afdeling   ? ((($tgl || $kode_kebun || $kode_rayon) ? " AND " : "WHERE ") . "d.afdeling = '"   . addslashes($afdeling)   . "'") : "");

                $analisisSD = \DB::table(\DB::raw('(SELECT ' . $baseSelect . $baseFrom . $whereSD . ' GROUP BY c.pg_penggiling, kategori) x'))
                    ->selectRaw($outerSelect)
                    ->groupBy('kategori')
                    ->get();

                // Hari ini
                $whereHI = ($tgl        ? "WHERE b.tanggal = '" . addslashes($tgl) . "'"                                                     : "")
                         . ($kode_kebun ? (($tgl                                 ? " AND " : "WHERE ") . "d.kode_kebun = '" . addslashes($kode_kebun) . "'") : "")
                         . ($kode_rayon ? ((($tgl || $kode_kebun)                ? " AND " : "WHERE ") . "d.kode_rayon = '" . addslashes($kode_rayon) . "'") : "")
                         . ($afdeling   ? ((($tgl || $kode_kebun || $kode_rayon) ? " AND " : "WHERE ") . "d.afdeling = '"   . addslashes($afdeling)   . "'") : "");

                $analisisHI = \DB::table(\DB::raw('(SELECT ' . $baseSelect . $baseFrom . $whereHI . ' GROUP BY c.pg_penggiling, kategori) x'))
                    ->selectRaw($outerSelect)
                    ->groupBy('kategori')
                    ->get();

                return response()->json([
                    'success' => true,
                    'data'    => [
                        'analisis_waktu_tempuh'          => $analisisSD->toArray(),
                        'analisis_waktu_tempuh_hari_ini' => $analisisHI->toArray(),
                        'kebun'                          => $namakebun ?? null,
                        'rayon'                          => $namarayon ?? null,
                    ],
                ]);
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'message' => 'Query failed: ' . $e->getMessage()]);
            }
        }

        /**
         * Fungsi 3: Analisis Cut to Crush & Kualitas Tebu.
         */
        public function getAnalisisCutToCrushDanKualitas(Request $request)
        {
            [
                'tgl'        => $tgl,
                'kode_kebun' => $kode_kebun,
                'kode_rayon' => $kode_rayon,
                'afdeling'   => $afdeling,
                'namakebun'  => $namakebun,
                'namarayon'  => $namarayon,
            ] = $this->resolveFilterFromRequest($request);

            try {
                $tglExpr = $tgl ? "'" . addslashes($tgl) . "'" : "CURDATE()";

                // --- Analisis Cut to Crush ---
                $cutToCrush = \DB::table(\DB::raw('(
                    SELECT
                        TIMESTAMPDIFF(MINUTE, CONCAT(c.tanggal, " ", c.jam), g.meja_tebu) AS cut_to_crush_menit,
                        g.meja_tebu AS tgl_giling,
                        CASE
                            WHEN TIMESTAMPDIFF(HOUR, CONCAT(c.tanggal, " ", c.jam), g.meja_tebu) > 48 THEN "Terlalu Lambat"
                            WHEN TIMESTAMPDIFF(HOUR, CONCAT(c.tanggal, " ", c.jam), g.meja_tebu) < 24 THEN "Terlalu Cepat"
                            ELSE "Wajar"
                        END AS kategori,
                        COUNT(*) AS jml_spta,
                        SUM(CASE WHEN DATE(g.meja_tebu) = ' . $tglExpr . ' THEN f.netto_final_kg / 1000 ELSE 0 END) AS ton_hi,
                        SUM(CASE WHEN DATE(g.meja_tebu) <= ' . $tglExpr . ' THEN f.netto_final_kg / 1000 ELSE 0 END) AS ton_sd
                    FROM data_selektor AS a
                    JOIN tx_pos_keluar AS b ON b.spta = a.no_spta
                    JOIN tx_petak_tebang AS c ON b.kode_booking = c.nomor_booking
                    JOIN master_pos_keluar d ON d.id = b.lokasi
                    JOIN master_pos_keluar_detail e ON e.id_pos = d.kode_pos AND e.pg_penggiling = c.pg_penggiling
                    JOIN data_timbangan f ON f.no_spta = a.no_spta
                    JOIN data_meja_tebu g ON g.no_spta = f.no_spta
                    JOIN q_takdes_petak h ON h.lahan_id = c.id_petak
                    WHERE g.meja_tebu IS NOT NULL AND c.tanggal IS NOT NULL
                    ' .
                    ($tgl        ? "AND c.tanggal <= '" . addslashes($tgl)        . "'" : "") .
                    ($kode_kebun ? " AND h.kode_kebun = '" . addslashes($kode_kebun) . "'" : "") .
                    ($kode_rayon ? " AND h.kode_rayon = '" . addslashes($kode_rayon) . "'" : "") .
                    ($afdeling   ? " AND h.afdeling = '"   . addslashes($afdeling)   . "'" : "") .
                    ' GROUP BY kategori
                ) x'))
                ->selectRaw('
                    kategori,
                    AVG(cut_to_crush_menit) AS rata_rata_menit_sd,
                    AVG(CASE WHEN DATE(tgl_giling) = ' . $tglExpr . ' THEN cut_to_crush_menit ELSE NULL END) AS rata_rata_menit_hi,
                    SUM(jml_spta) AS jumlah_spta,
                    ROUND(SUM(ton_hi), 2) AS ton_tebu_hi,
                    ROUND(SUM(ton_sd), 2) AS ton_tebu_sd,
                    ROUND(SUM(jml_spta) / SUM(SUM(jml_spta)) OVER () * 100, 2) AS persen_spta,
                    ROUND(SUM(ton_hi)   / SUM(SUM(ton_hi))   OVER () * 100, 2) AS persen_ton_hi,
                    ROUND(SUM(ton_sd)   / SUM(SUM(ton_sd))   OVER () * 100, 2) AS persen_ton_sd
                ')
                ->groupBy('kategori')
                ->get();

                // --- Analisis Kualitas Tebu ---
                $kualitasTebu = \DB::table(\DB::raw('(
                    SELECT
                        g.kualitas,
                        SUM(CASE WHEN DATE(g.meja_tebu) = ' . $tglExpr . ' THEN h.netto_final_kg / 1000 ELSE 0 END) AS ton_hi,
                        SUM(CASE WHEN DATE(g.meja_tebu) <= ' . $tglExpr . ' THEN h.netto_final_kg / 1000 ELSE 0 END) AS ton_sd
                    FROM data_selektor AS a
                    JOIN tx_pos_keluar AS b ON b.spta = a.no_spta
                    JOIN tx_petak_tebang AS c ON b.kode_booking = c.nomor_booking
                    JOIN q_takdes_petak AS d ON d.lahan_id = c.id_petak
                    JOIN master_pos_keluar e ON e.id = b.lokasi
                    JOIN master_pos_keluar_detail f ON f.id_pos = e.kode_pos AND f.pg_penggiling = c.pg_penggiling
                    JOIN data_timbangan h ON h.no_spta = a.no_spta
                    JOIN data_meja_tebu g ON g.no_spta = a.no_spta
                    WHERE g.meja_tebu IS NOT NULL AND c.tanggal IS NOT NULL
                    ' .
                    ($tgl        ? "AND c.tanggal <= '" . addslashes($tgl)        . "'" : "") .
                    ($kode_kebun ? " AND d.kode_kebun = '" . addslashes($kode_kebun) . "'" : "") .
                    ($kode_rayon ? " AND d.kode_rayon = '" . addslashes($kode_rayon) . "'" : "") .
                    ($afdeling   ? " AND d.afdeling = '"   . addslashes($afdeling)   . "'" : "") .
                    ' GROUP BY g.kualitas
                ) x'))
                ->selectRaw('
                    kualitas,
                    ROUND(ton_hi, 2) AS ton_hi,
                    ROUND(ton_sd, 2) AS ton_sd,
                    ROUND(ton_hi / SUM(ton_hi) OVER () * 100, 2) AS persen_ton_hi,
                    ROUND(ton_sd / SUM(ton_sd) OVER () * 100, 2) AS persen_ton_sd
                ')
                ->get();

                return response()->json([
                    'success' => true,
                    'data'    => [
                        'analisis_cut_to_crush'  => $cutToCrush->toArray(),
                        'analisis_kualitas_tebu' => $kualitasTebu->toArray(),
                        'kebun'                  => $namakebun ?? null,
                        'rayon'                  => $namarayon ?? null,
                    ],
                ]);
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'message' => 'Query failed: ' . $e->getMessage()]);
            }
        }

        public function getJmlPetakPerAfdeling(Request $request)
        {
            [
                'tgl'        => $tgl,
                'kode_kebun' => $kode_kebun,
                'kode_rayon' => $kode_rayon,
                'afdeling'   => $afdeling,
                'namakebun'  => $namakebun,
                'namarayon'  => $namarayon,
            ] = $this->resolveFilterFromRequest($request);

            try {
                $dataSd = DB::select(
                    'SELECT b.afdeling, COUNT(*) as jml_petak_sd
                    FROM tx_petak_tebang as a
                    JOIN q_takdes_petak as b ON b.lahan_id = a.id_petak ' .
                    ($tgl        ? "where a.tanggal <= '" . addslashes($tgl) . "'" : "") .
                    ($kode_kebun ? ($tgl ? " and " : "where ") . "b.kode_kebun = '" . addslashes($kode_kebun) . "'" : "") .
                    ($kode_rayon ? (($tgl || $kode_kebun) ? " and " : "where ") . "b.kode_rayon = '" . addslashes($kode_rayon) . "'" : "") .
                    ($afdeling   ? (($tgl || $kode_kebun || $kode_rayon) ? " and " : "where ") . "b.afdeling = '" . addslashes($afdeling) . "'" : "") .
                    ' GROUP BY b.afdeling'
                );

                $dataHi = DB::select(
                    'SELECT b.afdeling, COUNT(*) as jml_petak_hi
                    FROM tx_petak_tebang as a
                    JOIN q_takdes_petak as b ON b.lahan_id = a.id_petak ' .
                    ($tgl        ? "where a.tanggal = '" . addslashes($tgl) . "'" : "") .
                    ($kode_kebun ? ($tgl ? " and " : "where ") . "b.kode_kebun = '" . addslashes($kode_kebun) . "'" : "") .
                    ($kode_rayon ? (($tgl || $kode_kebun) ? " and " : "where ") . "b.kode_rayon = '" . addslashes($kode_rayon) . "'" : "") .
                    ($afdeling   ? (($tgl || $kode_kebun || $kode_rayon) ? " and " : "where ") . "b.afdeling = '" . addslashes($afdeling) . "'" : "") .
                    ' GROUP BY b.afdeling'
                );

                // Merge by afdeling
                $sdMap = collect($dataSd)->keyBy('afdeling');
                $hiMap = collect($dataHi)->keyBy('afdeling');
                $afdelings = $sdMap->keys()->merge($hiMap->keys())->unique()->sort()->values();

                $totalSd = 0;
                $totalHi = 0;

                $html  = '<style>';
                $html .= '.petak-table { width:100%; border-collapse:collapse; font-family:sans-serif; font-size:13px; }';
                $html .= '.petak-table thead tr { background: linear-gradient(135deg, #2e7d32, #66bb6a); color:#fff; }';
                $html .= '.petak-table thead th { padding:10px 8px; text-align:center; font-weight:600; letter-spacing:0.3px; }';
                $html .= '.petak-table tbody tr:nth-child(even) { background-color:#f1f8e9; }';
                $html .= '.petak-table tbody tr:nth-child(odd) { background-color:#ffffff; }';
                $html .= '.petak-table tbody tr:hover { background-color:#dcedc8; transition:background 0.2s; }';
                $html .= '.petak-table tbody td { padding:9px 8px; border-bottom:1px solid #c8e6c9; }';
                $html .= '.petak-table .col-afd { font-weight:600; color:#1b5e20; }';
                $html .= '.petak-table .col-num { text-align:right; color:#333; }';
                $html .= '.petak-table tfoot tr { background:#e8f5e9; font-weight:700; border-top:2px solid #388e3c; }';
                $html .= '.petak-table tfoot td { padding:9px 8px; color:#1b5e20; }';
                $html .= '.petak-label { font-size:11px; color:#888; display:block; font-weight:400; }';
                $html .= '</style>';

                $html .= '<table class="petak-table">';
                $html .= '<thead><tr>'
                    . '<th>Afdeling</th>'
                    . '<th>S/D<span class="petak-label text-white">' . htmlspecialchars($tgl) . '</span></th>'
                    . '<th>HI<span class="petak-label text-white">' . htmlspecialchars($tgl) . '</span></th>'
                    . '</tr></thead><tbody>';

                foreach ($afdelings as $afdeling) {
                    $sd = $sdMap->get($afdeling);
                    $hi = $hiMap->get($afdeling);
                    $sdVal = $sd ? $sd->jml_petak_sd : 0;
                    $hiVal = $hi ? $hi->jml_petak_hi : 0;
                    $totalSd += $sdVal;
                    $totalHi += $hiVal;
                    $html .= '<tr>'
                        . '<td class="col-afd">' . htmlspecialchars($afdeling) . '</td>'
                        . '<td class="col-num">' . number_format($sdVal) . '</td>'
                        . '<td class="col-num">' . number_format($hiVal) . '</td>'
                        . '</tr>';
                }

                $html .= '</tbody>';
                $html .= '<tfoot><tr>'
                    . '<td>Total</td>'
                    . '<td class="col-num">' . number_format($totalSd) . '</td>'
                    . '<td class="col-num">' . number_format($totalHi) . '</td>'
                    . '</tr></tfoot>';
                $html .= '</table>';

                return response()->json([
                    'success' => true,
                    'html'    => $html,
                    'data'    => [
                        'sd' => $dataSd,
                        'hi' => $dataHi,
                    ],
                ]);
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'message' => 'Query failed: ' . $e->getMessage()]);
            }
        }

        public function getJmlPetakPosKeluarPerAfdeling(Request $request)
        {
            [
                'tgl'        => $tgl,
                'kode_kebun' => $kode_kebun,
                'kode_rayon' => $kode_rayon,
                'afdeling'   => $afdeling,
                'namakebun'  => $namakebun,
                'namarayon'  => $namarayon,
            ] = $this->resolveFilterFromRequest($request);

            try {
                // S/D: tanggal <= $tgl, grouped by spta then by afdeling
                $dataSd = DB::select(
                    'SELECT z.afdeling, sum(z.jml_petak) as jml_petak_sd
                    FROM (
                        SELECT b.afdeling, COUNT(*) as jml_petak
                        FROM tx_pos_keluar as a
                        JOIN tx_petak_tebang as c ON a.kode_booking = c.nomor_booking
                        JOIN q_takdes_petak as b ON b.lahan_id = c.id_petak
                        WHERE 1=1 ' .
                        ($tgl        ? "AND a.tanggal <= '" . addslashes($tgl) . "'" : "") .
                        ($kode_kebun ? " AND b.kode_kebun = '" . addslashes($kode_kebun) . "'" : "") .
                        ($kode_rayon ? " AND b.kode_rayon = '" . addslashes($kode_rayon) . "'" : "") .
                        ($afdeling   ? " AND b.afdeling = '" . addslashes($afdeling) . "'" : "") .
                    ' GROUP BY a.spta
                    ) as z
                    GROUP BY z.afdeling'
                );

                // HI: tanggal = $tgl, grouped by spta then by afdeling
                $dataHi = DB::select(
                    'SELECT z.afdeling, sum(z.jml_petak) as jml_petak_hi
                    FROM (
                        SELECT b.afdeling, COUNT(*) as jml_petak
                        FROM tx_pos_keluar as a
                        JOIN tx_petak_tebang as c ON a.kode_booking = c.nomor_booking
                        JOIN q_takdes_petak as b ON b.lahan_id = c.id_petak
                        WHERE 1=1 ' .
                        ($tgl        ? "AND a.tanggal = '" . addslashes($tgl) . "'" : "") .
                        ($kode_kebun ? " AND b.kode_kebun = '" . addslashes($kode_kebun) . "'" : "") .
                        ($kode_rayon ? " AND b.kode_rayon = '" . addslashes($kode_rayon) . "'" : "") .
                        ($afdeling   ? " AND b.afdeling = '" . addslashes($afdeling) . "'" : "") .
                    ' GROUP BY a.spta
                    ) as z
                    GROUP BY z.afdeling'
                );

                // Merge by afdeling
                $sdMap = collect($dataSd)->keyBy('afdeling');
                $hiMap = collect($dataHi)->keyBy('afdeling');
                $afdelings = $sdMap->keys()->merge($hiMap->keys())->unique()->sort()->values();

                $totalSd = 0;
                $totalHi = 0;

                $html  = '<style>';
                $html .= '.petak-table { width:100%; border-collapse:collapse; font-family:sans-serif; font-size:13px; }';
                $html .= '.petak-table thead tr { background: linear-gradient(135deg, #2e7d32, #66bb6a); color:#fff; }';
                $html .= '.petak-table thead th { padding:10px 8px; text-align:center; font-weight:600; letter-spacing:0.3px; }';
                $html .= '.petak-table tbody tr:nth-child(even) { background-color:#f1f8e9; }';
                $html .= '.petak-table tbody tr:nth-child(odd) { background-color:#ffffff; }';
                $html .= '.petak-table tbody tr:hover { background-color:#dcedc8; transition:background 0.2s; }';
                $html .= '.petak-table tbody td { padding:9px 8px; border-bottom:1px solid #c8e6c9; }';
                $html .= '.petak-table .col-afd { font-weight:600; color:#1b5e20; }';
                $html .= '.petak-table .col-num { text-align:right; color:#333; }';
                $html .= '.petak-table tfoot tr { background:#e8f5e9; font-weight:700; border-top:2px solid #388e3c; }';
                $html .= '.petak-table tfoot td { padding:9px 8px; color:#1b5e20; }';
                $html .= '.petak-label { font-size:11px; color:#888; display:block; font-weight:400; }';
                $html .= '</style>';

                $html .= '<table class="petak-table">';
                $html .= '<thead><tr>'
                    . '<th>Afdeling</th>'
                    . '<th>S/D<span class="petak-label text-white">' . htmlspecialchars($tgl) . '</span></th>'
                    . '<th>HI<span class="petak-label text-white">' . htmlspecialchars($tgl) . '</span></th>'
                    . '</tr></thead><tbody>';

                foreach ($afdelings as $afdeling) {
                    $sd = $sdMap->get($afdeling);
                    $hi = $hiMap->get($afdeling);
                    $sdVal = $sd ? $sd->jml_petak_sd : 0;
                    $hiVal = $hi ? $hi->jml_petak_hi : 0;
                    $totalSd += $sdVal;
                    $totalHi += $hiVal;
                    $html .= '<tr>'
                        . '<td class="col-afd">' . htmlspecialchars($afdeling) . '</td>'
                        . '<td class="col-num">' . number_format($sdVal) . '</td>'
                        . '<td class="col-num">' . number_format($hiVal) . '</td>'
                        . '</tr>';
                }

                $html .= '</tbody>';
                $html .= '<tfoot><tr>'
                    . '<td>Total</td>'
                    . '<td class="col-num">' . number_format($totalSd) . '</td>'
                    . '<td class="col-num">' . number_format($totalHi) . '</td>'
                    . '</tr></tfoot>';
                $html .= '</table>';

                return response()->json([
                    'success' => true,
                    'html'    => $html,
                    'data'    => [
                        'sd' => $dataSd,
                        'hi' => $dataHi,
                    ],
                ]);
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'message' => 'Query failed: ' . $e->getMessage()]);
            }
        }

        public function getJmlPetakSelektorPerAfdeling(Request $request)
        {
            [
                'tgl'        => $tgl,
                'kode_kebun' => $kode_kebun,
                'kode_rayon' => $kode_rayon,
                'afdeling'   => $afdeling,
                'namakebun'  => $namakebun,
                'namarayon'  => $namarayon,
            ] = $this->resolveFilterFromRequest($request);

            try {
                // S/D: tgl_selektor <= $tgl, grouped by no_spta then by afdeling
                $dataSd = DB::select(
                    'select z.afdeling, sum(z.jml_petak) as jml_petak_sd from  	(
                        SELECT d.afdeling, COUNT(*) AS jml_petak
                        FROM data_selektor a
                        JOIN tx_pos_keluar as b ON b.spta = a.no_spta
                        JOIN tx_petak_tebang as c ON b.kode_booking = c.nomor_booking
                        JOIN tx_ajuan_tebang d ON d.lahan_id = a.no_petak
                        WHERE 1=1 ' .
                        ($tgl        ? "AND a.tgl_selektor <= '" . addslashes($tgl) . "'" : "") .
                        ($kode_kebun ? " AND left(d.rayon,4) = '" . addslashes($kode_kebun) . "'" : "") .
                        ($kode_rayon ? " AND d.rayon = '" . addslashes($kode_rayon) . "'" : "") .
                        ($afdeling   ? " AND d.afdeling = '" . addslashes($afdeling) . "'" : "") .
                     'GROUP BY a.no_spta	
                     ) as z
					group by z.afdeling'
                    
                );

                // HI: tgl_selektor = $tgl, grouped by no_spta then by afdeling
                $dataHi = DB::select(
                    'SELECT z.afdeling, SUM(z.jml_petak) as jml_petak_hi
                    FROM (
                        SELECT d.afdeling, COUNT(*) AS jml_petak
                        FROM data_selektor a
                        JOIN tx_pos_keluar as b ON b.spta = a.no_spta
                        JOIN tx_petak_tebang as c ON b.kode_booking = c.nomor_booking
                        JOIN tx_ajuan_tebang d ON d.lahan_id = a.no_petak
                        WHERE 1=1 ' .
                        ($tgl        ? "AND a.tgl_selektor = '" . addslashes($tgl) . "'" : "") .
                        ($kode_kebun ? " AND left(d.rayon,4) = '" . addslashes($kode_kebun) . "'" : "") .
                        ($kode_rayon ? " AND d.rayon = '" . addslashes($kode_rayon) . "'" : "") .
                        ($afdeling   ? " AND d.afdeling = '" . addslashes($afdeling) . "'" : "") .
                    ' GROUP BY a.no_spta
                    ) as z
                    GROUP BY z.afdeling'
                );
            
                // Merge by afdeling
                $sdMap = collect($dataSd)->keyBy('afdeling');
                $hiMap = collect($dataHi)->keyBy('afdeling');
                $afdelings = $sdMap->keys()->merge($hiMap->keys())->unique()->sort()->values();

                $totalSd = 0;
                $totalHi = 0;

                $html  = '<style>';
                $html .= '.petak-table { width:100%; border-collapse:collapse; font-family:sans-serif; font-size:13px; }';
                $html .= '.petak-table thead tr { background: linear-gradient(135deg, #2e7d32, #66bb6a); color:#fff; }';
                $html .= '.petak-table thead th { padding:10px 8px; text-align:center; font-weight:600; letter-spacing:0.3px; }';
                $html .= '.petak-table tbody tr:nth-child(even) { background-color:#f1f8e9; }';
                $html .= '.petak-table tbody tr:nth-child(odd) { background-color:#ffffff; }';
                $html .= '.petak-table tbody tr:hover { background-color:#dcedc8; transition:background 0.2s; }';
                $html .= '.petak-table tbody td { padding:9px 8px; border-bottom:1px solid #c8e6c9; }';
                $html .= '.petak-table .col-afd { font-weight:600; color:#1b5e20; }';
                $html .= '.petak-table .col-num { text-align:right; color:#333; }';
                $html .= '.petak-table tfoot tr { background:#e8f5e9; font-weight:700; border-top:2px solid #388e3c; }';
                $html .= '.petak-table tfoot td { padding:9px 8px; color:#1b5e20; }';
                $html .= '.petak-label { font-size:11px; color:#888; display:block; font-weight:400; }';
                $html .= '</style>';

                $html .= '<table class="petak-table">';
                $html .= '<thead><tr>'
                    . '<th>Afdeling</th>'
                    . '<th>S/D<span class="petak-label text-white">' . htmlspecialchars($tgl) . '</span></th>'
                    . '<th>HI<span class="petak-label text-white">' . htmlspecialchars($tgl) . '</span></th>'
                    . '</tr></thead><tbody>';

                foreach ($afdelings as $afdeling) {
                    $sd = $sdMap->get($afdeling);
                    $hi = $hiMap->get($afdeling);
                    $sdVal = $sd ? $sd->jml_petak_sd : 0;
                    $hiVal = $hi ? $hi->jml_petak_hi : 0;
                    $totalSd += $sdVal;
                    $totalHi += $hiVal;
                    $html .= '<tr>'
                        . '<td class="col-afd">' . htmlspecialchars($afdeling) . '</td>'
                        . '<td class="col-num">' . number_format($sdVal) . '</td>'
                        . '<td class="col-num">' . number_format($hiVal) . '</td>'
                        . '</tr>';
                }

                $html .= '</tbody>';
                $html .= '<tfoot><tr>'
                    . '<td>Total</td>'
                    . '<td class="col-num">' . number_format($totalSd) . '</td>'
                    . '<td class="col-num">' . number_format($totalHi) . '</td>'
                    . '</tr></tfoot>';
                $html .= '</table>';

                return response()->json([
                    'success' => true,
                    'html'    => $html,
                    'data'    => [
                        'sd' => $dataSd,
                        'hi' => $dataHi,
                    ],
                ]);
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'message' => 'Query failed: ' . $e->getMessage()]);
            }
        }


        public function getLkpPerKebunMob(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]);
        }

        function getComboselect( Request $request)
	    {

            //if($request->ajax() == true)
            //{
                $param = explode(':',$request->input('filter'));
                $parent = (!is_null($request->input('parent')) ? $request->input('parent') : null);
                $limit = (!is_null($request->input('limit')) ? $request->input('limit') : null);
                $rows = $this->getComboselectmodel($param,$limit,$parent);
                $items = array();
            
                $fields = explode("|",$param[2]);
                
                foreach($rows as $row) 
                {
                    $value = "";
                    foreach($fields as $item=>$val)
                    {
                        if ($val != "") {
                            $value .= $row->{$val};
                            if ($item < count($fields) - 1) {
                                $value .= " | ";
                            } else {
                                $value .= " ";
                            }
                        }
                    }
                    $items[] = array($row->{$param['1']} , $value); 	
        
                }
                
                return json_encode($items); 	
         //   } else {
           //     return json_encode(array('OMG'=>" Ops .. Cant access the page !"));
            //}	
	}

    static function getComboselectmodel( $params , $limit =null, $parent = null)
    {   
        $limit = explode(':',$limit);
        $parent = explode(':',$parent);

        if(count($limit) >=3)
        {
            $table = $params[0]; 
            $condition = $limit[0]." `".$limit[1]."` ".$limit[2]." '".$limit[3]."' "; 
            if(count($parent)>=2 )
            {
            	$row =  \DB::table($table)->where($parent[0],$parent[1])->get();
            	 $row =  \DB::select( "SELECT * FROM ".$table." ".$condition ." AND ".$parent[0]." = '".$parent[1]."'");
            } else  {
	           $row =  \DB::select( "SELECT * FROM ".$table." ".$condition);
            }        
        }else{

            $table = $params[0]; 
            if(count($parent)>=2 )
            {
            	$row =  \DB::table($table)->where($parent[0],$parent[1])->get();
            } else  {
	            $row =  \DB::table($table)->get();
            }	           
        }

        return $row;
    }	

    public function sendOtp(Request $request)
    {
        $json = $request->getContent();
        $data = json_decode($json, true);
        
        $phoneNumber = $data['phone_number'] ?? null;
        $thntnm = $data['thntnm'] ?? null;
        
        // if ($thntnm == "2425") {
        //     Config::set('database.default', session('database_name', 'mysql'));
        // } else if ($thntnm == "2526") {
            Config::set('database.default', session('database_name', 'mysql_2627'));
        // }
        
        $validator = Validator::make($data, [
            'phone_number' => 'required|string'
        ]);

        if ($validator->fails()) {
            return response()->json([
            'status' => 'error',
            'message' => 'Validation failed',
            'errors' => $validator->errors()
            ], 400);
        }

        try {
            // Check if phone number exists in master_nohp
            $user = \DB::table('master_nohp')
                ->where('nohp', $phoneNumber)
                ->first();

            if (!$user) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Nomor telepon tidak terdaftar'
                ], 404);
            }

            // Generate 6 digit OTP
            $otp = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
            $expiresAt = now()->addMinutes(5); // OTP valid for 5 minutes

            // Store OTP in database
            \DB::table('otp_codes')->updateOrInsert(
                ['phone_number' => $phoneNumber],
                [
                    'otp_code' => $otp,
                    'expires_at' => $expiresAt,
                    'is_used' => 0,
                    'created_at' => now(),
                    'updated_at' => now()
                ]
            );

            // TODO: Send OTP via SMS gateway
            // Example: $this->sendSms($phoneNumber, "Kode OTP Anda: " . $otp);
            $this->sendMessage2("Kode OTP Anda: " . $otp, $phoneNumber);

            // Generate unique session ID
            $sessionId = uniqid('otp_', true);
            
            // Update session_id in otp_codes table
            \DB::table('otp_codes')
                ->where('phone_number', $phoneNumber)
                ->update(['session_id' => $sessionId]);

            return response()->json([
                'success' => true,
                'session_id' => $sessionId,
                'message' => 'OTP sent successfully',
                'debug' => config('app.debug') ? ['otp' => $otp] : null
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Gagal mengirim OTP: ' . $e->getMessage()
            ], 500);
        }
    }

    public function verifyOtp(Request $request)
    {
        $data = $request->json()->all();

        // if (($data['thntnm'] ?? null) == "2425") {
        //     Config::set('database.default', session('database_name', 'mysql'));
        // } else if (($data['thntnm'] ?? null) == "2526") {
            Config::set('database.default', session('database_name', 'mysql_2627'));
        // } 

        $validator = Validator::make($data, [
            'phone_number' => 'required|string',
            'otp_code' => 'required|string|size:6',
            'session_id' => 'required|string'
        ]);

        if ($validator->fails()) {
            return response()->json([
            'success' => false,
            'message' => 'Validation failed',
            'errors' => $validator->errors()
            ], 400);
        }

        try {
            $phoneNumber = $data['phone_number'];
            $otpCode = $data['otp_code'];
            $sessionId = $data['session_id'];

            // Retrieve OTP record
            $otpRecord = \DB::table('otp_codes')
                ->where('phone_number', $phoneNumber)
                ->where('session_id', $sessionId)
                ->first();

            if (!$otpRecord) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid session'
                ], 404);
            }

            // Check if OTP is already used
            if ($otpRecord->is_used == 1) {
                return response()->json([
                    'success' => false,
                    'message' => 'OTP sudah digunakan'
                ], 400);
            }

            // Check if OTP is expired
            if (now()->greaterThan($otpRecord->expires_at)) {
                return response()->json([
                    'success' => false,
                    'message' => 'OTP sudah kadaluarsa'
                ], 400);
            }

            // Verify OTP code
            if ($otpRecord->otp_code !== $otpCode) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid OTP code'
                ], 400);
            }

            // Mark OTP as used
            \DB::table('otp_codes')
                ->where('phone_number', $phoneNumber)
                ->where('session_id', $sessionId)
                ->update([
                    'is_used' => 1,
                    'updated_at' => now()
                ]);

            // Get user data
            $user = \DB::table('master_nohp')
                ->where('nohp', $phoneNumber)
                ->first();


            $token = hash('sha256', Str::random(60));
					
					\DB::table('tb_token')->insert([
						'userId' => $user->id,
						'token' => $token,
						'created' => date("Y-m-d H:i:s")
					]);

            return response()->json([
                'success' => true,
                'token' => $token,
                'message' => 'OTP verified successfully',
                'user' => [
                    'phone_number' => $phoneNumber,
                    'user_id' => $user->id ?? null,
                    'nama' => $user->nama ?? null,
                    'jabatan' => $user->jabatan ?? null
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal verifikasi OTP: ' . $e->getMessage()
            ], 500);
        }
    }

    public function getlahan(Request $request)
	{
		Config::set('database.default', session('database_name', 'mysql_2627'));
		$userId = $request->input('user_id');  
        if ($userId) {
            $user = \DB::table('master_nohp')->where('id', $userId)->first();
            $afdeling = $user->afdeling ?? null;
        }

        // Ambil data petak berdasarkan afdeling user (jika ada)
        if (!empty($afdeling)) {
            // Jika $afdeling berisi lebih dari satu kode, pisahkan dan gunakan whereIn
            $afdelingArr = explode(',', $afdeling);
            $afdelingArr = array_map('trim', $afdelingArr);

            $query = \DB::table('master_petak')->whereIn('afd_new', $afdelingArr);
        }

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

        return response()->json([
            'success' => true,
            'data' => $results
        ]);
	}

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

        $data = $request->json()->all();

        $validator = Validator::make($data, [
            'lahan_id' => 'required|exists:master_petak,lahan_id',
            'tanggal' => 'required|date',
            'jumlah_batang' => 'required|integer|min:0',
            'tinggi_batang' => 'required|numeric|min:0',
            'diameter_batang' => 'required|numeric|min:0',
            'berat_batang_per_meter' => 'required|numeric|min:0',
            'jumlah_ruas' => 'required|integer|min:0',
            'foto' => 'required' // base64 string
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 400);
        }

      $filename = null;

                if (!empty($data['foto'])) {

                    $fotoData = $data['foto'];
                    $destinationPath = public_path('uploads/foto_morfologi');

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

                    // Cek base64
                    if (preg_match('/^data:image\/(\w+);base64,/', $fotoData, $type)) {

                        $fotoData = substr($fotoData, strpos($fotoData, ',') + 1);
                        $type = strtolower($type[1]);

                        if (!in_array($type, ['jpg', 'jpeg', 'png'])) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Invalid image type'
                            ], 400);
                        }

                        $fotoData = base64_decode($fotoData);

                        if ($fotoData === false) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Base64 decode failed'
                            ], 400);
                        }

                        $filename = time() . '_' . uniqid() . '.jpg';
                        $targetFile = $destinationPath . '/' . $filename;

                        $image = imagecreatefromstring($fotoData);

                        if ($image) {

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

                            /*
                            ============================
                            COMPRESS ORIGINAL
                            ============================
                            */

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

                            file_put_contents($targetFile, $imageData);


                            /*
                            ============================
                            THUMB 200px
                            ============================
                            */

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

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

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

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

                            imagejpeg($thumb, $thumbFile, 75);


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

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


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

                        } else {

                            file_put_contents($targetFile, $fotoData);
                            $this->uploadCDN($targetFile, $filename, 'foto_morfologi');

                        }

                    } else {

                        return response()->json([
                            'success' => false,
                            'message' => 'Invalid image data'
                        ], 400);

                    }
                }

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

        // Return success response
        return response()->json([
            'success' => true,
            'message' => 'Data morfologi berhasil disimpan'
        ]);
	}

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

                $data = $request->json()->all();

                $validator = Validator::make($data, [
                    'lahan_id' => 'required|exists:master_petak,lahan_id',
                    'tanggal' => 'required|date',
                    'foto' => 'required' // base64 string
                ]);

                if ($validator->fails()) {
                    return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                    ], 400);
                }

              $filename = null;

                if (!empty($data['foto'])) {

                    $fotoData = $data['foto'];
                    $destinationPath = public_path('uploads/foto_drone');

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

                    // Cek base64
                    if (preg_match('/^data:image\/(\w+);base64,/', $fotoData, $type)) {

                        $fotoData = substr($fotoData, strpos($fotoData, ',') + 1);
                        $type = strtolower($type[1]);

                        if (!in_array($type, ['jpg', 'jpeg', 'png'])) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Invalid image type'
                            ], 400);
                        }

                        $fotoData = base64_decode($fotoData);

                        if ($fotoData === false) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Base64 decode failed'
                            ], 400);
                        }

                        $filename = time() . '_' . uniqid() . '.jpg';
                        $targetFile = $destinationPath . '/' . $filename;

                        $image = imagecreatefromstring($fotoData);

                        if ($image) {

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

                            /*
                            ============================
                            COMPRESS ORIGINAL
                            ============================
                            */

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

                            file_put_contents($targetFile, $imageData);


                            /*
                            ============================
                            THUMB 200px
                            ============================
                            */

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

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

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

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

                            imagejpeg($thumb, $thumbFile, 75);


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

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


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

                        } else {

                            file_put_contents($targetFile, $fotoData);
                            $this->uploadCDN($targetFile, $filename, 'foto_drone');

                        }

                    } else {

                        return response()->json([
                            'success' => false,
                            'message' => 'Invalid image data'
                        ], 400);

                    }
                }

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

                return response()->json([
                    'success' => true,
                    'message' => 'Data foto drone berhasil disimpan'
                ]);
	}

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

        $data = $request->json()->all();

        $validator = Validator::make($data, [
            'lahan_id' => 'required|exists:master_petak,lahan_id',
            'tanggal' => 'required|date',
            'luas_roboh' => 'required|numeric|min:0',
            'foto' => 'required' // base64 string
        ]);

        if ($validator->fails()) {
            return response()->json([
            'success' => false,
            'message' => 'Validation failed',
            'errors' => $validator->errors()
            ], 400);
        }

       $filename = null;

                if (!empty($data['foto'])) {

                    $fotoData = $data['foto'];
                    $destinationPath = public_path('uploads/foto_tebu_roboh');

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

                    // Cek base64
                    if (preg_match('/^data:image\/(\w+);base64,/', $fotoData, $type)) {

                        $fotoData = substr($fotoData, strpos($fotoData, ',') + 1);
                        $type = strtolower($type[1]);

                        if (!in_array($type, ['jpg', 'jpeg', 'png'])) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Invalid image type'
                            ], 400);
                        }

                        $fotoData = base64_decode($fotoData);

                        if ($fotoData === false) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Base64 decode failed'
                            ], 400);
                        }

                        $filename = time() . '_' . uniqid() . '.jpg';
                        $targetFile = $destinationPath . '/' . $filename;

                        $image = imagecreatefromstring($fotoData);

                        if ($image) {

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

                            /*
                            ============================
                            COMPRESS ORIGINAL
                            ============================
                            */

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

                            file_put_contents($targetFile, $imageData);


                            /*
                            ============================
                            THUMB 200px
                            ============================
                            */

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

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

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

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

                            imagejpeg($thumb, $thumbFile, 75);


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

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


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

                        } else {

                            file_put_contents($targetFile, $fotoData);
                            $this->uploadCDN($targetFile, $filename, 'foto_tebu_roboh');

                        }

                    } else {

                        return response()->json([
                            'success' => false,
                            'message' => 'Invalid image data'
                        ], 400);

                    }
                }

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

        return response()->json([
            'success' => true,
            'message' => 'Data tebu roboh berhasil disimpan'
        ]);
	}

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

        $data = $request->json()->all();

        $validator = Validator::make($data, [
            'lahan_id' => 'required|exists:master_petak,lahan_id',
            'tanggal' => 'required|date',
            'luas_banjir' => 'required|numeric|min:0',
            'foto' => 'required' // base64 string
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 400);
        }

        $filename = null;

                if (!empty($data['foto'])) {

                    $fotoData = $data['foto'];
                    $destinationPath = public_path('uploads/foto_tebu_banjir');

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

                    // Cek base64
                    if (preg_match('/^data:image\/(\w+);base64,/', $fotoData, $type)) {

                        $fotoData = substr($fotoData, strpos($fotoData, ',') + 1);
                        $type = strtolower($type[1]);

                        if (!in_array($type, ['jpg', 'jpeg', 'png'])) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Invalid image type'
                            ], 400);
                        }

                        $fotoData = base64_decode($fotoData);

                        if ($fotoData === false) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Base64 decode failed'
                            ], 400);
                        }

                        $filename = time() . '_' . uniqid() . '.jpg';
                        $targetFile = $destinationPath . '/' . $filename;

                        $image = imagecreatefromstring($fotoData);

                        if ($image) {

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

                            /*
                            ============================
                            COMPRESS ORIGINAL
                            ============================
                            */

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

                            file_put_contents($targetFile, $imageData);


                            /*
                            ============================
                            THUMB 200px
                            ============================
                            */

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

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

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

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

                            imagejpeg($thumb, $thumbFile, 75);


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

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


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

                        } else {

                            file_put_contents($targetFile, $fotoData);
                            $this->uploadCDN($targetFile, $filename, 'foto_tebu_banjir');

                        }

                    } else {

                        return response()->json([
                            'success' => false,
                            'message' => 'Invalid image data'
                        ], 400);

                    }
                }
        \DB::table('tx_tebu_banjir')->insert([
            'lahan_id' => $data['lahan_id'],
            'tanggal' => $data['tanggal'],
            'luas_banjir' => $data['luas_banjir'],
            'foto' => $filename,
            'entry_by' => $data['nohp'] ?? '',
            'createdOn' => now(),
            'updatedOn' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Data tebu banjir berhasil disimpan'
        ]);
    
	}

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

            $data = $request->json()->all();

            $validator = Validator::make($data, [
                'lahan_id' => 'required|exists:master_petak,lahan_id',
                'tanggal' => 'required|date',
                'luas_serangan' => 'required|numeric|min:0',
                'jenis_hama_penyakit' => 'required|exists:master_hpt,id',
                'foto' => 'required' // base64 string
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 400);
            }

            $filename = null;

                if (!empty($data['foto'])) {

                    $fotoData = $data['foto'];
                    $destinationPath = public_path('uploads/foto_serangan_hpt');

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

                    // Cek base64
                    if (preg_match('/^data:image\/(\w+);base64,/', $fotoData, $type)) {

                        $fotoData = substr($fotoData, strpos($fotoData, ',') + 1);
                        $type = strtolower($type[1]);

                        if (!in_array($type, ['jpg', 'jpeg', 'png'])) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Invalid image type'
                            ], 400);
                        }

                        $fotoData = base64_decode($fotoData);

                        if ($fotoData === false) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Base64 decode failed'
                            ], 400);
                        }

                        $filename = time() . '_' . uniqid() . '.jpg';
                        $targetFile = $destinationPath . '/' . $filename;

                        $image = imagecreatefromstring($fotoData);

                        if ($image) {

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

                            /*
                            ============================
                            COMPRESS ORIGINAL
                            ============================
                            */

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

                            file_put_contents($targetFile, $imageData);


                            /*
                            ============================
                            THUMB 200px
                            ============================
                            */

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

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

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

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

                            imagejpeg($thumb, $thumbFile, 75);


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

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


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

                        } else {

                            file_put_contents($targetFile, $fotoData);
                            $this->uploadCDN($targetFile, $filename, 'foto_serangan_hpt');

                        }

                    } else {

                        return response()->json([
                            'success' => false,
                            'message' => 'Invalid image data'
                        ], 400);

                    }
                }

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

            return response()->json([
                'success' => true,
                'message' => 'Data serangan hama/penyakit berhasil disimpan'
            ]);
		}

        public function lkp(Request $request)
        {
            Config::set('database.default', session('database_name', 'mysql_2627'));
            $data = $request->json()->all();
            $validator = Validator::make($data, [
                'lahan_id' => 'required|exists:master_petak,lahan_id',
                'tanggal' => 'required|date',
                'pekerjaan' => 'required|string',
                'ha' => 'required'                
            ]);
            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 400);
            }
            \DB::table('TX_TOTAL_KSO')->insert([
                'lahan_id' => $data['lahan_id'],
                'tgl' => $data['tanggal'],
                'pekerjaan' => $data['pekerjaan'],
                'ha' => $data['ha'],
                'entry_by' => $data['nohp'] ?? '',
                'entry_date' => now()
            ]);
            return response()->json([
                'success' => true,
                'message' => 'Data LKP berhasil disimpan'
            ]);
        }

        public function fotoLkp(Request $request)
        {
            Config::set('database.default', session('database_name', 'mysql_2627'));
            $data = $request->json()->all();
            $validator = Validator::make($data, [
                'lahan_id' => 'required|exists:master_petak,lahan_id',
                'tanggal' => 'required|date',
                'pekerjaan' => 'required|string',
                'foto' => 'required' // base64 string
            ]);
            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 400);
            }
             $filename = null;

                if (!empty($data['foto'])) {

                    $fotoData = $data['foto'];
                    $destinationPath = public_path('uploads/foto_kebun');

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

                    // Cek base64
                    if (preg_match('/^data:image\/(\w+);base64,/', $fotoData, $type)) {

                        $fotoData = substr($fotoData, strpos($fotoData, ',') + 1);
                        $type = strtolower($type[1]);

                        if (!in_array($type, ['jpg', 'jpeg', 'png'])) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Invalid image type'
                            ], 400);
                        }

                        $fotoData = base64_decode($fotoData);

                        if ($fotoData === false) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Base64 decode failed'
                            ], 400);
                        }

                        $filename = time() . '_' . uniqid() . '.jpg';
                        $targetFile = $destinationPath . '/' . $filename;

                        $image = imagecreatefromstring($fotoData);

                        if ($image) {

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

                            /*
                            ============================
                            COMPRESS ORIGINAL
                            ============================
                            */

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

                            file_put_contents($targetFile, $imageData);


                            /*
                            ============================
                            THUMB 200px
                            ============================
                            */

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

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

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

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

                            imagejpeg($thumb, $thumbFile, 75);


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

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


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

                        } else {

                            file_put_contents($targetFile, $fotoData);
                            $this->uploadCDN($targetFile, $filename, 'foto_kebun');

                        }

                    } else {

                        return response()->json([
                            'success' => false,
                            'message' => 'Invalid image data'
                        ], 400);

                    }
                }
            // Simpan informasi foto ke database jika diperlukan
                \DB::table('tx_foto_kebun')->insert([
                    'lahan_id' => $data['lahan_id'],
                    'tanggal' => $data['tanggal'],
                    'pekerjaan' => $data['pekerjaan'],
                    'kualitas' => $data['kualitas'] ?? '',
                    'foto' => $filename,
                    'entry_by' => $data['nohp'] ?? '',
                    'createdOn' => now(),
                    'updatedOn' => now()
                ]);
            return response()->json([
                'success' => true,
                'message' => 'Foto LKP berhasil disimpan'
            ]);
        }

        public function tebuBerbunga(Request $request)
        {
            Config::set('database.default', session('database_name', 'mysql_2627'));
            $data = $request->json()->all();
            $validator = Validator::make($data, [
                'lahan_id' => 'required|exists:master_petak,lahan_id',
                'tanggal' => 'required|date',
                'luas_berbunga' => 'required|numeric|min:0',
                'foto' => 'required' // base64 string
            ]);
            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 400);
            }

             $filename = null;

                if (!empty($data['foto'])) {

                    $fotoData = $data['foto'];
                    $destinationPath = public_path('uploads/foto_tebu_berbunga');

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

                    // Cek base64
                    if (preg_match('/^data:image\/(\w+);base64,/', $fotoData, $type)) {

                        $fotoData = substr($fotoData, strpos($fotoData, ',') + 1);
                        $type = strtolower($type[1]);

                        if (!in_array($type, ['jpg', 'jpeg', 'png'])) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Invalid image type'
                            ], 400);
                        }

                        $fotoData = base64_decode($fotoData);

                        if ($fotoData === false) {
                            return response()->json([
                                'success' => false,
                                'message' => 'Base64 decode failed'
                            ], 400);
                        }

                        $filename = time() . '_' . uniqid() . '.jpg';
                        $targetFile = $destinationPath . '/' . $filename;

                        $image = imagecreatefromstring($fotoData);

                        if ($image) {

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

                            /*
                            ============================
                            COMPRESS ORIGINAL
                            ============================
                            */

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

                            file_put_contents($targetFile, $imageData);


                            /*
                            ============================
                            THUMB 200px
                            ============================
                            */

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

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

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

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

                            imagejpeg($thumb, $thumbFile, 75);


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

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


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

                        } else {

                            file_put_contents($targetFile, $fotoData);
                            $this->uploadCDN($targetFile, $filename, 'foto_tebu_berbunga');

                        }

                    } else {

                        return response()->json([
                            'success' => false,
                            'message' => 'Invalid image data'
                        ], 400);

                    }
                }
            \DB::table('tx_tebu_berbunga')->insert([
                'lahan_id' => $data['lahan_id'],
                'tanggal' => $data['tanggal'],
                'luas_berbunga' => $data['luas_berbunga'],
                'keterangan' => $data['keterangan'] ?? '',
                'foto' => $data['foto'],
                'entry_by' => $data['nohp'] ?? '',
                'createdOn' => now(),
                'updatedOn' => now()
            ]);
            return response()->json([
                'success' => true,
                'message' => 'Data tebu berbunga berhasil disimpan'
            ]);
        }


    public function sendMessage($pesan, $nohp)
	{

		$payload = array(
			'instance_key' => '9KuiSAaSoCrc',
			'jid' => $nohp,
			'message' => $pesan
		);

		$url = 'https://whatsva.id/api/sendMessageText';

		$ch = curl_init();

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

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

		curl_close($ch);

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

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

	
	}

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

		$url = 'http://waha.ksotebu.com/api/sendText';

		$ch = curl_init();

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

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

		curl_close($ch);

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

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

    function uploadCDN($filePath, $fileName, $folder)
	{
		$remotePath = "/web/prodiskso/public/uploads/".$folder."/".$fileName;
		$url = "https://cdn.nikochannel.com".$remotePath;

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

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

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

		curl_exec($ch);

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

}
