# Matendes HRM System - Complete API Documentation

**Version:** 2.0.0  
**Base URL:** `http://localhost/matendes/matendes-hrm/public/api/v1`  
**Laravel Version:** 11.x with SOLID Architecture  
**Target Audience:** Mobile App Developers, Frontend Developers, Integration Partners  
**Authentication:** Laravel Sanctum (SPA Authentication)  
**Last Updated:** January 2025

---

## 📱 Mobile Development Guide

### Mobile App Architecture

The Matendes HRM API is designed with mobile-first principles:

- **RESTful Design**: Stateless API with proper HTTP methods
- **JSON-Only Responses**: Consistent JSON format for all endpoints
- **Token Authentication**: Secure, stateless authentication
- **Offline Capability**: Support for offline data synchronization
- **Push Notifications**: Real-time updates via FCM/APNS
- **Image Optimization**: Multiple image sizes for different screen densities

### Mobile-Specific Endpoints

#### Device Registration
**POST** `/mobile/devices/register`

Register device for push notifications:
```json
{
    "device_token": "fcm_token_here",
    "platform": "android|ios",
    "app_version": "1.2.0",
    "device_model": "iPhone 15 Pro",
    "os_version": "17.1"
}
```

#### Sync Data
**GET** `/mobile/sync?last_sync=2025-01-01T10:00:00Z`

Get incremental data updates:
```json
{
    "success": true,
    "data": {
        "employees": [...],
        "attendance_records": [...],
        "notifications": [...],
        "last_sync": "2025-01-01T11:30:00Z"
    }
}
```

#### Offline Queue
**POST** `/mobile/offline-actions`

Sync offline actions when connection restored:
```json
{
    "actions": [
        {
            "id": "local_id_1",
            "action": "clock_in",
            "timestamp": "2025-01-01T09:00:00Z",
            "data": {
                "location": {
                    "latitude": 40.7128,
                    "longitude": -74.0060
                }
            }
        }
    ]
}
```

### Error Handling for Mobile

All API errors follow this structure:
```json
{
    "success": false,
    "error": {
        "type": "validation_error",
        "message": "The given data was invalid.",
        "code": 422,
        "context": {
            "validation_errors": {
                "email": ["The email field is required."]
            }
        },
        "timestamp": "2025-01-01T10:00:00Z",
        "trace_id": "hrm_64f7a1b2c3d4e"
    }
}
```

### Rate Limiting

API rate limits for mobile apps:
- **Authenticated requests**: 1000 per hour
- **Authentication endpoints**: 10 per minute
- **File uploads**: 50 per hour
- **Bulk operations**: 10 per hour

Headers included in responses:
```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
```

### Image Upload & Optimization

**POST** `/mobile/upload/image`

Upload images with automatic optimization:
```json
{
    "image": "base64_encoded_image_data",
    "type": "profile_photo|document",
    "quality": "high|medium|low",
    "max_width": 1024,
    "max_height": 1024
}
```

Response includes multiple sizes:
```json
{
    "success": true,
    "data": {
        "original": "https://api.example.com/storage/original.jpg",
        "thumbnail": "https://api.example.com/storage/thumb_150x150.jpg",
        "medium": "https://api.example.com/storage/medium_512x512.jpg",
        "large": "https://api.example.com/storage/large_1024x1024.jpg"
    }
}
```

---

## 🏗️ API Architecture & Improvements

### RESTful Route Organization
The API now follows strict RESTful conventions with improved organization:

- **Consistent Naming**: All routes use standardized naming patterns
- **Logical Grouping**: Resources are grouped by domain (HRM, Organization, Clients)
- **Version Prefix**: All endpoints are prefixed with `/api/v1/`
- **Nested Resources**: Sub-resources follow parent/child relationships

### Route Structure Examples
```
/api/v1/hrm/employees                    # Employee CRUD
/api/v1/hrm/employees/{id}/documents     # Employee documents  
/api/v1/clients/{id}/proposals           # Client proposals
/api/v1/organization/companies           # Company management
```

