<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\DataKK;
use App\Models\DataMustahik;

class RtController extends Controller
{
    /**
     * Dashboard Ketua RT
     */
    public function dashboard()
    {
        $user = Auth::user();
        $masjidId = $user->id_masjid;
        $wilayahId = $user->id_wilayah;

        $totalKk = DataKK::where('id_masjid', $masjidId)
            ->where('id_wilayah', $wilayahId)
            ->count();

        $totalMustahik = DataMustahik::whereHas('kk', function($q) use ($wilayahId) {
                $q->where('id_wilayah', $wilayahId);
            })
            ->where('id_masjid', $masjidId)
            ->count();

        $pendingMustahik = DataMustahik::whereHas('kk', function($q) use ($wilayahId) {
                $q->where('id_wilayah', $wilayahId);
            })
            ->where('id_masjid', $masjidId)
            ->where('status', 'Pending')
            ->count();

        $pengajuanTerbaru = DataMustahik::whereHas('kk', function($q) use ($wilayahId) {
                $q->where('id_wilayah', $wilayahId);
            })
            ->where('id_masjid', $masjidId)
            ->orderBy('tanggal_pengajuan', 'desc')
            ->take(5)
            ->get();

        return view('rt.dashboard', compact('totalKk', 'totalMustahik', 'pendingMustahik', 'pengajuanTerbaru'));
    }

    /**
     * Halaman Data KK & Mustahik untuk RT
     */
    public function dataWarga(Request $request)
    {
        $user = Auth::user();
        $masjidId = $user->id_masjid;
        $wilayahId = $user->id_wilayah;

        $dataKk = DataKK::where('id_masjid', $masjidId)
            ->where('id_wilayah', $wilayahId)
            ->orderBy('created_at', 'desc')
            ->paginate(15, ['*'], 'kk_page');

        // Untuk Dropdown Filter Mustahik
        $listKk = DataKK::where('id_masjid', $masjidId)
            ->where('id_wilayah', $wilayahId)
            ->get();

        $mustahikQuery = DataMustahik::where('id_masjid', $masjidId)
            ->whereHas('kk', function($q) use ($wilayahId) {
                $q->where('id_wilayah', $wilayahId);
            })
            ->with('kk');

        if ($request->filled('filter_kk')) {
            $mustahikQuery->where('id_kk', $request->filter_kk);
        }

        $dataMustahik = $mustahikQuery->orderBy('tanggal_pengajuan', 'desc')
            ->paginate(15, ['*'], 'mustahik_page')
            ->withQueryString();

        return view('rt.data_warga', compact('dataKk', 'listKk', 'dataMustahik'));
    }

    /**
     * Halaman Status Pengajuan Mustahik
     */
    public function statusPengajuan(Request $request)
    {
        $user = Auth::user();
        $masjidId = $user->id_masjid;
        $wilayahId = $user->id_wilayah;

        $query = DataMustahik::where('id_masjid', $masjidId)
            ->whereHas('kk', function($q) use ($wilayahId) {
                $q->where('id_wilayah', $wilayahId);
            })
            ->with(['kk', 'mustahikHistories' => function($q) {
                $q->orderBy('created_at', 'desc')->take(1);
            }]);

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

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('nama_mustahik', 'like', "%{$search}%");
        }

        $pengajuan = $query->orderBy('tanggal_pengajuan', 'desc')->paginate(15)->withQueryString();

