cms-frontend/app/Http/Controllers/Api/NotificationsController.php

120 lines
3.7 KiB
PHP

<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Services\Api\ApiService;
use Illuminate\Http\Request;
class NotificationsController extends Controller
{
protected ApiService $apiService;
public function __construct(ApiService $apiService)
{
$this->apiService = $apiService;
}
public function index()
{
try {
$response = $this->apiService->get('/notifications');
if ($response->successful()) {
return view('pages.notification', [
'notifications' => $response->json()['data']
]);
}
return back()->with('error', 'Unable to fetch notifications.');
} catch (\Exception $e) {
return back()->with('error', 'Service unavailable.');
}
}
public function store(Request $request)
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'message' => 'required|string',
'type' => 'required|string',
'target_users' => 'required|array',
'schedule_date' => 'nullable|date',
'status' => 'required|string|in:draft,scheduled,sent'
]);
try {
$response = $this->apiService->post('/notifications', $validated);
if ($response->successful()) {
return redirect()->route('notification')
->with('success', 'Notification created successfully.');
}
return back()->withErrors($response->json()['errors']);
} catch (\Exception $e) {
return back()->with('error', 'Unable to create notification.');
}
}
public function update(Request $request, $id)
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'message' => 'required|string',
'type' => 'required|string',
'target_users' => 'required|array',
'schedule_date' => 'nullable|date',
'status' => 'required|string|in:draft,scheduled,sent'
]);
try {
$response = $this->apiService->put("/notifications/{$id}", $validated);
if ($response->successful()) {
return redirect()->route('notification')
->with('success', 'Notification updated successfully.');
}
return back()->withErrors($response->json()['errors']);
} catch (\Exception $e) {
return back()->with('error', 'Unable to update notification.');
}
}
public function destroy($id)
{
try {
$response = $this->apiService->delete("/notifications/{$id}");
if ($response->successful()) {
return redirect()->route('notification')
->with('success', 'Notification deleted successfully.');
}
return back()->with('error', 'Unable to delete notification.');
} catch (\Exception $e) {
return back()->with('error', 'Service unavailable.');
}
}
public function batchDestroy(Request $request)
{
$ids = $request->validate([
'ids' => 'required|array',
'ids.*' => 'required|integer'
]);
try {
$response = $this->apiService->post("/notifications/batch-delete", $ids);
if ($response->successful()) {
return response()->json(['message' => 'Notifications deleted successfully']);
}
return response()->json(['error' => 'Unable to delete notifications'], 400);
} catch (\Exception $e) {
return response()->json(['error' => 'Service unavailable'], 503);
}
}
}