# API Documentation

## Overview

The QR Generator System provides a RESTful API for programmatic access to QR code management and analytics.

**Base URL:** `https://qr.company.com/api`

**Authentication:** Session-based (cookie authentication)

**Content-Type:** `application/json`

---

## Authentication

All API endpoints require authentication. Users must be logged in via the web interface or provide valid session cookies.

### Login

**Endpoint:** `POST /login`

**Request:**
```json
{
  "email": "staff@company.internal",
  "password": "password123"
}
```

**Response:**
```json
{
  "success": true,
  "user": {
    "id": 1,
    "name": "Staff Member",
    "email": "staff@company.internal",
    "role": "staff"
  }
}
```

---

## QR Codes

### List QR Codes

**Endpoint:** `GET /api/qr`

**Query Parameters:**
- `page` (int) - Page number (default: 1)
- `per_page` (int) - Items per page (default: 15)
- `search` (string) - Search by name
- `type` (string) - Filter by type: static, dynamic, multilink

**Example:**
```
GET /api/qr?page=1&per_page=20&type=dynamic
```

**Response:**
```json
{
  "data": [
    {
      "id": 1,
      "uuid": "550e8400-e29b-41d4-a716-446655440000",
      "name": "Summer Campaign",
      "type": "dynamic",
      "slug": "summer-campaign",
      "destination_url": "https://example.com/summer",
      "scan_count": 125,
      "status": "active",
      "created_at": "2024-01-15 10:30:00"
    }
  ],
  "total": 45,
  "per_page": 20,
  "current_page": 1,
  "last_page": 3
}
```

---

### Get Single QR Code

**Endpoint:** `GET /api/qr/{id}`

**Response:**
```json
{
  "id": 1,
  "uuid": "550e8400-e29b-41d4-a716-446655440000",
  "user_id": 5,
  "type": "dynamic",
  "name": "Summer Campaign",
  "description": "Main landing page for summer promotion",
  "slug": "summer-campaign",
  "destination_url": "https://example.com/summer",
  "size": 300,
  "margin": 10,
  "foreground_color": "#000000",
  "background_color": "#FFFFFF",
  "file_path": "storage/qrcodes/550e8400-e29b-41d4-a716-446655440000.png",
  "scan_count": 125,
  "last_scanned_at": "2024-01-20 14:22:00",
  "status": "active",
  "created_at": "2024-01-15 10:30:00",
  "updated_at": "2024-01-20 14:22:00"
}
```

---

### Create Static QR Code

**Endpoint:** `POST /api/qr`

**Request:**
```json
{
  "type": "static",
  "name": "Contact Card",
  "description": "Company contact information",
  "content_type": "url",
  "url": "https://company.com/contact",
  "size": 400,
  "foreground_color": "#000000",
  "background_color": "#FFFFFF",
  "campaign_id": 3
}
```

**Response:**
```json
{
  "id": 15,
  "uuid": "660e8400-e29b-41d4-a716-446655440001",
  "type": "static",
  "name": "Contact Card",
  "static_content": "https://company.com/contact",
  "file_path": "storage/qrcodes/660e8400-e29b-41d4-a716-446655440001.png",
  "status": "active",
  "created_at": "2024-01-21 09:15:00"
}
```

---

### Create Dynamic QR Code

**Endpoint:** `POST /api/qr`

**Request:**
```json
{
  "type": "dynamic",
  "name": "Product Launch",
  "description": "Redirects to product page",
  "destination_url": "https://company.com/products/new-launch",
  "size": 500,
  "expires_at": "2024-12-31 23:59:59",
  "campaign_id": 5
}
```

**Response:**
```json
{
  "id": 16,
  "uuid": "770e8400-e29b-41d4-a716-446655440002",
  "type": "dynamic",
  "name": "Product Launch",
  "slug": "product-launch",
  "destination_url": "https://company.com/products/new-launch",
  "redirect_url": "https://qr.company.com/r/product-launch",
  "file_path": "storage/qrcodes/770e8400-e29b-41d4-a716-446655440002.png",
  "status": "active",
  "created_at": "2024-01-21 09:20:00"
}
```

---

### Create Multi-Link QR Code

**Endpoint:** `POST /api/qr`

**Request:**
```json
{
  "type": "multilink",
  "name": "Social Media Links",
  "description": "All our social profiles",
  "page_title": "Follow Us",
  "page_description": "Connect with us on social media",
  "theme": "dark",
  "background_type": "gradient",
  "background_value": "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
  "links": [
    {
      "title": "Facebook",
      "url": "https://facebook.com/company",
      "icon": "fab fa-facebook"
    },
    {
      "title": "Instagram",
      "url": "https://instagram.com/company",
      "icon": "fab fa-instagram"
    },
    {
      "title": "LinkedIn",
      "url": "https://linkedin.com/company",
      "icon": "fab fa-linkedin"
    }
  ]
}
```

**Response:**
```json
{
  "id": 17,
  "uuid": "880e8400-e29b-41d4-a716-446655440003",
  "type": "multilink",
  "name": "Social Media Links",
  "slug": "social-media-links",
  "page_url": "https://qr.company.com/m/social-media-links",
  "file_path": "storage/qrcodes/880e8400-e29b-41d4-a716-446655440003.png",
  "status": "active",
  "created_at": "2024-01-21 09:25:00"
}
```

---

### Update QR Code

**Endpoint:** `PUT /api/qr/{id}`