### SOLID Architecture Implementation
The codebase follows SOLID principles:

- **Single Responsibility**: Each service has one clear purpose
- **Open/Closed**: Services can be extended without modification
- **Liskov Substitution**: Interfaces allow implementation substitution
- **Interface Segregation**: Small, focused interfaces
- **Dependency Inversion**: Dependencies are injected via interfaces

### Service Layer Pattern
```php
// Services are bound through interfaces
app()->bind(ClientManagementInterface::class, ClientManagementService::class);
app()->bind(EmployeeRepositoryInterface::class, EmployeeRepository::class);
```

### Controller Improvements
- Consistent response formatting using `ApiResponseTrait`
- Proper dependency injection through constructors
- Standardized error handling and validation
- Resource transformation using Laravel Resources

---

## 🌐 Internationalization

The API supports multiple languages through the `Accept-Language` header or `locale` parameter:
- English (en) - Default
- Spanish (es)
- French (fr)

```http
Accept-Language: es
# or
GET /endpoint?locale=es
```

## 🔐 Authentication & Authorization

All API endpoints require authentication unless otherwise specified. Include the bearer token in all requests:

```http
Content-Type: application/json
Accept: application/json
Authorization: Bearer {your_access_token}
Accept-Language: en
```

### Test Credentials
```
Administrator: admin@matendes.com / password123
HR Manager: hr@matendes.com / password123
Employee: employee@matendes.com / password123
```

---

## 📋 Authentication Endpoints

### Login
**POST** `/auth/login`

```json
{
    "email": "admin@matendes.com",
    "password": "password123",
    "remember": false
}
```

**Response (200):**
```json
{
    "success": true,
    "message": "Login successful",
    "data": {
        "user": {
            "id": "uuid",
            "name": "Administrator",
            "email": "admin@matendes.com"
        },
        "token": "1|laravel_sanctum_token_here",
        "expires_at": "2025-08-21T00:00:00.000000Z"
    },
    "timestamp": "2025-08-20T10:14:53Z"
}
```

### Register
**POST** `/auth/register`

```json
{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "password123",
    "password_confirmation": "password123"
}
```

### Get Current User
**GET** `/auth/me`

**Response (200):**
```json
{
    "success": true,
    "message": "Success",
    "data": {
        "user": {
            "id": "uuid",
            "name": "Administrator",
            "email": "admin@matendes.com"
        },
        "permissions": [
            {"name": "users.create", "resource": "users", "action": "create"}
        ]
    },
    "timestamp": "2025-08-20T10:14:53Z"
}
```

### Logout
**POST** `/auth/logout`

### Logout All Sessions
**POST** `/auth/logout-all`

### Refresh Token
**POST** `/auth/refresh`

### Change Password
**POST** `/auth/change-password`

```json
{
    "current_password": "old_password",
    "password": "new_password",
    "password_confirmation": "new_password"
}
```

### Update Profile
**PUT** `/auth/profile`

```json
{
    "name": "Updated Name",
    "email": "updated@example.com"
}
```

---

## 🔐 Two-Factor Authentication

### Enable 2FA
**POST** `/auth/2fa/enable`

**Response (200):**
```json
{
    "success": true,
    "message": "2FA setup initiated successfully. Please verify to complete setup.",
    "data": {
        "secret": "JBSWY3DPEHPK3PXP",
        "qr_code_url": "https://chart.googleapis.com/...",
        "backup_codes": ["ABC12345", "DEF67890"],
        "manual_entry_key": "JBSWY3DPEHPK3PXP"
    }
}
```

### Verify 2FA Setup
**POST** `/auth/2fa/verify`

```json
{
    "code": "123456"
}
```

### Disable 2FA
**POST** `/auth/2fa/disable`

```json
{
    "password": "current_password",
    "code": "123456"
}
```

