<?php

namespace App\Http\Controllers;

use App\Http\Requests\SpSiptRequest;
use App\Http\Requests\SpSiptUpdateStatusRequest;
use App\Models\Kampung;
use App\Models\Kecamatan;
use App\Models\SpSipt;
use App\Models\SpSiptDokumen;
use App\Models\SpSiptCatatan;
use App\Models\SpSiptCoordinate;
use App\Models\SpSiptJadwal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Exception;
use Illuminate\Support\Facades\Validator as FacadesValidator;
use Illuminate\Validation\Validator;

class SpSiptController extends Controller
{
    /**
     * Display a listing of the resource.
     */
     public function __construct()
    {
        $this->middleware('permission:sp-sipt.view', ['only' => [
            'index',
            'show',
            'dashboard',
            'getStatistics',
            'map',
            'report',
            'generateReport',
            'exportExcel',
            'downloadTemplate',
            'search',
            'getKelurahan',
            'getKecamatan',
            'getDetail',
            'downloadDocument',
            'activityLog'
        ]]);

        $this->middleware('permission:sp-sipt.create', ['only' => ['create', 'store', 'import', 'duplicate']]);
        $this->middleware('permission:sp-sipt.edit', ['only' => ['edit', 'update', 'storeCatatan', 'storeJadwal', 'updateJadwal']]);
        $this->middleware('permission:sp-sipt.delete', ['only' => ['destroy', 'destroyDokumen', 'deleteDokumen']]);
        $this->middleware('permission:sp-sipt.upload-document', ['only' => ['uploadDocument']]);
        $this->middleware('permission:sp-sipt.update-status', ['only' => ['updateStatus', 'updateStatusAjax', 'sendEmail']]);
        $this->middleware('permission:sp-sipt.preview', ['only' => ['preview']]);
        $this->middleware('permission:sp-sipt.print', ['only' => ['print', 'exportPdf']]);
    }

        // Helper untuk format rupiah
    public static function formatRupiah($angka)
    {
        if ($angka === null || $angka === '') return '';
        return 'Rp. ' . number_format($angka, 0, ',', '.') . ',-';
    }

