<?php

namespace App\Http\Controllers\Admin;

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

class KalenderController extends Controller
{
    public function index()
    {
        $events = Kalender::orderBy('tanggal')->get()->map(function ($item) {
            return [
                'id' => $item->id,
                'nama' => $item->nama,
                'tanggal' => $item->tanggal->translatedFormat('d M Y'),
                'tanggal_raw' => $item->tanggal->format('Y-m-d'),
                'waktu' => $item->waktu ? substr($item->waktu, 0, 5) : null,
                'type' => $item->tipe,
                'deskripsi' => $item->deskripsi,
                'tempat' => $item->tempat,
                'aktif' => $item->aktif,
            ];
        })->toArray();
        
        return view('admin.kalender.index', compact('events'));
    }

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

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

        Kalender::create([
            'nama' => $request->nama,
            'tanggal' => $request->tanggal,
            'waktu' => $request->waktu,
            'tipe' => $request->tipe,
            'deskripsi' => $request->deskripsi,
            'tempat' => $request->tempat,
            'aktif' => $request->has('aktif') || !$request->has('_method'),
        ]);

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

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

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

        $event = Kalender::findOrFail($id);
        $event->update([
            'nama' => $request->nama,
            'tanggal' => $request->tanggal,
            'waktu' => $request->waktu,
            'tipe' => $request->tipe,
            'deskripsi' => $request->deskripsi,
            'tempat' => $request->tempat,
            'aktif' => $request->has('aktif'),
        ]);

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

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