<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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

        // Calculate statistics
        $totalNotifications = $user->notifications()->count();
        $unreadCount = $user->unreadNotifications()->count();
        $readCount = $totalNotifications - $unreadCount;

        return view('notification-list', compact('notifications', 'totalNotifications', 'unreadCount', 'readCount'));
    }

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

        return redirect()->back()
            ->with('success_alert', __('Notification marked as read'));
    }

    public function markAllAsRead()
    {
        $user = Auth::user();
        $user->unreadNotifications->markAsRead();

        return redirect()->back()
            ->with('success_alert', __('All notifications marked as read'));
    }

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

        return redirect()->back()
            ->with('success_alert', __('Notification deleted'));
    }

    public function destroyAll()
    {
        $user = Auth::user();
        $user->notifications()->delete();

        return redirect()->back()
            ->with('success_alert', __('All notifications deleted'));
    }

    public function unreadCount()
    {
        $user = Auth::user();
        return response()->json([
            'count' => $user->unreadNotifications()->count()
        ]);
    }
}