### Get QR Code
**GET** `/auth/2fa/qr-code`

### Regenerate Recovery Codes
**POST** `/auth/2fa/recovery-codes/regenerate`

```json
{
    "password": "current_password",
    "code": "123456"
}
```

### Get Recovery Codes
**GET** `/auth/2fa/recovery-codes`

---

## 👥 User Management

### List Users
**GET** `/users`

**Query Parameters:**
- `page` (int): Page number
- `per_page` (int): Items per page (max 100)
- `search` (string): Search term
- `role` (string): Filter by role
- `status` (string): Filter by status

### Get User
**GET** `/users/{id}`

### Create User
**POST** `/users`

```json
{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "password123",
    "company_id": "uuid",
    "role": "employee"
}
```

### Update User
**PUT** `/users/{id}`

### Delete User
**DELETE** `/users/{id}`

### Assign Role
**POST** `/users/{id}/roles`

```json
{
    "role": "hr_manager"
}
```

### Remove Role
**DELETE** `/users/{id}/roles/{role}`

---

## 🏢 Company Management

### List Companies
**GET** `/companies`

### Get Company
**GET** `/companies/{id}`

### Create Company
**POST** `/companies`

```json
{
    "name": "Tech Corp Ltd",
    "email": "contact@techcorp.com",
    "phone": "+1234567890",
    "address": "123 Tech Street",
    "city": "Tech City",
    "state": "TC",
    "postal_code": "12345",
    "country": "US",
    "website": "https://techcorp.com",
    "industry": "Technology",
    "size": "50-100",
    "settings": {
        "timezone": "UTC",
        "date_format": "Y-m-d",
        "time_format": "H:i:s"
    }
}
```

### Update Company
**PUT** `/companies/{id}`

### Delete Company
**DELETE** `/companies/{id}`

---

## 👤 Employee Management

All employee endpoints are under `/api/v1/hrm/` and follow RESTful conventions.

### Employee CRUD Operations
- **GET** `/api/v1/hrm/employees` - List employees with filters and pagination
- **POST** `/api/v1/hrm/employees` - Create new employee
- **GET** `/api/v1/hrm/employees/{employee}` - Get employee details
- **PUT** `/api/v1/hrm/employees/{employee}` - Update employee information
- **DELETE** `/api/v1/hrm/employees/{employee}` - Delete employee

### Employee Search & Analytics
- **GET** `/api/v1/hrm/search` - Advanced employee search
- **POST** `/api/v1/hrm/filter` - Filter employees with complex criteria
- **GET** `/api/v1/hrm/statistics` - Employee statistics and metrics
- **GET** `/api/v1/hrm/org-chart` - Organization chart data

### Employee Lifecycle Operations
- **PATCH** `/api/v1/hrm/employees/{employee}/promote` - Promote employee
- **PATCH** `/api/v1/hrm/employees/{employee}/transfer` - Transfer employee
- **PATCH** `/api/v1/hrm/employees/{employee}/terminate` - Terminate employee
- **PATCH** `/api/v1/hrm/employees/{employee}/confirm` - Confirm employment

### Employee Sub-Resources
- **Documents**: `/api/v1/hrm/employees/{employee}/documents/*`
- **Onboarding**: `/api/v1/hrm/employees/{employee}/onboarding/*`
- **History**: `/api/v1/hrm/employees/{employee}/history/*`

### Bulk Operations
- **POST** `/api/v1/hrm/bulk-import` - Import multiple employees
- **POST** `/api/v1/hrm/bulk-export` - Export employee data
- **PATCH** `/api/v1/hrm/bulk-update` - Update multiple employees

### Create Employee
**POST** `/api/v1/hrm/employees`

