62 lines
2.0 KiB
PHP
62 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Subscription;
|
|
use App\Models\UserSubscription;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
class SubscriptionController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
$subscriptions = Subscription::where('is_active', true)->get();
|
|
$userSubscription = Auth::user()->subscriptions()->where('status', 'active')->first();
|
|
|
|
return view('subscriptions.index', compact('subscriptions', 'userSubscription'));
|
|
}
|
|
|
|
public function subscribe(Request $request, Subscription $subscription)
|
|
{
|
|
// Check if user already has an active subscription
|
|
$activeSubscription = Auth::user()->subscriptions()
|
|
->where('status', 'active')
|
|
->where('expires_at', '>', now())
|
|
->first();
|
|
|
|
if ($activeSubscription) {
|
|
return back()->with('error', 'You already have an active subscription.');
|
|
}
|
|
|
|
// Create new subscription
|
|
$userSubscription = UserSubscription::create([
|
|
'user_id' => Auth::id(),
|
|
'subscription_id' => $subscription->id,
|
|
'started_at' => now(),
|
|
'expires_at' => now()->addDays($subscription->duration_days),
|
|
'status' => 'active'
|
|
]);
|
|
|
|
// Here you would typically integrate with a payment processor
|
|
// For now, we'll just create the subscription
|
|
|
|
return redirect()->route('subscriptions.index')
|
|
->with('success', 'Successfully subscribed to ' . $subscription->name . ' plan!');
|
|
}
|
|
|
|
public function cancel(UserSubscription $userSubscription)
|
|
{
|
|
if ($userSubscription->user_id !== Auth::id()) {
|
|
return back()->with('error', 'Unauthorized action.');
|
|
}
|
|
|
|
$userSubscription->update([
|
|
'status' => 'cancelled',
|
|
'expires_at' => now()
|
|
]);
|
|
|
|
return redirect()->route('subscriptions.index')
|
|
->with('success', 'Subscription cancelled successfully.');
|
|
}
|
|
}
|