<?php

namespace App\Http\Controllers\Admin;

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

class KasusController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->input('search');
        $monthsOrder = "'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'";

        $query = Kasus::query();

        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('bulan', 'like', "%{$search}%")
                  ->orWhere('tahun', 'like', "%{$search}%")
                  ->orWhere('jumlah_kasus', 'like', "%{$search}%");
            });
        }

        $kasuses = $query->orderBy('tahun', 'desc')
                         ->orderByRaw("FIELD(bulan, $monthsOrder)")
                         ->paginate(10);

        return view('admin.kasus.index', compact('kasuses'));
    }

    public function create()
    {
        return view('admin.kasus.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'bulan' => 'required|string|max:255',
            'jumlah_kasus' => 'required|integer|min:0',
            'tahun' => 'required|integer|min:1900|max:' . (date('Y') + 1),
        ]);

        Kasus::create($validated);

        return redirect()->route('admin.kasus.index')->with('success', 'Data kasus berhasil ditambahkan.');
    }

    // Edit dengan parameter model binding nama $kasus agar konsisten dengan update
    public function edit(Kasus $kasu)
{
    return view('admin.kasus.edit', compact('kasu'));
}


    // Update method pakai parameter $kasus dan input spesifik
public function update(Request $request, Kasus $kasu)
{
    $validated = $request->validate([
        'bulan' => 'required|string|max:255',
        'jumlah_kasus' => 'required|integer|min:0',
        'tahun' => 'required|integer|min:1900|max:' . (date('Y') + 1),
    ]);

    $kasu->update($validated);

    return redirect()->route('admin.kasus.index')->with('success', 'Data kasus berhasil diperbarui.');
}


    public function destroy(Kasus $kasus)
    {
        $kasus->delete();
        return redirect()->route('admin.kasus.index')->with('success', 'Data kasus berhasil dihapus.');
    }
}