<?php

namespace App\Http\Controllers\SchoolAdmin;

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

class AnnouncementController extends Controller
{
    public function index()
    {
        $announcements = Announcement::where('school_id', auth()->user()->school_id)
            ->latest()
            ->paginate(10);
        return view('schooladmin.communication.announcements.index', compact('announcements'));
    }

    public function create()
    {
        return view('schooladmin.communication.announcements.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'target_role' => 'required|string', // students, teachers, parents, all
        ]);

        Announcement::create([
            'school_id' => auth()->user()->school_id,
            'title' => $request->title,
            'content' => $request->content,
            'target_role' => $request->target_role,
            'created_by' => auth()->id(),
        ]);

        return redirect()->route('schooladmin.communication.announcements.index')
            ->with('success', 'Announcement broadcasted successfully.');
    }

    public function edit(Announcement $announcement)
    {
        return view('schooladmin.communication.announcements.edit', compact('announcement'));
    }

    public function update(Request $request, Announcement $announcement)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'target_role' => 'required|string',
        ]);

        $announcement->update($request->only('title', 'content', 'target_role'));

        return redirect()->route('schooladmin.communication.announcements.index')
            ->with('success', 'Announcement updated successfully.');
    }

    public function destroy(Announcement $announcement)
    {
        $announcement->delete();
        return redirect()->route('schooladmin.communication.announcements.index')
            ->with('success', 'Announcement deleted.');
    }
}
