<?php

namespace App\Http\Controllers;

use App\Models\InventoryItem;
use App\Models\RealtimeNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class NotificationController extends Controller
{
    public function index()
    {
        $now = Carbon::now();
        $realtimeNotificationTotal = RealtimeNotification::count();
        $realtimeNotifications = RealtimeNotification::latest()
            ->limit(15)
            ->get();
        $newNotificationIds = $realtimeNotifications
            ->whereNull('dibaca_pada')
            ->pluck('id');

        RealtimeNotification::whereNull('dibaca_pada')->update(['dibaca_pada' => $now]);

        $nearEndOfLife = InventoryItem::with(['category', 'room'])
            ->whereRaw('(tahun_perolehan + umur_manfaat_tahun) <= ?', [$now->year + 1])
            ->orderBy('tahun_perolehan')
            ->get();

        $maintenanceDue = InventoryItem::with(['category', 'room'])
            ->whereDate('tanggal_jadwal_pemeliharaan', '<=', $now->copy()->addDays(30))
            ->orderBy('tanggal_jadwal_pemeliharaan')
            ->get();

        $replacementRequests = InventoryItem::with(['category', 'room'])
            ->where('pengajuan_penggantian', true)
            ->latest()
            ->get();

        return view('notifications.index', compact(
            'nearEndOfLife',
            'maintenanceDue',
            'replacementRequests',
            'realtimeNotifications',
            'realtimeNotificationTotal',
            'newNotificationIds',
        ));
    }

    public function clear()
    {
        $deleted = RealtimeNotification::query()->delete();

        return redirect()
            ->route('notifications.index')
            ->with('success', $deleted > 0
                ? 'Riwayat notifikasi realtime berhasil dibersihkan.'
                : 'Tidak ada riwayat notifikasi yang perlu dibersihkan.');
    }

    public function deleteSelected(Request $request)
    {
        $validated = $request->validate([
            'notification_ids' => ['required', 'array', 'min:1'],
            'notification_ids.*' => ['integer', 'exists:realtime_notifications,id'],
        ], [
            'notification_ids.required' => 'Pilih minimal satu notifikasi yang ingin dihapus.',
        ]);

        $deleted = RealtimeNotification::query()
            ->whereKey($validated['notification_ids'])
            ->delete();

        return redirect()
            ->route('notifications.index')
            ->with('success', "{$deleted} notifikasi berhasil dihapus.");
    }
}
