<?php
namespace App\Http\Controllers;

use App\Models\Kampung;
use App\Models\Kecamatan;
use App\Models\Peninjauan;
use App\Models\PeninjauanPeralihan;
use App\Models\PeninjauanCoordinate;
use App\Models\PeninjauanDocument;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class PeninjauanController extends Controller
{
    /**
     * Update status_verifikasi BeritaAcaraPeninjauan (AJAX)
     */
    public function updateVerifikasiStatus(Request $request)
    {
        $id = $request->input('id');
        $status = $request->input('status_verifikasi');
        $userId = auth()->id();

        $ba = \App\Models\BeritaAcaraPeninjauan::find($id);
        if (!$ba) {
            return response()->json(['success' => false, 'message' => 'Data tidak ditemukan'], 404);
        }

        $ba->status_verifikasi = $status;
        $ba->verifikator_id = $userId;
        $ba->save();

        return response()->json(['success' => true, 'message' => 'Status verifikasi berhasil diupdate']);
    }
    /**
     * AJAX: Ambil daftar BeritaAcaraPeninjauan untuk peninjauan tertentu
     */
    public function beritaAcaraList($id)
    {
        // Pastikan model BeritaAcaraPeninjauan sudah di-import
        $list = \App\Models\BeritaAcaraPeninjauan::where('peninjauan_id', $id)->get();

        $data = $list->map(function($item) {
            // Judul dinamis sesuai type
            $judul = '';
            if ($item->type === 'pengukuran') {
                $judul = 'Berita Acara Pengukuran Bidang Tanah';
            } elseif ($item->type === 'persetujuan') {
                $judul = 'Berita Acara Persetujuan Pengukuran Tanah';
            } elseif ($item->type === 'penelitian') {
                $judul = 'Berita Acara Penelitian Penguasaan';
            } else {
                $judul = $item->type;
            }
            return [
                'id' => $item->id,
                'type' => $item->type,
                'nomor_berita_acara' => $item->nomor_berita_acara,
                'judul' => $judul,
                'status' => $item->status,
                'status_verifikasi' => $item->status_verifikasi,
                'verifikator_id' => $item->verifikator_id,
            ];
        });

        return response()->json([
            'success' => true,
            'data' => $data
        ]);
    }
    /**
     * Display a listing of the resource.
     */
    public function __construct()
    {
        $this->middleware('permission:peninjauan.view', ['only' => ['index', 'show']]);
        $this->middleware('permission:peninjauan.create', ['only' => ['create', 'store']]);
        $this->middleware('permission:peninjauan.edit', ['only' => ['edit', 'update']]);
        $this->middleware('permission:peninjauan.delete', ['only' => ['destroy', 'restore']]);
        $this->middleware('permission:peninjauan.update-status', ['only' => ['updateStatus']]);
        $this->middleware('permission:peninjauan.print', ['only' => ['exportPdf']]);
    }
    public function index(Request $request)
    {
        // Build query with relationships
        $query = Peninjauan::with(['documents','skpt'])
            ->orderBy('created_at', 'desc');

        // Apply search filter
        if ($request->filled('search')) {
            $search = $request->get('search');

            $query->where(function ($q) use ($search) {
                $q->whereRelation('skpt', 'no_registrasi', 'like', "%{$search}%")
                ->orWhereRelation('skpt', 'nama_pemohon', 'like', "%{$search}%")
                ->orWhere('nama_pemilik', 'like', "%{$search}%")
                ->orWhere('jalan_gg_blok', 'like', "%{$search}%")
                ->orWhere('kampung_kelurahan', 'like', "%{$search}%")
                ->orWhere('saksi1_nama', 'like', "%{$search}%")
                ->orWhere('saksi2_nama', 'like', "%{$search}%");
            });
        }

        // Apply status filter
        if ($request->filled('status')) {
            $query->where('status', $request->get('status'));
        }

        // Apply type filter
        if ($request->filled('type')) {
            $query->where('type_permohonan', $request->get('type'));
        }

        // Apply year filter
        if ($request->filled('year')) {
            $year = $request->get('year');
            $query->whereYear('ba_tanggal', $year);
        }

        if (auth()->user()->hasRole('guest')) {
            $query->where('created_by', auth()->id());
        }

        // Paginate results
        $peninjauanList = $query->paginate(10);

        // Get years for filter dropdown
        $years = Peninjauan::selectRaw('YEAR(ba_tanggal) as year')
            ->whereNotNull('ba_tanggal')
            ->distinct()
            ->orderBy('year', 'desc')
            ->pluck('year')
            ->filter();

        // Calculate statistics for cards
        $totalPeninjauan = $query->count();
        $completedCount = Peninjauan::where('status', 'completed')->count();
        $pendingCount = Peninjauan::whereIn('status', ['draft', 'submitted', 'verified'])->count();
        $rejectedCount = Peninjauan::where('status', 'rejected')->count();

        // Add stats to pagination collection for view
        $peninjauanList->appends($request->all());

        return view('admin.peninjauan.index', compact(
            'peninjauanList',
            'years',
            'totalPeninjauan',
            'completedCount',
            'pendingCount',
            'rejectedCount'
        ));
    }

    public function updateStatus(Request $request, $id)
    {

        // dd($request->all());
        $application = Peninjauan::findOrFail($id);
        $application->status = $request->status;
        $application->save();

        return response()->json(['success' => true]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.peninjauan.create');
    }

    private function generateNomorBA()
    {
        $prefix = 'BA-' . date('Ymd'); // contoh: BA-20250921

        // Cari nomor terakhir di hari ini
        $lastRecord = Peninjauan::whereDate('created_at', now())
            ->where('nomor_ba_kesaksian', 'like', $prefix . '%')
            ->latest('id')
            ->first();

        if ($lastRecord) {
            // Ambil urutan terakhir
            $lastNumber = (int) substr($lastRecord->nomor_ba_kesaksian, -4);
            $newNumber = str_pad($lastNumber + 1, 4, '0', STR_PAD_LEFT);
        } else {
            $newNumber = '0001';
        }

        return $prefix . '-' . $newNumber;
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        DB::beginTransaction();

        try {
            // Validation rules
            $validated = $request->validate([
                // 'type_permohonan' => 'nullable|in:SKPT,Sertifikat,Lainnya',
                'ba_tanggal' => 'required|date',
                'saksi1_nama' => 'required|string|max:255',
                'saksi2_nama' => 'required|string|max:255',
                'nama_pemilik' => 'nullable|string|max:255',
                'jalan_gg_blok' => 'nullable|string|max:500',
                'kampung_kelurahan' => 'nullable|string|max:255',

                // Map related fields
                'nomor_ba_pengukuran' => 'nullable|string|max:255',
                'tanggal_pengukuran' => 'nullable|date',
                'surat_tugas_nomor' => 'nullable|string|max:255',
                'surat_tugas_tanggal' => 'nullable|date',
                'petugas_ukur' => 'nullable|string|max:255',
                'sistem_koordinat' => 'nullable|string|max:100',
                'cm_x' => 'nullable|string|max:100',
                'ukuran_patok' => 'nullable|numeric',
                'tanggal_pengukuran_koordinat' => 'nullable|date',
                'luas_terukur_otomatis' => 'nullable|numeric',

                // JSON fields
                'coordinates_data' => 'nullable|string',
                'map_image_data' => 'nullable|string',
                'polygon_bounds' => 'nullable|string',

                // Coordinate arrays (alternative format)
                'lat' => 'nullable|array',
                'lng' => 'nullable|array',
                'lat.*' => 'nullable|numeric|between:-90,90',
                'lng.*' => 'nullable|numeric|between:-180,180',
            ]);

            // Set default values
            $validated['created_by'] = Auth::id();
            $validated['status'] = $request->boolean('save_as_draft') ? 'draft' : 'belum selesai';
            $validated['updated_by'] = Auth::id();
            $validated['nomor_ba_kesaksian'] = $this->generateNomorBA();
            $validated['type_permohonan'] = $validated['type_permohonan'] ?? 'SKPT';

            // Handle coordinates data
            $coordinates = $this->processCoordinatesData($request);

            // Store processed coordinates
            if (!empty($coordinates)) {
                $validated['coordinates_data'] = json_encode($coordinates);
            }

            // Create the peninjauan record
            $peninjauan = Peninjauan::create($validated);

            // Store individual coordinates in separate table
            if (!empty($coordinates)) {
                $this->storeCoordinates($peninjauan->id, $coordinates);
            }

            // Store map image if provided
            if ($request->filled('map_image_data')) {
                $this->storeMapImage($peninjauan, $request->get('map_image_data'));
            }

            // Handle file uploads
            $this->handleFileUploads($request, $peninjauan);

            DB::commit();

            // Log successful creation
            Log::info('Peninjauan created successfully', [
                'id' => $peninjauan->id,
                'user_id' => Auth::id(),
                'coordinates_count' => count($coordinates),
                'status' => $validated['status']
            ]);

            // Determine response based on request type
            if ($request->ajax() || $request->wantsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => $request->boolean('save_as_draft')
                        ? 'Draft berhasil disimpan!'
                        : 'Peninjauan berhasil dibuat dan disubmit!',
                    'data' => $peninjauan->load('coordinates'),
                    'redirect' => route('peninjauan.index')
                ]);
            }

            $message = $request->boolean('save_as_draft')
                ? 'Draft peninjauan berhasil disimpan!'
                : 'Peninjauan berhasil dibuat dan disubmit!';

            return redirect()->route('peninjauan.index')->with('success', $message);

        } catch (ValidationException $e) {
            DB::rollback();

            Log::warning('Validation failed for peninjauan creation', [
                'errors' => $e->errors(),
                'user_id' => Auth::id()
            ]);

            if ($request->ajax() || $request->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $e->errors()
                ], 422);
            }

            return redirect()->back()
                ->withErrors($e->errors())
                ->withInput()
                ->with('error', 'Terdapat kesalahan pada form. Silakan periksa kembali.');

        } catch (\Exception $e) {
            DB::rollback();

            Log::error('Error storing peninjauan', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'user_id' => Auth::id(),
                'request_data' => $request->except(['map_image_data']) // Exclude large data
            ]);

            if ($request->ajax() || $request->wantsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Terjadi kesalahan sistem. Silakan coba lagi.',
                    'error' => config('app.debug') ? $e->getMessage() : null
                ], 500);
            }

            return redirect()->back()
                ->withInput()
                ->with('error', 'Terjadi kesalahan sistem. Silakan coba lagi.');
        }
    }

    /**
     * Process coordinates data from different input formats
     */
    private function processCoordinatesData(Request $request)
    {
        $coordinates = [];

        // Try to get from JSON string first
        if ($request->filled('coordinates_data')) {
            $jsonData = $request->get('coordinates_data');
            if (is_string($jsonData)) {
                $decoded = json_decode($jsonData, true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                    $coordinates = $decoded;
                }
            }
        }

        // If no JSON data, try to get from separate lat/lng arrays
        if (empty($coordinates) && $request->has('lat') && $request->has('lng')) {
            $latitudes = $request->get('lat', []);
            $longitudes = $request->get('lng', []);

            foreach ($latitudes as $index => $lat) {
                if (isset($longitudes[$index]) && !empty($lat) && !empty($longitudes[$index])) {
                    $coordinates[] = [
                        'lat' => (float) $lat,
                        'lng' => (float) $longitudes[$index]
                    ];
                }
            }
        }

        // Validate coordinates
        return $this->validateCoordinates($coordinates);
    }

    /**
     * Validate coordinates array
     */
    private function validateCoordinates(array $coordinates)
    {
        $validCoordinates = [];

        foreach ($coordinates as $coord) {
            if (isset($coord['lat'], $coord['lng'])) {
                $lat = (float) $coord['lat'];
                $lng = (float) $coord['lng'];

                // Validate coordinate ranges
                if ($lat >= -90 && $lat <= 90 && $lng >= -180 && $lng <= 180) {
                    $validCoordinates[] = [
                        'lat' => $lat,
                        'lng' => $lng
                    ];
                }
            }
        }

        return $validCoordinates;
    }

    /**
     * Store coordinates in separate table
     */
    private function storeCoordinates($peninjauanId, array $coordinates)
    {
        foreach ($coordinates as $index => $coord) {
            PeninjauanCoordinate::create([
                'peninjauan_id' => $peninjauanId,
                'point_number' => $index + 1,
                'latitude' => $coord['lat'],
                'longitude' => $coord['lng'],
                'sequence' => $index
            ]);
        }
    }

    /**
     * Store map image data
     */
    private function storeMapImage($peninjauan, $imageData)
    {
        try {
            // Check if it's a base64 image
            if (strpos($imageData, 'data:image') === 0) {
                // Extract base64 data
                $imageData = substr($imageData, strpos($imageData, ',') + 1);
                $imageData = base64_decode($imageData);

                if ($imageData !== false) {
                    $filename = 'map_' . $peninjauan->id . '_' . time() . '.png';
                    $path = 'peninjauan/maps/' . $peninjauan->id . '/' . $filename;

                    // Create directory if not exists (for shared hosting compatibility)
                    $fullPath = storage_path('app/public/' . dirname($path));
                    if (!file_exists($fullPath)) {
                        mkdir($fullPath, 0755, true);
                    }

                    // Store image using file_put_contents as fallback for shared hosting
                    $storagePath = storage_path('app/public/' . $path);
                    if (file_put_contents($storagePath, $imageData) !== false) {
                        // Create document record
                        PeninjauanDocument::create([
                            'peninjauan_id' => $peninjauan->id,
                            'document_type' => 'map_image',
                            'file_name' => $filename,
                            'file_path' => $path,
                            'file_size' => strlen($imageData),
                            'file_extension' => 'png',
                            'description' => 'Map capture image'
                        ]);
                    } else {
                        throw new \Exception('Failed to write map image file');
                    }
                }
            } else {
                // Assume it's JSON map data
                $mapData = json_decode($imageData, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $filename = 'map_data_' . $peninjauan->id . '_' . time() . '.json';
                    $path = 'peninjauan/maps/' . $peninjauan->id . '/' . $filename;

                    // Create directory if not exists (for shared hosting compatibility)
                    $fullPath = storage_path('app/public/' . dirname($path));
                    if (!file_exists($fullPath)) {
                        mkdir($fullPath, 0755, true);
                    }

                    // Store JSON using file_put_contents as fallback for shared hosting
                    $storagePath = storage_path('app/public/' . $path);
                    if (file_put_contents($storagePath, $imageData) !== false) {
                        PeninjauanDocument::create([
                            'peninjauan_id' => $peninjauan->id,
                            'document_type' => 'map_data',
                            'file_name' => $filename,
                            'file_path' => $path,
                            'file_size' => strlen($imageData),
                            'file_extension' => 'json',
                            'description' => 'Map configuration data'
                        ]);
                    } else {
                        throw new \Exception('Failed to write map data file');
                    }
                }
            }
        } catch (\Exception $e) {
            Log::warning('Failed to store map image', [
                'peninjauan_id' => $peninjauan->id,
                'error' => $e->getMessage()
            ]);
        }
    }

    /**
     * Handle file uploads
     */
    private function handleFileUploads(Request $request, $peninjauan)
    {
        $uploadFields = [
            'photo_dokumentasi' => 'Photo dokumentasi/kwitansi'
        ];

        foreach ($uploadFields as $field => $description) {
            if ($request->hasFile($field)) {
                $files = is_array($request->file($field)) ? $request->file($field) : [$request->file($field)];

                foreach ($files as $file) {
                    if ($file->isValid()) {
                        $fileName = time() . '_' . $file->getClientOriginalName();
                        $filePath = $file->storeAs('peninjauan/documents/' . $peninjauan->id, $fileName, 'public');

                        PeninjauanDocument::create([
                            'peninjauan_id' => $peninjauan->id,
                            'document_type' => $field,
                            'file_name' => $file->getClientOriginalName(),
                            'file_path' => $filePath,
                            'file_size' => $file->getSize(),
                            'file_extension' => $file->getClientOriginalExtension(),
                            'description' => $description
                        ]);
                    }
                }
            }
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Peninjauan $peninjauan)
    {
        if (auth()->user()->hasRole('guest') && $peninjauan->created_by !== auth()->id()) {
                abort(403, 'Anda tidak memiliki akses ke data ini.');
        }
        $peninjauan->load([
            'peralihan',
            'coordinates',
            'documents',
            'creator',
            'updater',
            'verifier'
        ]);

        return view('admin.peninjauan.show', compact('peninjauan'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Peninjauan $peninjauan)
    {
        if (auth()->user()->hasRole('guest') && $peninjauan->created_by !== auth()->id()) {
                abort(403, 'Anda tidak memiliki akses ke data ini.');
        }
        // Check permission
        if ($peninjauan->status !== 'draft') {
            return redirect()
                ->route('peninjauan.index')
                ->with('error', 'Hanya draft yang dapat diedit.');
        }

        $kecamatans = Kecamatan::orderBy('nama_kecamatan')->get();
        $data_kampung = Kampung::orderBy('nama_kampung')->get();
        $utmCoordinates = \DB::table('utm_coordinates')
        ->where('peninjauan_id', $peninjauan->id)
        ->orderBy('point_number')
        ->get();

        $peninjauan->load(['peralihan', 'coordinates', 'documents']);

        return view('admin.peninjauan.edit', compact('peninjauan','kecamatans','data_kampung','utmCoordinates'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Peninjauan $peninjauan)
    {
        // Check permission
        if ($peninjauan->status !== 'draft') {
            return redirect()
                ->route('peninjauan.index')
                ->with('error', 'Hanya draft yang dapat diedit.');
        }

        DB::beginTransaction();
         $validated = $request->validate([
                'type_permohonan' => 'required|in:SKPT,Sertifikat,Lainnya',
                'ba_tanggal' => 'required|date',
                'saksi1_nama' => 'nullable|string|max:255',
                'saksi2_nama' => 'nullable|string|max:255',
                'nama_pemilik' => 'nullable|string|max:255',
                'jalan_gg_blok' => 'nullable|string|max:500',
                'kampung_kelurahan' => 'nullable|string|max:255',
                // Map related fields
                'nomor_ba_pengukuran' => 'nullable|string|max:255',
                'tanggal_pengukuran' => 'nullable|date',
                'surat_tugas_nomor' => 'nullable|string|max:255',
                'surat_tugas_tanggal' => 'nullable|date',
                'petugas_ukur' => 'nullable|string|max:255',
                'sistem_koordinat' => 'nullable|string|max:100',
                'cm_x' => 'nullable|string|max:100',
                'ukuran_patok' => 'nullable|numeric',
                'tanggal_pengukuran_koordinat' => 'nullable|date',
                'luas_terukur_otomatis' => 'nullable|numeric',
                'penggunaan_tanah' => 'nullable|string|max:255',
                'riwayat_perolehan' => 'nullable|string|max:255',
                'no_imb' => 'nullable|string|max:255',
                'imb_tanggal' => 'nullable|date',
                'sppt_pbb_tahun' => 'nullable|integer',
                'photo_dokumentasi.*' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:10240',
                // JSON fields
                'coordinates_data' => 'nullable|string',
                'map_image_data' => 'nullable|string',
                'polygon_bounds' => 'nullable|string',
                // Coordinate arrays
                'lat' => 'nullable|array',
                'lng' => 'nullable|array',
                'video_pemohon' => 'nullable|file|mimetypes:video/mp4,video/avi,video/quicktime,video/x-matroska,video/x-msvideo,video/x-ms-wmv|max:51200',
                'video_saksi_batas' => 'nullable|file|mimetypes:video/mp4,video/avi,video/quicktime,video/x-matroska,video/x-msvideo,video/x-ms-wmv|max:51200',
            ]);

        try {
            // Validation

            // Prepare data
            $data = $request->except(['coordinates_data', 'lat', 'lng', 'peralihan', 'documents', '_token', '_method', 'map_image_data']);
            $data['updated_by'] = Auth::id();

            // Update status if submitting final
            if ($request->input('submit_final')) {
                $data['status'] = 'submitted';
            }

            // Handle checkbox fields
            $checkboxFields = [
                'rekomendasi_skpt',
                'rekomendasi_sertifikat',
                'rekomendasi_mediasi',
                'rekomendasi_verifikasi',
                'rekomendasi_tolak'
            ];

            foreach ($checkboxFields as $field) {
                $data[$field] = $request->has($field) ? true : false;
            }


            // Process coordinates
            $coordinates = $this->processCoordinatesData($request);
            if (!empty($coordinates)) {
                $data['coordinates_data'] = json_encode($coordinates);
            }

            // Process UTM coordinates
            $eastingArr = $request->get('easting', []);
            $northingArr = $request->get('northing', []);
            // dd($data);
            // Hapus data UTM lama
            \DB::table('utm_coordinates')->where('peninjauan_id', $peninjauan->id)->delete();
            // Simpan data UTM baru
            foreach ($eastingArr as $idx => $easting) {
                $northing = $northingArr[$idx] ?? null;
                if ($easting && $northing) {
                    \DB::table('utm_coordinates')->insert([
                        'peninjauan_id' => $peninjauan->id,
                        'point_number' => $idx + 1,
                        'easting' => $easting,
                        'northing' => $northing,
                        'sequence' => $idx,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }

            // Update main record
            $peninjauan->update($data);
            // Update coordinates
            $peninjauan->coordinates()->delete();
            if (!empty($coordinates)) {
                $this->storeCoordinates($peninjauan->id, $coordinates);
            }

            // Store new map image if provided
            if ($request->filled('map_image_data')) {

                // Delete old map images
                $oldMapDocs = $peninjauan->documents()
                    ->whereIn('document_type', ['map_image', 'map_data'])
                    ->get();
                // dd($oldMapDocs);
                foreach ($oldMapDocs as $doc) {
                    $doc->delete(); // This will also delete the file
                }

                // Store new map image
                $this->storeMapImage($peninjauan, $request->get('map_image_data'));
            }

            // Update peralihan
            $peninjauan->peralihan()->delete();

            if ($request->has('pemilik') && is_array($request->pemilik)) {
                foreach ($request->pemilik as $urutan => $data) {
                    // Only create if at least one field has data
                    if (!empty($data['pada_tahun']) || !empty($data['dikuasai_oleh']) || !empty($data['dialihkan']) || !empty($data['luas'])) {
                        PeninjauanPeralihan::create([
                            'peninjauan_id' => $peninjauan->id,
                            'urutan' => $urutan,
                            'pada_tahun' => $data['pada_tahun'] ?? null,
                            'dikuasai_oleh' => $data['dikuasai_oleh'] ?? null,
                            'dialihkan' => $data['dialihkan'] ?? null,
                            'luas' => $data['luas'] ?? null
                        ]);
                    }
                }
            }

            // Handle new file uploads
            $this->handleFileUploads($request, $peninjauan);

            // Handle video_pemohon upload
            if ($request->hasFile('video_pemohon')) {
                // Delete old file if exists
                if ($peninjauan->video_pemohon) {
                    try {
                        Storage::disk('public')->delete($peninjauan->video_pemohon);
                    } catch (\Exception $e) {
                        Log::warning('Failed to delete old video_pemohon: ' . $e->getMessage());
                    }
                }
                $file = $request->file('video_pemohon');
                if ($file->isValid()) {
                    $fileName = time() . '_' . $file->getClientOriginalName();
                    $filePath = $file->storeAs('peninjauan/videos/' . $peninjauan->id, $fileName, 'public');
                    $peninjauan->video_pemohon = $filePath;
                    $peninjauan->save();
                }
            }

            // Handle video_saksi_batas upload
            if ($request->hasFile('video_saksi_batas')) {
                // Delete old file if exists
                if ($peninjauan->video_saksi_batas) {
                    try {
                        Storage::disk('public')->delete($peninjauan->video_saksi_batas);
                    } catch (\Exception $e) {
                        Log::warning('Failed to delete old video_saksi_batas: ' . $e->getMessage());
                    }
                }
                $file = $request->file('video_saksi_batas');
                if ($file->isValid()) {
                    $fileName = time() . '_' . $file->getClientOriginalName();
                    $filePath = $file->storeAs('peninjauan/videos/' . $peninjauan->id, $fileName, 'public');
                    $peninjauan->video_saksi_batas = $filePath;
                    $peninjauan->save();
                }
            }

            // Delete removed documents
            if ($request->has('delete_documents')) {
                $deleteIds = $request->input('delete_documents');
                PeninjauanDocument::whereIn('id', $deleteIds)
                    ->where('peninjauan_id', $peninjauan->id)
                    ->get()
                    ->each(function($doc) {
                        $doc->delete(); // This will also delete the file
                    });
            }

            DB::commit();

            Log::info('Peninjauan updated successfully', [
                'id' => $peninjauan->id,
                'user_id' => Auth::id(),
                'coordinates_count' => count($coordinates)
            ]);

            return redirect()
                ->route('peninjauan.index')
                ->with('success', 'Data peninjauan berhasil diperbarui.');

        } catch (\Exception $e) {
            DB::rollback();

            Log::error('Error updating peninjauan', [
                'id' => $peninjauan->id,
                'error' => $e->getMessage(),
                'user_id' => Auth::id()
            ]);

            return redirect()
                ->back()
                ->withInput()
                ->with('error', 'Terjadi kesalahan: ' . $e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Peninjauan $peninjauan)
    {

        // Check permission
        if ($peninjauan->created_by !== Auth::id()) {
            return redirect()
                ->route('peninjauan.index')
                ->with('error', 'Anda tidak memiliki izin untuk menghapus data ini.');
        }

        // Only allow deletion of draft status
        if ($peninjauan->status !== 'draft') {
            return redirect()
                ->route('peninjauan.index')
                ->with('error', 'Hanya draft yang dapat dihapus.');
        }

        try {
            // Soft delete (data masih tersimpan di database)
            $peninjauan->delete();

            return redirect()
                ->route('peninjauan.index')
                ->with('success', 'Data peninjauan berhasil dihapus.');

        } catch (\Exception $e) {
            return redirect()
                ->back()
                ->with('error', 'Terjadi kesalahan: ' . $e->getMessage());
        }
    }

    /**
     * Restore soft deleted resource
     */
    public function restore($id)
    {
        try {
            $peninjauan = Peninjauan::withTrashed()->findOrFail($id);
            $peninjauan->restore();

            return redirect()
                ->route('peninjauan.index')
                ->with('success', 'Data peninjauan berhasil dipulihkan.');

        } catch (\Exception $e) {
            return redirect()
                ->back()
                ->with('error', 'Terjadi kesalahan: ' . $e->getMessage());
        }
    }

    /**
     * Export to PDF
     */
    public function exportPdf(Peninjauan $peninjauan)
    {
        $peninjauan->load(['peralihan', 'coordinates', 'documents']);

        return view('admin.peninjauan.pdf', compact('peninjauan'));
    }

        /**
     * Update status dokumen berita acara (AJAX)
     */
    public function updateDokumenStatus(Request $request, $id)
    {
        $peninjauan = Peninjauan::findOrFail($id);
        $judul = $request->input('judul');
        $status = $request->input('status');
        $idx = $request->input('idx');

        // Simpan status dokumen, misal ke kolom JSON dokumen_status
        $dokumenStatus = $peninjauan->dokumen_status ?? [];
        if (is_string($dokumenStatus)) {
            $dokumenStatus = json_decode($dokumenStatus, true) ?: [];
        }
        $dokumenStatus[$idx] = [
            'judul' => $judul,
            'status' => $status,
            'updated_at' => now()->toDateTimeString(),
        ];
        $peninjauan->dokumen_status = json_encode($dokumenStatus);
        $peninjauan->save();

        return response()->json(['success' => true, 'message' => 'Status dokumen berhasil diupdate']);
    }

    public function downloadPdf(Request $request, $id)
    {
        $type = $request->get('type', 'penelitian');
        $peninjauan = Peninjauan::with(['lastMapImage'])->findOrFail($id); // biar relation ke-load

        // Pilih blade & nama file
        switch ($type) {
            case 'pengukuran':
                $view = 'admin.peninjauan.berita_acara_pengukuran';
                $filename = 'berita_acara_pengukuran.pdf';
                break;
            case 'persetujuan':
                $view = 'admin.peninjauan.berita_acara_persetujuan';
                $filename = 'berita_acara_persetujuan.pdf';
                break;
            default:
                $view = 'admin.peninjauan.berita_acara_penelitian';
                $filename = 'berita_acara_penelitian.pdf';
        }

        // === Siapkan gambar peta sebagai base64 ===
        $mapImg = null;
        if ($peninjauan->lastMapImage && $peninjauan->lastMapImage->file_path) {
            // ASUMSI: file disimpan di disk 'public' (storage/app/public/..)
            // Jika berbeda, sesuaikan disk-nya.
            $relative = ltrim($peninjauan->lastMapImage->file_path, '/'); // contoh: peninjauan/maps/13/map_13_1761183872.png

            // Jika field menyimpan path "storage/peninjauan/..." hapus prefix "storage/"
            $relative = preg_replace('#^storage/#', '', $relative);

            $absPath = Storage::disk('public')->path($relative);

            if (is_file($absPath) && is_readable($absPath)) {
                $mime = @mime_content_type($absPath) ?: 'image/png';
                $mapImg = 'data:' . $mime . ';base64,' . base64_encode(file_get_contents($absPath));
            }
        }

        $pdf = app('dompdf.wrapper')->loadView($view, [
            'peninjauan' => $peninjauan,
            'mapImg'     => $mapImg, // kirim ke blade
        ]);

        // (Opsional) kalau butuh HTML5 parsing untuk CSS modern
        $pdf->setOptions(['isHtml5ParserEnabled' => true]);

        if ($request->has('download')) {
            return $pdf->download($filename);
        }
        return $pdf->stream($filename);
    }

}
