MIF_E31230356/app/Http/Controllers/Admin/NotifikasiController.php

70 lines
2.7 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Materi;
use App\Models\Tugas;
use App\Models\PesertaChallenge;
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(),
]);
// Siswa yang mengumpulkan challenge
$challengeKumpul = PesertaChallenge::with(['siswa', 'challenge'])
->where('waktu_submit', '>=', $since)
->orderBy('waktu_submit', 'desc')
->get()
->map(fn($p) => [
'type' => 'challenge',
'title' => 'Challenge Dikumpulkan',
'message' => optional($p->siswa)->nama . ' mengumpulkan challenge',
'sub' => optional($p->challenge)->judul_challenge ?? '-',
'time' => Carbon::parse($p->waktu_submit)->diffForHumans(),
'time_raw'=> Carbon::parse($p->waktu_submit)->toIso8601String(),
]);
$notifications = $materiBaru
->concat($tugasBaru)
->concat($challengeKumpul)
->sortByDesc('time_raw')
->values();
return response()->json([
'count' => $notifications->count(),
'notifications' => $notifications,
]);
}
}