# Collection Agent API Documentation

## Overview
This API provides functionality to fetch collection agent data along with their assigned lines and loan entries that are due today. The API supports two implementation approaches:
login agent mobile 

curl -X POST 'http://your-domain.com/collection_agent_auth.php?generate_otp=1' \
  -H 'Content-Type: application/json' \
  -d '{
    "mobile_no": "7675675652"
  }'
1. **Standalone API Endpoint** (`collection_agent_fetch.php`)
2. **Integrated Routes API** (via `collection_agent_auth.php`)

## Database Structure
The API works with the following tables:
- `collection_agent` - Collection agents with their assigned lines
- `line_entry` - Line and area mappings for companies
- `loan_entry` - Loan records with due dates and areas

## API Endpoints

### 1. Standalone API Endpoint

**URL:** `collection_agent_fetch.php`  
**Method:** `GET`  
**Authentication:** JWT Token required

#### Parameters
- No parameters required - line is automatically determined from the authenticated agent's data

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

#### Example Request
```bash
curl -X GET 'http://your-domain.com/collection_agent_fetch.php' \
  -H 'Authorization: Bearer YOUR_JWT_TOKEN' \
  -H 'Content-Type: application/json'
```

### 2. Integrated Routes API

**URL:** `collection_agent_auth.php`  
**Method:** `GET`  
**Authentication:** JWT Token required

#### Parameters
- `fetch_agent_data=1` (required): Flag to enable the fetch functionality
- No line parameter required - automatically determined from authenticated agent

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

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

## Response Format

### Success 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": [
      {
        "id": "1",
        "com_id": "9",
        "area": "erode",
        "line": "main line",
        "created_on": "0000-00-00 00:00:00"
      },
      {
        "id": "2",
        "com_id": "9",
        "area": "salem",
        "line": "main line",
        "created_on": "0000-00-00 00:00:00"
      }
    ],
    "loan_entries": [
      {
        "id": "5",
        "loan_id": "DL2025002",
        "com_id": "9",
        "cus_name": "Raja",
        "cust_mobile": "1234567890",
        "area": "salem",
        "loan_type": "Daily",
        "loan_amt": "10000",
        "next_due_date": "2025-09-23",
        "per_due_amt": "167"
      }
    ],
    "query_info": {
      "company_id": "9",
      "line": "main line",
      "today": "2025-09-23",
      "areas_found": ["erode", "salem"],
      "total_agents": 1,
      "total_line_entries": 2,
      "total_loan_entries": 1
    }
  }
}
```

### Error Responses

#### Missing Authorization
```json
{
  "success": false,
  "message": "Authorization header missing"
}
```

#### Invalid Token
```json
{
  "success": false,
  "message": "JWT decode failed: [error details]"
}
```

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

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

## API Logic Flow

1. **Authentication**: Validates JWT token and extracts company_id and agent ID
2. **Agent Line Lookup**: Gets the authenticated agent's assigned line from database
3. **Collection Agents**: Fetches all agents assigned to the same line
4. **Line Entries**: Gets areas associated with the line for the company
5. **Loan Entries**: Finds loans due today in the areas covered by the line
6. **Response**: Returns all data with query summary information

## Database Queries

### Agent Line Lookup Query
```sql
SELECT line, com_id FROM collection_agent WHERE id = ?
```

### Collection Agents Query
```sql
SELECT id, name, mobile_no, address, aadhar_no, report_in, reporting_time, status, line 
FROM collection_agent 
WHERE com_id = ? AND line = ?
```

### Line Entries Query
```sql
SELECT id, com_id, area, line, created_on 
FROM line_entry 
WHERE com_id = ? AND line = ?
```

### Loan Entries Query
```sql
SELECT id, loan_id, com_id, loan_date, cust_id, cus_name, cust_mobile, 
       cust_contact, aadhaar_no, cust_address, cust_address2, area, 
       loan_type, loan_amt, dues, interest, interest_amt, ledger, 
       due_schedule, createdOn, total_amt, per_due_amt, next_due_date, 
       last_due_date, pre_interest
FROM loan_entry 
WHERE com_id = ? AND area IN (areas) AND next_due_date = ?
```

## Usage Examples

### JavaScript/Fetch API
```javascript
const fetchAgentData = async (line, token) => {
  try {
    const response = await fetch(`collection_agent_fetch.php?line=${encodeURIComponent(line)}`, {
      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);
  }
};
```

### PHP cURL
```php
function fetchAgentData($line, $token) {
    $url = "collection_agent_fetch.php?line=" . urlencode($line);
    
    $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);
}
```

## Security Features

- JWT token authentication
- Prepared statements to prevent SQL injection
- Company-based data isolation
- Input validation and sanitization

## Error Handling

- Comprehensive error messages
- HTTP status codes for different error types
- Database error logging
- Graceful failure handling

## Testing

Use the provided `test_collection_agent_api.php` file to test the API endpoints and understand the expected responses.

## Files Created/Modified

1. `collection_agent_fetch.php` - Standalone API endpoint
2. `controllers/routes.php` - Added integrated route
3. `test_collection_agent_api.php` - Test documentation
4. `COLLECTION_AGENT_API_DOCUMENTATION.md` - This documentation

## Requirements

- PHP 7.4+
- MySQL 5.7+
- JWT library (firebase/php-jwt)
- Valid database connection
- Proper CORS headers for web requests
