# Stripe Payment System - Testing Guide

## Manual Testing Scenarios

### Scenario 1: Create a Package with Stripe Pricing

**Setup:**
1. Login as admin
2. Go to `/admin/packages`
3. Create new package

**Fill in:**
```
Name: Startup Package
Description: Perfect for small operations
Driver Limit: 5
Truck Limit: 2
Price: 50.00 (legacy field)
Base Price: $30.00
Price Per Driver: $10.00
Billing Cycle: monthly
Features: [Select features]
Is Active: Yes
```

**Expected:** Package saves successfully

---

### Scenario 2: Setup Stripe Payment Method

**Prerequisites:** Admin access

**Steps:**
1. Go to `/admin/payment-methods`
2. Click "Create Payment Method"
3. Fill in:
   - Name: "Stripe Production"
   - Provider: "stripe"
   - Description: "Stripe recurring billing"
   - Is Active: Yes
4. Under Credentials, add:
   - Key: "api_key"
   - Value: `sk_test_...` (your test key)
5. Click "Test"

**Expected:** "Stripe credentials are valid" message

---

### Scenario 3: User Subscribes to Package

**Preconditions:**
- Company created (owner has already onboarded)
- Package exists with pricing
- Payment method configured

**Steps:**
1. Login as owner/company user
2. Go to `/subscriptions/select-package`
3. Click "Select" on Startup Package
4. Review terms and click "Subscribe"
5. Redirected to `/payments/subscription/{id}/create-stripe`

**Expected:**
- Subscription record created with status='pending'
- Can proceed to payment section

---

### Scenario 4: Process First Payment

**Preconditions:**
- Subscription created
- Driver count: 3

**Calculation:**
```
Monthly charge = $30 + (3 × $10) = $60
```

**Steps:**
1. Go to `/payments/checkout/{subscription_id}`
2. Select "Stripe" payment method
3. Click "Pay Now"
4. Enter test card: `4242 4242 4242 4242`
5. Expiry: Any future (e.g., 12/26)
6. CVC: Any 3 digits (e.g., 123)
7. Click "Pay"

**Expected:**
- Payment intent created
- Stripe charges card
- Payment status: "completed"
- Subscription status: "active"
- Redirected to success page

---

### Scenario 5: Add Drivers (Mid-Cycle)

**Preconditions:**
- Subscription active with 3 drivers
- Current driver limit: 5

**Steps:**
1. Go to `/owner/drivers`
2. Click "Add Driver"
3. Fill in driver info:
   - First Name: "John"
   - Last Name: "Doe"
   - Email: "john@example.com"
   - Phone: "555-1234"
4. Submit

**Expected:**
- Driver created successfully
- System detects: Driver count 3 → 4
- Metadata updated in Stripe subscription
- Pro-rated charge calculated
- Next billing date remains same
- New monthly amount = $30 + (4 × $10) = $70

---

### Scenario 6: Reach Driver Limit

**Preconditions:**
- Package has driver_limit = 5
- Already have 5 drivers

**Steps:**
1. Go to `/owner/drivers`
2. Try to click "Add Driver" button

**Expected:**
- Button is disabled/grayed out
- Info badge shows "5 of 5 drivers used"
- Cannot create new driver

**Trying to create anyway (API):**
```bash
curl -X POST http://localhost/api/fleet/drivers \
  -H "Authorization: Bearer {token}" \
  -H "Content-Type: application/json" \
  -d '{"name":"test"}'
```

**Expected response (422):**
```json
{
  "success": false,
  "message": "Driver limit reached for your current package."
}
```

---

### Scenario 7: Manual Billing Trigger

**Prerequisites:**
- Subscription with next_billing_date ≤ today
- Multiple subscriptions with different driver counts

**Command:**
```bash
php artisan billing:process-recurring-payments
```

**Output:**
```
Processing 2 subscriptions...
Processing subscription 1...
✓ Subscription 1 processed successfully
Processing subscription 2...
✓ Subscription 2 processed successfully
Done.
```

**Expected in database:**
- Payment records created with:
  - `amount` = calculated based on drivers
  - `invoice_amount` = same as amount
  - `driver_count` = actual driver count
  - `status` = "pending" (until webhook received)
- Subscription `next_billing_date` updated to next month

---

### Scenario 8: Update Driver Charges

**Prerequisites:**
- Driver count changed mid-cycle
- Update command needs to run

**Command:**
```bash
php artisan billing:update-driver-charges
```

**Output:**
```
Checking 2 subscriptions...
Subscription 1: Driver count changed from 3 to 4
✓ Updated charges for subscription 1
Updated 1 subscription(s).
```

**Expected:**
- Stripe subscription metadata updated
- Subscription `last_driver_count` updated to current count
- Pro-rated adjustment calculated (if needed)

---

### Scenario 9: Webhook Payment Success

**Precondition:**
- Payment created with status='pending'
- Stripe webhook configured

**Manual Test (using curl):**
```bash
# Generate test event
curl https://api.stripe.com/v1/test_helpers/test_clock/advance \
  -u sk_test_...: \
  -d "frozen_time=1234567890"

# Then trigger payment via dashboard
```

