<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Kegiatan;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class KegiatanController extends Controller
{
    public function index()
    {
        $kegiatanList = Kegiatan::orderBy('created_at', 'desc')->paginate(10);

        return view('admin.kegiatan.index', compact('kegiatanList'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'nama' => 'required|string|max:255',
            'tipe' => 'required|in:rutin,khusus',
        ]);

        Kegiatan::create([
            'nama' => $request->nama,
            'slug' => Str::slug($request->nama),
            'tipe' => $request->tipe,
            'jadwal' => $request->jadwal,
            'tanggal' => $request->tanggal,
            'waktu' => $request->waktu,
            'tempat' => $request->tempat,
            'deskripsi' => $request->deskripsi,
            'kategori' => $request->kategori,
            'dokumentasi' => null,
            'aktif' => $request->has('aktif'),
        ]);

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

    public function edit($id)
    {
        $kegiatan = Kegiatan::findOrFail($id);
        return view('admin.kegiatan.form', compact('kegiatan'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'nama' => 'required|string|max:255',
            'tipe' => 'required|in:rutin,khusus',
        ]);

        $kegiatan = Kegiatan::findOrFail($id);
        $kegiatan->update([
            'nama' => $request->nama,
            'slug' => Str::slug($request->nama),
            'tipe' => $request->tipe,
            'jadwal' => $request->jadwal,
            'tanggal' => $request->tanggal,
            'waktu' => $request->waktu,
            'tempat' => $request->tempat,
            'deskripsi' => $request->deskripsi,
            'kategori' => $request->kategori,
            'aktif' => $request->has('aktif'),
        ]);

        return redirect()->route('admin.kegiatan.index')->with('success', 'Kegiatan berhasil diupdate.');
    }

    public function destroy($id)
    {
        Kegiatan::findOrFail($id)->delete();
        return redirect()->route('admin.kegiatan.index')->with('success', 'Kegiatan berhasil dihapus.');
    }
}
