# Stripe Payment System - Quick Start Guide

## Prerequisites

- ✅ Composer dependencies installed (stripe/stripe-php already added)
- ✅ Database migrations run
- ✅ Stripe account created at https://stripe.com

## Setup Steps

### 1. Get Stripe API Keys

1. Go to https://dashboard.stripe.com/apikeys
2. Copy your:
   - **Publishable key** (pk_test_...)
   - **Secret key** (sk_test_...)
3. Create a webhook endpoint:
   - Go to https://dashboard.stripe.com/webhooks
   - Add endpoint: `https://yourdomain.com/payments/webhook/stripe`
   - Select events: `invoice.payment_succeeded`, `invoice.payment_failed`
   - Copy the **Signing secret** (whsec_...)

### 2. Configure Environment

Update `.env` file:

```env
STRIPE_PUBLIC_KEY=pk_test_your_key
STRIPE_SECRET_KEY=sk_test_your_key
STRIPE_WEBHOOK_SECRET=whsec_your_secret
```

### 3. Admin: Create Payment Method

1. Login as admin
2. Go to `/admin/payment-methods`
3. Click "Create Payment Method"
4. Fill in:
   - **Name:** "Stripe"
   - **Provider:** "stripe"
   - **Credentials - api_key:** `sk_test_...`
5. Click "Test" to verify
6. Save

### 4. Admin: Create Packages

1. Go to `/admin/packages`
2. Create package with Stripe pricing:

**Example: Professional Package**
```
Name: Professional
Driver Limit: 10
Truck Limit: 5
Base Price: $50/month
Price Per Driver: $15/month
Billing Cycle: monthly
Features: [...your features...]
```

**Example: Enterprise Package**
```
Name: Enterprise
Driver Limit: 50
Truck Limit: 20
Base Price: $100/month
Price Per Driver: $10/month
Billing Cycle: monthly
Features: [...your features...]
```

### 5. User: Subscribe to Package

1. User logs in as owner/company
2. Go to `/subscriptions/select-package`
3. Select a package
4. Click "Subscribe"
5. System redirects to checkout
6. Complete payment with Stripe

### 6. Automatic Billing Setup

The system automatically processes billing daily:
- **1:00 AM** - Updates driver count charges (update-driver-charges)
- **2:00 AM** - Processes recurring payments (process-recurring-payments)

These commands are scheduled in `app/Console/Kernel.php` and run via Laravel scheduler.

**To set up scheduler** (on your production server):

Add to crontab:
```bash
* * * * * cd /path/to/app && php artisan schedule:run >> /dev/null 2>&1
```

### 7. Test Locally

To test billing without cron:

```bash
# Process billing for due subscriptions
php artisan billing:process-recurring-payments

# Update driver charges
php artisan billing:update-driver-charges
```

## How It Works

### User Journey

1. **Owner selects package** with base price and per-driver cost
2. **System creates Stripe customer** and subscription
3. **Monthly/weekly automatic charges** based on driver count
4. **Driver changes automatically adjust** next billing amount
5. **Webhooks confirm payments** and update status

### Billing Calculation

For each billing cycle:

```
Monthly Amount = Base Price + (Driver Count × Price Per Driver)
```

**Example (Professional Package):**
- Base Price: $50
- Drivers: 5
- Price Per Driver: $15
- Monthly Charge: $50 + (5 × $15) = $125

### Admin Actions

| Action | Path |
|--------|------|
| View all payments | `/admin/payments` |
| View payment details | `/admin/payments/{id}` |
| Manually update status | `/admin/payments/{id}` → Update Status |
| Manage payment methods | `/admin/payment-methods` |
| Create packages | `/admin/packages` |

## Testing with Stripe Test Cards

Use these cards in test mode:

| Card | Status | 
|------|--------|
| 4242 4242 4242 4242 | Success |
| 4000 0000 0000 0002 | Decline |
| 4000 0025 0000 3155 | 3D Secure |

Expiry: Any future date (e.g., 12/25)
CVC: Any 3 digits

## Troubleshooting

### ❌ "Stripe API key not configured"
- Check `.env` has `STRIPE_SECRET_KEY`
- Verify payment method in admin has credentials

### ❌ "Driver limit reached" (422 error)
- This is expected! User needs to upgrade package or remove drivers
- Swagger checks `company.drivers().count() >= package.driver_limit`

### ❌ Payment webhook not received
- Verify webhook URL in Stripe dashboard
- Check webhook endpoint: `POST /payments/webhook/stripe`
- Review Stripe webhook logs for errors

### ❌ Billing not processing
- Check Laravel scheduler is running: `php artisan schedule:work`
- Manually run: `php artisan billing:process-recurring-payments`
- Check laravel.log for errors

### ❌ "Invalid signature" on webhook
- Verify `STRIPE_WEBHOOK_SECRET` in `.env` matches Stripe dashboard
- Check webhook was created for correct events

## Monitoring

### Check Scheduled Tasks
```bash
php artisan schedule:list
```

### View Recent Payments
```bash
# In Laravel Tinker
>>>$payments = App\Models\Payment::latest()->take(10)->get();
>>$payments->each(fn($p) => echo $p->id . ": " . $p->status . "\n");
```

### View Subscription Status
```bash
>>>$sub = App\Models\Subscription::with('user', 'package')->first();
>>>echo "Status: " . $sub->status . "\n";
>>>echo "Next Billing: " . $sub->next_billing_date . "\n";
>>>echo "Amount: $" . $sub->getNextBillingAmount() . "\n";
```

## Next Steps

1. ✅ Phase 1: Stripe integration complete
2. 🔄 Phase 2: Admin UI for billing management
3. 🔄 Phase 3: Mobile app integration
4. 🔄 Phase 4: PayPal & Wise integration
5. 🔄 Phase 5: Advanced analytics & reports

## Support

For issues:
1. Check `STRIPE_PAYMENT_SYSTEM.md` for detailed documentation
2. Review logs: `tail -f storage/logs/laravel.log`
3. Test payment method connection in admin
4. Check Stripe dashboard for webhook errors

## Key Files

- **Services:** `app/Services/StripeService.php`, `BillingService.php`
- **Commands:** `app/Console/Commands/ProcessRecurringPayments.php`
- **Controller:** `app/Http/Controllers/PaymentController.php`
- **Documentation:** `STRIPE_PAYMENT_SYSTEM.md`
- **Config:** `config/services.php` (Stripe section)
- **Routes:** `routes/web.php` (payments prefix)
