<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreAnnouncementRequest;
use App\Models\Announcement;
use App\Models\Department;
use App\Models\Role;
use App\Services\AnnouncementService;
use Inertia\Inertia;
use Inertia\Response;

class AnnouncementController extends Controller
{
    public function __construct(
        protected AnnouncementService $announcementService
    ) {}

    public function index(): Response
    {
        $announcements = Announcement::with(['creator', 'departments', 'roles'])
            ->withCount('readByUsers')
            ->latest()
            ->when(request('search'), function ($query, $search) {
                $query->where('title', 'like', "%{$search}%");
            })
            ->paginate(10)
            ->withQueryString();

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

    public function create(): Response
    {
        return Inertia::render('Admin/Announcements/Create', [
            'departments' => Department::where('status', true)->get(),
            'roles' => Role::all(),
            'users' => \App\Models\User::where('type', 'employee')->where('status', 'active')->get(),
        ]);
    }

    public function store(StoreAnnouncementRequest $request)
    {
        $this->announcementService->save($request->validated());

        return redirect()->route('admin.announcements.index')
            ->with('success', __('announcement_created_successfully'));
    }

    public function edit(Announcement $announcement): Response
    {
        $announcement->load(['departments', 'roles', 'users']);

        return Inertia::render('Admin/Announcements/Edit', [
            'announcement' => $announcement,
            'departments' => Department::where('status', true)->get(),
            'roles' => Role::all(),
            'users' => \App\Models\User::where('type', 'employee')->where('status', 'active')->get(),
        ]);
    }

    public function update(StoreAnnouncementRequest $request, Announcement $announcement)
    {
        $this->announcementService->save($request->validated(), $announcement);

        return redirect()->route('admin.announcements.index')
            ->with('success', __('announcement_updated_successfully'));
    }

    public function destroy(Announcement $announcement)
    {
        $announcement->delete();

        return redirect()->back()
            ->with('success', __('announcement_deleted_successfully'));
    }
}