```json
{
    "user_id": "uuid",
    "employee_id": "EMP001",
    "department": "Engineering",
    "position": "Software Developer",
    "salary": 75000.00,
    "currency": "USD",
    "hire_date": "2025-01-15",
    "work_schedule": "full_time",
    "manager_id": "uuid",
    "address": "123 Employee St",
    "phone": "+1234567890",
    "emergency_contact_name": "Jane Doe",
    "emergency_contact_phone": "+0987654321"
}
```

### Update Employee
**PUT** `/employees/{id}`

### Delete Employee
**DELETE** `/employees/{id}`

### Upload Photo
**POST** `/employees/{id}/photo`

```
Content-Type: multipart/form-data
photo: (file)
```

### Add Skill
**POST** `/employees/{id}/skills`

```json
{
    "skill_name": "Laravel",
    "proficiency_level": "expert",
    "years_experience": 3
}
```

---

## 📅 Attendance Management

### Get Attendance Records
**GET** `/attendance`

**Query Parameters:**
- `employee_id` (uuid)
- `date_from` (date)
- `date_to` (date)
- `status` (string)

### Clock In
**POST** `/attendance/clock-in`

```json
{
    "latitude": 40.7128,
    "longitude": -74.0060,
    "method": "qr_scan",
    "qr_code": "attendance_qr_token",
    "photo": "base64_image_data"
}
```

### Clock Out
**POST** `/attendance/clock-out`

```json
{
    "latitude": 40.7128,
    "longitude": -74.0060,
    "method": "manual"
}
```

### Generate QR Code
**POST** `/attendance/qr-generate`

**Response (200):**
```json
{
    "success": true,
    "message": "QR code generated successfully",
    "data": {
        "qr_code": "base64_qr_image",
        "token": "attendance_qr_token",
        "expires_at": "2025-08-20T10:19:53Z"
    }
}
```

### Scan QR Code
**POST** `/attendance/qr-scan`

```json
{
    "qr_token": "attendance_qr_token",
    "action": "clock_in",
    "latitude": 40.7128,
    "longitude": -74.0060
}
```

### Face Recognition Setup
**POST** `/attendance/face/enroll`

```json
{
    "photos": ["base64_image1", "base64_image2", "base64_image3"]
}
```

### Face Recognition Attendance
**POST** `/attendance/face/recognize`

```json
{
    "photo": "base64_image_data",
    "action": "clock_in",
    "latitude": 40.7128,
    "longitude": -74.0060
}
```

### Fingerprint Enrollment
**POST** `/attendance/fingerprint/enroll`

```json
{
    "fingerprint_data": "base64_fingerprint_data",
    "finger_position": "right_thumb"
}
```

### Fingerprint Authentication
**POST** `/attendance/fingerprint/verify`

```json
{
    "fingerprint_data": "base64_fingerprint_data",
    "action": "clock_in",
    "latitude": 40.7128,
    "longitude": -74.0060
}
```

---

## 🌍 Geolocation & Geofencing

### Add Work Location
**POST** `/locations`

```json
{
    "name": "Main Office",
    "latitude": 40.7128,
    "longitude": -74.0060,
    "radius": 100,
    "address": "123 Business Ave",
    "is_active": true
}
```

### List Work Locations
**GET** `/locations`

### Verify Location
**POST** `/attendance/verify-location`

```json
{
    "latitude": 40.7128,
    "longitude": -74.0060
}
```

**Response (200):**
```json
{
    "success": true,
    "message": "Location verified successfully",
    "data": {
        "within_geofence": true,
        "location": "Main Office",
        "distance": 25
    }
}
```

---

## 🏖️ Leave Management

### List Leave Requests
**GET** `/leave-requests`

### Get Leave Request
**GET** `/leave-requests/{id}`

### Create Leave Request
**POST** `/leave-requests`

```json
{
    "leave_type_id": "uuid",
    "start_date": "2025-09-01",
    "end_date": "2025-09-05",
    "reason": "Family vacation",
    "is_half_day": false,
    "half_day_period": null
}
```

### Update Leave Request
**PUT** `/leave-requests/{id}`