        return view('rt.status_pengajuan', compact('pengajuan'));
    }

    /**
     * Menyimpan data KK baru dari RT
     */
    public function storeKk(Request $request)
    {
        $request->validate([
            'nik_kepala_kk' => 'required|string|max:20|unique:DataKK,nik_kepala_kk',
            'nama_kepala_kk' => 'required|string|max:100',
            'alamat_rumah' => 'required|string',
            'jumlah_tanggungan' => 'required|integer|min:0'
        ]);

        DataKK::create([
            'id_masjid' => Auth::user()->id_masjid,
            'id_wilayah' => Auth::user()->id_wilayah,
            'nik_kepala_kk' => $request->nik_kepala_kk,
            'nama_kepala_kk' => $request->nama_kepala_kk,
            'alamat_rumah' => $request->alamat_rumah,
            'jumlah_tanggungan' => $request->jumlah_tanggungan,
            'status_ekonomi' => 'Mampu' // default
        ]);

        return redirect()->back()->with('success', 'Data Kartu Keluarga berhasil ditambahkan!');
    }

    /**
     * Menyimpan data Mustahik baru dari RT
     */
    public function storeMustahik(Request $request)
    {
        if ($request->has('pendapatan_bulanan')) {
            $request->merge([
                'pendapatan_bulanan' => preg_replace('/[^0-9]/', '', $request->pendapatan_bulanan)
            ]);
        }

        $request->validate([
            'id_kk' => 'required|exists:DataKK,id_kk',
            'nama_mustahik' => 'required|string|max:100',
            'nik_kepala_kk' => 'required|string',
            'hub_dengan_kk' => 'nullable|string',
            'pekerjaan' => 'required|string',
            'pendapatan_bulanan' => 'required|numeric',
            'status_kepemilikan_rumah' => 'required|in:Milik Sendiri,Sewa,Menumpang,Lainnya',
            'status_kondisi_warga' => 'required|in:Mampu,Tidak Mampu',
            'kategori_asnaf' => 'required|in:Fakir,Miskin,Gharim,Ibnu Sabil'
        ]);

        DataMustahik::create([
            'id_masjid' => Auth::user()->id_masjid,
            'id_kk' => $request->id_kk,
            'nama_mustahik' => $request->nama_mustahik,
            'nik_kepala_kk' => $request->nik_kepala_kk,
            'hub_dengan_kk' => $request->hub_dengan_kk,
            'no_hp' => $request->no_hp ?? '-',
            'tgl_lahir' => $request->tgl_lahir ?? date('Y-m-d'),
            'pekerjaan' => $request->pekerjaan,
            'pendapatan_bulanan' => $request->pendapatan_bulanan,
            'status_kepemilikan_rumah' => $request->status_kepemilikan_rumah,
            'status_kondisi_warga' => $request->status_kondisi_warga,
            'kategori_asnaf' => $request->kategori_asnaf,
            'status' => 'Pending',
            'tanggal_pengajuan' => now()
        ]);

        return redirect()->back()->with('success', 'Data pengajuan Mustahik berhasil dikirim ke Amil!');
    }

    /**
     * Update data KK
     */
    public function updateKk(Request $request, $id)
    {
        $kk = DataKK::where('id_masjid', Auth::user()->id_masjid)
                    ->where('id_wilayah', Auth::user()->id_wilayah)
                    ->findOrFail($id);

        $request->validate([
            'nik_kepala_kk' => 'required|string|max:20|unique:DataKK,nik_kepala_kk,' . $id . ',id_kk',
            'nama_kepala_kk' => 'required|string|max:100',
            'alamat_rumah' => 'required|string',
            'jumlah_tanggungan' => 'required|integer|min:0'
        ]);

        $kk->update([
            'nik_kepala_kk' => $request->nik_kepala_kk,
            'nama_kepala_kk' => $request->nama_kepala_kk,
            'alamat_rumah' => $request->alamat_rumah,
            'jumlah_tanggungan' => $request->jumlah_tanggungan,
        ]);

        return redirect()->back()->with('success', 'Data Kartu Keluarga berhasil diubah!');
    }

    /**
     * Update data Mustahik
     */
    public function updateMustahik(Request $request, $id)
    {
        $mustahik = DataMustahik::where('id_masjid', Auth::user()->id_masjid)
                                ->where('status', 'Pending') // Hanya bisa diedit jika masih pending
                                ->findOrFail($id);

        if ($request->has('pendapatan_bulanan')) {
            $request->merge([
                'pendapatan_bulanan' => preg_replace('/[^0-9]/', '', $request->pendapatan_bulanan)
            ]);
        }

        $request->validate([
            'nama_mustahik' => 'required|string|max:100',
            'nik_kepala_kk' => 'required|string',
            'hub_dengan_kk' => 'nullable|string',
            'pekerjaan' => 'required|string',
            'pendapatan_bulanan' => 'required|numeric',
            'status_kepemilikan_rumah' => 'required|in:Milik Sendiri,Sewa,Menumpang,Lainnya',
            'status_kondisi_warga' => 'required|in:Mampu,Tidak Mampu',
            'kategori_asnaf' => 'required|in:Fakir,Miskin,Gharim,Ibnu Sabil'
        ]);

        $mustahik->update([
            'nama_mustahik' => $request->nama_mustahik,
            'nik_kepala_kk' => $request->nik_kepala_kk,
            'hub_dengan_kk' => $request->hub_dengan_kk,
            'pekerjaan' => $request->pekerjaan,
            'pendapatan_bulanan' => $request->pendapatan_bulanan,
            'status_kepemilikan_rumah' => $request->status_kepemilikan_rumah,
            'status_kondisi_warga' => $request->status_kondisi_warga,
            'kategori_asnaf' => $request->kategori_asnaf,
        ]);

        return redirect()->back()->with('success', 'Data Mustahik berhasil diubah!');
    }
}
