<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreAnnouncementRequest;
use App\Http\Requests\Admin\UpdateAnnouncementRequest;
use App\Models\Announcement;
use App\Services\ActivityLogService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class AnnouncementController extends Controller
{
    public function __construct(
        protected ActivityLogService $activityLogService
    ) {}

    /**
     * Display a listing of announcements.
     */
    public function index(): Response
    {
        $announcements = Announcement::latest()->paginate(15);

        return Inertia::render('Admin/Announcements/Index', [
            'announcements' => $announcements,
        ]);
    }

    /**
     * Show the form for creating a new announcement.
     */
    public function create(): Response
    {
        return Inertia::render('Admin/Announcements/Create');
    }

    /**
     * Store a newly created announcement.
     */
    public function store(StoreAnnouncementRequest $request): RedirectResponse
    {
        $announcement = Announcement::create($request->validated());

        // Log create activity
        $this->activityLogService->logCreate($announcement);

        return redirect()->route('admin.announcements.index')
            ->with('success', 'Announcement berhasil dibuat.');
    }

    /**
     * Show the form for editing the specified announcement.
     */
    public function edit(Announcement $announcement): Response
    {
        return Inertia::render('Admin/Announcements/Edit', [
            'announcement' => $announcement,
        ]);
    }

    /**
     * Update the specified announcement.
     */
    public function update(UpdateAnnouncementRequest $request, Announcement $announcement): RedirectResponse
    {
        $announcement->update($request->validated());

        // Log update activity
        $this->activityLogService->logUpdate($announcement);

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

    /**
     * Remove the specified announcement.
     */
    public function destroy(Announcement $announcement): RedirectResponse
    {
        // Log delete activity
        $this->activityLogService->logDelete($announcement);

        $announcement->delete();

        return redirect()->route('admin.announcements.index')
            ->with('success', 'Announcement berhasil dihapus.');
    }
}