    // Helper untuk konversi angka ke terbilang (Indonesia)
    public static function terbilang($angka)
    {
        $angka = (int)$angka;
        $huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
        if ($angka < 12)
            return $huruf[$angka];
        elseif ($angka < 20)
            return self::terbilang($angka - 10) . " belas";
        elseif ($angka < 100)
            return self::terbilang($angka / 10) . " puluh" . ($angka % 10 != 0 ? " " . self::terbilang($angka % 10) : "");
        elseif ($angka < 200)
            return "seratus" . ($angka - 100 != 0 ? " " . self::terbilang($angka - 100) : "");
        elseif ($angka < 1000)
            return self::terbilang($angka / 100) . " ratus" . ($angka % 100 != 0 ? " " . self::terbilang($angka % 100) : "");
        elseif ($angka < 2000)
            return "seribu" . ($angka - 1000 != 0 ? " " . self::terbilang($angka - 1000) : "");
        elseif ($angka < 1000000)
            return self::terbilang($angka / 1000) . " ribu" . ($angka % 1000 != 0 ? " " . self::terbilang($angka % 1000) : "");
        elseif ($angka < 1000000000)
            return self::terbilang($angka / 1000000) . " juta" . ($angka % 1000000 != 0 ? " " . self::terbilang($angka % 1000000) : "");
        elseif ($angka < 1000000000000)
            return self::terbilang($angka / 1000000000) . " milyar" . ($angka % 1000000000 != 0 ? " " . self::terbilang($angka % 1000000000) : "");
        else
            return "terlalu besar";
    }
    public function index(Request $request)
    {
        $query = SpSipt::query();

        // Filter by year
        if ($request->filled('year')) {
            $query->whereYear('created_at', $request->year);
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Search functionality
        if ($request->filled('search')) {
            $query->search($request->search);
        }
        if (auth()->user()->hasRole('guest')) {
            $query->where('created_by', auth()->id());
        }
        // Ordering
        $query->orderBy('created_at', 'desc');

        // Paginate
        $spSipts = $query->paginate(10)->withQueryString();

        // Data for year filter
        $years = SpSipt::selectRaw('YEAR(created_at) as year')
                       ->distinct()
                       ->orderBy('year', 'desc')
                       ->pluck('year');

        return view('admin.sp-sipt.index', compact('spSipts', 'years'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $statusTanahOptions = [
            SpSipt::TANAH_HAK_MILIK => 'Hak Milik',
            SpSipt::TANAH_HGB => 'Hak Guna Bangunan',
            SpSipt::TANAH_HGU => 'Hak Guna Usaha',
            SpSipt::TANAH_HAK_PAKAI => 'Hak Pakai',
            SpSipt::TANAH_NEGARA => 'Tanah Negara',
            SpSipt::TANAH_LAINNYA => 'Lainnya'
        ];

        $jenisDokumenOptions = [
            SpSiptDokumen::DOK_KTP_PEMOHON => 'KTP Pemohon',
            SpSiptDokumen::DOK_KTP_TERLAPOR => 'KTP Terlapor',
            SpSiptDokumen::DOK_SERTIFIKAT => 'Sertifikat Tanah',
            SpSiptDokumen::DOK_SURAT_UKUR => 'Surat Ukur',
            SpSiptDokumen::DOK_IMB => 'IMB',
            SpSiptDokumen::DOK_PBB => 'PBB',
            SpSiptDokumen::DOK_AJB => 'Akta Jual Beli',
            SpSiptDokumen::DOK_SURAT_WARIS => 'Surat Waris',
            SpSiptDokumen::DOK_SURAT_HIBAH => 'Surat Hibah',
            SpSiptDokumen::DOK_PUTUSAN => 'Putusan Pengadilan',
            SpSiptDokumen::DOK_BERITA_ACARA => 'Berita Acara',
            SpSiptDokumen::DOK_FOTO => 'Foto Lokasi',
            SpSiptDokumen::DOK_LAINNYA => 'Dokumen Lainnya',
            SpSiptDokumen::DOK_KWITANSI => 'Dokumen Kwitansi',

        ];
        $title = 'Create SPMPT';
        $kampungs = Kampung::where('status','Aktif')->orderBy('nama_kampung','ASC')->get();
        $kecamatans = Kecamatan::orderBy('nama_kecamatan')->get();

        return view('admin.sp-sipt.create', compact('statusTanahOptions', 'jenisDokumenOptions','title','kampungs','kecamatans'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // Validate basic fields
        $validated = $request->validate([
            'pemohon_nama' => 'required|string|max:255',
            'pemohon_nik' => 'required|digits:16',
            'pemohon_alamat' => 'required|string',
            'terlapor_nama' => 'required|string|max:255',
            'terlapor_nik' =>  'required|digits:16',
            'terlapor_alamat' => 'required|string',
            'pemohon_tempat_lahir' => 'nullable',
            'pemohon_tanggal_lahir' => 'nullable',
            'pemohon_pekerjaan' => 'nullable',
            'terlapor_tempat_lahir' => 'nullable',
            'terlapor_pekerjaan' => 'nullable',
            'terlapor_tanggal_lahir' => 'nullable',
            'terlapor_tanggal_lahir' => 'nullable',
            'ketua_rt' => 'nullable',
            'nama_rt' => 'nullable',
            'lokasi_tanah_rt' => 'nullable',
            'kampung' => 'nullable',
            'kecamatan_id' => 'nullable',
            'lokasi_kota' => 'nullable',
            'batas_utara' => 'nullable',
            'batas_timur' => 'nullable',
            'batas_selatan' => 'nullable',
            'batas_barat' => 'nullable',
            'tanggal_sertifikat' => 'date',
            'nomor_tanggal_surat_penguasaan_tanah' => 'nullable',
            'peruntukan_bidang_tanah' => 'nullable',
            'uang_ganti_kerugian' => 'nullable',







            // ... other validation rules ...

            // Coordinate validation
            'coordinates_data' => 'nullable|json',
            'lat.*' => 'nullable|numeric|between:-90,90',
            'lng.*' => 'nullable|numeric|between:-180,180',
            'easting.*' => 'nullable|numeric',
            'northing.*' => 'nullable|numeric',
            'map_image_data' => 'nullable|string',
        ]);

        DB::beginTransaction();

        try {
            // Create SP-SIPT
            $validated['created_by'] = auth()->id();
            $validated['updated_by'] = auth()->id();
            $spSipt = SpSipt::create($validated);

            // Handle coordinates from multiple inputs
            $coordinates = [];

            // Method 1: From individual lat/lng inputs (with UTM data)
            if ($request->has('lat') && $request->has('lng')) {
                $latitudes = $request->input('lat', []);
                $longitudes = $request->input('lng', []);
                $eastings = $request->input('easting', []);
                $northings = $request->input('northing', []);

                foreach ($latitudes as $key => $lat) {
                    if (isset($longitudes[$key]) && $lat && $longitudes[$key]) {
                        $coordinates[] = [
                            'lat' => (float) $lat,
                            'lng' => (float) $longitudes[$key],
                            'easting' => isset($eastings[$key]) ? (float) $eastings[$key] : null,
                            'northing' => isset($northings[$key]) ? (float) $northings[$key] : null,
                            'utm_zone' => '50S' // Default UTM Zone for Kalimantan
                        ];
                    }
                }
            }

            // Method 2: From JSON coordinates_data
            if (empty($coordinates) && $request->has('coordinates_data')) {
                $coordinatesJson = $request->input('coordinates_data');
                if ($coordinatesJson) {
                    $decodedCoords = json_decode($coordinatesJson, true);
                    if (is_array($decodedCoords)) {
                        $coordinates = $decodedCoords;
                    }
                }
            }

            // Save coordinates if available
            if (!empty($coordinates)) {
                SpSiptCoordinate::savePolygonCoordinates($spSipt->id, $coordinates);

                // Save luas_terukur from frontend calculation (if provided)
                if ($request->has('luas_terukur') && $request->input('luas_terukur')) {
                    $spSipt->luas_terukur = $request->input('luas_terukur');
                } else {
                    // Fallback: Calculate area from saved coordinates
                    $spSipt->luas_terukur = SpSiptCoordinate::calculateArea($spSipt->id);
                }

                // Calculate bounds
                $spSipt->polygon_bounds = $spSipt->calculatePolygonBounds();
            }

            // Handle map image
            if ($request->has('map_image_data')) {
                $mapImageData = $request->input('map_image_data');

                // Check if it's base64 image
                if (strpos($mapImageData, 'data:image') === 0) {
                    try {
                        // Extract base64 data
                        $imageData = explode(',', $mapImageData);
                        $imageData = base64_decode($imageData[1] ?? $imageData[0]);

                        // Generate filename
                        $filename = 'map_' . $spSipt->id . '_' . time() . '.png';
                        $path = 'sp-sipt/maps/' . $filename;

                        // Create directory if not exists
                        $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) {
                            $spSipt->map_image = $path;
                        } else {
                            throw new \Exception('Failed to write map image file');
                        }
                    } catch (\Exception $e) {
                        // Log error and continue without map image
                        Log::error('Failed to save map image: ' . $e->getMessage());
                        $spSipt->map_image = null; // Don't save if failed
                    }
                } else {
                    // Store as JSON data if not image
                    $spSipt->map_image = $mapImageData;
                }
            }

            // Handle file uploads
            if ($request->hasFile('kwitansi')) {
                $path = $request->file('kwitansi')->store('sp-sipt/documents', 'public');
                $spSipt->dokumen()->create([
                    'jenis_dokumen' => 'kwitansi',
                    'nama_file' => $request->file('kwitansi')->getClientOriginalName(),
                    'path_file' => $path,
                    'mime_type' => $request->file('kwitansi')->getMimeType(),
                    'ukuran_file' => $request->file('kwitansi')->getSize(),
                ]);
            }

            if ($request->hasFile('dokumen_template')) {
                $path = $request->file('dokumen_template')->store('sp-sipt/documents', 'public');
                $spSipt->dokumen()->create([
                    'jenis_dokumen' => 'dokumen_pendukung_lainnya',
                    'nama_file' => $request->file('dokumen_template')->getClientOriginalName(),
                    'path_file' => $path,
                    'mime_type' => $request->file('dokumen_template')->getMimeType(),
                    'ukuran_file' => $request->file('dokumen_template')->getSize(),
                ]);
            }
            // Nomor surat sudah otomatis di-generate di boot method saat creating
            // Tidak perlu generate lagi di sini

            DB::commit();

            return redirect()
                ->route('sp-sipt.index')
                ->with('success', 'Data berhasil disimpan dengan ' . count($coordinates) . ' titik koordinat.');

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

            return back()
                ->withInput()
                ->withErrors(['error' => 'Terjadi kesalahan: ' . $e->getMessage()]);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(SpSipt $spSipt)
    {
        if (auth()->user()->hasRole('guest') && $spSipt->created_by !== auth()->id()) {
            abort(403, 'Anda tidak memiliki akses ke data ini.');
        }
        $spSipt->load([
            'dokumen',
            'statusHistory.changedBy',
            'catatan' => function($query) {
                $query->latest();
            },
            'catatan.creator',
            'jadwal' => function($query) {
                $query->orderBy('tanggal_waktu', 'desc');
            },
            'jadwal.creator',
            'creator',
            'updater',
            'approver'
        ]);

        // Get catatan visible to pemohon (for public view)


        return view('sp-sipt.show', compact(
            'spSipt',

        ));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {

        $spSipt = SpSipt::findOrFail($id);
         if (auth()->user()->hasRole('guest') && $spSipt->created_by !== auth()->id()) {
            abort(403, 'Anda tidak memiliki akses ke data ini.');
        }
        $kampungs = Kampung::all();
        $kecamatans = Kecamatan::all();

        return view('admin.sp-sipt.edit', compact('spSipt', 'kampungs', 'kecamatans'));
    }

    /**
     * Update the specified resource in storage.
     */
   public function update(Request $request, $id)
    {
        $spSipt = SpSipt::findOrFail($id);

        // Validation rules
        $validated = $request->validate([
            'pemohon_nama' => 'required|string|max:255',
            'pemohon_nik' => 'required|digits:16',
            'pemohon_alamat' => 'required|string',
            'terlapor_nama' => 'required|string|max:255',
            'terlapor_nik' => 'nullable|digits:16',
            'terlapor_alamat' => 'nullable|string',
            'pemohon_tempat_lahir' => 'nullable|string|max:255',
            'pemohon_tanggal_lahir' => 'nullable|date',
            'pemohon_pekerjaan' => 'nullable|string|max:255',
            'terlapor_tempat_lahir' => 'nullable|string|max:255',
            'terlapor_tanggal_lahir' => 'nullable|date',
            'terlapor_pekerjaan' => 'nullable|string|max:255',
            'ketua_rt' => 'nullable|string|max:255',
            'nama_rt' => 'nullable|string|max:255',
            'lokasi_tanah_rt' => 'nullable|string|max:255',
            'kampung' => 'required|exists:kampung,id',
            'kecamatan_id' => 'required|exists:kecamatan,id',
            'lokasi_kota' => 'nullable|string|max:255',
            'batas_utara' => 'nullable|string|max:255',
            'batas_timur' => 'nullable|string|max:255',
            'batas_selatan' => 'nullable|string|max:255',
            'batas_barat' => 'nullable|string|max:255',
            'tanggal_sertifikat' => 'nullable|date',
            'nomor_tanggal_surat_penguasaan_tanah' => 'nullable|string',
            'peruntukan_bidang_tanah' => 'nullable|string|max:255',
            'uang_ganti_kerugian' => 'nullable|string|max:255',
            'kwitansi' => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120', // 5MB
            'dokumen_template' => 'nullable|file|mimes:pdf,doc,docx,jpg,jpeg,png|max:10240', // 10MB
            'coordinates_data' => 'nullable|json',
            'lat.*' => 'nullable|numeric|between:-90,90',
            'lng.*' => 'nullable|numeric|between:-180,180',
            'easting.*' => 'nullable|numeric',
            'northing.*' => 'nullable|numeric',
            'map_image_data' => 'nullable|string',
        ]);

        DB::beginTransaction();

        try {
            // Update basic fields
            // dd($validated);
            $spSipt->update($validated);

            // Handle coordinates from multiple inputs
            $coordinates = [];

            // Method 1: From individual lat/lng inputs (with UTM data)
            if ($request->has('lat') && $request->has('lng')) {
                $latitudes = $request->input('lat', []);
                $longitudes = $request->input('lng', []);
                $eastings = $request->input('easting', []);
                $northings = $request->input('northing', []);

                foreach ($latitudes as $key => $lat) {
                    if (isset($longitudes[$key]) && $lat && $longitudes[$key]) {
                        $coordinates[] = [
                            'lat' => (float) $lat,
                            'lng' => (float) $longitudes[$key],
                            'easting' => isset($eastings[$key]) ? (float) $eastings[$key] : null,
                            'northing' => isset($northings[$key]) ? (float) $northings[$key] : null,
                            'utm_zone' => '50S' // Default UTM Zone for Kalimantan
                        ];
                    }
                }
            }

            // Method 2: From JSON coordinates_data
            if (empty($coordinates) && $request->has('coordinates_data')) {
                $coordinatesJson = $request->input('coordinates_data');
                if ($coordinatesJson) {
                    $decodedCoords = json_decode($coordinatesJson, true);
                    if (is_array($decodedCoords)) {
                        $coordinates = $decodedCoords;
                    }
                }
            }

            // Save coordinates if available
            if (!empty($coordinates)) {
                // Delete old coordinates
                SpSiptCoordinate::where('sp_sipt_id', $spSipt->id)->delete();

                // Save new coordinates
                SpSiptCoordinate::savePolygonCoordinates($spSipt->id, $coordinates);

                // Save luas_terukur from frontend calculation (if provided)
                if ($request->has('luas_terukur') && $request->input('luas_terukur')) {
                    $spSipt->luas_terukur = $request->input('luas_terukur');
                } else {
                    // Fallback: Calculate area from saved coordinates
                    $spSipt->luas_terukur = SpSiptCoordinate::calculateArea($spSipt->id);
                }

                // Calculate bounds
                $spSipt->polygon_bounds = $spSipt->calculatePolygonBounds();
            }

            // Handle map image
            if ($request->has('map_image_data')) {
                $mapImageData = $request->input('map_image_data');

                // Delete old map image if exists
                if ($spSipt->map_image && Storage::disk('public')->exists($spSipt->map_image)) {
                    try {
                        Storage::disk('public')->delete($spSipt->map_image);
                    } catch (\Exception $e) {
                        // Log error but continue
                        Log::warning('Failed to delete old map image: ' . $e->getMessage());
                    }
                }

                // Check if it's base64 image
                if (strpos($mapImageData, 'data:image') === 0) {
                    try {
                        // Extract base64 data
                        $imageData = explode(',', $mapImageData);
                        $imageData = base64_decode($imageData[1] ?? $imageData[0]);

                        // Generate filename
                        $filename = 'map_' . $spSipt->id . '_' . time() . '.png';
                        $path = 'sp-sipt/maps/' . $filename;

                        // Create directory if not exists
                        $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) {
                            $spSipt->map_image = $path;
                        } else {
                            throw new \Exception('Failed to write map image file');
                        }
                    } catch (\Exception $e) {
                        // Log error and store as JSON data instead
                        Log::error('Failed to save map image: ' . $e->getMessage());
                        $spSipt->map_image = null; // Don't save if failed
                    }
                } else {
                    // Store as JSON data if not image
                    $spSipt->map_image = $mapImageData;
                }
            }

            // Handle file uploads - KWITANSI
            if ($request->hasFile('kwitansi')) {
                // Hapus dokumen kwitansi lama jika ada
                $oldKwitansi = $spSipt->dokumen()->where('jenis_dokumen', 'kwitansi')->first();
                if ($oldKwitansi) {
                    if (Storage::disk('public')->exists($oldKwitansi->path_file)) {
                        Storage::disk('public')->delete($oldKwitansi->path_file);
                    }
                    $oldKwitansi->delete();
                }

                // Upload kwitansi baru
                $path = $request->file('kwitansi')->store('sp-sipt/documents', 'public');
                $spSipt->dokumen()->create([
                    'jenis_dokumen' => 'kwitansi',
                    'nama_file' => $request->file('kwitansi')->getClientOriginalName(),
                    'path_file' => $path,
                    'mime_type' => $request->file('kwitansi')->getMimeType(),
                    'ukuran_file' => $request->file('kwitansi')->getSize(),
                ]);
            }

            // Handle file uploads - DOKUMEN PENDUKUNG
            if ($request->hasFile('dokumen_template')) {
                // Hapus dokumen pendukung lama jika ada
                $oldDokumen = $spSipt->dokumen()->where('jenis_dokumen', 'dokumen_pendukung_lainnya')->first();
                if ($oldDokumen) {
                    if (Storage::disk('public')->exists($oldDokumen->path_file)) {
                        Storage::disk('public')->delete($oldDokumen->path_file);
                    }
                    $oldDokumen->delete();
                }

                // Upload dokumen pendukung baru
                $path = $request->file('dokumen_template')->store('sp-sipt/documents', 'public');
                $spSipt->dokumen()->create([
                    'jenis_dokumen' => 'dokumen_pendukung_lainnya',
                    'nama_file' => $request->file('dokumen_template')->getClientOriginalName(),
                    'path_file' => $path,
                    'mime_type' => $request->file('dokumen_template')->getMimeType(),
                    'ukuran_file' => $request->file('dokumen_template')->getSize(),
                ]);
            }

            // Save all changes
            $spSipt->save();

            DB::commit();

            return redirect()
                ->route('sp-sipt.index')
                ->with('success', 'Data berhasil diperbarui dengan ' . count($coordinates) . ' titik koordinat.');

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

            return back()
                ->withInput()
                ->withErrors(['error' => 'Terjadi kesalahan: ' . $e->getMessage()]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(SpSipt $spSipt)
    {
        if (auth()->user()->hasRole('guest') && $spSipt->created_by !== auth()->id()) {
            abort(403, 'Anda tidak memiliki akses ke data ini.');
        }
        try {
            // Only allow deletion of draft status
            if ($spSipt->status !== SpSipt::STATUS_DRAFT) {
                return back()->with('error', 'Hanya pengaduan dengan status draft yang dapat dihapus.');
            }

            $spSipt->delete();

            return redirect()
                ->route('sp-sipt.index')
                ->with('success', 'Pengaduan berhasil dihapus.');

        } catch (Exception $e) {
            return back()->with('error', 'Gagal menghapus pengaduan: ' . $e->getMessage());
        }
    }

    /**
     * Update status of the SP-SIPT
     */
    // public function updateStatus(SpSipt $spSipt)
    // {
    //     DB::beginTransaction();

    //     try {



    //         DB::commit();

    //         return redirect()
    //             ->route('sp-sipt.show', $spSipt)
    //             ->with('success', 'Status pengaduan berhasil diperbarui.');

    //     } catch (Exception $e) {
    //         DB::rollBack();

    //         return back()->with('error', 'Gagal mengubah status: ' . $e->getMessage());
    //     }
    // }

    public function updateStatus(Request $request, SpSipt $spSipt)
    {

        $request->validate(['status' => 'required|in:selesai,belum selesai']);

        $spSipt->status = $request->status;
        $spSipt->save();

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

    /**
     * Add catatan to SP-SIPT
     */
    public function storeCatatan(Request $request, SpSipt $spSipt)
    {
        $validated = $request->validate([
            'catatan' => 'required|string|max:5000',
            'jenis_catatan' => 'required|in:internal,feedback,revisi',
            'is_visible_to_pemohon' => 'boolean'
        ]);

        $spSipt->catatan()->create([
            'catatan' => $validated['catatan'],
            'jenis_catatan' => $validated['jenis_catatan'],
            'is_visible_to_pemohon' => $validated['is_visible_to_pemohon'] ?? false,
            'created_by' => auth()->id()
        ]);

        return redirect()
            ->route('sp-sipt.show', $spSipt)
            ->with('success', 'Catatan berhasil ditambahkan.');
    }

    /**
     * Store jadwal for SP-SIPT
     */
    public function storeJadwal(Request $request, SpSipt $spSipt)
    {
        $validated = $request->validate([
            'tanggal_waktu' => 'required|date|after:now',
            'tempat' => 'required|string|max:255',
            'jenis_kegiatan' => 'required|in:mediasi,survey,pertemuan,sidang',
            'agenda' => 'nullable|string|max:1000'
        ]);

        $spSipt->jadwal()->create([
            'tanggal_waktu' => $validated['tanggal_waktu'],
            'tempat' => $validated['tempat'],
            'jenis_kegiatan' => $validated['jenis_kegiatan'],
            'agenda' => $validated['agenda'],
            'status' => SpSiptJadwal::STATUS_SCHEDULED,
            'created_by' => auth()->id()
        ]);

        return redirect()
            ->route('sp-sipt.show', $spSipt)
            ->with('success', 'Jadwal berhasil dibuat.');
    }

    /**
     * Update jadwal status
     */
    public function updateJadwal(Request $request, SpSipt $spSipt, SpSiptJadwal $jadwal)
    {
        // Ensure jadwal belongs to this SP-SIPT
        if ($jadwal->sp_sipt_id !== $spSipt->id) {
            abort(404);
        }

        $validated = $request->validate([
            'status' => 'required|in:scheduled,ongoing,completed,cancelled',
            'hasil' => 'nullable|string|max:2000'
        ]);

        switch ($validated['status']) {
            case SpSiptJadwal::STATUS_COMPLETED:
                $jadwal->markAsCompleted($validated['hasil'] ?? null);
                break;

            case SpSiptJadwal::STATUS_CANCELLED:
                $jadwal->cancel($validated['hasil'] ?? null);
                break;

            case SpSiptJadwal::STATUS_ONGOING:
                $jadwal->markAsOngoing();
                break;

            default:
                $jadwal->update($validated);
        }

        return redirect()
            ->route('sp-sipt.show', $spSipt)
            ->with('success', 'Status jadwal berhasil diperbarui.');
    }

    /**
     * Delete document
     */
    public function destroyDokumen(SpSipt $spSipt, SpSiptDokumen $dokumen)
    {
        // Ensure document belongs to this SP-SIPT
        if ($dokumen->sp_sipt_id !== $spSipt->id) {
            abort(404);
        }

        // Check if SP-SIPT can be edited
        if (!$spSipt->canBeEdited()) {
            return back()->with('error', 'Dokumen tidak dapat dihapus karena status pengaduan.');
        }

        try {
            $dokumen->delete(); // File will be auto deleted by model

            return back()->with('success', 'Dokumen berhasil dihapus.');
        } catch (Exception $e) {
            return back()->with('error', 'Gagal menghapus dokumen: ' . $e->getMessage());
        }
    }

    /**
     * Print SP-SIPT
     */
    public function print(SpSipt $spSipt)
    {
        $spSipt->load([
            'dokumen',
            'statusHistory.changedBy',
            'catatan.creator',
            'jadwal',
            'creator'
        ]);

        return view('admin.sp-sipt.print', compact('spSipt'));
    }

    /**
     * Export SP-SIPT to PDF
     */

    /**
     * Get map view
     */
    public function map(Request $request)
    {
        $spSipts = SpSipt::query()
            ->whereNotNull('latitude')
            ->whereNotNull('longitude')
            ->when($request->filled('status'), function($q) use ($request) {
                $q->where('status', $request->status);
            })
            ->get(['id', 'nomor_surat', 'pemohon_nama', 'latitude', 'longitude',
                   'polygon_coordinates', 'status', 'lokasi_kelurahan']);

        return view('sp-sipt.map', compact('spSipts'));
    }

    /**
     * Dashboard view
     */
    public function dashboard()
    {
        $statistics = [
            'total' => SpSipt::count(),
            'this_month' => SpSipt::whereMonth('created_at', date('m'))->count(),
            'draft' => SpSipt::draft()->count(),
            'submitted' => SpSipt::submitted()->count(),
            'in_review' => SpSipt::inReview()->count(),
            'approved' => SpSipt::approved()->count(),
            'rejected' => SpSipt::rejected()->count(),
        ];

        // Recent SP-SIPT
        $recent = SpSipt::with('creator')
            ->latest()
            ->take(10)
            ->get();

        // Upcoming jadwal
        $upcomingJadwal = SpSiptJadwal::upcoming()
            ->with('spSipt')
            ->take(5)
            ->get();

        // By kelurahan
        $byKelurahan = SpSipt::select('lokasi_kelurahan', DB::raw('count(*) as total'))
            ->whereNotNull('lokasi_kelurahan')
            ->groupBy('lokasi_kelurahan')
            ->orderByDesc('total')
            ->take(10)
            ->get();

        // By status tanah
        $byStatusTanah = SpSipt::select('status_tanah', DB::raw('count(*) as total'))
            ->whereNotNull('status_tanah')
            ->groupBy('status_tanah')
            ->get()
            ->map(function($item) {
                $item->label = match($item->status_tanah) {
                    SpSipt::TANAH_HAK_MILIK => 'Hak Milik',
                    SpSipt::TANAH_HGB => 'Hak Guna Bangunan',
                    SpSipt::TANAH_HGU => 'Hak Guna Usaha',
                    SpSipt::TANAH_HAK_PAKAI => 'Hak Pakai',
                    SpSipt::TANAH_NEGARA => 'Tanah Negara',
                    SpSipt::TANAH_LAINNYA => 'Lainnya',
                    default => 'Unknown'
                };
                return $item;
            });

        // Monthly trend (last 12 months)
        $monthlyTrend = SpSipt::select(
                DB::raw('YEAR(created_at) as year'),
                DB::raw('MONTH(created_at) as month'),
                DB::raw('COUNT(*) as total')
            )
            ->where('created_at', '>=', now()->subMonths(12))
            ->groupBy('year', 'month')
            ->orderBy('year')
            ->orderBy('month')
            ->get()
            ->map(function($item) {
                $item->month_name = date('M Y', mktime(0, 0, 0, $item->month, 1, $item->year));
                return $item;
            });

        return view('sp-sipt.dashboard', compact(
            'statistics',
            'recent',
            'upcomingJadwal',
            'byKelurahan',
            'byStatusTanah',
            'monthlyTrend'
        ));
    }

    /**
     * Handle file uploads
     */
    private function handleFileUploads(Request $request, SpSipt $spSipt)
    {
        // Handle multiple document uploads
        if ($request->hasFile('dokumen')) {
            foreach ($request->file('dokumen') as $jenisDokumen => $file) {
                if (is_array($file)) {
                    // Multiple files for same type
                    foreach ($file as $singleFile) {
                        $this->uploadDokumen($singleFile, $jenisDokumen, $spSipt);
                    }
                } else {
                    // Single file
                    $this->uploadDokumen($file, $jenisDokumen, $spSipt);
                }
            }
        }

        // Handle individual document fields
        $documentFields = [
            'ktp_pemohon' => SpSiptDokumen::DOK_KTP_PEMOHON,
            'ktp_terlapor' => SpSiptDokumen::DOK_KTP_TERLAPOR,
            'sertifikat_tanah' => SpSiptDokumen::DOK_SERTIFIKAT,
            'surat_ukur' => SpSiptDokumen::DOK_SURAT_UKUR,
            'imb' => SpSiptDokumen::DOK_IMB,
            'pbb' => SpSiptDokumen::DOK_PBB,
            'akta_jual_beli' => SpSiptDokumen::DOK_AJB,
            'surat_waris' => SpSiptDokumen::DOK_SURAT_WARIS,
            'surat_hibah' => SpSiptDokumen::DOK_SURAT_HIBAH,
            'putusan_pengadilan' => SpSiptDokumen::DOK_PUTUSAN,
            'berita_acara' => SpSiptDokumen::DOK_BERITA_ACARA,
            'foto_lokasi' => SpSiptDokumen::DOK_FOTO,
        ];

        foreach ($documentFields as $field => $jenisDokumen) {
            if ($request->hasFile($field)) {
                $files = $request->file($field);
                if (!is_array($files)) {
                    $files = [$files];
                }

                foreach ($files as $file) {
                    $this->uploadDokumen($file, $jenisDokumen, $spSipt);
                }
            }
        }
    }

    /**
     * Upload single dokumen
     */
    private function uploadDokumen($file, $jenisDokumen, SpSipt $spSipt)
    {
        $fileName = time() . '_' . Str::random(10) . '.' . $file->getClientOriginalExtension();
        $path = $file->storeAs('sp-sipt/dokumen/' . $spSipt->id, $fileName, 'public');

        $spSipt->dokumen()->create([
            'jenis_dokumen' => $jenisDokumen,
            'nama_file' => $file->getClientOriginalName(),
            'path_file' => $path,
            'mime_type' => $file->getMimeType(),
            'ukuran_file' => $file->getSize(),
        ]);
    }

    /**
     * Search for autocomplete
     */
    public function search(Request $request)
    {
        $query = $request->get('q');
        $field = $request->get('field', 'pemohon_nama');

        $results = SpSipt::select($field)
            ->where($field, 'like', '%' . $query . '%')
            ->distinct()
            ->limit(10)
            ->pluck($field);

        return response()->json($results);
    }

    /**
     * Get kelurahan list for dropdown
     */
    public function getKelurahan(Request $request)
    {
        $kecamatan = $request->get('kecamatan');

        $kelurahan = SpSipt::select('lokasi_kelurahan')
            ->when($kecamatan, function($q) use ($kecamatan) {
                $q->where('lokasi_kecamatan', $kecamatan);
            })
            ->whereNotNull('lokasi_kelurahan')
            ->distinct()
            ->orderBy('lokasi_kelurahan')
            ->pluck('lokasi_kelurahan');

        return response()->json($kelurahan);
    }

    /**
     * Get kecamatan list for dropdown
     */
    public function getKecamatan(Request $request)
    {
        $kota = $request->get('kota');

        $kecamatan = SpSipt::select('lokasi_kecamatan')
            ->when($kota, function($q) use ($kota) {
                $q->where('lokasi_kota', $kota);
            })
            ->whereNotNull('lokasi_kecamatan')
            ->distinct()
            ->orderBy('lokasi_kecamatan')
            ->pluck('lokasi_kecamatan');

        return response()->json($kecamatan);
    }

    /**
     * Restore soft deleted SP-SIPT
     */
    public function restore($id)
    {
        $spSipt = SpSipt::withTrashed()->findOrFail($id);

        if (!auth()->user()->can('restore', $spSipt)) {
            return back()->with('error', 'Anda tidak memiliki izin untuk mengembalikan pengaduan ini.');
        }

        $spSipt->restore();

        return redirect()
            ->route('sp-sipt.show', $spSipt)
            ->with('success', 'Pengaduan berhasil dikembalikan.');
    }

    /**
     * Force delete SP-SIPT
     */
    public function forceDestroy($id)
    {
        $spSipt = SpSipt::withTrashed()->findOrFail($id);

        if (!auth()->user()->can('forceDelete', $spSipt)) {
            return back()->with('error', 'Anda tidak memiliki izin untuk menghapus permanen pengaduan ini.');
        }

        // Delete all related files
        Storage::deleteDirectory('sp-sipt/dokumen/' . $spSipt->id);
        Storage::deleteDirectory('sp-sipt/signatures/' . $spSipt->id);

        $spSipt->forceDelete();

        return redirect()
            ->route('sp-sipt.index')
            ->with('success', 'Pengaduan berhasil dihapus permanen.');
    }

    /**
     * Duplicate SP-SIPT as draft
     */
    public function duplicate(SpSipt $spSipt)
    {
        DB::beginTransaction();

        try {
            // Clone SP-SIPT
            $newSpSipt = $spSipt->replicate();
            $newSpSipt->status = SpSipt::STATUS_DRAFT;
            $newSpSipt->nomor_surat = null; // Will be auto-generated
            $newSpSipt->submitted_at = null;
            $newSpSipt->approved_at = null;
            $newSpSipt->approved_by = null;
            $newSpSipt->rejection_reason = null;
            $newSpSipt->ttd_pemohon_path = null;
            $newSpSipt->ttd_terlapor_path = null;
            $newSpSipt->created_by = auth()->id();
            $newSpSipt->updated_by = null;
            $newSpSipt->save();

            DB::commit();

            return redirect()
                ->route('sp-sipt.edit', $newSpSipt)
                ->with('success', 'Pengaduan berhasil diduplikasi sebagai draft baru.');

        } catch (Exception $e) {
            DB::rollBack();

            return back()->with('error', 'Gagal menduplikasi pengaduan: ' . $e->getMessage());
        }
    }

    /**
     * Bulk update status
     */
    public function bulkUpdateStatus(Request $request)
    {
        $validated = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:sp_sipt,id',
            'status' => 'required|in:submitted,in_review,approved,rejected'
        ]);

        $updated = 0;
        $failed = [];

        foreach ($validated['ids'] as $id) {
            $spSipt = SpSipt::find($id);

            try {
                // Check permissions
                if ($validated['status'] === SpSipt::STATUS_APPROVED ||
                    $validated['status'] === SpSipt::STATUS_REJECTED) {
                    if (!auth()->user()->can('approve', $spSipt)) {
                        $failed[] = $spSipt->nomor_surat;
                        continue;
                    }
                }

                $spSipt->updateStatus($validated['status'], 'Bulk status update');
                $updated++;

            } catch (Exception $e) {
                $failed[] = $spSipt->nomor_surat;
            }
        }

        $message = "{$updated} pengaduan berhasil diperbarui.";
        if (count($failed) > 0) {
            $message .= " Gagal: " . implode(', ', $failed);
        }

        return back()->with('success', $message);
    }

    /**
     * Export to Excel
     */
    public function exportExcel(Request $request)
    {
        // You'll need to install maatwebsite/excel package
        // composer require maatwebsite/excel

        return \Excel::download(new SpSiptExport($request->all()), 'sp-sipt-' . date('Y-m-d') . '.xlsx');
    }

    /**
     * Import from Excel
     */
    public function import(Request $request)
    {
        $request->validate([
            'file' => 'required|mimes:xlsx,xls,csv|max:10240'
        ]);

        try {
            \Excel::import(new SpSiptImport, $request->file('file'));

            return back()->with('success', 'Data berhasil diimpor.');
        } catch (Exception $e) {
            return back()->with('error', 'Gagal mengimpor data: ' . $e->getMessage());
        }
    }

    /**
     * Download template for import
     */
    public function downloadTemplate()
    {
        $file = storage_path('app/templates/sp-sipt-template.xlsx');

        if (!file_exists($file)) {
            // Create template file
            $this->createImportTemplate();
        }

        return response()->download($file, 'template-sp-sipt.xlsx');
    }

    /**
     * Create import template
     */
    private function createImportTemplate()
    {
        // Implementation for creating Excel template
        // This would create an Excel file with proper headers
    }

    /**
     * Get statistics for charts
     */
    public function statistics(Request $request)
    {
        $type = $request->get('type', 'monthly');

        switch ($type) {
            case 'daily':
                $data = SpSipt::select(
                        DB::raw('DATE(created_at) as date'),
                        DB::raw('COUNT(*) as total')
                    )
                    ->where('created_at', '>=', now()->subDays(30))
                    ->groupBy('date')
                    ->orderBy('date')
                    ->get();
                break;

            case 'monthly':
                $data = SpSipt::select(
                        DB::raw('YEAR(created_at) as year'),
                        DB::raw('MONTH(created_at) as month'),
                        DB::raw('COUNT(*) as total')
                    )
                    ->where('created_at', '>=', now()->subYear())
                    ->groupBy('year', 'month')
                    ->orderBy('year')
                    ->orderBy('month')
                    ->get();
                break;

            case 'status':
                $data = SpSipt::select('status', DB::raw('COUNT(*) as total'))
                    ->groupBy('status')
                    ->get();
                break;

            case 'kelurahan':
                $data = SpSipt::select('lokasi_kelurahan', DB::raw('COUNT(*) as total'))
                    ->whereNotNull('lokasi_kelurahan')
                    ->groupBy('lokasi_kelurahan')
                    ->orderByDesc('total')
                    ->limit(20)
                    ->get();
                break;

            default:
                $data = [];
        }

        return response()->json($data);
    }

    /**
     * Activity log
     */
    public function activityLog(SpSipt $spSipt)
    {
        $activities = collect();

        // Add status history
        foreach ($spSipt->statusHistory as $history) {
            $activities->push([
                'type' => 'status_change',
                'description' => $history->getActionDescription(),
                'user' => $history->changedBy->name ?? 'System',
                'timestamp' => $history->changed_at,
                'data' => [
                    'from' => $history->status_from,
                    'to' => $history->status_to,
                    'catatan' => $history->catatan
                ]
            ]);
        }

        // Add catatan
        foreach ($spSipt->catatan as $catatan) {
            $activities->push([
                'type' => 'catatan_added',
                'description' => 'Menambahkan ' . $catatan->jenis_catatan_label,
                'user' => $catatan->creator->name ?? 'System',
                'timestamp' => $catatan->created_at,
                'data' => [
                    'catatan' => Str::limit($catatan->catatan, 100),
                    'jenis' => $catatan->jenis_catatan
                ]
            ]);
        }

        // Add jadwal
        foreach ($spSipt->jadwal as $jadwal) {
            $activities->push([
                'type' => 'jadwal_created',
                'description' => 'Membuat jadwal ' . $jadwal->jenis_kegiatan_label,
                'user' => $jadwal->creator->name ?? 'System',
                'timestamp' => $jadwal->created_at,
                'data' => [
                    'tanggal' => $jadwal->formatted_date_time,
                    'tempat' => $jadwal->tempat
                ]
            ]);
        }

        // Sort by timestamp
        $activities = $activities->sortByDesc('timestamp')->values();

        return view('sp-sipt.activity-log', compact('spSipt', 'activities'));
    }

    /**
     * Generate report
     */
    public function report(Request $request)
    {
        $validated = $request->validate([
            'date_from' => 'required|date',
            'date_to' => 'required|date|after_or_equal:date_from',
            'status' => 'nullable|array',
            'kelurahan' => 'nullable|array',
            'format' => 'required|in:pdf,excel'
        ]);

        $query = SpSipt::whereBetween('created_at', [
            $validated['date_from'],
            $validated['date_to']
        ]);

        if (!empty($validated['status'])) {
            $query->whereIn('status', $validated['status']);
        }

        if (!empty($validated['kelurahan'])) {
            $query->whereIn('lokasi_kelurahan', $validated['kelurahan']);
        }

        $data = $query->with(['dokumen', 'jadwal'])->get();

        $statistics = [
            'total' => $data->count(),
            'by_status' => $data->groupBy('status')->map->count(),
            'by_kelurahan' => $data->groupBy('lokasi_kelurahan')->map->count(),
            'total_luas_tanah' => $data->sum('luas_tanah')
        ];

        if ($validated['format'] === 'pdf') {
            $pdf = \PDF::loadView('sp-sipt.report-pdf', compact('data', 'statistics', 'validated'));
            return $pdf->download('laporan-sp-sipt-' . date('Y-m-d') . '.pdf');
        } else {
            return \Excel::download(
                new SpSiptReportExport($data, $statistics, $validated),
                'laporan-sp-sipt-' . date('Y-m-d') . '.xlsx'
            );
        }
    }

    public function getDetail(SpSipt $spSipt)
{
    try {
        // Load related data
        $spSipt->load([
            'dokumen',
            'dataKampung',
            'kecamatan',
            'creator',
            'updater',
            'approver'
        ]);

        // Prepare data for popup
        $data = [
            'id' => $spSipt->id,
            'nomor_surat' => $spSipt->nomor_surat ?? 'Belum digenerate',
            'nomor_ba' => $spSipt->nomor_surat ?? 'Belum digenerate',

            // Pemohon data
            'pemohon' => [
                'nama' => $spSipt->pemohon_nama,
                'nik' => $spSipt->pemohon_nik,
                'alamat' => $spSipt->pemohon_alamat,
                'tempat_lahir' => $spSipt->pemohon_tempat_lahir,
                'tanggal_lahir' => $spSipt->pemohon_tanggal_lahir,
                'pekerjaan' => $spSipt->pemohon_pekerjaan
            ],

            // Terlapor data
            'terlapor' => [
                'nama' => $spSipt->terlapor_nama,
                'nik' => $spSipt->terlapor_nik,
                'alamat' => $spSipt->terlapor_alamat,
                'tempat_lahir' => $spSipt->terlapor_tempat_lahir,
                'tanggal_lahir' => $spSipt->terlapor_tanggal_lahir,
                'pekerjaan' => $spSipt->terlapor_pekerjaan
            ],

            // Lokasi data
            'lokasi' => [
                'ketua_rt' => $spSipt->ketua_rt,
                'nama_rt' => $spSipt->nama_rt,
                'lokasi_tanah_rt' => $spSipt->lokasi_tanah_rt,
                'kampung' => $spSipt->dataKampung->nama_kampung ?? 'Tidak tersedia',
                'kecamatan' => $spSipt->kecamatan->nama_kecamatan ?? 'Tidak tersedia',
                'kota' => $spSipt->lokasi_kota,
                'batas_utara' => $spSipt->batas_utara,
                'batas_timur' => $spSipt->batas_timur,
                'batas_selatan' => $spSipt->batas_selatan,
                'batas_barat' => $spSipt->batas_barat
            ],

            // Document info
            'dokumen_info' => [
                'tanggal_sertifikat' => $spSipt->tanggal_sertifikat ?
                    \Carbon\Carbon::parse($spSipt->tanggal_sertifikat)->format('d/m/Y') : 'Tidak tersedia',
                'nomor_tanggal_surat_penguasaan_tanah' => $spSipt->nomor_tanggal_surat_penguasaan_tanah,
                'peruntukan_bidang_tanah' => $spSipt->peruntukan_bidang_tanah,
                'uang_ganti_kerugian' => $spSipt->uang_ganti_kerugian
            ],

            // Status and dates
            'status' => $spSipt->status,
            'status_label' => $this->getStatusLabel($spSipt->status),
            'status_class' => $this->getStatusClass($spSipt->status),
            'created_at' => $spSipt->created_at->format('d/m/Y H:i'),
            'updated_at' => $spSipt->updated_at->format('d/m/Y H:i'),

            // Coordinates info
            'coordinates_count' => count($spSipt->coordinates_array ?? []),
            'luas_terukur' => $spSipt->luas_terukur,

            // Documents
            'dokumen' => $spSipt->dokumen->map(function($doc) {
                return [
                    'id' => $doc->id,
                    'jenis_dokumen' => $doc->jenis_dokumen,
                    'nama_file' => $doc->nama_file,
                    'path_file' => $doc->path_file,
                    'mime_type' => $doc->mime_type,
                    'ukuran_file' => $this->formatFileSize($doc->ukuran_file),
                    'url' => Storage::url($doc->path_file)
                ];
            }),

            // Created by info
            'created_by' => $spSipt->creator->name ?? 'System',
            'updated_by' => $spSipt->updater->name ?? null,
            'approved_by' => $spSipt->approver->name ?? null,

            // URLs for actions
            'urls' => [
                'show' => route('sp-sipt.show', $spSipt),
                'edit' => route('sp-sipt.edit', $spSipt),
                'print' => route('sp-sipt.print', $spSipt),
                'download' => route('sp-sipt.exportPdf', $spSipt)
            ]
        ];

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

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

/**
 * Get status label for display
 */
private function getStatusLabel($status)
{
    return match($status) {
        'draft' => 'Draft',
        'submitted' => 'Belum Selesai',
        'in_review' => 'Sedang Ditinjau',
        'approved' => 'Terverifikasi',
        'rejected' => 'Ditolak',
        default => 'Status Tidak Dikenal'
    };
}

/**
 * Get status CSS class
 */
private function getStatusClass($status)
{
    return match($status) {
        'draft' => 'text-secondary',
        'submitted' => 'text-warning',
        'in_review' => 'text-info',
        'approved' => 'text-success',
        'rejected' => 'text-danger',
        default => 'text-muted'
    };
}

/**
 * Format file size for display
 */
private function formatFileSize($bytes)
{
    if ($bytes === null || $bytes === 0) {
        return '0 B';
    }

    $units = ['B', 'KB', 'MB', 'GB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);

    $bytes /= (1 << (10 * $pow));

    return round($bytes, 2) . ' ' . $units[$pow];
}

/**
 * Update status via AJAX (untuk popup)
 */
public function updateStatusAjax(Request $request, SpSipt $spSipt)
{
    try {
        $validated = $request->validate([
            'status' => 'required|in:draft,submitted,in_review,approved,rejected',
            'catatan' => 'nullable|string|max:1000'
        ]);

        // Check permissions
        if (in_array($validated['status'], ['approved', 'rejected'])) {
            if (!auth()->user()->can('approve', $spSipt)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki izin untuk mengubah status ini.'
                ], 403);
            }
        }

        DB::beginTransaction();

        // Update status
        $spSipt->updateStatus(
            $validated['status'],
            $validated['catatan'] ?? null,
            auth()->id()
        );

        // Add catatan if provided
        if (!empty($validated['catatan'])) {
            $spSipt->catatan()->create([
                'catatan' => $validated['catatan'],
                'jenis_catatan' => $validated['status'] === 'rejected'
                    ? SpSiptCatatan::JENIS_REVISI
                    : SpSiptCatatan::JENIS_FEEDBACK,
                'is_visible_to_pemohon' => true,
                'created_by' => auth()->id()
            ]);
        }

        DB::commit();

        return response()->json([
            'success' => true,
            'message' => 'Status berhasil diperbarui.',
            'data' => [
                'status' => $spSipt->status,
                'status_label' => $this->getStatusLabel($spSipt->status),
                'status_class' => $this->getStatusClass($spSipt->status),
                'updated_at' => $spSipt->updated_at->format('d/m/Y H:i')
            ]
        ]);

    } catch (\Illuminate\Validation\ValidationException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Data tidak valid.',
            'errors' => $e->errors()
        ], 422);

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

        return response()->json([
            'success' => false,
            'message' => 'Gagal mengubah status: ' . $e->getMessage()
        ], 500);
    }
}

/**
 * Download document via AJAX
 */
public function downloadDocument(SpSipt $spSipt, $documentType = null)
{
    try {
        // If specific document type requested
        if ($documentType) {
            $dokumen = $spSipt->dokumen()
                ->where('jenis_dokumen', $documentType)
                ->first();

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

            if (!Storage::exists($dokumen->path_file)) {
                return response()->json([
                    'success' => false,
                    'message' => 'File tidak ditemukan di server.'
                ], 404);
            }

            return Storage::download($dokumen->path_file, $dokumen->nama_file);
        }

        // Default: generate PDF document
        return $this->exportPdf($spSipt);

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

/**
 * Send document via email
 */
public function sendEmail(Request $request, SpSipt $spSipt)
{
    try {
        $validated = $request->validate([
            'email' => 'required|email',
            'subject' => 'nullable|string|max:255',
            'message' => 'nullable|string|max:1000'
        ]);

        $subject = $validated['subject'] ?? 'Dokumen SP-MPT ' . $spSipt->nomor_surat;
        $message = $validated['message'] ?? 'Terlampir dokumen Surat Pernyataan Melepaskan Penguasaan Tanah.';

        // Generate PDF for attachment
        $pdf = \PDF::loadView('sp-sipt.pdf', compact('spSipt'));
        $pdfContent = $pdf->output();

        // Send email with attachment
        \Mail::send('emails.sp-sipt-document', [
            'spSipt' => $spSipt,
            'message' => $message
        ], function ($mail) use ($validated, $subject, $pdfContent, $spSipt) {
            $mail->to($validated['email'])
                 ->subject($subject)
                 ->attachData($pdfContent, 'SP-MPT-' . $spSipt->nomor_surat . '.pdf', [
                     'mime' => 'application/pdf'
                 ]);
        });

        return response()->json([
            'success' => true,
            'message' => 'Email berhasil dikirim ke ' . $validated['email']
        ]);

    } catch (\Illuminate\Validation\ValidationException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Data tidak valid.',
            'errors' => $e->errors()
        ], 422);

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

/**
 * Get statistics for popup dashboard
 */
public function getStatistics()
{
    try {
        $statistics = [
            'total' => SpSipt::count(),
            'draft' => SpSipt::where('status', 'draft')->count(),
            'submitted' => SpSipt::where('status', 'submitted')->count(),
            'in_review' => SpSipt::where('status', 'in_review')->count(),
            'approved' => SpSipt::where('status', 'approved')->count(),
            'rejected' => SpSipt::where('status', 'rejected')->count(),
            'this_month' => SpSipt::whereMonth('created_at', date('m'))
                                 ->whereYear('created_at', date('Y'))
                                 ->count(),
            'this_week' => SpSipt::whereBetween('created_at', [
                now()->startOfWeek(),
                now()->endOfWeek()
            ])->count(),
        ];

        // Monthly trend (last 6 months)
        $monthlyTrend = SpSipt::select(
                DB::raw('YEAR(created_at) as year'),
                DB::raw('MONTH(created_at) as month'),
                DB::raw('COUNT(*) as total')
            )
            ->where('created_at', '>=', now()->subMonths(6))
            ->groupBy('year', 'month')
            ->orderBy('year')
            ->orderBy('month')
            ->get()
            ->map(function($item) {
                $item->month_name = date('M Y', mktime(0, 0, 0, $item->month, 1, $item->year));
                return $item;
            });

        // By location
        $byLocation = SpSipt::select('kampung', DB::raw('COUNT(*) as total'))
            ->whereNotNull('kampung')
            ->with('kampung:id,nama_kampung')
            ->groupBy('kampung')
            ->orderByDesc('total')
            ->limit(10)
            ->get()
            ->map(function($item) {
                $item->kampung_name = $item->kampung->nama_kampung ?? 'Tidak diketahui';
                return $item;
            });

        return response()->json([
            'success' => true,
            'data' => [
                'statistics' => $statistics,
                'monthly_trend' => $monthlyTrend,
                'by_location' => $byLocation
            ]
        ]);

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

    public function exportPdf(SpSipt $spSipt)
    {
        try {
            $spSipt->load([
                'dokumen',
                'dataKampung',
                'kecamatan',
                'creator'
            ]);

            // Install package jika belum ada: composer require barryvdh/laravel-dompdf
            $pdf = \PDF::loadView('admin.sp-sipt.pdf', compact('spSipt'));

            return $pdf->download('SP-MPT-' . ($spSipt->nomor_surat ?? $spSipt->id) . '.pdf');

        } catch (\Exception $e) {
            return back()->with('error', 'Gagal mengunduh PDF: ' . $e->getMessage());
        }
    }
    // Tambahkan method di SpSiptController
    public function preview(SpSipt $spSipt)
    {
        $spSipt->load([
            'dokumen',
            'dataKampung',
            'kecamatan',
            'creator'
        ]);

        return view('admin.sp-sipt.print', compact('spSipt'))
            ->with('preview', true);
    }
    public function deleteDokumen($id)
{
    $dokumen = SpSiptDokumen::findOrFail($id);

    // Hapus file dari storage
    if (Storage::exists($dokumen->path_file)) {
        Storage::delete($dokumen->path_file);
    }

    // Hapus record dari database
    $dokumen->delete();

    return back()->with('success', 'Dokumen berhasil dihapus');
}
}
