# Presentation Plan Limit Checking Documentation

## 🚀 Plan Limit Enforcement

Your backend now automatically checks user plan limits when creating presentations. Here's how it works:

## 📋 What's Implemented

### **1. Create Presentation Limit Check**
- **Endpoint**: `POST /api/store-presentation`
- **Check**: `user->canCreatePresentation()` method
- **Action**: Blocks creation if limit exceeded

### **2. Update Presentation Limit Check**
- **Endpoint**: `POST /api/update-presentation/{id}`
- **Check**: Allows updates to existing presentations
- **Action**: Blocks updates to non-owned presentations

## 🔍 How It Works

### **Plan Limit Logic:**
```php
// User model methods used:
$user->canCreatePresentation()     // Returns true/false
$user->getPresentationLimit()      // Returns limit number or null
$user->currentPlan()               // Returns active plan or null
$user->presentations()->count()    // Current presentation count
```

### **Unlimited Plans:**
- Plans with `max_presentations = null` are unlimited
- Users can create unlimited presentations
- `canCreatePresentation()` always returns `true`

### **Limited Plans:**
- Plans with `max_presentations = N` are limited
- Users can create up to N presentations
- `canCreatePresentation()` returns `false` when limit reached

## 📊 Response Format

### **Success (Within Limits):**
```json
{
  "success": true,
  "message": "Presentation is created successfully",
  "data": {
    "id": 123,
    "title": "My Presentation",
    "description": "Description",
    "user_id": 456,
    "status": 1,
    "created_at": "2026-03-04T20:00:00.000000Z"
  }
}
```

### **Error (Limit Exceeded):**
```json
{
  "success": false,
  "message": "Presentation limit exceeded",
  "error": "You have reached your plan limit for presentations",
  "data": {
    "current_presentations": 3,
    "plan_limit": 3,
    "plan_name": "Basic Plan",
    "unlimited": false
  }
}
```

### **No Active Plan:**
```json
{
  "success": false,
  "message": "Presentation limit exceeded",
  "error": "You have reached your plan limit for presentations",
  "data": {
    "current_presentations": 0,
    "plan_limit": null,
    "plan_name": "No active plan",
    "unlimited": false
  }
}
```

## 🎯 Frontend Integration

### **JavaScript Example:**
```javascript
async createPresentation(title, description) {
  try {
    const token = localStorage.getItem('auth_token');
    
    const response = await fetch('/api/store-presentation', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        title: title,
        description: description
      })
    });

    const data = await response.json();

    if (response.ok && data.success) {
      // Success - presentation created
      console.log('Presentation created:', data.data);
      return data.data;
    } else {
      // Handle limit exceeded
      if (response.status === 403 && data.message === 'Presentation limit exceeded') {
        this.handlePlanLimitExceeded(data.data);
      } else {
        throw new Error(data.message || 'Failed to create presentation');
      }
    }
  } catch (error) {
    console.error('Create presentation error:', error);
    throw error;
  }
}

handlePlanLimitExceeded(limitData) {
  // Show upgrade modal or message
  const { current_presentations, plan_limit, plan_name, unlimited } = limitData;
  
  if (unlimited) {
    // This shouldn't happen with unlimited plans, but just in case
    console.error('Unexpected limit error with unlimited plan');
    return;
  }

  // Show user-friendly message
  const message = `You've reached your ${plan_name} limit of ${plan_limit} presentations. 
                   You currently have ${current_presentations} presentations.
                   Upgrade your plan to create more!`;

  // Show upgrade modal
  this.showUpgradeModal(message, plan_name);
}

showUpgradeModal(message, currentPlan) {
  // Display modal with upgrade options
  const modal = document.getElementById('upgrade-modal');
  const messageEl = document.getElementById('upgrade-message');
  
  messageEl.textContent = message;
  modal.style.display = 'block';
  
  // Handle upgrade button click
  document.getElementById('upgrade-btn').onclick = () => {
    window.location.href = '/plans';
  };
}
```

### **React Hook Example:**
```javascript
import { useState } from 'react';

function usePresentationLimits() {
  const [limitError, setLimitError] = useState(null);

  const createPresentation = async (title, description) => {
    try {
      const token = localStorage.getItem('auth_token');
      
      const response = await fetch('/api/store-presentation', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ title, description })
      });

      const data = await response.json();

      if (response.ok && data.success) {
        setLimitError(null);
        return data.data;
      } else {
        if (response.status === 403) {
          setLimitError(data.data);
        }
        throw new Error(data.message);
      }
    } catch (error) {
      throw error;
    }
  };

  return { createPresentation, limitError, clearLimitError: () => setLimitError(null) };
}

// Usage in component
function PresentationCreator() {
  const { createPresentation, limitError, clearLimitError } = usePresentationLimits();
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    try {
      await createPresentation(title, description);
      // Handle success
      setTitle('');
      setDescription('');
    } catch (error) {
      // Handle error (limitError will be set if it's a plan limit issue)
    }
  };

  return (
    <div>
      {limitError && (
        <div className="alert alert-warning">
          <h4>Plan Limit Reached</h4>
          <p>You've used {limitError.current_presentations} of {limitError.plan_limit} presentations on your {limitError.plan_name}.</p>
          <button onClick={() => window.location.href = '/plans'}>
            Upgrade Plan
          </button>
        </div>
      )}
      
      <form onSubmit={handleSubmit}>
        <input 
          value={title} 
          onChange={(e) => setTitle(e.target.value)}
          placeholder="Presentation title"
          disabled={!!limitError}
        />
        <textarea 
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="Description"
          disabled={!!limitError}
        />
        <button type="submit" disabled={!!limitError}>
          Create Presentation
        </button>
      </form>
    </div>
  );
}
```

## 🔄 Update Behavior

### **Existing Presentations:**
- Users can **always update** their existing presentations
- Even if they've reached their limit
- Prevents data loss and allows editing

### **New Presentations:**
- Users **cannot create** new presentations when limit reached
- Must upgrade plan or delete existing presentations
- Clear error message provided

## 🧪 Testing

### **Test Scenarios Covered:**
1. ✅ Create presentation within limit
2. ✅ Block creation when limit exceeded
3. ✅ Unlimited plans allow unlimited presentations
4. ✅ No plan blocks all presentations
5. ✅ Can update existing presentations at limit
6. ✅ Cannot update other users' presentations

### **Run Tests:**
```bash
php artisan test tests/Feature/PresentationPlanLimitTest.php
```

## 🎯 Best Practices

### **Frontend:**
1. **Check limits before showing create button**
2. **Display current usage to users**
3. **Show upgrade prompts when limit reached**
4. **Handle 403 responses gracefully**

### **Backend:**
1. **Always check limits before creation**
2. **Provide detailed error information**
3. **Allow updates to existing content**
4. **Use proper HTTP status codes**

### **User Experience:**
1. **Clear messaging about limits**
2. **Easy upgrade path**
3. **Visual indicators of current usage**
4. **Prevent data loss**

Your presentation creation now respects user plan limits automatically! 🚀
