Files
biiproject-kit-v2/app/Http/Controllers/NotificationController.php
T

79 lines
2.7 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\NotificationLog;
use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Log;
class NotificationController extends Controller
{
public function index(Request $request)
{
abort_if(!auth()->user()->can('notifications.view'), 403, 'Unauthorized. Notification view permission required.');
$logs = NotificationLog::with(['targetUser', 'sender'])
->latest()
->paginate(10);
$users = User::select('id', 'first_name', 'last_name', 'email')
->where('status', 'active')
->get();
return Inertia::render('Notifications/Index', [
'logs' => [
'data' => $logs->items(),
'meta' => [
'current_page' => $logs->currentPage(),
'last_page' => $logs->lastPage(),
'total' => $logs->total(),
'per_page' => $logs->perPage(),
],
'links' => $logs->linkCollection()->toArray(),
],
'users' => $users,
]);
}
public function store(Request $request)
{
abort_if(!auth()->user()->can('notifications.send'), 403, 'Unauthorized. Notification send permission required.');
$validated = $request->validate([
'title' => 'required|string|max:255',
'body' => 'required|string',
'image_url' => 'nullable|url',
'deep_link' => 'nullable|string',
'target_type' => 'required|in:all,individual',
'target_user_id' => 'required_if:target_type,individual|nullable|exists:users,id',
]);
try {
// Mocking FCM Sending logic
// In production, use Kreait/Firebase-PHP or Laravel-Notification-Channels/WebPush
$status = 'sent';
$errorMessage = null;
// Log the notification
NotificationLog::create([
'title' => $validated['title'],
'body' => $validated['body'],
'image_url' => $validated['image_url'],
'deep_link' => $validated['deep_link'],
'target_type' => $validated['target_type'],
'target_user_id' => $validated['target_user_id'],
'sender_id' => auth()->id(),
'status' => $status,
'error_message' => $errorMessage,
]);
return back()->with('success', 'Notification dispatched successfully.');
} catch (\Exception $e) {
Log::error('FCM Error: ' . $e->getMessage());
return back()->with('error', 'Failed to send notification: ' . $e->getMessage());
}
}
}