<?php

namespace App\Http\Controllers\School;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class AnnouncementController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $announcements = $schoolId
            ? DB::table('announcements')
                ->leftJoin('users', 'users.id', '=', 'announcements.created_by')
                ->where('announcements.school_id', $schoolId)
                ->orderByDesc('announcements.created_at')
                ->limit(50)
                ->get([
                    'announcements.id',
                    'announcements.title',
                    'announcements.body',
                    'announcements.audience',
                    'announcements.is_important',
                    'announcements.published_at',
                    'users.first_name as creator_first_name',
                    'users.last_name as creator_last_name',
                ])
            : collect();

        return Inertia::render('School/Announcements', [
            'announcements' => $announcements->map(fn ($ann): array => [
                'id' => (int) $ann->id,
                'title' => $ann->title,
                'body' => $ann->body,
                'audience' => $ann->audience,
                'isImportant' => (bool) $ann->is_important,
                'publishedAt' => $ann->published_at ? $this->jalaliDate($ann->published_at, true) : 'پیش‌نویس',
                'creator' => trim(($ann->creator_first_name ?? '').' '.($ann->creator_last_name ?? '')) ?: '—',
            ])->values(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        abort_unless($schoolId, 422, 'مدرسه مشخص نیست.');

        $data = $request->validate([
            'title' => ['required', 'string', 'max:190'],
            'body' => ['required', 'string', 'max:5000'],
            'audience' => ['required', 'string', 'in:all,students,teachers,parents'],
            'is_important' => ['boolean'],
        ]);

        DB::table('announcements')->insert([
            'school_id' => $schoolId,
            'title' => $data['title'],
            'body' => $data['body'],
            'audience' => $data['audience'],
            'is_important' => $data['is_important'] ?? false,
            'published_at' => now(),
            'created_by' => $request->user()?->id,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return redirect()->route('school.announcements')->with('success', 'اطلاعیه منتشر شد.');
    }

    public function destroy(Request $request, int $id): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);

        $exists = DB::table('announcements')
            ->where('school_id', $schoolId)
            ->where('id', $id)
            ->exists();

        abort_unless($exists, 404);

        DB::table('announcements')->where('id', $id)->delete();

        return redirect()->route('school.announcements')->with('success', 'اطلاعیه حذف شد.');
    }
}
