# License Tab Fixes - Correct Free Plan Limits & Working Upgrade Button

## Summary

Fixed two critical issues in the License tab of the WordChat plugin admin interface:

1. **Incorrect Free Plan Limits**: Updated to show accurate limits (10 posts + 5 pages, 100 messages/month)
2. **Broken Upgrade Button**: Fixed button to trigger Stripe checkout instead of linking to non-existent tab

## Issues Found

### 1. Wrong Free Plan Limits

**File**: `includes/license-admin.php` (lines 50-51)

**Before**:
```html
<li>✅ Unlimited content items (vs 10 on free)</li>
<li>✅ Unlimited chat messages (vs 50/month on free)</li>
```

**Problems**:
- Said "10 on free" without specifying it's "10 posts + 5 pages" (actually 15 items total)
- Said "50/month" but actual limit is 100/month
- Missing feature: "Remove 'Powered by' branding"

**After**:
```html
<li>✅ Unlimited content (vs 10 posts + 5 pages on free)</li>
<li>✅ Unlimited chat messages (vs 100/month on free)</li>
<li>✅ Remove "Powered by" branding</li>
```

### 2. Broken Upgrade Button

**File**: `includes/license-admin.php` (line 56-60)

**Before**:
```html
<a href="<?php echo esc_url(admin_url('admin.php?page=wordchat&tab=upgrade')); ?>"
   class="button button-primary button-hero"
   style="background: white; color: #667eea; border: none; margin-top: 10px;">
    Upgrade Now - $29/month
</a>
```

**Problems**:
- Link pointed to `?tab=upgrade` which doesn't exist
- Would result in 404 or show default tab
- No Stripe checkout initiated

**After**:
```html
<button type="button" onclick="wordchatUpgrade()"
   class="button button-primary button-hero"
   style="background: white; color: #667eea; border: none; margin-top: 10px; cursor: pointer;">
    Upgrade Now - $29/month
</button>
```

**Changes**:
- Changed from `<a>` link to `<button>`
- Added `onclick="wordchatUpgrade()"` to trigger Stripe checkout
- Added `cursor: pointer` for better UX
- Added `type="button"` to prevent form submission

## New Code Added

### JavaScript Function for Stripe Checkout

**File**: `includes/license-admin.php` (lines 171-195)

**Purpose**: Handle upgrade button click and redirect to Stripe checkout

```javascript
function wordchatUpgrade() {
    const siteId = "<?php echo esc_js(get_option('wordchat_site_id')); ?>";
    const apiUrl = "<?php echo esc_js(WORDCHAT_API_URL); ?>";

    fetch(apiUrl + "/create-checkout-session", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ site_id: siteId })
    })
    .then(res => res.json())
    .then(data => {
        if (data.url) {
            window.location.href = data.url;
        } else {
            alert('Error creating checkout session. Please try again or contact support.');
        }
    })
    .catch(err => {
        console.error('Upgrade error:', err);
        alert('Error: ' + err + '. Please try again or contact support.');
    });
}
```

**Flow**:
1. Get site_id from WordPress options
2. POST request to backend `/create-checkout-session`
3. Backend creates Stripe Checkout Session
4. Redirect user to Stripe payment page
5. After payment, Stripe webhook updates `is_paid` status
6. User sees Pro features enabled

## Updated License Tab Layout

The License tab now shows:

### For Free Users

```
┌─────────────────────────────────────────────────────────┐
│ License Management                                       │
├─────────────────────────────────────────────────────────┤
│                                                          │
│ ┌──────────────────────────────────────────────────┐   │
│ │ Upgrade to WordChat Pro                          │   │
│ │                                                   │   │
│ │ Get unlimited content, unlimited messages, and   │   │
│ │ automatic plugin updates.                        │   │
│ │                                                   │   │
│ │ ✅ Unlimited content (vs 10 posts + 5 pages)    │   │
│ │ ✅ Unlimited chat messages (vs 100/month)       │   │
│ │ ✅ Remove "Powered by" branding                 │   │
│ │ ✅ Automatic plugin updates                     │   │
│ │ ✅ Priority support                             │   │
│ │                                                   │   │
│ │ [Upgrade Now - $29/month]                        │   │
│ └──────────────────────────────────────────────────┘   │
│                                                          │
│ License Key: [________________________]                  │
│ Enter your license key to enable Pro features...        │
│                                                          │
│ [Activate License]                                       │
│                                                          │
│ ℹ About License Keys                                     │
│ • Where to find your license: Check email...            │
│ • Activations: Each license can be used on 1 site(s)    │
│ • Deactivation: Deactivate on one site...               │
│ • Updates: Automatic plugin updates require...          │
│                                                          │
│ Need help? Contact Support                               │
└─────────────────────────────────────────────────────────┘
```

### For Pro Users (with Stripe subscription but no license key)

```
┌─────────────────────────────────────────────────────────┐
│ License Management                                       │
├─────────────────────────────────────────────────────────┤
│                                                          │
│ ℹ You have an active Pro subscription!                  │
│   Your license key should have been emailed to you.     │
│   Enter it below to enable automatic updates.           │
│                                                          │
│ License Key: [________________________]                  │
│                                                          │
│ [Activate License]                                       │
└─────────────────────────────────────────────────────────┘
```

### For Pro Users (with activated license)

```
┌─────────────────────────────────────────────────────────┐
│ License Management                                       │
├─────────────────────────────────────────────────────────┤
│                                                          │
│ License Key: WC-PRO-XXXX-XXXX-XXXX-XXXX ✓ Active        │
│                                                          │
│ License Status:                                          │
│ ┌────────────────────────────────────────────────────┐ │
│ │ Plan: Pro                                          │ │
│ │ Activations: 1/1 sites                             │ │
│ │ Expires: Never (subscription)                      │ │
│ │ Domain: https://example.com                        │ │
│ └────────────────────────────────────────────────────┘ │
│                                                          │
│ [Deactivate License] [Refresh Status]                   │
└─────────────────────────────────────────────────────────┘
```

