<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class NotifikasiController extends Controller
{
    public function index()
    {
        $notifications = Auth::user()
            ->notifications()
            ->orderBy('created_at', 'desc')
            ->get();

        return view('web_user.notifikasi', [
            'notifikasi' => $notifications
        ]);
    }

    public function show($id)
    {
        $notification = Auth::user()->notifications()->findOrFail($id);

        if (is_null($notification->read_at)) {
            $notification->markAsRead();
            $notification->refresh();
        }

        return view('web_user.lihat-notifikasi', [
            'notif' => $notification
        ]);
    }

    public function baca($id)
    {
        $notification = Auth::user()->notifications()->findOrFail($id);

        if (is_null($notification->read_at)) {
            $notification->markAsRead();
        }

        return redirect()->back()->with('success', 'Notifikasi ditandai sebagai dibaca.');
    }

    public function bacaSemua()
    {
        Auth::user()->unreadNotifications->markAsRead();

        return redirect()->back()->with('success', 'Semua notifikasi ditandai sebagai dibaca.');
    }

    public function hapus($id)
    {
        $notification = Auth::user()->notifications()->findOrFail($id);
        $notification->delete();

        return redirect()->back()->with('success', 'Notifikasi berhasil dihapus.');
    }

    public function hapusSemua()
    {
        Auth::user()->notifications()->delete();

        return redirect()->back()->with('success', 'Semua notifikasi berhasil dihapus.');
    }
}