# Subscription System - Complete Setup & Testing Guide

## 📦 Step 1: Install Required Packages

```bash
# Install Razorpay PHP SDK
composer require razorpay/razorpay

# Install PDF generation library for invoices
composer require barryvdh/laravel-dompdf
```

---

## 🗄️ Step 2: Run Database Migrations

```bash
# Run all migrations
php artisan migrate

# Seed default subscription plans
php artisan db:seed --class=SubscriptionPlansSeeder
```

This will create 4 default plans:
- **Starter** (Free) - 1 social account, 5 content ideas/month, 1 proposal/month
- **Pro** (₹999/month) - 5 social accounts, 3 campaigns, unlimited proposals, 30 content ideas/month
- **Business** (₹2999/month) - Unlimited everything, all features
- **Enterprise** (Custom) - Everything + white-label, API access

---

## 🔑 Step 3: Configure Razorpay

### 3.1 Get Razorpay Credentials

1. Sign up at [Razorpay Dashboard](https://dashboard.razorpay.com)
2. Go to **Settings → API Keys**
3. Generate Test/Live API keys
4. Copy **Key ID** and **Key Secret**

### 3.2 Configure in Application

**Option A: Via Super Admin Panel (Recommended)**
1. Login as Super Admin
2. Navigate to **Billing → Razorpay Settings**
3. Enter your API credentials
4. Set currency (INR/USD)
5. Enable Test Mode for testing
6. Click "Test Connection" to verify
7. Enable Razorpay

**Option B: Via Environment File**
Add to `.env`:
```env
RAZORPAY_KEY_ID=rzp_test_xxxxxxxxxxxxx
RAZORPAY_KEY_SECRET=your_secret_key_here
RAZORPAY_WEBHOOK_SECRET=your_webhook_secret
```

### 3.3 Configure Webhook

1. In Razorpay Dashboard, go to **Settings → Webhooks**
2. Click **Create New Webhook**
3. Enter webhook URL: `https://yourdomain.com/webhooks/razorpay`
4. Select events to listen:
   - ✅ payment.authorized
   - ✅ payment.captured
   - ✅ payment.failed
   - ✅ subscription.activated
   - ✅ subscription.charged
   - ✅ subscription.cancelled
   - ✅ subscription.completed
   - ✅ refund.created
5. Copy the **Webhook Secret**
6. Add it to Razorpay Settings in Super Admin panel

---

## 🧪 Step 4: Test the System

### 4.1 Test Plan Management (Super Admin)

1. Login as Super Admin
2. Go to **Billing → Subscription Plans**
3. Verify 4 default plans are visible
4. Click "Create New Plan" and create a test plan
5. Edit an existing plan
6. Toggle plan status (activate/deactivate)
7. View plan details

### 4.2 Test Subscription Flow (User)

#### Test Free Plan
1. Logout from Super Admin
2. Register a new Brand/Creator/Agency account
3. Go to `/subscription/plans`
4. Click "Get Started Free" on Starter plan
5. Verify subscription is activated
6. Go to `/subscription/manage`
7. Verify plan details and usage limits

#### Test Paid Plan (Test Mode)
1. Click "Change Plan" or go to `/subscription/plans`
2. Select "Pro" plan
3. Click "Subscribe Now"
4. Razorpay checkout modal should open
5. Use Razorpay test card:
   - Card: `4111 1111 1111 1111`
   - CVV: Any 3 digits
   - Expiry: Any future date
6. Complete payment
7. Verify redirect to success page
8. Check subscription status in `/subscription/manage`
9. Verify invoice is generated

#### Test Razorpay Test Cards
```
Success: 4111 1111 1111 1111
Failure: 4000 0000 0000 0002
3D Secure: 4000 0027 6000 3184
```

### 4.3 Test Feature Access Control

1. Subscribe to Starter plan
2. Try to access `/brand/ads` (should be blocked)
3. Try to access `/brand/competitor-insights` (should be blocked)
4. Upgrade to Pro plan
5. Access `/brand/ads` (should work now)
6. Try to access `/brand/competitor-insights` (still blocked - Business+ only)
7. Upgrade to Business plan
8. Access all features (should all work)

### 4.4 Test Usage Limits

1. Subscribe to Starter plan (5 content ideas/month)
2. Create 5 content ideas
3. Try to create 6th content idea (should be blocked)
4. Verify error message about limit
5. Upgrade to Pro plan (30 content ideas/month)
6. Verify you can now create more content ideas

### 4.5 Test Subscription Management

1. Go to `/subscription/manage`
2. Verify current plan details
3. Verify usage statistics
4. Test "Change Plan" (upgrade/downgrade)
5. Test "Cancel Subscription"
6. Verify cancellation message
7. Test "Resume Subscription"
8. View invoices at `/subscription/invoices`
9. Download invoice PDF

### 4.6 Test Webhooks

1. Make a test payment
2. Check Laravel logs for webhook events
3. Verify subscription status updated
4. Verify transaction recorded
5. Verify invoice generated

---

## 🔧 Step 5: Apply Feature Access Control

Follow the detailed guide in [`FEATURE_ACCESS_CONTROL_GUIDE.md`](FEATURE_ACCESS_CONTROL_GUIDE.md)

### Quick Implementation:

#### 1. Protect Routes
```php
// In routes/web.php - wrap existing routes with middleware

// Ads Manager (Pro+)
Route::middleware(['subscription', 'feature:has_ads_manager'])->prefix('ads')->group(function () {
    // Existing ads routes here
});

// Competitor Insights (Business+)
Route::middleware(['subscription', 'feature:has_competitor_insights'])->prefix('competitor-insights')->group(function () {
    // Existing competitor routes here
});
```

#### 2. Add Usage Tracking
```php
// In ContentIdeaController.php
public function store(Request $request)
{
    if (!auth()->user()->subscription->canUseFeature('max_content_ideas_per_month')) {
        return redirect()->back()->with('error', 'Monthly limit reached');
    }
    
    // ... create content idea ...
    
    auth()->user()->subscription->incrementUsage('max_content_ideas_per_month');
}
```

#### 3. Update Sidebars
```blade
{{-- Show only if plan has feature --}}
@if(auth()->user()->currentPlan()?->has_ads_manager)
    <a href="{{ route('brand.ads.index') }}">Ads Manager</a>
@endif
```

---

## 📊 Step 6: Monitor & Manage

### Super Admin Dashboard

Access at `/superadmin/subscriptions-analytics`:
- View Monthly Recurring Revenue (MRR)
- View Annual Recurring Revenue (ARR)
- Monitor churn rate
- See revenue by plan
- View active subscriptions count
- Track payment success/failure rates

### Subscription Management

Access at `/superadmin/subscriptions`:
- View all subscriptions
- Filter by status/plan
- Search by user
- Manually create subscriptions
- Force upgrade/downgrade users
- Cancel subscriptions
- View transaction history

### Transaction Monitoring

Access at `/superadmin/subscriptions-transactions`:
- View all payment transactions
- Filter by status/type/date
- See total revenue
- Track failed payments
- Export transaction data

---

## 🚨 Troubleshooting

### Issue: Razorpay checkout not opening
**Solution:**
- Verify Razorpay credentials are correct
- Check browser console for JavaScript errors
- Ensure Razorpay script is loaded: `https://checkout.razorpay.com/v1/checkout.js`
- Verify `is_active` is true in razorpay_settings table

### Issue: Payment successful but subscription not activated
**Solution:**
- Check Laravel logs for errors
- Verify webhook is configured in Razorpay
- Check webhook signature verification
- Ensure webhook URL is accessible (not localhost for production)

### Issue: Feature access not working
**Solution:**
- Verify middleware is registered in `bootstrap/app.php`
- Check if user has active subscription: `auth()->user()->hasActiveSubscription()`
- Verify plan has the feature enabled
- Clear route cache: `php artisan route:clear`

### Issue: Usage limits not enforced
**Solution:**
- Verify `incrementUsage()` is called after creating resources
- Check `subscription_feature_usage` table for records
- Ensure period dates are correct
- Verify plan limits are set correctly

### Issue: Invoices not generating
**Solution:**
- Install dompdf: `composer require barryvdh/laravel-dompdf`
- Check storage permissions
- Verify invoice template exists
- Check Laravel logs for PDF generation errors

---

## 🔐 Security Checklist

- [x] Razorpay credentials encrypted in database
- [x] Webhook signature verification implemented
- [x] Payment signature validation
- [x] CSRF protection on all forms
- [x] Middleware-based access control
- [x] Super Admin bypass for testing
- [x] Secure transaction logging
- [ ] Rate limiting on payment endpoints (add if needed)
- [ ] SSL/HTTPS enforced in production

---

## 📈 Going Live

### Pre-Launch Checklist

1. **Switch to Live Mode**
   - Get Live API keys from Razorpay
   - Update Razorpay settings in Super Admin
   - Disable Test Mode
   - Update webhook URL to production domain

2. **Test in Production**
   - Make a real ₹1 payment
   - Verify webhook works
   - Check invoice generation
   - Test subscription activation

3. **Configure Email**
   - Set up email service (SMTP/SendGrid/etc.)
   - Test subscription confirmation emails
   - Test invoice emails
   - Test payment failure notifications

4. **Monitor**
   - Watch Laravel logs
   - Monitor Razorpay dashboard
   - Check subscription analytics
   - Track failed payments

---

## 📞 Support & Resources

### Documentation
- [`SUBSCRIPTION_SYSTEM_STATUS.md`](SUBSCRIPTION_SYSTEM_STATUS.md) - Current implementation status
- [`SUBSCRIPTION_SYSTEM_IMPLEMENTATION.md`](SUBSCRIPTION_SYSTEM_IMPLEMENTATION.md) - Detailed technical guide
- [`FEATURE_ACCESS_CONTROL_GUIDE.md`](FEATURE_ACCESS_CONTROL_GUIDE.md) - Feature protection guide

### External Resources
- [Razorpay Documentation](https://razorpay.com/docs/)
- [Razorpay PHP SDK](https://github.com/razorpay/razorpay-php)
- [Laravel Cashier](https://laravel.com/docs/billing) - For reference

### Common Commands
```bash
# Clear caches
php artisan cache:clear
php artisan route:clear
php artisan config:clear
php artisan view:clear

# Check queue
php artisan queue:work

# View logs
tail -f storage/logs/laravel.log

# Tinker (test in console)
php artisan tinker
>>> $user = User::find(1);
>>> $user->subscription;
>>> $user->currentPlan();
```

---

## ✅ Final Checklist

### Setup
- [ ] Packages installed (razorpay/razorpay, barryvdh/laravel-dompdf)
- [ ] Migrations run
- [ ] Plans seeded
- [ ] Razorpay configured
- [ ] Webhook configured
- [ ] Test payment successful

### Features
- [ ] Pricing page accessible
- [ ] Checkout flow works
- [ ] Payment processing works
- [ ] Webhooks processing
- [ ] Invoices generating
- [ ] Subscription management works
- [ ] Plan changes work
- [ ] Cancellation works

### Access Control
- [ ] Route protection applied
- [ ] Usage tracking implemented
- [ ] Sidebars updated
- [ ] Dashboard widgets added
- [ ] Feature restrictions working

### Super Admin
- [ ] Can create/edit plans
- [ ] Can view all subscriptions
- [ ] Can manage user subscriptions
- [ ] Analytics dashboard working
- [ ] Transaction history visible

### Production Ready
- [ ] Live API keys configured
- [ ] Webhook URL updated
- [ ] SSL/HTTPS enabled
- [ ] Email configured
- [ ] Monitoring setup
- [ ] Backup configured

---

**System Status:** 93% Complete (14/15 tasks done)
**Remaining:** Feature access control integration (2-3 hours)
**Ready for:** Testing and deployment