<?php

namespace App\Http\Controllers;

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

class LaporanController extends Controller
{
    /**
     * Tampilkan laporan data mustahik dengan filter
     * Aktor: Admin Masjid
     */
    public function index(Request $request)
    {
        $masjidId = Auth::user()->id_masjid;

        // Daftar wilayah untuk dropdown filter
        $wilayahList = Wilayah::where('id_masjid', $masjidId)->orderBy('rt')->get();

        // Query mustahik dengan filter
        $query = DataMustahik::where('id_masjid', $masjidId)
                             ->with(['kk.wilayah']);

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

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

        // Filter wilayah (melalui join DataKK)
        if ($request->filled('wilayah')) {
            $niks = DataKK::where('id_wilayah', $request->wilayah)->pluck('nik_kepala_kk');
            $query->whereIn('nik_kepala_kk', $niks);
        }

        // Search NIK atau Nama
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('nama_mustahik', 'like', "%{$search}%")
                  ->orWhere('nik_kepala_kk', 'like', "%{$search}%");
            });
        }

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

        return view('admin.laporan.index', compact('mustahik', 'wilayahList'));
    }

    /**
     * Export Excel (placeholder)
     */
    public function exportExcel(Request $request)
    {
        // TODO: Implementasi dengan Laravel Excel / Maatwebsite
        return redirect('/admin/laporan')->with('success', 'Fitur export Excel akan segera tersedia.');
    }

    /**
     * Export PDF (placeholder)
     */
    public function exportPdf(Request $request)
    {
        // TODO: Implementasi dengan Dompdf / Barryvdh
        return redirect('/admin/laporan')->with('success', 'Fitur export PDF akan segera tersedia.');
    }
}
