<?php

namespace App\Http\Controllers\Admin\DataUmum;

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

class EkstrakulikulerController extends Controller
{
    public function index()
    {
        try {
            $items = Ekstrakulikuler::orderByRaw("CASE WHEN kategori='wajib 1' THEN 1 WHEN kategori='wajib 2' THEN 2 WHEN kategori='wajib 3' THEN 3 WHEN kategori='pilihan' THEN 4 ELSE 5 END")
                ->orderBy('nama')
                ->paginate(15);
        } catch (\Throwable $e) {
            $items = collect();
        }

        return view('admin.data-umum.ekstrakulikuler.index', compact('items'));
    }

    public function create()
    {
        return view('admin.data-umum.ekstrakulikuler.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'nama' => 'required|string|max:255',
            'keterangan' => 'nullable|string',
            'kategori' => 'required|string|in:wajib 1,wajib 2,wajib 3,pilihan',
        ]);

        try {
            Ekstrakulikuler::create($validated);
            return redirect('admin/data-umum/ekstrakulikuler')->with('success', 'Ekstrakulikuler berhasil ditambahkan.');
        } catch (\Throwable $e) {
            return redirect()->back()->with('error', 'Gagal menyimpan: ' . $e->getMessage());
        }
    }

    public function edit($id)
    {
        $item = Ekstrakulikuler::findOrFail($id);
        return view('admin.data-umum.ekstrakulikuler.edit', compact('item'));
    }

    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'nama' => 'required|string|max:255',
            'keterangan' => 'nullable|string',
            'kategori' => 'required|string|in:wajib 1,wajib 2,wajib 3,pilihan',
        ]);

        try {
            $item = Ekstrakulikuler::findOrFail($id);
            $item->update($validated);
            return redirect('admin/data-umum/ekstrakulikuler')->with('success', 'Ekstrakulikuler berhasil diperbarui.');
        } catch (\Throwable $e) {
            return redirect()->back()->with('error', 'Gagal memperbarui: ' . $e->getMessage());
        }
    }

    public function destroy($id)
    {
        try {
            $item = Ekstrakulikuler::findOrFail($id);
            $item->delete();
            return redirect()->back()->with('success', 'Ekstrakulikuler berhasil dihapus.');
        } catch (\Throwable $e) {
            return redirect()->back()->with('error', 'Gagal menghapus: ' . $e->getMessage());
        }
    }
}
