<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Pengumuman;

class PengumumanController extends Controller
{
    public function index()
    {
        $pengumumen = Pengumuman::latest()->get();
        return view('admin.pengumuman.index', compact('pengumumen'));
    }

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

    public function store(Request $request)
    {
        $request->validate([
            'keterangan' => 'required|string|max:255',
            'tarikh_mula_papar' => 'required|date',
            'tarikh_tamat_papar' => 'required|date|after_or_equal:tarikh_mula_papar',
        ]);

        Pengumuman::create([
            'keterangan' => $request->keterangan,
            'tarikh_mula_papar' => $request->tarikh_mula_papar,
            'tarikh_tamat_papar' => $request->tarikh_tamat_papar,
            'admin_id' => Auth::id(),
        ]);

        return redirect()->route('pengumuman.index')->with('success', 'Pengumuman berjaya ditambah.');
    }

    public function edit(Pengumuman $pengumuman)
    {
        return view('admin.pengumuman.edit', compact('pengumuman'));
    }

    public function update(Request $request, Pengumuman $pengumuman)
    {
        $request->validate([
            'keterangan' => 'required|string|max:255',
            'tarikh_mula_papar' => 'required|date',
            'tarikh_tamat_papar' => 'required|date|after_or_equal:tarikh_mula_papar',
        ]);

        $pengumuman->update([
            'keterangan' => $request->keterangan,
            'tarikh_mula_papar' => $request->tarikh_mula_papar,
            'tarikh_tamat_papar' => $request->tarikh_tamat_papar,
        ]);

        return redirect()->route('pengumuman.index')->with('success', 'Pengumuman berjaya dikemaskini.');
    }

    public function destroy(Pengumuman $pengumuman)
    {
        $pengumuman->delete();
        return redirect()->route('pengumuman.index')->with('success', 'Pengumuman dipadam.');
    }
}
