<?php

namespace App\Http\Controllers\Admin;

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

class JadwalController extends Controller
{
    public function index()
    {
        $jadwalList = JadwalIbadah::orderBy('hari')->orderBy('waktu')->paginate(10);

        return view('admin.jadwal.index', compact('jadwalList'));
    }

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

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

        JadwalIbadah::create([
            'nama' => $request->nama,
            'hari' => $request->hari,
            'waktu' => $request->waktu,
            'tempat' => $request->tempat,
            'pelayan' => $request->pelayan,
            'tipe' => $request->tipe ?? 'mingguan',
            'aktif' => $request->has('aktif'),
        ]);

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

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

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

        $jadwal = JadwalIbadah::findOrFail($id);
        $jadwal->update([
            'nama' => $request->nama,
            'hari' => $request->hari,
            'waktu' => $request->waktu,
            'tempat' => $request->tempat,
            'pelayan' => $request->pelayan,
            'tipe' => $request->tipe ?? 'mingguan',
            'aktif' => $request->has('aktif'),
        ]);

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

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