<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\AppNotification;
use App\Models\Notice;
use Illuminate\Http\Request;

// G2 — Notices & circulars; publishing also raises an in-app notification.
class NoticeController extends Controller
{
    public function index(Request $request)
    {
        $rows = Notice::query()
            ->when($request->query('audience'), fn ($q, $a) => $q->where('audience', $a))
            ->orderByDesc('created_at')
            ->limit(500)
            ->get();

        return response()->json(['data' => $rows]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => ['required', 'string'],
            'body' => ['nullable', 'string'],
            'audience' => ['required', 'in:all,students,parents,staff,class'],
            'class_id' => ['nullable', 'integer'],
            'priority' => ['nullable', 'in:normal,high'],
            'publish_at' => ['nullable', 'string'],
            'expire_at' => ['nullable', 'string'],
        ]);
        $data['branch_id'] = $request->header('X-Branch-Id');
        $data['created_by'] = $request->user()?->name;
        $data['publish_at'] = $data['publish_at'] ?? now()->toDateString();

        $notice = Notice::create($data);
        // Raise an in-app notification for the bell.
        AppNotification::create([
            'title' => $notice->title,
            'body' => mb_substr($notice->body ?? '', 0, 160),
            'icon' => 'campaign',
            'priority' => $notice->priority === 'high' ? 'high' : 'medium',
        ]);
        ActivityLog::record('create', 'communication', "Published notice: {$notice->title}", $notice);

        return response()->json(['data' => $notice], 201);
    }

    public function update(Request $request, Notice $notice)
    {
        $notice->update($request->only(['title', 'body', 'audience', 'class_id', 'priority', 'publish_at', 'expire_at']));

        return response()->json(['data' => $notice]);
    }

    public function destroy(Notice $notice)
    {
        $notice->delete();
        ActivityLog::record('delete', 'communication', "Deleted notice: {$notice->title}", $notice);

        return response()->json(['success' => true]);
    }
}
