# Image Upload Guide for Create Agent API

## Overview
The Create Agent API (`POST /admin/agents`) supports image uploads in two ways:
1. **File Upload** (multipart/form-data) - Recommended for web/mobile apps
2. **Base64 String** (application/json) - Alternative method

## Supported Image Formats
- JPEG / JPG
- PNG
- GIF
- WEBP

## File Size Limit
- Maximum: **5MB** per image

## Method 1: File Upload (multipart/form-data)

### Using cURL
```bash
curl -X POST "https://dayloanapp.xesstechlink.com/admin/agents" \
  -H "accept: application/json" \
  -H "authorization: Bearer YOUR_ADMIN_JWT_TOKEN" \
  -F "name=Ravi Kumar" \
  -F "mobile_no=9876543210" \
  -F "aadhar_no=1234 5678 9012" \
  -F "address=123 Main Street, Erode" \
  -F "login_time=9:00 AM" \
  -F "logout_time=8:30 PM" \
  -F "status=active" \
  -F "line=Line 1" \
  -F "photo=@/path/to/agent-photo.jpg"
```

### Using JavaScript (Fetch API)
```javascript
const formData = new FormData();
formData.append('name', 'Ravi Kumar');
formData.append('mobile_no', '9876543210');
formData.append('aadhar_no', '1234 5678 9012');
formData.append('address', '123 Main Street, Erode');
formData.append('login_time', '9:00 AM');
formData.append('logout_time', '8:30 PM');
formData.append('status', 'active');
formData.append('line', 'Line 1');

// Add photo file
const photoInput = document.getElementById('photoInput'); // File input element
if (photoInput.files[0]) {
  formData.append('photo', photoInput.files[0]);
}

fetch('https://dayloanapp.xesstechlink.com/admin/agents', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_ADMIN_JWT_TOKEN'
  },
  body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
```

### Using JavaScript (Axios)
```javascript
const formData = new FormData();
formData.append('name', 'Ravi Kumar');
formData.append('mobile_no', '9876543210');
formData.append('photo', photoFile); // File object from input

axios.post('https://dayloanapp.xesstechlink.com/admin/agents', formData, {
  headers: {
    'Authorization': 'Bearer YOUR_ADMIN_JWT_TOKEN',
    'Content-Type': 'multipart/form-data'
  }
})
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
```

### Using React Native
```javascript
import FormData from 'form-data';
import { Platform } from 'react-native';

const createAgent = async (agentData, photoUri) => {
  const formData = new FormData();
  
  formData.append('name', agentData.name);
  formData.append('mobile_no', agentData.mobile_no);
  formData.append('aadhar_no', agentData.aadhar_no);
  formData.append('address', agentData.address);
  formData.append('login_time', agentData.login_time);
  formData.append('logout_time', agentData.logout_time);
  formData.append('status', agentData.status);
  formData.append('line', agentData.line);
  
  // Add photo
  if (photoUri) {
    formData.append('photo', {
      uri: Platform.OS === 'ios' ? photoUri.replace('file://', '') : photoUri,
      type: 'image/jpeg',
      name: 'photo.jpg'
    });
  }
  
  try {
    const response = await fetch('https://dayloanapp.xesstechlink.com/admin/agents', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_ADMIN_JWT_TOKEN',
        'Content-Type': 'multipart/form-data'
      },
      body: formData
    });
    
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
};
```

## Method 2: Base64 String (application/json)

### Using cURL
```bash
curl -X POST "https://dayloanapp.xesstechlink.com/admin/agents" \
  -H "accept: application/json" \
  -H "authorization: Bearer YOUR_ADMIN_JWT_TOKEN" \
  -H "content-type: application/json" \
  -d '{
    "name": "Ravi Kumar",
    "mobile_no": "9876543210",
    "aadhar_no": "1234 5678 9012",
    "address": "123 Main Street, Erode",
    "login_time": "9:00 AM",
    "logout_time": "8:30 PM",
    "status": "active",
    "line": "Line 1",
    "photo": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ..."
  }'
```

### Converting Image to Base64 (JavaScript)
```javascript
// Method 1: From File Input
function convertFileToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

// Usage
const fileInput = document.getElementById('photoInput');
const file = fileInput.files[0];
const base64String = await convertFileToBase64(file);

// Method 2: From Image URL
async function convertImageUrlToBase64(imageUrl) {
  const response = await fetch(imageUrl);
  const blob = await response.blob();
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
    reader.readAsDataURL(blob);
  });
}

// Usage
const base64String = await convertImageUrlToBase64('https://example.com/image.jpg');
```

