<?php

namespace App\Http\Controllers;

use App\Models\Kampung;
use App\Models\Kecamatan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class KampungController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

     public function __construct()
    {
        $this->middleware('permission:kampung.view', ['only' => ['index', 'show']]);
        $this->middleware('permission:kampung.create', ['only' => ['create', 'store']]);
        $this->middleware('permission:kampung.edit', ['only' => ['edit', 'update']]);
        $this->middleware('permission:kampung.delete', ['only' => ['destroy']]);
    }
    public function index(Request $request)
    {
        $query = Kampung::query();

        // Filter pencarian (kode atau nama kampung)
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('kode', 'like', "%{$search}%")
                ->orWhere('nama', 'like', "%{$search}%");
            });
        }

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

        $kampungs = $query->paginate(10)->appends($request->query());

        return view('admin.kampung.index', compact('kampungs'));
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $kecamatans = Kecamatan::all();
        return view('admin.kampung.create', compact('kecamatans'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'kode_kampung' => 'required|unique:kampung,kode_kampung',
            'nama_kampung' => 'required',
            'kecamatan_id' => 'required|exists:kecamatan,id',
            'alamat_kantor_kampung' => 'required',
            'kode_pos' => 'required|numeric',
            'nama_kepala_kampung' => 'required',
            'nip' => 'nullable',
            'golongan' => 'nullable',
            'pangkat' => 'nullable',
            'luas_wilayah' => 'required|numeric',
            'jumlah_rt' => 'required|integer',
            'jumlah_rw' => 'required|integer',
            'jumlah_penduduk' => 'required|integer',
            'status' => 'required|in:Aktif,Nonaktif',
            'warna' => 'required',
            'geojson' => 'nullable|file|mimes:json|max:2048', // Validasi file GeoJSON
        ]);

        $data = $request->all();

        // Handle file GeoJSON jika ada
        if ($request->hasFile('geojson')) {
            $geojsonFile = $request->file('geojson');
            $fileName = time() . '_' . $geojsonFile->getClientOriginalName();
            $geojsonContent = file_get_contents($geojsonFile->getRealPath());
            $data['geojson'] = json_encode(json_decode($geojsonContent)); // Simpan konten JSON
            $data['geojson_file'] = $fileName; // Simpan nama file
            Storage::putFileAs('public/geojson', $geojsonFile, $fileName); // Simpan file ke storage
        }

        Kampung::create($data);

        return redirect()->route('kampung.index')->with('success', 'Kampung berhasil ditambahkan.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Kampung  $kampung
     * @return \Illuminate\Http\Response
     */
    public function show(Kampung $kampung)
    {
        return view('kampung.show', compact('kampung'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Kampung  $kampung
     * @return \Illuminate\Http\Response
     */
    public function edit(Kampung $kampung)
    {
        $kecamatans = Kecamatan::all();
        return view('admin.kampung.edit', compact('kampung', 'kecamatans'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Kampung  $kampung
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Kampung $kampung)
    {
        $request->validate([
            'kode_kampung' => 'required|unique:kampung,kode_kampung,' . $kampung->id,
            'nama_kampung' => 'required',
            'kecamatan_id' => 'required|exists:kecamatan,id',
            'alamat_kantor_kampung' => 'required',
            'kode_pos' => 'required|numeric',
            'nama_kepala_kampung' => 'required',
            'nip' => 'nullable',
            'golongan' => 'nullable',
            'pangkat' => 'nullable',
            'luas_wilayah' => 'required|numeric',
            'jumlah_rt' => 'required|integer',
            'jumlah_rw' => 'required|integer',
            'jumlah_penduduk' => 'required|integer',
            'status' => 'required|in:Aktif,Nonaktif',
            'warna' => 'required',
            'geojson' => 'nullable|file|mimes:json|max:2048', // Validasi file GeoJSON
        ]);

        $data = $request->all();

        // Handle file GeoJSON jika ada
        if ($request->hasFile('geojson')) {
            // Hapus file lama jika ada
            if ($kampung->geojson_file && Storage::exists('public/geojson/' . $kampung->geojson_file)) {
                Storage::delete('public/geojson/' . $kampung->geojson_file);
            }

            $geojsonFile = $request->file('geojson');
            $fileName = time() . '_' . $geojsonFile->getClientOriginalName();
            $geojsonContent = file_get_contents($geojsonFile->getRealPath());
            $data['geojson'] = json_encode(json_decode($geojsonContent)); // Simpan konten JSON
            $data['geojson_file'] = $fileName; // Simpan nama file baru
            Storage::putFileAs('public/geojson', $geojsonFile, $fileName); // Simpan file baru
        } elseif ($request->input('geojson') === null && $request->has('remove_geojson')) {
            // Hapus file dan konten jika ada permintaan penghapusan
            if ($kampung->geojson_file && Storage::exists('public/geojson/' . $kampung->geojson_file)) {
                Storage::delete('public/geojson/' . $kampung->geojson_file);
            }
            $data['geojson'] = null;
            $data['geojson_file'] = null;
        }

        $kampung->update($data);

        return redirect()->route('kampung.index')->with('success', 'Kampung berhasil diperbarui.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Kampung  $kampung
     * @return \Illuminate\Http\Response
     */
    public function destroy(Kampung $kampung)
    {
        $kampung->delete();

        return redirect()->route('admin.kampung.index')->with('success', 'Kampung berhasil dihapus.');
    }
}
