# Enhanced Device API Documentation

This directory contains enhanced APIs for device management, monitoring, and communication.

## Table of Contents
1. [Installation](#installation)
2. [API Endpoints](#api-endpoints)
3. [Database Schema](#database-schema)
4. [Testing](#testing)
5. [Security](#security)

## Installation

### 1. Database Setup

Run the migration SQL file to create necessary tables:

```bash
mysql -u your_username -p your_database < database/migrations.sql
```

Or import via phpMyAdmin or your preferred MySQL client.

### 2. File Structure

```
api/
├── IsConnectEnhanced.php    # Device heartbeat & health check
├── ConfigSync.php            # Configuration synchronization
├── QueryCommands.php         # Retrieve pending commands
├── CommandResponse.php       # Submit command execution results
├── DeviceStatistics.php      # Get device statistics
├── UpdateStatistics.php      # Update device statistics
├── DeviceStatus.php          # Get real-time device status
└── README.md                 # This file

database/
└── migrations.sql            # Database schema
```

### 3. Configuration

The APIs use the existing database connection from `config/config.php`. No additional configuration needed.

## API Endpoints

### 1. IsConnectEnhanced.php

**Purpose:** Device heartbeat and health check

**Method:** POST or GET

**Parameters:**
- `SN` (optional): Device serial number
- `FirmwareVersion` (optional): Device firmware version
- `DeviceInfo` (optional): Additional device information

**Response:**
```json
{
  "DateTime": "2024-02-24 10:30:00",
  "ServerStatus": "online",
  "Status": 1,
  "DeviceStatus": "registered",
  "Message": "Heartbeat recorded"
}
```

**Example Request:**
```bash
curl -X POST http://your-domain/api/IsConnectEnhanced.php \
  -H "Content-Type: application/json" \
  -d '{"SN":"DEVICE001","FirmwareVersion":"1.2.3"}'
```

---

### 2. ConfigSync.php

**Purpose:** Check if device configuration needs synchronization

**Method:** POST

**Parameters:**
- `SN` (required): Device serial number
- `CurrentVersion` (optional): Current config version on device

**Response:**
```json
{
  "DateTime": "2024-02-24 10:30:00",
  "Status": 1,
  "ConfigVersion": "1.0.0",
  "RequireSync": true,
  "ConfigData": {
    "device_id": "DEVICE001",
    "settings": {
      "relay_time": 5000,
      "beep_time": 1000
    }
  },
  "Message": "Configuration update available"
}
```

**Example Request:**
```bash
curl -X POST http://your-domain/api/ConfigSync.php \
  -H "Content-Type: application/json" \
  -d '{"SN":"DEVICE001","CurrentVersion":"1.0.0"}'
```

---

### 3. QueryCommands.php

**Purpose:** Retrieve pending commands for a device

**Method:** POST

**Parameters:**
- `SN` (required): Device serial number
- `MaxCommands` (optional): Maximum commands to retrieve (default: 5)

**Response:**
```json
{
  "DateTime": "2024-02-24 10:30:00",
  "Status": 1,
  "PendingCommands": 2,
  "Commands": [
    {
      "CmdID": 123,
      "CmdCode": 1,
      "CmdName": "Reboot",
      "CmdParams": {}
    },
    {
      "CmdID": 124,
      "CmdCode": 2,
      "CmdName": "UpdateConfig",
      "CmdParams": {"key": "value"}
    }
  ],
  "Message": "Commands retrieved"
}
```

**Example Request:**
```bash
curl -X POST http://your-domain/api/QueryCommands.php \
  -H "Content-Type: application/json" \
  -d '{"SN":"DEVICE001","MaxCommands":5}'
```

---

### 4. CommandResponse.php

**Purpose:** Submit command execution results from device

**Method:** POST

**Parameters:**
- `SN` (required): Device serial number
- `CmdID` (required): Command ID
- `Status` (required): Execution status (1=success, 0=failed)
- `Response` (optional): Response data

**Response:**
```json
{
  "DateTime": "2024-02-24 10:30:00",
  "Status": 1,
  "Message": "Command response recorded"
}
```

**Example Request:**
```bash
curl -X POST http://your-domain/api/CommandResponse.php \
  -H "Content-Type: application/json" \
  -d '{"SN":"DEVICE001","CmdID":123,"Status":1,"Response":"Reboot successful"}'
```

---

### 5. DeviceStatistics.php

**Purpose:** Get device statistics and monitoring data

**Method:** POST or GET

**Parameters:**
- `SN` (optional): Device serial number (if not provided, returns all devices)
- `StartDate` (optional): Start date (default: 7 days ago)
- `EndDate` (optional): End date (default: today)

**Response (Single Device):**
```json
{
  "DateTime": "2024-02-24 10:30:00",
  "Status": 1,
  "DeviceInfo": {
    "DeviceID": "DEVICE001",
    "DeviceName": "Main Entrance",
    "Status": "active",
    "ConnectionStatus": "online",
    "LastHeartbeat": "2024-02-24 10:29:00"
  },
  "Statistics": {
    "Period": {
      "StartDate": "2024-02-17",
      "EndDate": "2024-02-24"
    },
    "Summary": {
      "TotalScans": 1500,
      "SuccessfulScans": 1450,
      "FailedScans": 50
    }
  }
}
```

**Example Request:**
```bash
curl -X GET "http://your-domain/api/DeviceStatistics.php?SN=DEVICE001"
```

---

### 6. UpdateStatistics.php

**Purpose:** Device reports its daily statistics

**Method:** POST

**Parameters:**
- `SN` (required): Device serial number
- `Date` (optional): Statistics date (default: today)
- `TotalScans`: Total number of scans
- `SuccessfulScans`: Successful scans
- `FailedScans`: Failed scans
- `UptimeMinutes`: Device uptime in minutes

**Response:**
```json
{
  "DateTime": "2024-02-24 10:30:00",
  "Status": 1,
  "Message": "Statistics recorded"
}
```

**Example Request:**
```bash
curl -X POST http://your-domain/api/UpdateStatistics.php \
  -H "Content-Type: application/json" \
  -d '{"SN":"DEVICE001","TotalScans":150,"SuccessfulScans":145,"FailedScans":5,"UptimeMinutes":1440}'
```

---

### 7. DeviceStatus.php

**Purpose:** Get real-time status of devices

**Method:** GET or POST

**Parameters:**
- `SN` (optional): Device serial number
- `IncludeOffline` (optional): Include offline devices (default: true)

**Response:**
```json
{
  "DateTime": "2024-02-24 10:30:00",
  "Status": 1,
  "TotalDevices": 10,
  "Devices": [
    {
      "DeviceID": "DEVICE001",
      "DeviceName": "Main Entrance",
      "ConnectionStatus": "online",
      "LastHeartbeat": "2024-02-24 10:29:00",
      "IPAddress": "192.168.1.100",
      "FirmwareVersion": "1.2.3",
      "SecondsSinceLastHeartbeat": 60,
      "IsOnline": true
    }
  ]
}
```

**Example Request:**
```bash
curl -X GET "http://your-domain/api/DeviceStatus.php?IncludeOffline=false"
```

## Database Schema

### Tables Created

1. **device_heartbeats** - Tracks device connectivity
2. **device_commands** - Command queue for devices
3. **device_configurations** - Device configuration versions
4. **device_statistics** - Daily device statistics
5. **api_request_logs** - API request logging
6. **server_configuration** - Server-wide configuration

See `database/migrations.sql` for complete schema.

## Testing

### Test Script

Create a test file `test_apis.php`:

```php
<?php
// Test all APIs
$base_url = 'http://your-domain/api';
$device_id = 'TEST_DEVICE_001';

// Test 1: IsConnectEnhanced
echo "Testing IsConnectEnhanced...\n";
$response = file_get_contents($base_url . '/IsConnectEnhanced.php', false, stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => 'Content-Type: application/json',
        'content' => json_encode(['SN' => $device_id, 'FirmwareVersion' => '1.0.0'])
    ]
]));
echo $response . "\n\n";

// Test 2: ConfigSync
echo "Testing ConfigSync...\n";
$response = file_get_contents($base_url . '/ConfigSync.php', false, stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => 'Content-Type: application/json',
        'content' => json_encode(['SN' => $device_id])
    ]
]));
echo $response . "\n\n";

// Test 3: DeviceStatus
echo "Testing DeviceStatus...\n";
$response = file_get_contents($base_url . '/DeviceStatus.php?SN=' . $device_id);
echo $response . "\n\n";
```

### Using cURL

```bash
# Test heartbeat
curl -X POST http://your-domain/api/IsConnectEnhanced.php \
  -H "Content-Type: application/json" \
  -d '{"SN":"TEST001"}'

# Test config sync
curl -X POST http://your-domain/api/ConfigSync.php \
  -H "Content-Type: application/json" \
  -d '{"SN":"TEST001"}'

# Test device status
curl -X GET "http://your-domain/api/DeviceStatus.php"
```

## Security

### Recommendations

1. **Add Authentication:**
```php
// Add to each API file
$api_key = $_SERVER['HTTP_X_API_KEY'] ?? '';
if ($api_key !== 'your-secret-key') {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}
```

2. **Rate Limiting:**
Already implemented basic IP-based tracking in logs.

3. **HTTPS Only:**
Configure your web server to enforce HTTPS.

4. **Input Validation:**
All APIs validate required fields and sanitize inputs.

## Monitoring

### Check Device Health

```sql
-- Devices that haven't sent heartbeat in 5 minutes
SELECT device_id, last_heartbeat, connection_status
FROM device_heartbeats
WHERE last_heartbeat < DATE_SUB(NOW(), INTERVAL 5 MINUTE);

-- Today's statistics summary
SELECT 
    SUM(total_scans) as total,
    SUM(successful_scans) as successful,
    SUM(failed_scans) as failed
FROM device_statistics
WHERE stat_date = CURDATE();
```

## Support

For issues or questions, check the API request logs:

```sql
SELECT * FROM api_request_logs 
WHERE endpoint = 'IsConnectEnhanced' 
ORDER BY created_at DESC 
LIMIT 10;
```
