# AIPT API Documentation
## Complete API Reference Guide

---

## Table of Contents

1. [Authentication](#authentication)
2. [Base URL & Headers](#base-url--headers)
3. [Response Format](#response-format)
4. [Error Handling](#error-handling)
5. [Core Endpoints](#core-endpoints)
6. [Module-Specific Endpoints](#module-specific-endpoints)
7. [Webhook Events](#webhook-events)
8. [Rate Limiting](#rate-limiting)
9. [SDK Examples](#sdk-examples)

---

## Authentication

### Authentication Methods

#### 1. Session-Based Authentication (Web)
```http
POST /login
Content-Type: application/x-www-form-urlencoded

username=your_username&password=your_password
```

**Response:**
```json
{
    "success": true,
    "message": "Login successful",
    "user": {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com",
        "role": "admin"
    },
    "redirect": "/dashboard"
}
```

#### 2. API Token Authentication
```http
GET /api/trademarks
Authorization: Bearer your_api_token
Content-Type: application/json
```

### Getting API Token
```http
POST /api/auth/token
Content-Type: application/json

{
    "username": "your_username",
    "password": "your_password"
}
```

**Response:**
```json
{
    "success": true,
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "expires_at": "2024-12-31T23:59:59Z"
}
```

---

## Base URL & Headers

### Base URLs
- **Development**: `http://localhost/AIPT`
- **Staging**: `https://staging.aipt.com`
- **Production**: `https://api.aipt.com`

### Required Headers
```http
Content-Type: application/json
Accept: application/json
Authorization: Bearer your_token
X-Requested-With: XMLHttpRequest
```

### Optional Headers
```http
X-Client-Version: 1.0.0
X-Platform: web
X-User-Agent: AIPT-Client/1.0
```

---

## Response Format

### Success Response
```json
{
    "success": true,
    "data": {
        "id": 1,
        "name": "Example",
        "created_at": "2024-01-01T00:00:00Z",
        "updated_at": "2024-01-01T00:00:00Z"
    },
    "message": "Operation completed successfully",
    "meta": {
        "total": 100,
        "per_page": 15,
        "current_page": 1,
        "last_page": 7
    }
}
```

### Error Response
```json
{
    "success": false,
    "error": {
        "code": "VALIDATION_ERROR",
        "message": "The given data was invalid",
        "details": {
            "name": ["The name field is required."],
            "email": ["The email must be a valid email address."]
        }
    },
    "debug": {
        "file": "app/Http/Controllers/UserController.php",
        "line": 45,
        "trace": "..."
    }
}
```

---

## Error Handling

### HTTP Status Codes

| Code | Description |
|------|-------------|
| 200 | Success |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 422 | Validation Error |
| 429 | Too Many Requests |
| 500 | Internal Server Error |

### Error Types

#### Validation Errors (422)
```json
{
    "success": false,
    "error": {
        "code": "VALIDATION_ERROR",
        "message": "The given data was invalid",
        "details": {
            "field_name": ["Error message"]
        }
    }
}
```

#### Authentication Errors (401)
```json
{
    "success": false,
    "error": {
        "code": "UNAUTHORIZED",
        "message": "Authentication required"
    }
}
```

#### Permission Errors (403)
```json
{
    "success": false,
    "error": {
        "code": "FORBIDDEN",
        "message": "Insufficient permissions"
    }
}
```

---

## Core Endpoints

### User Management

#### Get All Users
```http
GET /api/users
```

**Query Parameters:**
- `page` (int): Page number (default: 1)
- `per_page` (int): Items per page (default: 15)
- `search` (string): Search term
- `role` (string): Filter by role
- `department` (int): Filter by department ID

**Response:**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "John Doe",
            "email": "john@example.com",
            "username": "johndoe",
            "role": "admin",
            "department": "IT",
            "status": "active",
            "created_at": "2024-01-01T00:00:00Z"
        }
    ],
    "meta": {
        "total": 50,
        "per_page": 15,
        "current_page": 1,
        "last_page": 4
    }
}
```

#### Create User
```http
POST /api/users
Content-Type: application/json

{
    "name": "Jane Doe",
    "email": "jane@example.com",
    "username": "janedoe",
    "password": "secure_password",
    "role_id": 2,
    "department_id": 1
}
```

#### Update User
```http
PUT /api/users/{id}
Content-Type: application/json

{
    "name": "Jane Smith",
    "email": "jane.smith@example.com"
}
```

#### Delete User
```http
DELETE /api/users/{id}
```

### Department Management

#### Get All Departments
```http
GET /api/departments
```

#### Create Department
```http
POST /api/departments
Content-Type: application/json

{
    "department_name": "Legal Department"
}
```

---

## Module-Specific Endpoints

### Trademark Management

#### Get All Trademarks
```http
GET /api/trademarks
```

**Query Parameters:**
- `page` (int): Page number
- `per_page` (int): Items per page
- `search` (string): Search term
- `country` (int): Country ID filter
- `client` (int): Client ID filter
- `status` (string): Status filter
- `date_from` (date): Start date filter
- `date_to` (date): End date filter

**Response:**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "trademark_name": "Example Brand",
            "aiptref": "TM-2024-001",
            "clientref": "CL-001",
            "country": "United States",
            "client": "Example Corp",
            "status": "pending",
            "filing_date": "2024-01-01",
            "renewal_date": "2034-01-01",
            "created_at": "2024-01-01T00:00:00Z"
        }
    ]
}
```

#### Create Trademark
```http
POST /api/trademarks
Content-Type: application/json

{
    "trademark_name": "New Brand",
    "aiptref": "TM-2024-002",
    "clientref": "CL-002",
    "client_id": 1,
    "country_id": 1,
    "associate_id": 1,
    "methode_id": 1,
    "procedure_id": 1,
    "applicant_id": 1,
    "class": "35",
    "filing_date": "2024-01-01",
    "renewal_date": "2034-01-01"
}
```

#### Update Trademark
```http
PUT /api/trademarks/{id}
Content-Type: application/json

{
    "trademark_name": "Updated Brand Name",
    "status": "approved"
}
```

#### Upload Trademark Document
```http
POST /api/trademarks/{id}/documents
Content-Type: multipart/form-data

file: [binary data]
comment: "Trademark logo file"
```

### Accounting Transactions

#### Get All Transactions
```http
GET /api/transactions
```

**Query Parameters:**
- `related_table` (string): Related table name
- `related_id` (int): Related record ID
- `type` (string): Transaction type
- `status` (string): Transaction status
- `date_from` (date): Start date
- `date_to` (date): End date
- `currency` (string): Currency filter

#### Create Transaction
```http
POST /api/transactions
Content-Type: application/json

{
    "reference_no": "TXN-2024-001",
    "type": "invoice",
    "value": 1000.00,
    "currency": "USD",
    "description": "Trademark filing fee",
    "related_table": "trade_mark_tickets",
    "related_id": 1,
    "department_id": 1
}
```

#### Approve Transaction
```http
POST /api/transactions/{id}/approve
Content-Type: application/json

{
    "comment": "Approved by manager"
}
```

### Patent Management

#### Get All Patents
```http
GET /api/patents
```

#### Create Patent
```http
POST /api/patents
Content-Type: application/json

{
    "title": "Innovative Technology",
    "aiptref": "PT-2024-001",
    "clientref": "CL-001",
    "client_id": 1,
    "country_id": 1,
    "pct_no": "PCT/US2024/000001",
    "pct_date": "2024-01-01",
    "regular_no": "US2024000001",
    "regular_date": "2024-01-01"
}
```

### Litigation Management

#### Get All Cases
```http
GET /api/litigation/cases
```

#### Create Case
```http
POST /api/litigation/cases
Content-Type: application/json

{
    "title": "Trademark Infringement Case",
    "case_number": "CASE-2024-001",
    "client_id": 1,
    "attorney_id": 1,
    "case_type": "trademark",
    "status": "open",
    "filing_date": "2024-01-01",
    "description": "Case description"
}
```

### HR Management

#### Get All Employees
```http
GET /api/hr/employees
```

#### Create Employee
```http
POST /api/hr/employees
Content-Type: application/json

{
    "user_id": 1,
    "employee_id": "EMP-001",
    "position": "Software Developer",
    "department": "IT",
    "hire_date": "2024-01-01",
    "salary": 50000.00
}
```

#### Get Attendance Records
```http
GET /api/hr/attendance
```

**Query Parameters:**
- `employee_id` (int): Employee ID
- `date_from` (date): Start date
- `date_to` (date): End date

---

## Webhook Events

### Available Events

#### Trademark Events
- `trademark.created` - New trademark created
- `trademark.updated` - Trademark updated
- `trademark.status_changed` - Status changed
- `trademark.deadline_approaching` - Deadline approaching

#### Transaction Events
- `transaction.created` - New transaction created
- `transaction.approved` - Transaction approved
- `transaction.rejected` - Transaction rejected
- `transaction.paid` - Transaction paid

#### User Events
- `user.created` - New user created
- `user.updated` - User updated
- `user.login` - User logged in
- `user.logout` - User logged out

### Webhook Payload Example
```json
{
    "event": "trademark.created",
    "timestamp": "2024-01-01T00:00:00Z",
    "data": {
        "id": 1,
        "trademark_name": "Example Brand",
        "aiptref": "TM-2024-001",
        "created_by": {
            "id": 1,
            "name": "John Doe"
        }
    }
}
```

### Setting Up Webhooks
```http
POST /api/webhooks
Content-Type: application/json

{
    "url": "https://your-app.com/webhook",
    "events": ["trademark.created", "transaction.approved"],
    "secret": "your_webhook_secret"
}
```

---

## Rate Limiting

### Rate Limits
- **General API**: 1000 requests per hour
- **Authentication**: 10 requests per minute
- **File Upload**: 50 requests per hour
- **Report Generation**: 100 requests per hour

### Rate Limit Headers
```http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
```

### Rate Limit Exceeded Response
```json
{
    "success": false,
    "error": {
        "code": "RATE_LIMIT_EXCEEDED",
        "message": "Too many requests. Please try again later.",
        "retry_after": 3600
    }
}
```

---

## SDK Examples

### JavaScript/Node.js
```javascript
const AIPTClient = require('aipt-sdk');

const client = new AIPTClient({
    baseURL: 'https://api.aipt.com',
    apiKey: 'your_api_key'
});

// Get all trademarks
const trademarks = await client.trademarks.list({
    page: 1,
    per_page: 20,
    search: 'example'
});

// Create new trademark
const newTrademark = await client.trademarks.create({
    trademark_name: 'New Brand',
    aiptref: 'TM-2024-003',
    client_id: 1,
    country_id: 1
});
```

### PHP
```php
<?php
use AIPT\Client;

$client = new Client([
    'base_url' => 'https://api.aipt.com',
    'api_key' => 'your_api_key'
]);

// Get all trademarks
$trademarks = $client->trademarks()->list([
    'page' => 1,
    'per_page' => 20,
    'search' => 'example'
]);

// Create new trademark
$newTrademark = $client->trademarks()->create([
    'trademark_name' => 'New Brand',
    'aiptref' => 'TM-2024-003',
    'client_id' => 1,
    'country_id' => 1
]);
?>
```

### Python
```python
import aipt

client = aipt.Client(
    base_url='https://api.aipt.com',
    api_key='your_api_key'
)

# Get all trademarks
trademarks = client.trademarks.list(
    page=1,
    per_page=20,
    search='example'
)

# Create new trademark
new_trademark = client.trademarks.create({
    'trademark_name': 'New Brand',
    'aiptref': 'TM-2024-003',
    'client_id': 1,
    'country_id': 1
})
```

### cURL Examples

#### Get All Trademarks
```bash
curl -X GET "https://api.aipt.com/api/trademarks" \
  -H "Authorization: Bearer your_token" \
  -H "Content-Type: application/json"
```

#### Create Trademark
```bash
curl -X POST "https://api.aipt.com/api/trademarks" \
  -H "Authorization: Bearer your_token" \
  -H "Content-Type: application/json" \
  -d '{
    "trademark_name": "New Brand",
    "aiptref": "TM-2024-003",
    "client_id": 1,
    "country_id": 1
  }'
```

#### Upload Document
```bash
curl -X POST "https://api.aipt.com/api/trademarks/1/documents" \
  -H "Authorization: Bearer your_token" \
  -F "file=@document.pdf" \
  -F "comment=Trademark document"
```

---

## Testing

### Test Environment
- **Base URL**: `https://staging-api.aipt.com`
- **Test Credentials**: Available upon request
- **Mock Data**: Pre-populated test data

### Postman Collection
Download the complete Postman collection: [AIPT API Collection](./postman/AIPT_API_Collection.json)

### API Testing Tools
- **Postman**: Recommended for manual testing
- **Insomnia**: Alternative API client
- **curl**: Command-line testing
- **SDK Examples**: Language-specific examples

---

## Support

### API Support
- **Email**: api-support@aipt.com
- **Documentation**: This guide and inline help
- **Status Page**: https://status.aipt.com
- **Changelog**: https://changelog.aipt.com

### Getting Help
1. Check this documentation
2. Review error messages
3. Test with provided examples
4. Contact support team

---

*This API documentation is maintained by the AIPT development team. For the most up-to-date information, always refer to the latest version of this guide.*

**Last Updated**: [Current Date]  
**API Version**: 1.0  
**Documentation Version**: 1.0