**Note:** Only dynamic QR codes can update destination_url. Other types require regeneration.

**Request:**
```json
{
  "destination_url": "https://company.com/new-destination",
  "description": "Updated description"
}
```

**Response:**
```json
{
  "id": 16,
  "destination_url": "https://company.com/new-destination",
  "description": "Updated description",
  "updated_at": "2024-01-21 10:00:00"
}
```

---

### Delete QR Code

**Endpoint:** `DELETE /api/qr/{id}`

**Response:**
```json
{
  "message": "QR Code deleted successfully"
}
```

---

## Analytics

### Dashboard Statistics

**Endpoint:** `GET /api/analytics/dashboard`

**Response:**
```json
{
  "total_qr_codes": 45,
  "total_scans": 3542,
  "active_campaigns": 8,
  "scans_today": 127
}
```

---

### QR Code Analytics

**Endpoint:** `GET /api/analytics/qr/{id}`

**Query Parameters:**
- `days` (int) - Number of days to retrieve (default: 30)

**Example:**
```
GET /api/analytics/qr/5?days=7
```

**Response:**
```json
{
  "total_scans": 125,
  "scans_by_date": [
    {
      "date": "2024-01-15",
      "count": 18
    },
    {
      "date": "2024-01-16",
      "count": 22
    },
    {
      "date": "2024-01-17",
      "count": 15
    }
  ],
  "device_stats": [
    {
      "device_type": "mobile",
      "count": 78
    },
    {
      "device_type": "desktop",
      "count": 32
    },
    {
      "device_type": "tablet",
      "count": 15
    }
  ],
  "browser_stats": [
    {
      "browser": "Chrome",
      "count": 65
    },
    {
      "browser": "Safari",
      "count": 35
    },
    {
      "browser": "Firefox",
      "count": 25
    }
  ]
}
```

---

## Error Responses

### 400 Bad Request
```json
{
  "error": "Invalid request parameters",
  "details": {
    "name": "The name field is required",
    "type": "The type must be one of: static, dynamic, multilink"
  }
}
```

### 401 Unauthorized
```json
{
  "error": "Unauthenticated",
  "message": "Please login to access this resource"
}
```

### 403 Forbidden
```json
{
  "error": "Forbidden",
  "message": "You do not have permission to perform this action"
}
```

### 404 Not Found
```json
{
  "error": "QR Code not found"
}
```

### 422 Validation Error
```json
{
  "errors": {
    "email": ["The email has already been taken"],
    "password": ["The password must be at least 8 characters"]
  }
}
```

### 500 Internal Server Error
```json
{
  "error": "Internal server error",
  "message": "An unexpected error occurred"
}
```

---

## Rate Limiting

**Current Limits:**
- 100 requests per minute per user
- 1000 requests per hour per user

**Rate Limit Headers:**
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1642780800
```

---

## Webhooks (Future Feature)

Coming soon: Webhook notifications for QR scan events.

---

## Code Examples

### JavaScript (Axios)

```javascript
// Login
const login = async () => {
  const response = await axios.post('/login', {
    email: 'staff@company.internal',
    password: 'password123'
  });
  return response.data;
};

// Get QR Codes
const getQRCodes = async () => {
  const response = await axios.get('/api/qr', {
    params: {
      page: 1,
      per_page: 20,
      type: 'dynamic'
    }
  });
  return response.data;
};

// Create Dynamic QR
const createQR = async () => {
  const response = await axios.post('/api/qr', {
    type: 'dynamic',
    name: 'My QR Code',
    destination_url: 'https://example.com'
  });
  return response.data;
};

// Get Analytics
const getAnalytics = async (qrId) => {
  const response = await axios.get(`/api/analytics/qr/${qrId}`, {
    params: { days: 30 }
  });
  return response.data;
};
```

### PHP (cURL)

```php
<?php

// Login
$ch = curl_init('https://qr.company.com/login');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'email' => 'staff@company.internal',
    'password' => 'password123'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
$response = curl_exec($ch);
curl_close($ch);

// Create QR Code
$ch = curl_init('https://qr.company.com/api/qr');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'type' => 'dynamic',
    'name' => 'My QR Code',
    'destination_url' => 'https://example.com'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
$response = curl_exec($ch);
curl_close($ch);

echo $response;
```

### Python (Requests)

```python
import requests

# Login
session = requests.Session()
login_response = session.post('https://qr.company.com/login', json={
    'email': 'staff@company.internal',
    'password': 'password123'
})

# Create QR Code
qr_response = session.post('https://qr.company.com/api/qr', json={
    'type': 'dynamic',
    'name': 'My QR Code',
    'destination_url': 'https://example.com'
})

print(qr_response.json())

# Get Analytics
analytics = session.get('https://qr.company.com/api/analytics/qr/5', params={
    'days': 30
})

print(analytics.json())
```

---

## Best Practices

1. **Always use HTTPS** in production
2. **Store session cookies securely**
3. **Implement proper error handling**
4. **Respect rate limits**
5. **Validate all input data**
6. **Use appropriate HTTP methods** (GET, POST, PUT, DELETE)
7. **Handle authentication failures gracefully**
8. **Log API usage for debugging**

---

## Support

For API support, contact:
- Technical Support: api-support@company.internal
- Documentation: https://qr.company.com/docs

---

**Version:** 1.0.0  
**Last Updated:** 2024-01-21
