<?php

namespace App\Http\Controllers\Admin;

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

class DemografiController extends Controller
{
    // Middleware is handled at route level in web.php

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $demografi = Demografi::orderBy('kategori')->orderBy('label')->paginate(15);
        return view('admin.demografi.index', compact('demografi'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.demografi.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'kategori' => 'required|string|max:100',
            'label' => 'required|string|max:255',
            'jumlah' => 'required|integer|min:0',
            'keterangan' => 'nullable|string',
            'tahun' => 'required|integer|min:1900|max:' . (date('Y') + 1),
        ]);

        Demografi::create($request->all());

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

    /**
     * Display the specified resource.
     */
    public function show(Demografi $demografi)
    {
        return view('admin.demografi.show', compact('demografi'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Demografi $demografi)
    {
        return view('admin.demografi.edit', compact('demografi'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Demografi $demografi)
    {
        $request->validate([
            'kategori' => 'required|string|max:100',
            'label' => 'required|string|max:255',
            'jumlah' => 'required|integer|min:0',
            'keterangan' => 'nullable|string',
            'tahun' => 'required|integer|min:1900|max:' . (date('Y') + 1),
        ]);

        $demografi->update($request->all());

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Demografi $demografi)
    {
        $demografi->delete();

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