<?php

namespace App\Http\Controllers;

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

class NotificationController extends Controller
{
    public function index(Request $request)
    {
        $category = $request->query('category');
    
        $query = Notification::where('user_id', Auth::id())->where('is_read', 0);
    
        if ($category && $category != 'all') {
            if ($category == 'system') {
                $query->where('category', 'system');
            } else if ($category == 'alert') {
                $query->where('category', '!=', 'system');
            }
        }
    
        $notifications = $query->orderBy('created_at', 'desc')->get();
    
        return response()->json($notifications);
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'message' => 'required|string',
            'category' => 'required|in:user,system,success,warning,error',
        ]);

        $notification = Notification::create([
            'user_id' => Auth::id(),
            'title' => $request->title,
            'message' => $request->message,
            'category' => $request->category,
            'is_read' => false,
        ]);

        return response()->json([
            'message' => 'Notifikasi berhasil ditambahkan.',
            'notification' => $notification
        ]);
    }

    public function markAsRead($id)
    {
        $notification = Notification::where('user_id', Auth::id())->findOrFail($id);
        $notification->update(['is_read' => true]);

        return response()->json(['message' => 'Success!']);
    }
    
    public function markAllAsRead()
    {
        $notification = Notification::where('user_id', Auth::id())
                                    ->where(function ($query) {
                                        $query->where('is_read', 0)
                                              ->orWhereNull('is_read');
                                    });
    
        $notification->update(['is_read' => 1]);
    
        return response()->json(['message' => 'Success!']);
    }

    public function destroy($id)
    {
        Notification::where('user_id', Auth::id())->findOrFail($id)->delete();
        return response()->json(['message' => 'Notifikasi berhasil dihapus.']);
    }
}
