<?php

namespace App\Http\Controllers;

use App\Models\Notification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class NotificationController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $notifications = $user->notifications()->latest()->get();

        [$absensiNotifications, $adminNotifications] = $notifications->partition(function ($notif) {
            $title = Str::lower($notif->title ?? '');
            $message = Str::lower($notif->message ?? '');
            $absensiKeywords = ['absensi', 'clock in', 'clock out', 'jobdesk', 'job desk', 'catatan'];
            $shouldBeAbsensi = Str::contains($title, $absensiKeywords) || Str::contains($message, $absensiKeywords);

            if ($shouldBeAbsensi && $notif->type !== 'absensi') {
                $notif->type = 'absensi';
                $notif->save();
            }

            if (!empty($notif->type)) {
                return $notif->type === 'absensi';
            }

            return $shouldBeAbsensi;
        });

        return view('notifications.index', [
            'absensiNotifications' => $absensiNotifications->values(),
            'adminNotifications' => $adminNotifications->values(),
        ]);
    }

    public function markAsRead($id)
    {
        $notification = Notification::where('user_id', Auth::id())->findOrFail($id);
        $notification->is_read = true;
        $notification->save();
        return back();
    }
}