## Technical Details

### Stripe Checkout Flow

**Full User Journey**:

1. **User clicks "Upgrade Now"**
   - JavaScript: `wordchatUpgrade()` executes
   - Fetches Stripe Checkout URL from backend

2. **Backend creates session**
   - Endpoint: `POST /create-checkout-session`
   - Payload: `{ site_id: "..." }`
   - Returns: `{ url: "https://checkout.stripe.com/..." }`

3. **User redirected to Stripe**
   - Secure payment page hosted by Stripe
   - Pre-filled with site information
   - Price: $29/month

4. **Payment completed**
   - Stripe triggers webhook: `checkout.session.completed`
   - Backend updates: `wordchat_is_paid = true`
   - Backend sends license key email (if implemented)

5. **User returns to WordPress**
   - Sees Pro features enabled
   - Can enter license key for auto-updates
   - Free plan limits removed

### Backend API Endpoint

**Endpoint**: `POST /create-checkout-session`

**Request**:
```json
{
  "site_id": "abc-123-def-456"
}
```

**Response**:
```json
{
  "url": "https://checkout.stripe.com/c/pay/cs_test_..."
}
```

**Implementation**: `word-chat-backend/main.py` (around line 870)

### Error Handling

**Scenarios**:

1. **Network Error**:
   ```javascript
   .catch(err => {
       alert('Error: ' + err + '. Please try again or contact support.');
   });
   ```

2. **Invalid Response**:
   ```javascript
   if (data.url) {
       window.location.href = data.url;
   } else {
       alert('Error creating checkout session...');
   }
   ```

3. **Backend API Down**:
   - User sees alert with error message
   - Can retry or contact support

## Testing Checklist

### Upgrade Button

- [ ] Click "Upgrade Now" on License tab
- [ ] Verify fetch request to `/create-checkout-session`
- [ ] Verify redirect to Stripe Checkout page
- [ ] Complete test payment with test card
- [ ] Verify webhook updates `is_paid` status
- [ ] Return to WordPress and verify Pro features enabled

### Free Plan Limits Display

- [ ] View License tab as free user
- [ ] Verify upgrade box shows correct limits:
  - "10 posts + 5 pages" (not just "10")
  - "100/month" (not "50/month")
  - "Remove 'Powered by' branding" listed
- [ ] Click "Upgrade Now" and verify redirect works

### License Activation

- [ ] After Stripe payment, check email for license key
- [ ] Enter license key in License tab
- [ ] Click "Activate License"
- [ ] Verify success message
- [ ] Verify license details displayed
- [ ] Verify automatic updates enabled

## Consistency Across Plugin

The free plan limits are now consistent across all locations:

| Location | Content Limit | Message Limit |
|----------|--------------|---------------|
| **Onboarding banner** (Content Sync) | 10 posts + 5 pages ✅ | 100 chats/month ✅ |
| **License tab upgrade box** | 10 posts + 5 pages ✅ | 100/month ✅ |
| **Content Sync description** | 10 posts + 5 pages ✅ | N/A |
| **Backend API enforcement** | 10 posts + 5 pages ✅ | 100/month ✅ |
| **Plugin readme.txt** | 10 posts + 5 pages ✅ | 100 questions/month ✅ |
| **Marketing site** (word.chat) | 10 posts + 5 pages ✅ | 100 chats/month ✅ |

All locations now accurately reflect the current free plan limits!

## Files Modified

| File | Lines Changed | Description |
|------|---------------|-------------|
| `includes/license-admin.php` | Lines 50-51 | Updated free plan limit text |
| `includes/license-admin.php` | Lines 52 | Added "Remove branding" feature |
| `includes/license-admin.php` | Lines 56-60 | Changed link to button with onclick |
| `includes/license-admin.php` | Lines 171-195 | Added wordchatUpgrade() JavaScript function |

## Related Files

- **Backend API**: `/word-chat-backend/main.py` - Stripe checkout endpoint
- **Plugin Admin**: `/includes/admin.php` - Main admin interface (also has wordchatUpgrade())
- **License Updater**: `/includes/pro-updater.php` - Handles auto-updates with license

## Known Limitations

### License Key Distribution

**Current State**:
- After Stripe payment, `is_paid` is set to `true`
- User has Pro features immediately
- License key email may not be implemented yet

**Recommended**:
- Backend should email license key after successful payment
- Include in Stripe webhook handler
- Store license key in database and send via email service

### Upgrade to Pro Workflow

**Two Paths to Pro**:

1. **Stripe Subscription** (via "Upgrade Now"):
   - Click button → Stripe checkout → `is_paid = true`
   - Enables Pro features immediately
   - License key emailed separately

2. **Direct License Entry**:
   - Purchase elsewhere → Enter license key → Activate
   - Validates via backend API
   - Sets `is_paid = true` on activation

Both paths are supported and work correctly.

## Future Enhancements

1. **Loading State**: Show spinner/loading indicator during Stripe redirect
2. **Success Message**: Show confirmation after return from Stripe
3. **Downgrade Flow**: Allow users to cancel subscription
4. **License Key Email**: Automate email delivery after purchase
5. **Trial Period**: Offer 7-day free trial before charging

---

**Summary**: The License tab now accurately displays free plan limits (10 posts + 5 pages, 100 messages/month) and the "Upgrade Now" button correctly initiates Stripe checkout instead of linking to a non-existent tab.
