<?php

namespace App\Http\Controllers;

use App\Models\Notification;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class NotificationController extends Controller
{

    public function list()
    {
        if (auth()->user()->role == 'mahasiswa' || auth()->user()->role == 'dosen') {
            $total = Notification::where('receiver', auth()->id())
                ->where('seen', 0)->count();
            $notifs = Notification::where('receiver', auth()->id())
                ->orderByDesc('created_at')
                ->take(30)
                ->get();
        } else {

            $total = Notification::where('role', auth()->user()->role)
                ->where('seen', 0)->count();
            $notifs = Notification::where('role', auth()->user()->role)
                // ->where('seen', 0)
                ->orderByDesc('created_at')
                ->take(30)
                ->get();
        }
        $data = [];
        $data[] = '
        <span class="dropdown-item dropdown-header">' . $total . ' Notifikasi Baru</span>';
        foreach ($notifs as $notif) {
            $textCls = '';
            if ($notif->seen == 1)
                $textCls = 'text-muted';

            if (!empty($notif->user->photo)) {

                $imgs = asset('storage/' . $notif->user->photo);
            } else {

                $imgs = asset('images/nopic.jpg');
            }
            $data[] = '
            <div class="dropdown-divider"></div>
            <div class="row ' . $textCls . ' px-3 py-2" style="overflow-wrap: break-word !important;"> 
                <div class="col-3">
                    <img  src="' . $imgs . '" alt="Picture" class="img-fluid rounded-circle">
                </div>
            
                <div class="col-9">
                    <b><p style="line-height:1rem;">' . $notif->user->name . '</b> ' . $notif->text . '</p>
                    <p class="text-muted mt-n1"><small>' . Carbon::parse($notif->created_at)->translatedFormat('d M Y') . '</small></p>
                </div>
            </div>
            ';
        }
        $datax = [
            'total' => $total,
            'data' => $data,
        ];
        return response()->json($datax);
    }

    public function update()
    {
        if (auth()->user()->role == 'mahasiswa' || auth()->user()->role == 'dosen') {
            Notification::where('receiver', auth()->id())
                ->update(['seen' => 1]);
        } else {
            Notification::where('role', auth()->user()->role)
                ->update(['seen' => 1]);
        }

        return $this->list();
    }
}
