<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Materi;
use App\Models\Tugas;
use Carbon\Carbon;

class NotifikasiController extends Controller
{
    public function index()
    {
        $since = Carbon::now()->subDays(7);

        // Materi baru dari semua guru
        $materiBaru = Materi::with(['mengajar.guru', 'mengajar.mapel', 'mengajar.kelas'])
            ->where('created_at', '>=', $since)
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(fn($m) => [
                'type'    => 'materi',
                'title'   => 'Materi Diunggah',
                'message' => optional($m->mengajar->guru)->nama . ' mengupload: ' . $m->judul_materi,
                'sub'     => optional($m->mengajar->mapel)->nama_mapel . ' · ' . optional($m->mengajar->kelas)->nama_kelas,
                'time'    => $m->created_at->diffForHumans(),
                'time_raw'=> $m->created_at->toIso8601String(),
            ]);

        // Tugas baru dari semua guru
        $tugasBaru = Tugas::with(['mengajar.guru', 'mengajar.mapel', 'mengajar.kelas'])
            ->where('created_at', '>=', $since)
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(fn($t) => [
                'type'    => 'tugas',
                'title'   => 'Tugas Dibuat',
                'message' => optional($t->mengajar->guru)->nama . ' membuat: ' . $t->judul_tugas,
                'sub'     => optional($t->mengajar->mapel)->nama_mapel . ' · ' . optional($t->mengajar->kelas)->nama_kelas,
                'time'    => $t->created_at->diffForHumans(),
                'time_raw'=> $t->created_at->toIso8601String(),
            ]);

        $notifications = $materiBaru->concat($tugasBaru)
            ->sortByDesc('time_raw')
            ->values();

        return response()->json([
            'count'         => $notifications->count(),
            'notifications' => $notifications,
        ]);
    }
}