**OR: Use Stripe CLI (local testing)**
```bash
# Install Stripe CLI from https://stripe.com/docs/stripe-cli
stripe listen --forward-to localhost:8000/payments/webhook/stripe

# In another terminal, trigger test event
stripe trigger invoice.payment_succeeded
```

**Expected:**
- Payment webhook received
- Payment status updated to "completed"
- Subscription payment_status = "completed"
- Subscription amount_paid increased

---

### Scenario 10: Webhook Payment Failure

**Precondition:**
- Payment created
- Card will be declined

**Steps:**
1. Retry failed payment with card: `4000 0000 0000 0002` (declined)
2. Webhook will send `invoice.payment_failed` event

**Expected:**
- Payment status = "failed"
- Failure reason recorded
- Can retry manually

**Retry:**
```
POST /payments/{payment_id}/retry
```

---

## Laravel Tinker Testing

Quick tests in Laravel Tinker:

### Check Package Pricing
```php
$package = App\Models\Package::find(1);
$package->base_price;      // 30.00
$package->price_per_driver; // 10.00
$package->billing_cycle;   // 'monthly'
```

### Calculate Billing Amount
```php
$billingService = app(\App\Services\BillingService::class);
$amount = $billingService->calculateBillingAmount($package, 5);
// Returns: 30 + (5 * 10) = 80
```

### Check Subscription Status
```php
$sub = App\Models\Subscription::find(1);
$sub->status;              // 'active'
$sub->payment_status;      // 'completed'
$sub->next_billing_date;   // DateTime
$sub->stripe_subscription_id; // 'sub_...'
$sub->getNextBillingAmount(); // Calculated amount
```

### Get Due Subscriptions
```php
$billingService = app(\App\Services\BillingService::class);
$subscriptions = $billingService->getSubscriptionsDueForBilling();
$subscriptions->count(); // Number due for billing
```

### View Payment Details
```php
$payment = App\Models\Payment::find(1);
$payment->amount;            // 80.00
$payment->invoice_amount;    // 80.00
$payment->driver_count;      // 5
$payment->status;            // 'completed'
$payment->transaction_id;    // 'in_...' (Stripe invoice ID)
```

---

## Stripe Dashboard Verification

After each scenario, verify in Stripe Dashboard:

1. **Customers:** `/admin/customers`
   - Should see new customer for each company
   - Metadata includes company_id and user_id

2. **Subscriptions:** `/admin/subscriptions`
   - Should see active subscription
   - Status: active
   - Metadata shows current driver_count

3. **Invoices:** `/admin/invoices`
   - One invoice per billing cycle
   - Amount = base_price + (drivers × price_per_driver)
   - Status: paid (after webhook)

4. **Webhooks:** `/developers/webhooks`
   - Subscribe to: `invoice.payment_succeeded`, `invoice.payment_failed`
   - Verify signing secret matches `.env`
   - Check delivery logs

---

## Common Issues & Debugging

### Issue: "Stripe API key not configured"

**Check:**
```php
config('services.stripe.secret'); // Should return sk_test_...
```

**Fix:**
- Verify `.env` has `STRIPE_SECRET_KEY`
- Verify payment method in admin has api_key credential

### Issue: Webhook not received

**Check:**
1. Webhook endpoint URL correct: `https://yourdomain/payments/webhook/stripe`
2. Signing secret in `.env` matches Stripe dashboard
3. Webhook event types subscribed: `invoice.payment_*`

**Test:**
```php
// Manually trigger  webhook
Route::post('/test-webhook', fn() => 
    app(PaymentController::class)->stripeWebhook(
        new Request(['success' => true])
    )
);
```

### Issue: Driver limit not enforced

**Check:**
```php
$company = App\Models\Company::find(1);
$subscription = $company->getActiveSubscription();
$subscription->package->driver_limit; // Should be number
$company->drivers()->count(); // Check actual count
```

**Debug:**
```php
// In DriverController::store()
$limit = $this->resolveDriverLimit($user);
$count = $user->company->drivers()->count();
// $count should >= $limit to block
```

---

## Performance Testing

### Test High Volume Billing

```bash
# Create 100 test subscriptions
php artisan tinker

>>> for($i = 1; $i <= 100; $i++) {
    $sub = App\Models\Subscription::create([
        'user_id' => 1,
        'package_id' => 1,
        'status' => 'active',
        'payment_status' => 'completed',
        'next_billing_date' => now(),
        'billing_cycle' => 'monthly',
    ]);
}

# Run billing
time php artisan billing:process-recurring-payments
```

**Expected:** Complete in under 60 seconds for 100 subscriptions

---

## Final Verification Checklist

- [ ] Stripe API keys configured
- [ ] Payment method created and tested
- [ ] Package created with driver pricing
- [ ] User can subscribe to package
- [ ] Payment processes successfully
- [ ] Driver can be added within limit
- [ ] Driver limit is enforced
- [ ] Billing command processes payments
- [ ] Webhook updates payment status
- [ ] Pro-rated charges calculated
- [ ] Admin dashboard shows all payments
- [ ] Retry failed payment works
- [ ] No errors in logs

---

**Ready to Deploy!** ✅

Once all scenarios pass, the system is ready for production deployment with live Stripe keys.
