<?php

namespace App\Http\Controllers\Guru;

use App\Http\Controllers\Controller;
use App\Models\PengumpulanTugas;
use App\Models\Mengajar;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

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

        $idMengajars = Mengajar::where('id_guru', $guru->id_guru)
            ->pluck('id_mengajar');

        // Ambil id_tugas dari mengajar guru ini
        $idTugas = \App\Models\Tugas::whereIn('id_mengajar', $idMengajars)
            ->pluck('id_tugas');

        // Pengumpulan tugas terbaru
        $pengumpulan = PengumpulanTugas::with(['siswa', 'tugas.mengajar.mapel'])
            ->whereIn('id_tugas', $idTugas)
            ->where('created_at', '>=', $since)
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(fn($p) => [
                'type'    => 'pengumpulan',
                'title'   => 'Tugas Dikumpulkan',
                'message' => optional($p->siswa)->nama . ' mengumpulkan: ' . optional($p->tugas)->judul_tugas,
                'status'  => $p->status,
                'time'    => $p->created_at->diffForHumans(),
                'time_raw'=> $p->created_at->toIso8601String(),
            ]);

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