### Using Base64 in API Request
```javascript
const agentData = {
  name: 'Ravi Kumar',
  mobile_no: '9876543210',
  aadhar_no: '1234 5678 9012',
  address: '123 Main Street, Erode',
  login_time: '9:00 AM',
  logout_time: '8:30 PM',
  status: 'active',
  line: 'Line 1',
  photo: base64String // Base64 string with data:image prefix
};

fetch('https://dayloanapp.xesstechlink.com/admin/agents', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_ADMIN_JWT_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(agentData)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
```

## Image Storage

### How Images are Stored
- Images are stored in the database as **BLOB** (Binary Large Object)
- The file is temporarily saved to `/uploads/agents/` directory
- File is read and stored in database
- Original filename: `agent-{timestamp}-{random}.{ext}`

### Database Field
- Field name: `photo`
- Type: `BLOB('long')`
- Nullable: Yes (photo is optional)

## Response

### Success Response with Photo
```json
{
  "status": "success",
  "message": "Collection agent created successfully",
  "data": {
    "agent": {
      "id": 5,
      "name": "Ravi Kumar",
      "mobile_no": "9876543210",
      "has_photo": true,
      ...
    }
  }
}
```

### Success Response without Photo
```json
{
  "status": "success",
  "message": "Collection agent created successfully",
  "data": {
    "agent": {
      "id": 5,
      "name": "Ravi Kumar",
      "mobile_no": "9876543210",
      "has_photo": false,
      ...
    }
  }
}
```

## Error Handling

### Invalid File Type
```json
{
  "status": "error",
  "message": "Only image files are allowed (jpeg, jpg, png, gif, webp)"
}
```

### File Too Large
```json
{
  "status": "error",
  "message": "File too large. Maximum size is 5MB"
}
```

## Best Practices

1. **Use File Upload (multipart/form-data)** for better performance with large images
2. **Compress images** before uploading to reduce file size
3. **Validate file type** on client side before upload
4. **Show file size** to user before upload
5. **Handle upload progress** for better UX
6. **Use Base64** only for small images (< 1MB)

## Example: Complete React Component

```javascript
import React, { useState } from 'react';

function CreateAgentForm() {
  const [formData, setFormData] = useState({
    name: '',
    mobile_no: '',
    aadhar_no: '',
    address: '',
    login_time: '9:00 AM',
    logout_time: '8:30 PM',
    status: 'active',
    line: ''
  });
  const [photo, setPhoto] = useState(null);
  const [uploading, setUploading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setUploading(true);

    const formDataToSend = new FormData();
    Object.keys(formData).forEach(key => {
      formDataToSend.append(key, formData[key]);
    });
    
    if (photo) {
      formDataToSend.append('photo', photo);
    }

    try {
      const response = await fetch('https://dayloanapp.xesstechlink.com/admin/agents', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        },
        body: formDataToSend
      });

      const data = await response.json();
      if (data.status === 'success') {
        alert('Agent created successfully!');
        // Reset form
        setFormData({...formData, name: '', mobile_no: ''});
        setPhoto(null);
      } else {
        alert(data.message);
      }
    } catch (error) {
      console.error('Error:', error);
      alert('Failed to create agent');
    } finally {
      setUploading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Name"
        value={formData.name}
        onChange={(e) => setFormData({...formData, name: e.target.value})}
        required
      />
      <input
        type="tel"
        placeholder="Mobile No"
        value={formData.mobile_no}
        onChange={(e) => setFormData({...formData, mobile_no: e.target.value})}
        required
      />
      <input
        type="file"
        accept="image/*"
        onChange={(e) => setPhoto(e.target.files[0])}
      />
      <button type="submit" disabled={uploading}>
        {uploading ? 'Creating...' : 'Create Agent'}
      </button>
    </form>
  );
}
```

## Testing Image Upload

### Test with a Sample Image
```bash
# Download a test image first
curl -o test-image.jpg https://via.placeholder.com/300

# Upload with the image
curl -X POST "https://dayloanapp.xesstechlink.com/admin/agents" \
  -H "authorization: Bearer YOUR_ADMIN_JWT_TOKEN" \
  -F "name=Test Agent" \
  -F "mobile_no=9876543210" \
  -F "photo=@test-image.jpg"
```

## Notes

- Photo upload is **optional** - agents can be created without a photo
- The `has_photo` field in response indicates if photo was uploaded
- Photos are stored in database, not as separate files
- File uploads are temporarily stored in `/uploads/agents/` directory
- Base64 strings must include the data URI prefix: `data:image/jpeg;base64,...`

