# Collection Agent Controller Documentation

## Overview
The `CollectionAgentController` is a dedicated controller for handling collection agent data operations with advanced filtering capabilities based on `report_in` and `reporting_time` fields.

## Controller Features

### 1. **Time-Based Filtering**
- Filters agents based on `report_in` and `reporting_time` fields
- Supports custom time range queries
- Automatic filtering for current time conditions

### 2. **Separated Logic**
- Clean separation of concerns
- Reusable methods
- Better error handling
- Centralized agent data operations

## API Endpoints

### 1. **Fetch Agent Data (with Time Filtering)**

**URL:** `collection_agent_auth.php?fetch_agent_data=1`  
**Method:** `GET`  
**Authentication:** Auth Token required

#### Description
Fetches collection agent data with automatic filtering based on `report_in` and `reporting_time` fields. Only returns agents where:
- `report_in <= NOW()` (agent has reported in)
- `reporting_time >= NOW()` (agent is still within reporting time)

#### Headers
```
Authorization: Bearer [AUTH_TOKEN]
Content-Type: application/json
```

#### Example Request
```bash
curl -X GET 'http://localhost:9000/collection_agent_auth.php?fetch_agent_data=1' \
  -H 'Authorization: Bearer YOUR_AUTH_TOKEN' \
  -H 'Content-Type: application/json'
```

#### Response
```json
{
  "status": "success",
  "data": {
    "agents": [
      {
        "id": 1,
        "name": "baby",
        "mobile_no": "7675675652",
        "address": "komarapalayam",
        "aadhar_no": "4850394580594",
        "report_in": "2025-09-25 15:15:55",
        "reporting_time": "2025-09-25 15:15:55",
        "status": "active",
        "line": "main area"
      }
    ],
    "line_entries": [],
    "loan_entries": [],
    "query_info": {
      "company_id": 9,
      "line": "main area",
      "today": "2025-10-01",
      "areas_found": [],
      "total_agents": 0,
      "total_line_entries": 0,
      "total_loan_entries": 0,
      "filter_info": {
        "filtered_by_report_time": true,
        "report_in_condition": "report_in <= NOW()",
        "reporting_time_condition": "reporting_time >= NOW()"
      }
    }
  }
}
```

### 2. **Get Agents by Time Range**

**URL:** `collection_agent_auth.php?get_agents_by_time=1`  
**Method:** `GET`  
**Authentication:** Auth Token required

#### Parameters
- `start_time` (optional): Start time filter (YYYY-MM-DD HH:MM:SS)
- `end_time` (optional): End time filter (YYYY-MM-DD HH:MM:SS)

#### Example Request
```bash
# Get all agents
curl -X GET 'http://localhost:9000/collection_agent_auth.php?get_agents_by_time=1' \
  -H 'Authorization: Bearer YOUR_AUTH_TOKEN' \
  -H 'Content-Type: application/json'

# Get agents within specific time range
curl -X GET 'http://localhost:9000/collection_agent_auth.php?get_agents_by_time=1&start_time=2025-09-25%2010:00:00&end_time=2025-09-25%2018:00:00' \
  -H 'Authorization: Bearer YOUR_AUTH_TOKEN' \
  -H 'Content-Type: application/json'
```

#### Response
```json
{
  "status": "success",
  "data": {
    "agents": [
      {
        "id": 1,
        "name": "baby",
        "mobile_no": "7675675652",
        "address": "komarapalayam",
        "aadhar_no": "4850394580594",
        "report_in": "2025-09-25 15:15:55",
        "reporting_time": "2025-09-25 15:15:55",
        "status": "active",
        "line": "main area"
      }
    ],
    "total_agents": 1,
    "time_range": {
      "start_time": null,
      "end_time": null
    }
  }
}
```

## Controller Methods

### 1. **fetchAgentData($auth_token)**
- **Purpose**: Fetch complete agent data with time filtering
- **Returns**: Agents, line entries, loan entries with query info
- **Filtering**: Automatic time-based filtering

### 2. **getAgentsByTimeRange($auth_token, $start_time, $end_time)**
- **Purpose**: Get agents within specific time range
- **Parameters**: 
  - `$start_time`: Optional start time filter
  - `$end_time`: Optional end time filter
- **Returns**: Filtered agents list

### 3. **getAuthenticatedUser($auth_token)**
- **Purpose**: Validate and get authenticated user
- **Returns**: User data or false if not authenticated

## Database Queries

### Time-Filtered Agent Query
```sql
SELECT id, name, mobile_no, address, aadhar_no, report_in, reporting_time, status, line 
FROM collection_agent 
WHERE com_id = ? AND line = ? 
AND report_in IS NOT NULL 
AND reporting_time IS NOT NULL
AND report_in <= NOW() 
AND reporting_time >= NOW()
```

### Custom Time Range Query
```sql
SELECT id, name, mobile_no, address, aadhar_no, report_in, reporting_time, status, line 
FROM collection_agent 
WHERE com_id = ? AND line = ? 
AND report_in >= ? 
AND reporting_time <= ?
```

## Filtering Logic

### 1. **Automatic Time Filtering (fetchAgentData)**
- Only returns agents who have reported in (`report_in <= NOW()`)
- Only returns agents still within reporting time (`reporting_time >= NOW()`)
- Ensures data integrity by checking both conditions

### 2. **Custom Time Range Filtering (getAgentsByTimeRange)**
- Optional start time filter (`report_in >= start_time`)
- Optional end time filter (`reporting_time <= end_time`)
- Flexible time range queries

## Error Handling

### Authentication Errors
```json
{
  "status": "error",
  "message": "Not authenticated"
}
```

### Agent Not Found
```json
{
  "status": "error",
  "message": "Agent not found"
}
```

### Database Errors
```json
{
  "status": "error",
  "message": "Database error: [error details]"
}
```

## Usage Examples

### JavaScript/Fetch API
```javascript
// Fetch agent data with time filtering
const fetchAgentData = async (token) => {
  try {
    const response = await fetch('collection_agent_auth.php?fetch_agent_data=1', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching agent data:', error);
  }
};

// Get agents by time range
const getAgentsByTime = async (token, startTime, endTime) => {
  try {
    const url = `collection_agent_auth.php?get_agents_by_time=1&start_time=${startTime}&end_time=${endTime}`;
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching agents by time:', error);
  }
};
```

### PHP cURL
```php
function fetchAgentData($token) {
    $url = "collection_agent_auth.php?fetch_agent_data=1";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

function getAgentsByTime($token, $startTime = null, $endTime = null) {
    $url = "collection_agent_auth.php?get_agents_by_time=1";
    
    if ($startTime) {
        $url .= "&start_time=" . urlencode($startTime);
    }
    if ($endTime) {
        $url .= "&end_time=" . urlencode($endTime);
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}
```

## Benefits of Separate Controller

1. **Separation of Concerns**: Agent logic separated from authentication logic
2. **Reusability**: Methods can be used across different endpoints
3. **Maintainability**: Easier to modify agent-specific functionality
4. **Testing**: Easier to unit test individual methods
5. **Scalability**: Can add more agent-related methods easily

## Files Created/Modified

1. `controllers/CollectionAgentController.php` - New dedicated controller
2. `controllers/routes.php` - Updated to use new controller
3. `COLLECTION_AGENT_CONTROLLER_DOCUMENTATION.md` - This documentation

## Requirements

- PHP 7.4+
- MySQL 5.7+
- Valid database connection
- Proper authentication system
- CORS headers for web requests
