# Membership System Documentation

## Overview
The platform now requires users to purchase a membership plan before accessing dashboard features. Two plans are available:

### Personal Plan - $49/month
- ✅ Unlimited video consultations
- ✅ Digital health records
- ✅ Store discounts (10%)
- ✅ Priority scheduling

### Family Plan - $99/month (Most Popular)
- ✅ Up to 8 family members
- ✅ All Personal features
- ✅ Family wellness plans
- ✅ Shared health dashboard
- ✅ Enhanced store discounts (20%)

## How It Works

### 1. New User Flow
1. User registers/logs in as client
2. Redirected to `/dashboard/user/choose-plan.php` (no active membership)
3. User selects Personal or Family plan
4. Payment is processed (currently demo mode)
5. Membership activated via API
6. User redirected to dashboard

### 2. Existing User Flow
1. User logs in
2. System checks `user_memberships` table for active plan
3. If active membership exists → Dashboard loads
4. If no membership → Redirected to plan selection

### 3. Membership Check Logic
Location: `dashboard/user/index.php` (lines 11-25)

```php
$membershipStmt = $db->prepare("
    SELECT id, plan_type, expires_at 
    FROM user_memberships 
    WHERE user_id = ? AND status = 'active' AND expires_at > NOW()
    ORDER BY expires_at DESC LIMIT 1
");
$membershipStmt->execute([$authUser['id']]);
$activeMembership = $membershipStmt->fetch(PDO::FETCH_ASSOC);

if (!$activeMembership) {
    header('Location: /files/atasteofafricanmarketplace/dashboard/user/choose-plan.php');
    exit;
}
```

## Database Schema

### user_memberships Table
```sql
CREATE TABLE user_memberships (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    plan_type VARCHAR(50) NOT NULL,      -- 'personal' or 'family'
    status VARCHAR(20) DEFAULT 'active',  -- 'active', 'expired', 'cancelled'
    amount DECIMAL(10,2) NOT NULL,
    paypal_order_id VARCHAR(100),
    paypal_payment_id VARCHAR(100),
    starts_at DATETIME NOT NULL,
    expires_at DATETIME NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id),
    UNIQUE KEY unique_user_membership (user_id)
);
```

## API Endpoints

### Activate Membership
**Endpoint:** `/api/membership/activate.php`  
**Method:** POST  
**Auth Required:** Yes (client role)

**Request Body:**
```json
{
    "plan_type": "personal",           // or "family"
    "amount": 49,                      // or 99
    "payment_method": "paypal",        // or "demo" for testing
    "paypal_order_id": "ORDER_123",
    "paypal_payment_id": "PAY_456"
}
```

**Response:**
```json
{
    "success": true,
    "message": "Membership activated successfully"
}
```

### Check Membership Status
**Endpoint:** `/api/membership/status.php`  
**Method:** GET  
**Auth Required:** Yes

**Response:**
```json
{
    "success": true,
    "membership": {
        "plan_type": "family",
        "status": "active",
        "expires_at": "2024-02-15 10:30:00"
    }
}
```

## UI Components

### Plan Selection Page
**File:** `dashboard/user/choose-plan.php`

Features:
- Modern gradient design matching site color scheme
- Side-by-side plan comparison
- "Most Popular" badge on Family plan
- Trust indicators (Secure Payment, Cancel Anytime, 24/7 Support)
- One-click plan selection
- Demo payment activation

### Dashboard Integration
**File:** `dashboard/user/index.php`

Features:
- Membership badge in sidebar profile
- "My Membership" link in navigation
- Plan type display (Personal 👤 or Family 👨‍👩‍👧‍👦)
- Color-coded badges (green for Personal, gold for Family)

## Testing

### Test with Demo Payment
1. Login as client: `client@test.com` / `testpass123`
2. You'll be redirected to plan selection
3. Click "Get Started" on either plan
4. Confirm the alert
5. Membership will activate with demo payment
6. Redirected to dashboard

### Manual Database Activation
```sql
-- Activate Personal plan for user ID 5
INSERT INTO user_memberships (user_id, plan_type, status, amount, starts_at, expires_at)
VALUES (5, 'personal', 'active', 49.00, NOW(), DATE_ADD(NOW(), INTERVAL 1 MONTH));

-- Activate Family plan for user ID 6
INSERT INTO user_memberships (user_id, plan_type, status, amount, starts_at, expires_at)
VALUES (6, 'family', 'active', 99.00, NOW(), DATE_ADD(NOW(), INTERVAL 1 MONTH));
```

## Color Scheme
Consistent with platform theme:
- **Forest Green:** `#0f5240` (primary)
- **Ochre Gold:** `#d4ad31` (accent/Family plan)
- **Gradients:** Used for backgrounds and cards
- **Personal Plan:** Green accents
- **Family Plan:** Gold accents with "Most Popular" badge

## Future Enhancements

### Payment Integration
- [ ] Integrate PayPal Checkout API
- [ ] Add Stripe payment option
- [ ] Handle recurring billing
- [ ] Send payment confirmation emails

### Family Plan Features
- [ ] Add family member management
- [ ] Implement shared dashboard
- [ ] Family member invitation system
- [ ] Individual profiles under family account

### Membership Management
- [ ] Cancel/pause subscription
- [ ] Upgrade/downgrade plans
- [ ] Payment history page
- [ ] Auto-renewal notifications
- [ ] Expiration warnings

### Feature Gates
- [ ] Restrict appointments based on plan
- [ ] Apply discount codes at store checkout
- [ ] Priority scheduling for members
- [ ] Family wellness plan templates

## Files Modified

1. **dashboard/user/choose-plan.php** - NEW
   - Plan selection interface
   - Demo payment activation
   - Trust indicators

2. **dashboard/user/index.php**
   - Added membership check (lines 11-25)
   - Added plan badge to sidebar profile
   - Added "My Membership" navigation link

3. **api/membership/activate.php**
   - Updated to accept `plan_type` parameter
   - Support for 'personal' and 'family' plans
   - Validates plan type before activation

## Support

For membership issues:
- Check `user_memberships` table for active record
- Verify `expires_at > NOW()`
- Check `status = 'active'`
- Review payment_logs for transaction history

Common issues:
- **Stuck in redirect loop:** Check if membership record exists but expired
- **Payment not activating:** Verify API endpoint returns success
- **Wrong plan showing:** Clear browser cache and reload

## Conclusion

The membership system successfully gates dashboard access while providing a clear, attractive upgrade path for users. The demo payment mode allows for easy testing while the structure is ready for production payment integration.