### Cancel Leave Request
**DELETE** `/leave-requests/{id}`

### Approve/Reject Leave
**PATCH** `/leave-requests/{id}/status`

```json
{
    "status": "approved",
    "comments": "Approved for the requested dates"
}
```

### Get Leave Types
**GET** `/leave-types`

### Get Leave Balance
**GET** `/leave-balance/{employee_id}`

**Response (200):**
```json
{
    "success": true,
    "message": "Leave balance retrieved successfully",
    "data": {
        "annual_leave": {
            "total": 25,
            "used": 5,
            "remaining": 20
        },
        "sick_leave": {
            "total": 10,
            "used": 2,
            "remaining": 8
        }
    }
}
```

---

## 🔔 Notification System

### Get Notifications
**GET** `/notifications`

### Mark Notification as Read
**PATCH** `/notifications/{id}/read`

### Mark All as Read
**PATCH** `/notifications/mark-all-read`

### Update Notification Settings
**PUT** `/notification-settings`

```json
{
    "email_notifications": true,
    "push_notifications": false,
    "sms_notifications": false,
    "notification_types": {
        "leave_requests": true,
        "attendance_alerts": true,
        "system_updates": false
    }
}
```

---

## 📊 Reporting & Analytics

### Attendance Summary
**GET** `/reports/attendance-summary`

**Query Parameters:**
- `employee_id` (uuid)
- `date_from` (date)
- `date_to` (date)
- `department` (string)

### Leave Report
**GET** `/reports/leave-summary`

### Employee Performance
**GET** `/reports/employee-performance/{id}`

---

## ⚙️ System Administration

### System Health Check
**GET** `/health`

**Response (200):**
```json
{
    "success": true,
    "message": "System is healthy",
    "data": {
        "database": "connected",
        "redis": "connected",
        "storage": "accessible",
        "version": "1.0.0"
    }
}
```

### Feature Toggles
**GET** `/features`

### Update Feature
**PUT** `/features/{feature}`

```json
{
    "enabled": true
}
```

---

## 🚨 Error Handling

All API responses follow a consistent format:

**Success Response:**
```json
{
    "success": true,
    "message": "Operation completed successfully",
    "data": {...},
    "timestamp": "2025-08-20T10:14:53Z"
}
```

**Error Response:**
```json
{
    "success": false,
    "message": "Error description",
    "errors": {...},
    "timestamp": "2025-08-20T10:14:53Z"
}
```

**HTTP Status Codes:**
- `200` - Success
- `201` - Created
- `400` - Bad Request
- `401` - Unauthorized
- `403` - Forbidden
- `404` - Not Found
- `422` - Validation Error
- `429` - Rate Limited
- `500` - Server Error

---

## 📝 Rate Limiting

- Authentication endpoints: 5 requests per minute
- General API endpoints: 60 requests per minute
- File upload endpoints: 10 requests per minute

Rate limit headers are included in responses:
```http
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
X-RateLimit-Reset: 1692532493
```

---

## 🔒 Security Features

### API Security
- Laravel Sanctum for token-based authentication
- Rate limiting on all endpoints
- CORS protection
- SQL injection prevention
- XSS protection

### Data Protection
- Sensitive data encryption
- Secure password hashing (bcrypt)
- Two-factor authentication support
- Audit logging for sensitive operations

### Geolocation Security
- Encrypted location data
- Geofencing validation
- Location spoofing detection
- Privacy-compliant data handling

---

## 📱 Mobile App Integration

The API is designed to support mobile applications with:
- Offline-first attendance tracking
- Push notification support
- Biometric authentication
- GPS-based location verification
- Photo capture and upload
- QR code generation and scanning

---

## 👥 Epic 6 - Client Management System

Epic 6 introduces advanced client relationship management with AI-powered automation and business intelligence.

