mad-lawsuit/app/Http/Controllers/SubscriptionController.php
TheMaddax 474df2aa61 Add unsubscribe confirmation page
- Created Unsubscribe.vue with matching site styling
- Added showUnsubscribe method to SubscriptionController
- Updated routes: GET /unsubscribe/{token} shows confirmation page
- POST /api/unsubscribe/{token} processes unsubscribe
- Updated email template to use new unsubscribe route
- Prevents accidental unsubscribes with confirmation dialog
2025-12-18 11:33:47 -07:00

103 lines
2.9 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Subscription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
class SubscriptionController extends Controller
{
/**
* Subscribe an email address to notifications.
*/
public function subscribe(Request $request): JsonResponse
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|max:255',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'message' => 'Please provide a valid email address.',
'errors' => $validator->errors(),
], 422);
}
$email = $request->input('email');
// Check if email already exists
$existing = Subscription::where('email', $email)->first();
if ($existing) {
if ($existing->is_active) {
return response()->json([
'success' => false,
'message' => 'This email is already subscribed to notifications.',
], 409);
} else {
// Reactivate subscription
$existing->is_active = true;
$existing->save();
return response()->json([
'success' => true,
'message' => 'Your subscription has been reactivated! You will receive email notifications for new docket entries.',
]);
}
}
// Create new subscription
Subscription::create([
'email' => $email,
'is_active' => true,
]);
return response()->json([
'success' => true,
'message' => 'Successfully subscribed! You will receive email notifications for new docket entries.',
]);
}
/**
* Show unsubscribe confirmation page.
*/
public function showUnsubscribe(string $token)
{
$subscription = Subscription::where('unsubscribe_token', $token)->first();
if (!$subscription) {
abort(404, 'Invalid unsubscribe token.');
}
return inertia('Unsubscribe', [
'token' => $token,
'email' => $subscription->email,
]);
}
/**
* Process unsubscribe request.
*/
public function unsubscribe(Request $request, string $token): JsonResponse
{
$subscription = Subscription::where('unsubscribe_token', $token)->first();
if (!$subscription) {
return response()->json([
'success' => false,
'message' => 'Invalid unsubscribe token.',
], 404);
}
$subscription->is_active = false;
$subscription->save();
return response()->json([
'success' => true,
'message' => 'You have been successfully unsubscribed from notifications.',
]);
}
}