<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Aduan;
use Illuminate\Http\Request;

class AduanController extends Controller
{
    // Daftar 21 Desa di Kecamatan Wonosalam, Kabupaten Demak, Jawa Tengah
    const DESA_WONOSALAM = [
        'botorejo'    => 'Botorejo',
        'bunderan'    => 'Bunderan',
        'doreng'      => 'Doreng',
        'getas'       => 'Getas',
        'jogoloyo'    => 'Jogoloyo',
        'kalianyar'   => 'Kalianyar',
        'karangrejo'  => 'Karangrejo',
        'karangrowo'  => 'Karangrowo',
        'kendaldoyong'=> 'Kendaldoyong',
        'kerangkulon' => 'Kerangkulon',
        'kuncir'      => 'Kuncir',
        'lempuyang'   => 'Lempuyang',
        'mojodemak'   => 'Mojodemak',
        'mranak'      => 'Mranak',
        'mrisen'      => 'Mrisen',
        'pilangrejo'  => 'Pilangrejo',
        'sidomulyo'   => 'Sido Mulyo',
        'tlogodowo'   => 'Tlogodowo',
        'tlogorejo'   => 'Tlogorejo',
        'trengguli'   => 'Trengguli',
        'wonosalam'   => 'Wonosalam',
    ];

    /**
     * Tampilkan daftar aduan aktif (menunggu & diproses).
     */
    public function index(Request $request)
    {
        $query = Aduan::whereIn('status', ['menunggu', 'diproses']);

        // 1. Terapkan Pencarian
        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('nama_pelapor', 'LIKE', "%{$search}%")
                  ->orWhere('nik', 'LIKE', "%{$search}%")
                  ->orWhere('isi_aduan', 'LIKE', "%{$search}%");
            });
        }

        // 2. Terapkan Filter Desa
        if ($desa = $request->input('desa')) {
            $query->where('desa', $desa);
        }

        // 3. Terapkan Filter Status
        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }

        // 4. Terapkan Filter Prioritas
        if ($prioritas = $request->input('prioritas')) {
            $query->where('prioritas', $prioritas);
        }

        // 5. Limit Tampilan (Pagination)
        $perPage = (int) $request->input('per_page', 10);
        if (!in_array($perPage, [10, 50, 100])) {
            $perPage = 10;
        }

        // 6. Urutan (Sort) Prioritas dulu, lalu Tanggal Terbaru
        $aduans = $query->orderByRaw("
            CASE 
                WHEN prioritas = 'penting' THEN 1
                WHEN prioritas = 'biasa' THEN 2
                ELSE 3
            END
        ")->orderBy('created_at', 'desc')->paginate($perPage)->withQueryString();

        return view('admin.index', [
            'aduans'    => $aduans,
            'desaList'  => self::DESA_WONOSALAM,
            'filters'   => $request->only(['search', 'desa', 'status', 'prioritas', 'per_page']),
        ]);
    }

    /**
     * Tampilkan daftar aduan selesai.
     */
    public function selesai(Request $request)
    {
        $query = Aduan::where('status', 'selesai');

        // 1. Terapkan Pencarian
        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('nama_pelapor', 'LIKE', "%{$search}%")
                  ->orWhere('nik', 'LIKE', "%{$search}%")
                  ->orWhere('isi_aduan', 'LIKE', "%{$search}%");
            });
        }

        // 2. Terapkan Filter Desa
        if ($desa = $request->input('desa')) {
            $query->where('desa', $desa);
        }

        // 3. Terapkan Filter Prioritas
        if ($prioritas = $request->input('prioritas')) {
            $query->where('prioritas', $prioritas);
        }

        // 4. Limit Tampilan (Pagination)
        $perPage = (int) $request->input('per_page', 10);
        if (!in_array($perPage, [10, 50, 100])) {
            $perPage = 10;
        }

        $aduans = $query->latest()->paginate($perPage)->withQueryString();

        return view('admin.selesai', [
            'aduans'    => $aduans,
            'desaList'  => self::DESA_WONOSALAM,
            'filters'   => $request->only(['search', 'desa', 'prioritas', 'per_page']),
        ]);
    }

    /**
     * Tampilkan formulir edit / peninjauan aduan.
     */
    public function edit($id)
    {
        $aduan = Aduan::findOrFail($id);

        return view('admin.edit', [
            'aduan'    => $aduan,
            'desaList' => self::DESA_WONOSALAM,
        ]);
    }

    /**
     * Simpan pembaruan aduan (tanggapan, status, prioritas).
     */
    public function update(Request $request, $id)
    {
        $aduan = Aduan::findOrFail($id);

        $request->validate([
            'status'    => 'required|in:menunggu,diproses,selesai',
            'prioritas' => 'required|in:penting,biasa',
            'tanggapan' => 'nullable|string|min:5',
        ], [
            'status.in'        => 'Status yang dipilih tidak valid.',
            'prioritas.in'     => 'Prioritas yang dipilih tidak valid.',
            'tanggapan.min'    => 'Tanggapan minimal berisi 5 karakter.',
        ]);

        $aduan->update([
            'status'    => $request->status,
            'prioritas' => $request->prioritas,
            'tanggapan' => $request->tanggapan,
        ]);

        $redirectRoute = $aduan->status === 'selesai' ? 'admin.aduan.selesai' : 'admin.aduan.index';

        return redirect()->route($redirectRoute)
            ->with('success', 'Aduan berhasil diperbarui dan tanggapan telah disimpan!');
    }

    /**
     * Hapus aduan dari database.
     */
    public function destroy($id)
    {
        $aduan = Aduan::findOrFail($id);
        $aduan->delete();

        return back()->with('success', 'Data pengaduan berhasil dihapus secara permanen.');
    }
}