### Core Features
- **Client Lifecycle Management** - Complete client journey tracking
- **Business Intelligence Dashboard** - Real-time analytics and KPIs
- **AI-Powered Automation** - Machine learning driven insights
- **Integration Hub** - Third-party service connections
- **Client Segmentation** - Advanced targeting and personalization

### Client Management Endpoints

All client endpoints follow RESTful conventions under `/api/v1/clients`.

#### Client CRUD Operations
- **GET** `/api/v1/clients` - List all clients with filtering and pagination
- **POST** `/api/v1/clients` - Create new client profile  
- **GET** `/api/v1/clients/{client}` - Get specific client details
- **PUT** `/api/v1/clients/{client}` - Update client information
- **DELETE** `/api/v1/clients/{client}` - Delete client (soft delete)

#### Client Specific Actions
- **POST** `/api/v1/clients/{client}/verify` - Verify client information
- **POST** `/api/v1/clients/{client}/refresh-financials` - Update financial data

#### Client Sub-Resources
- **Deals**: `/api/v1/clients/{client}/deals/*` - Manage client deals
- **Proposals**: `/api/v1/clients/{client}/proposals/*` - Handle proposals  
- **Invoices**: `/api/v1/clients/{client}/invoices/*` - Manage invoicing

#### Client Analytics
- **GET** `/api/v1/clients/statistics` - Get client analytics and metrics

#### Create Client Profile
**POST** `/api/v1/clients`

```json
{
    "company_name": "Tech Solutions Inc",
    "contact_person": "John Smith",
    "email": "john@techsolutions.com",
    "phone": "+1-555-0123",
    "industry": "technology",
    "client_type": "enterprise",
    "priority_level": "high",
    "lifecycle_stage": "prospect",
    "lead_source": "website",
    "credit_limit": 100000.00,
    "payment_terms_days": 30,
    "tags": ["high-potential", "enterprise"],
    "primary_contact": {
        "first_name": "John",
        "last_name": "Smith",
        "title": "CTO",
        "email": "john@techsolutions.com"
    }
}
```

#### Get Client Analytics
**GET** `/clients/{id}/analytics`

Returns comprehensive client analytics including financial metrics, behavioral patterns, and predictive insights.

#### Business Intelligence Dashboard
**GET** `/business-intelligence/executive-dashboard?timeframe=month`

Returns executive-level metrics and KPIs including revenue, client retention, and project success rates.

#### AI Lead Scoring
**GET** `/automation/lead-scoring`

Returns AI-powered lead scores with conversion probabilities and actionable recommendations.

#### Client Segmentation
**POST** `/clients/auto-segmentation`

Performs automatic client segmentation using machine learning algorithms.

### Integration Endpoints

#### Available Integrations
**GET** `/integrations/available`

Returns all available third-party integrations including payment gateways, accounting systems, and communication tools.

#### Configure Integration
**POST** `/integrations/configure`

```json
{
    "integration_type": "payment_gateway",
    "name": "stripe",
    "credentials": {
        "api_key": "sk_test_...",
        "webhook_secret": "whsec_..."
    },
    "features": ["process_payments", "subscriptions"]
}
```

For comprehensive Epic 6 documentation, see: `docs/EPIC_6_CLIENT_MANAGEMENT_API.md`

---

## 🛠️ Development & Testing

### Postman Collections
- **Main API Collection**: Complete HRM system endpoints
- **Epic 6 Collection**: Client management and business intelligence endpoints

Import the provided Postman collections for comprehensive API testing with pre-configured requests and test data.

### Test Environment
```
Base URL: http://localhost/matendes/matendes-hrm/public/api/v1
Database: Fresh seeded data available
Test Users: Multiple roles with proper permissions
Epic 6 Features: Enabled with sample client data
```

### API Versioning
Current version: `v1`
Future versions will maintain backward compatibility and include migration guides.

---

*This documentation covers all available API endpoints as of August 2025. For the latest updates, refer to the API response schemas and test the endpoints using the provided Postman collection.*