# Admin Report API Documentation

## Overview

The Admin Report API provides comprehensive reporting capabilities for administrators to view user recharge reports and service usage reports. These endpoints help admins track user activity, analyze transactions, and generate detailed reports.

---

## Base URL

```
https://api.alldigtalseva.com/api
```

**Authentication:** All endpoints require Admin Bearer Token

---

## API Endpoints

### 1. User Recharge Report

Get detailed recharge history for users with filtering and summary statistics.

**Endpoint:** `GET /admin/report/recharge`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| user_id | integer | No | Filter by specific user ID |
| status | string | No | Filter by status: `pending`, `approved`, `rejected` |
| start_date | date | No | Filter by start date (YYYY-MM-DD) - based on created_at |
| end_date | date | No | Filter by end date (YYYY-MM-DD) - based on created_at |
| approved_start_date | date | No | Filter by approved start date (YYYY-MM-DD) |
| approved_end_date | date | No | Filter by approved end date (YYYY-MM-DD) |
| sort_by | string | No | Sort by field (default: `created_at`) |
| sort_order | string | No | Sort order: `asc` or `desc` (default: `desc`) |
| per_page | integer | No | Items per page (1-100, default: 15) |

**Response (Success - 200):**
```json
{
    "success": true,
    "summary": {
        "total_requests": 50,
        "total_amount": 50000.00,
        "total_credited": 55000.00,
        "pending_requests": 5,
        "approved_requests": 40,
        "rejected_requests": 5,
        "pending_amount": 5000.00,
        "approved_amount": 45000.00
    },
    "data": [
        {
            "id": 1,
            "user_id": 1,
            "upi_id": 1,
            "recharge_offer_id": null,
            "amount": "1000.00",
            "discount_amount": "0.00",
            "cashback_amount": "0.00",
            "final_credited_amount": "1000.00",
            "status": "approved",
            "rejection_reason": null,
            "approved_by": 1,
            "approved_at": "2025-12-06T10:30:00.000000Z",
            "created_at": "2025-12-06T10:00:00.000000Z",
            "updated_at": "2025-12-06T10:30:00.000000Z",
            "user": {
                "id": 1,
                "email": "user@example.com",
                "phone_number": "1234567890",
                "name": "John Doe",
                "user_type": "user"
            },
            "upi": {
                "id": 1,
                "upi_id": "payment@paytm",
                "name": "Main UPI"
            }
        }
    ],
    "pagination": {
        "current_page": 1,
        "per_page": 15,
        "total": 50,
        "last_page": 4
    }
}
```

**Response (Unauthorized - 401):**
```json
{
    "success": false,
    "message": "Unauthorized. Admin access required."
}
```

**cURL Examples:**

```bash
# Get all recharge reports
curl -X GET "https://api.alldigtalseva.com/api/admin/report/recharge" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get recharge report for specific user
curl -X GET "https://api.alldigtalseva.com/api/admin/report/recharge?user_id=1" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get approved recharges for date range
curl -X GET "https://api.alldigtalseva.com/api/admin/report/recharge?status=approved&start_date=2025-12-01&end_date=2025-12-31" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get pending recharges with pagination
curl -X GET "https://api.alldigtalseva.com/api/admin/report/recharge?status=pending&per_page=20" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"
```

---

### 2. User Service Report

Get detailed service usage history for users with filtering and summary statistics.

**Endpoint:** `GET /admin/report/service`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| user_id | integer | No | Filter by specific user ID |
| service_id | integer | No | Filter by specific service ID |
| service_type | string | No | Filter by service type: `farmer_id`, `bocw_id`, etc. |
| status | string | No | Filter by status: `pending`, `success`, `failed` |
| start_date | date | No | Filter by start date (YYYY-MM-DD) |
| end_date | date | No | Filter by end date (YYYY-MM-DD) |
| sort_by | string | No | Sort by field (default: `created_at`) |
| sort_order | string | No | Sort order: `asc` or `desc` (default: `desc`) |
| per_page | integer | No | Items per page (1-100, default: 15) |

**Response (Success - 200):**
```json
{
    "success": true,
    "summary": {
        "total_transactions": 100,
        "total_amount": 2500.00,
        "successful_transactions": 85,
        "failed_transactions": 10,
        "pending_transactions": 5,
        "successful_amount": 2125.00,
        "failed_amount": 250.00
    },
    "service_type_breakdown": [
        {
            "service_type": "farmer_id",
            "count": 60,
            "total_amount": 1500.00
        },
        {
            "service_type": "bocw_id",
            "count": 40,
            "total_amount": 1000.00
        }
    ],
    "data": [
        {
            "id": 1,
            "user_id": 1,
            "service_id": 1,
            "amount": "25.00",
            "service_type": "farmer_id",
            "status": "success",
            "request_data": {
                "aadhar": "123456789012"
            },
            "response_data": {
                "data": {
                    "farmerID": "FARM123456",
                    "farmerNameEn": "John Doe"
                }
            },
            "error_message": null,
            "created_at": "2025-12-06T10:00:00.000000Z",
            "updated_at": "2025-12-06T10:00:05.000000Z",
            "user": {
                "id": 1,
                "email": "user@example.com",
                "phone_number": "1234567890",
                "name": "John Doe",
                "user_type": "user"
            },
            "service": {
                "id": 1,
                "name": "Farmer ID",
                "path": "/user/farmerid"
            }
        }
    ],
    "pagination": {
        "current_page": 1,
        "per_page": 15,
        "total": 100,
        "last_page": 7
    }
}
```

**Response (Unauthorized - 401):**
```json
{
    "success": false,
    "message": "Unauthorized. Admin access required."
}
```

**cURL Examples:**

```bash
# Get all service reports
curl -X GET "https://api.alldigtalseva.com/api/admin/report/service" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get service report for specific user
curl -X GET "https://api.alldigtalseva.com/api/admin/report/service?user_id=1" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get Farmer ID service reports
curl -X GET "https://api.alldigtalseva.com/api/admin/report/service?service_type=farmer_id" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get successful services for date range
curl -X GET "https://api.alldigtalseva.com/api/admin/report/service?status=success&start_date=2025-12-01&end_date=2025-12-31" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get failed services
curl -X GET "https://api.alldigtalseva.com/api/admin/report/service?status=failed" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"
```

---

### 3. User Complete Report

Get comprehensive report for a specific user including both recharge and service statistics.

**Endpoint:** `GET /admin/report/user/{userId}`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**URL Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| userId | integer | Yes | User ID |

**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| start_date | date | No | Filter by start date (YYYY-MM-DD) |
| end_date | date | No | Filter by end date (YYYY-MM-DD) |

**Response (Success - 200):**
```json
{
    "success": true,
    "user": {
        "id": 1,
        "email": "user@example.com",
        "phone_number": "1234567890",
        "name": "John Doe",
        "user_type": "user",
        "wallet_balance": 500.00,
        "is_verified": true
    },
    "recharge_statistics": {
        "total_requests": 10,
        "total_amount": 10000.00,
        "total_credited": 11000.00,
        "pending": 1,
        "approved": 8,
        "rejected": 1
    },
    "service_statistics": {
        "total_transactions": 25,
        "total_amount": 625.00,
        "successful": 20,
        "failed": 3,
        "pending": 2
    },
    "service_type_breakdown": [
        {
            "service_type": "farmer_id",
            "count": 15,
            "total_amount": 375.00
        },
        {
            "service_type": "bocw_id",
            "count": 10,
            "total_amount": 250.00
        }
    ],
    "recent_recharges": [
        {
            "id": 10,
            "user_id": 1,
            "amount": "1000.00",
            "status": "approved",
            "created_at": "2025-12-06T10:00:00.000000Z",
            "upi": {
                "id": 1,
                "upi_id": "payment@paytm",
                "name": "Main UPI"
            }
        }
    ],
    "recent_services": [
        {
            "id": 25,
            "service_type": "farmer_id",
            "amount": "25.00",
            "status": "success",
            "created_at": "2025-12-06T10:00:00.000000Z",
            "service": {
                "id": 1,
                "name": "Farmer ID",
                "path": "/user/farmerid"
            }
        }
    ]
}
```

**Response (Unauthorized - 401):**
```json
{
    "success": false,
    "message": "Unauthorized. Admin access required."
}
```

**Response (Not Found - 404):**
```json
{
    "success": false,
    "message": "User not found"
}
```

**cURL Examples:**

```bash
# Get complete report for user
curl -X GET "https://api.alldigtalseva.com/api/admin/report/user/1" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get complete report for date range
curl -X GET "https://api.alldigtalseva.com/api/admin/report/user/1?start_date=2025-12-01&end_date=2025-12-31" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"
```

---

## JavaScript/Angular Examples

### User Recharge Report

```typescript
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AdminReportService {
  private apiUrl = 'https://api.alldigtalseva.com/api';
  private headers: HttpHeaders;

  constructor(private http: HttpClient) {
    const token = localStorage.getItem('admin_token');
    this.headers = new HttpHeaders({
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    });
  }

  getUserRechargeReport(params?: {
    user_id?: number;
    status?: string;
    start_date?: string;
    end_date?: string;
    approved_start_date?: string;
    approved_end_date?: string;
    sort_by?: string;
    sort_order?: string;
    per_page?: number;
  }): Observable<any> {
    let queryParams = new HttpParams();
    
    if (params) {
      Object.keys(params).forEach(key => {
        if (params[key] !== undefined) {
          queryParams = queryParams.set(key, params[key].toString());
        }
      });
    }

    return this.http.get(`${this.apiUrl}/admin/report/recharge`, {
      headers: this.headers,
      params: queryParams
    });
  }
}

// Usage in component
// Get all recharge reports
this.adminReportService.getUserRechargeReport().subscribe(
  (response) => {
    if (response.success) {
      console.log('Summary:', response.summary);
      console.log('Recharges:', response.data);
      console.log('Pagination:', response.pagination);
    }
  }
);

// Get recharge report for specific user
this.adminReportService.getUserRechargeReport({
  user_id: 1,
  status: 'approved',
  start_date: '2025-12-01',
  end_date: '2025-12-31'
}).subscribe(
  (response) => {
    if (response.success) {
      console.log('User Recharge Report:', response);
    }
  }
);
```

### User Service Report

```typescript
getUserServiceReport(params?: {
  user_id?: number;
  service_id?: number;
  service_type?: string;
  status?: string;
  start_date?: string;
  end_date?: string;
  sort_by?: string;
  sort_order?: string;
  per_page?: number;
}): Observable<any> {
  let queryParams = new HttpParams();
  
  if (params) {
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined) {
        queryParams = queryParams.set(key, params[key].toString());
      }
    });
  }

  return this.http.get(`${this.apiUrl}/admin/report/service`, {
    headers: this.headers,
    params: queryParams
  });
}

// Usage
// Get all service reports
this.adminReportService.getUserServiceReport().subscribe(
  (response) => {
    if (response.success) {
      console.log('Summary:', response.summary);
      console.log('Service Type Breakdown:', response.service_type_breakdown);
      console.log('Services:', response.data);
    }
  }
);

// Get Farmer ID service reports
this.adminReportService.getUserServiceReport({
  service_type: 'farmer_id',
  status: 'success',
  start_date: '2025-12-01',
  end_date: '2025-12-31'
}).subscribe(
  (response) => {
    if (response.success) {
      console.log('Farmer ID Reports:', response);
    }
  }
);
```

### User Complete Report

```typescript
getUserCompleteReport(userId: number, params?: {
  start_date?: string;
  end_date?: string;
}): Observable<any> {
  let queryParams = new HttpParams();
  
  if (params) {
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined) {
        queryParams = queryParams.set(key, params[key].toString());
      }
    });
  }

  return this.http.get(`${this.apiUrl}/admin/report/user/${userId}`, {
    headers: this.headers,
    params: queryParams
  });
}

// Usage
// Get complete report for user
this.adminReportService.getUserCompleteReport(1).subscribe(
  (response) => {
    if (response.success) {
      console.log('User:', response.user);
      console.log('Recharge Stats:', response.recharge_statistics);
      console.log('Service Stats:', response.service_statistics);
      console.log('Recent Recharges:', response.recent_recharges);
      console.log('Recent Services:', response.recent_services);
    }
  }
);

// Get complete report for date range
this.adminReportService.getUserCompleteReport(1, {
  start_date: '2025-12-01',
  end_date: '2025-12-31'
}).subscribe(
  (response) => {
    if (response.success) {
      console.log('User Report:', response);
    }
  }
);
```

---

## React/Next.js Examples

### User Recharge Report

```javascript
const getUserRechargeReport = async (adminToken, params = {}) => {
  try {
    const queryString = new URLSearchParams(params).toString();
    const url = `https://api.alldigtalseva.com/api/admin/report/recharge${queryString ? `?${queryString}` : ''}`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${adminToken}`,
        'Content-Type': 'application/json',
      },
    });

    const data = await response.json();
    
    if (data.success) {
      return {
        success: true,
        summary: data.summary,
        data: data.data,
        pagination: data.pagination
      };
    } else {
      return {
        success: false,
        message: data.message
      };
    }
  } catch (error) {
    console.error('Error:', error);
    return {
      success: false,
      message: 'An error occurred'
    };
  }
};

// Usage
const adminToken = localStorage.getItem('admin_token');

// Get all recharge reports
getUserRechargeReport(adminToken).then(result => {
  if (result.success) {
    console.log('Summary:', result.summary);
    console.log('Recharges:', result.data);
  }
});

// Get recharge report for specific user
getUserRechargeReport(adminToken, {
  user_id: 1,
  status: 'approved',
  start_date: '2025-12-01',
  end_date: '2025-12-31'
}).then(result => {
  if (result.success) {
    console.log('User Recharge Report:', result);
  }
});
```

### User Service Report

```javascript
const getUserServiceReport = async (adminToken, params = {}) => {
  try {
    const queryString = new URLSearchParams(params).toString();
    const url = `https://api.alldigtalseva.com/api/admin/report/service${queryString ? `?${queryString}` : ''}`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${adminToken}`,
        'Content-Type': 'application/json',
      },
    });

    const data = await response.json();
    
    if (data.success) {
      return {
        success: true,
        summary: data.summary,
        serviceTypeBreakdown: data.service_type_breakdown,
        data: data.data,
        pagination: data.pagination
      };
    } else {
      return {
        success: false,
        message: data.message
      };
    }
  } catch (error) {
    console.error('Error:', error);
    return {
      success: false,
      message: 'An error occurred'
    };
  }
};

// Usage
const adminToken = localStorage.getItem('admin_token');

// Get all service reports
getUserServiceReport(adminToken).then(result => {
  if (result.success) {
    console.log('Summary:', result.summary);
    console.log('Service Type Breakdown:', result.serviceTypeBreakdown);
    console.log('Services:', result.data);
  }
});

// Get Farmer ID service reports
getUserServiceReport(adminToken, {
  service_type: 'farmer_id',
  status: 'success'
}).then(result => {
  if (result.success) {
    console.log('Farmer ID Reports:', result);
  }
});
```

### User Complete Report

```javascript
const getUserCompleteReport = async (adminToken, userId, params = {}) => {
  try {
    const queryString = new URLSearchParams(params).toString();
    const url = `https://api.alldigtalseva.com/api/admin/report/user/${userId}${queryString ? `?${queryString}` : ''}`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${adminToken}`,
        'Content-Type': 'application/json',
      },
    });

    const data = await response.json();
    
    if (data.success) {
      return {
        success: true,
        user: data.user,
        rechargeStatistics: data.recharge_statistics,
        serviceStatistics: data.service_statistics,
        serviceTypeBreakdown: data.service_type_breakdown,
        recentRecharges: data.recent_recharges,
        recentServices: data.recent_services
      };
    } else {
      return {
        success: false,
        message: data.message
      };
    }
  } catch (error) {
    console.error('Error:', error);
    return {
      success: false,
      message: 'An error occurred'
    };
  }
};

// Usage
const adminToken = localStorage.getItem('admin_token');

// Get complete report for user
getUserCompleteReport(adminToken, 1).then(result => {
  if (result.success) {
    console.log('User:', result.user);
    console.log('Recharge Stats:', result.rechargeStatistics);
    console.log('Service Stats:', result.serviceStatistics);
  }
});
```

---

## Use Cases

### 1. View All Recharge Reports

Get a comprehensive view of all recharge requests with summary statistics:
- Total requests and amounts
- Pending, approved, and rejected counts
- Filter by date range, user, or status

### 2. View Service Usage Reports

Track service usage across the platform:
- Total transactions and revenue
- Success/failure rates
- Service type breakdown
- Filter by service type, user, or date

### 3. User Activity Analysis

Get complete user activity report:
- User profile information
- Recharge history and statistics
- Service usage statistics
- Recent transactions

### 4. Financial Reporting

Generate financial reports:
- Total recharge amounts
- Total service revenue
- Pending amounts
- Date range filtering

### 5. Service Performance Analysis

Analyze service performance:
- Service type usage
- Success rates
- Revenue per service
- User engagement

---

## Error Handling

### Common Error Scenarios

1. **Unauthorized Access (401)**
   - Status: 401
   - Message: "Unauthorized. Admin access required."
   - Solution: Ensure valid admin token is provided

2. **User Not Found (404)**
   - Status: 404
   - Message: "User not found"
   - Solution: Verify user ID exists

3. **Invalid Date Format (422)**
   - Status: 422
   - Message: "Validation error"
   - Solution: Use YYYY-MM-DD format for dates

---

## Best Practices

1. **Pagination**: Always use pagination for large datasets
2. **Date Filtering**: Use date ranges to limit data and improve performance
3. **Caching**: Consider caching reports for frequently accessed data
4. **Error Handling**: Implement proper error handling in frontend
5. **Loading States**: Show loading indicators during API calls
6. **Export Functionality**: Consider adding export to CSV/Excel for reports

---

## Integration Checklist

- [ ] Implement recharge report view with filters
- [ ] Implement service report view with filters
- [ ] Add user complete report view
- [ ] Add date range picker
- [ ] Add user selection dropdown
- [ ] Add status/service type filters
- [ ] Implement pagination
- [ ] Add sorting functionality
- [ ] Display summary statistics
- [ ] Handle loading and error states
- [ ] Add export functionality (optional)
- [ ] Test with various filters
- [ ] Verify admin authentication

---

## Support

For issues or questions regarding the Admin Report API, please contact the development team.

---

### 4. Referral Report

Get comprehensive referral statistics showing user referrals, downline, and their recharge activity.

**Endpoint:** `GET /admin/report/referral`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| user_id | integer | No | Filter by specific user ID |
| user_type | string | No | Filter by user type: `user`, `distributor` |
| has_referrals | string | No | Filter users who have referrals: `true` |
| start_date | date | No | Filter by start date (YYYY-MM-DD) |
| end_date | date | No | Filter by end date (YYYY-MM-DD) |
| sort_by | string | No | Sort by: `total_referrals` (default), `total_downline_recharge`, `total_earnings` |
| sort_order | string | No | Sort order: `asc` or `desc` (default: `desc`) |
| per_page | integer | No | Items per page (1-100, default: 15) |

**Response (Success - 200):**
```json
{
    "success": true,
    "summary": {
        "total_users_with_referrals": 50,
        "total_referrals": 200,
        "total_level_1_referrals": 150,
        "total_downline_recharge": 500000.00,
        "total_referral_earnings": 50000.00
    },
    "data": [
        {
            "user_id": 1,
            "user": {
                "id": 1,
                "email": "user@example.com",
                "phone_number": "1234567890",
                "name": "John Doe",
                "user_type": "user",
                "referral_code": "ABC12345"
            },
            "referral_statistics": {
                "level_1_referrals": 10,
                "total_downline_count": 25
            },
            "downline_recharge": {
                "total_recharge_amount": 50000.00,
                "total_recharge_count": 50,
                "total_credited_amount": 55000.00
            },
            "level_breakdown": [
                {
                    "level": 1,
                    "referral_count": 10,
                    "recharge_amount": 40000.00,
                    "recharge_count": 40
                },
                {
                    "level": 2,
                    "referral_count": 15,
                    "recharge_amount": 10000.00,
                    "recharge_count": 10
                }
            ],
            "referral_earnings": {
                "total_earnings": 5000.00,
                "pending_earnings": 500.00,
                "total_earning_count": 30
            }
        }
    ],
    "pagination": {
        "current_page": 1,
        "per_page": 15,
        "total": 50,
        "last_page": 4
    }
}
```

**Response (Unauthorized - 401):**
```json
{
    "success": false,
    "message": "Unauthorized. Admin access required."
}
```

**cURL Examples:**

```bash
# Get all referral reports
curl -X GET "https://api.alldigtalseva.com/api/admin/report/referral" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get referral report for specific user
curl -X GET "https://api.alldigtalseva.com/api/admin/report/referral?user_id=1" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get users with referrals only
curl -X GET "https://api.alldigtalseva.com/api/admin/report/referral?has_referrals=true" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get referral report for date range
curl -X GET "https://api.alldigtalseva.com/api/admin/report/referral?start_date=2025-12-01&end_date=2025-12-31" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Sort by downline recharge amount
curl -X GET "https://api.alldigtalseva.com/api/admin/report/referral?sort_by=total_downline_recharge&sort_order=desc" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"
```

---

### 5. User-Specific Referral Report

Get detailed referral report for a specific user including level-wise breakdown and downline recharge details.

**Endpoint:** `GET /admin/report/referral/user/{userId}`

**Headers:**
```
Authorization: Bearer {admin_token}
Content-Type: application/json
```

**URL Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| userId | integer | Yes | User ID |

**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| start_date | date | No | Filter by start date (YYYY-MM-DD) |
| end_date | date | No | Filter by end date (YYYY-MM-DD) |

**Response (Success - 200):**
```json
{
    "success": true,
    "user": {
        "id": 1,
        "email": "user@example.com",
        "phone_number": "1234567890",
        "name": "John Doe",
        "user_type": "user",
        "referral_code": "ABC12345"
    },
    "referral_statistics": {
        "level_1_referrals": 10,
        "total_downline_count": 25
    },
    "level_1_referrals": [
        {
            "user_id": 2,
            "email": "user2@example.com",
            "phone_number": "9876543210",
            "name": "Jane Smith",
            "user_type": "user",
            "joined_at": "2025-12-01T10:00:00.000000Z"
        }
    ],
    "level_breakdown": [
        {
            "level": 1,
            "referral_count": 10,
            "referrals": [
                {
                    "user_id": 2,
                    "email": "user2@example.com",
                    "phone_number": "9876543210",
                    "name": "Jane Smith",
                    "user_type": "user",
                    "joined_at": "2025-12-01T10:00:00.000000Z"
                }
            ],
            "recharge_amount": 40000.00,
            "recharge_count": 40
        },
        {
            "level": 2,
            "referral_count": 15,
            "referrals": [],
            "recharge_amount": 10000.00,
            "recharge_count": 10
        }
    ],
    "downline_recharge": {
        "total_recharge_amount": 50000.00,
        "total_recharge_count": 50,
        "total_credited_amount": 55000.00
    },
    "downline_recharges": [
        {
            "id": 1,
            "user": {
                "id": 2,
                "email": "user2@example.com",
                "phone_number": "9876543210",
                "name": "Jane Smith"
            },
            "amount": 1000.00,
            "final_credited_amount": 1100.00,
            "approved_at": "2025-12-06T10:00:00.000000Z"
        }
    ],
    "referral_earnings": {
        "total_earnings": 5000.00,
        "pending_earnings": 500.00,
        "total_earning_count": 30
    },
    "earnings": [
        {
            "id": 1,
            "referred_user": {
                "id": 2,
                "email": "user2@example.com",
                "name": "Jane Smith"
            },
            "level": 1,
            "earning_type": "topup",
            "amount": 1000.00,
            "commission_amount": 100.00,
            "status": "credited",
            "created_at": "2025-12-06T10:00:00.000000Z",
            "credited_at": "2025-12-06T10:05:00.000000Z"
        }
    ]
}
```

**Response (Unauthorized - 401):**
```json
{
    "success": false,
    "message": "Unauthorized. Admin access required."
}
```

**Response (Not Found - 404):**
```json
{
    "success": false,
    "message": "User not found"
}
```

**cURL Examples:**

```bash
# Get referral report for user
curl -X GET "https://api.alldigtalseva.com/api/admin/report/referral/user/1" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"

# Get referral report for date range
curl -X GET "https://api.alldigtalseva.com/api/admin/report/referral/user/1?start_date=2025-12-01&end_date=2025-12-31" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"
```

---

## JavaScript/Angular Examples

### Referral Report

```typescript
getReferralReport(params?: {
  user_id?: number;
  user_type?: string;
  has_referrals?: string;
  start_date?: string;
  end_date?: string;
  sort_by?: string;
  sort_order?: string;
  per_page?: number;
}): Observable<any> {
  let queryParams = new HttpParams();
  
  if (params) {
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined) {
        queryParams = queryParams.set(key, params[key].toString());
      }
    });
  }

  return this.http.get(`${this.apiUrl}/admin/report/referral`, {
    headers: this.headers,
    params: queryParams
  });
}

// Usage
// Get all referral reports
this.adminReportService.getReferralReport().subscribe(
  (response) => {
    if (response.success) {
      console.log('Summary:', response.summary);
      console.log('Referral Data:', response.data);
    }
  }
);

// Get referral report for specific user
this.adminReportService.getReferralReport({
  user_id: 1,
  start_date: '2025-12-01',
  end_date: '2025-12-31'
}).subscribe(
  (response) => {
    if (response.success) {
      console.log('User Referral Report:', response);
    }
  }
);
```

### User-Specific Referral Report

```typescript
getUserReferralReport(userId: number, params?: {
  start_date?: string;
  end_date?: string;
}): Observable<any> {
  let queryParams = new HttpParams();
  
  if (params) {
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined) {
        queryParams = queryParams.set(key, params[key].toString());
      }
    });
  }

  return this.http.get(`${this.apiUrl}/admin/report/referral/user/${userId}`, {
    headers: this.headers,
    params: queryParams
  });
}

// Usage
// Get complete referral report for user
this.adminReportService.getUserReferralReport(1).subscribe(
  (response) => {
    if (response.success) {
      console.log('User:', response.user);
      console.log('Level 1 Referrals:', response.level_1_referrals);
      console.log('Level Breakdown:', response.level_breakdown);
      console.log('Downline Recharge:', response.downline_recharge);
      console.log('Referral Earnings:', response.referral_earnings);
    }
  }
);
```

---

## React/Next.js Examples

### Referral Report

```javascript
const getReferralReport = async (adminToken, params = {}) => {
  try {
    const queryString = new URLSearchParams(params).toString();
    const url = `https://api.alldigtalseva.com/api/admin/report/referral${queryString ? `?${queryString}` : ''}`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${adminToken}`,
        'Content-Type': 'application/json',
      },
    });

    const data = await response.json();
    
    if (data.success) {
      return {
        success: true,
        summary: data.summary,
        data: data.data,
        pagination: data.pagination
      };
    } else {
      return {
        success: false,
        message: data.message
      };
    }
  } catch (error) {
    console.error('Error:', error);
    return {
      success: false,
      message: 'An error occurred'
    };
  }
};

// Usage
const adminToken = localStorage.getItem('admin_token');

// Get all referral reports
getReferralReport(adminToken).then(result => {
  if (result.success) {
    console.log('Summary:', result.summary);
    console.log('Referral Data:', result.data);
  }
});

// Get referral report for specific user
getReferralReport(adminToken, {
  user_id: 1,
  start_date: '2025-12-01',
  end_date: '2025-12-31'
}).then(result => {
  if (result.success) {
    console.log('User Referral Report:', result);
  }
});
```

### User-Specific Referral Report

```javascript
const getUserReferralReport = async (adminToken, userId, params = {}) => {
  try {
    const queryString = new URLSearchParams(params).toString();
    const url = `https://api.alldigtalseva.com/api/admin/report/referral/user/${userId}${queryString ? `?${queryString}` : ''}`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${adminToken}`,
        'Content-Type': 'application/json',
      },
    });

    const data = await response.json();
    
    if (data.success) {
      return {
        success: true,
        user: data.user,
        referralStatistics: data.referral_statistics,
        level1Referrals: data.level_1_referrals,
        levelBreakdown: data.level_breakdown,
        downlineRecharge: data.downline_recharge,
        downlineRecharges: data.downline_recharges,
        referralEarnings: data.referral_earnings,
        earnings: data.earnings
      };
    } else {
      return {
        success: false,
        message: data.message
      };
    }
  } catch (error) {
    console.error('Error:', error);
    return {
      success: false,
      message: 'An error occurred'
    };
  }
};

// Usage
const adminToken = localStorage.getItem('admin_token');

// Get complete referral report for user
getUserReferralReport(adminToken, 1).then(result => {
  if (result.success) {
    console.log('User:', result.user);
    console.log('Level 1 Referrals:', result.level1Referrals);
    console.log('Level Breakdown:', result.levelBreakdown);
    console.log('Downline Recharge:', result.downlineRecharge);
  }
});
```

---

## Use Cases

### 1. Referral Performance Analysis

Analyze referral performance across the platform:
- Users with most referrals
- Downline recharge activity
- Referral earnings
- Level-wise breakdown

### 2. User Referral Tracking

Track individual user referral activity:
- Level 1 referrals count
- Total downline count
- Downline recharge amounts
- Referral earnings

### 3. Multi-Level Referral Analysis

Analyze multi-level referral structure:
- Level 1, 2, 3+ breakdown
- Recharge activity per level
- Referral distribution

### 4. Revenue from Referrals

Track revenue generated from referrals:
- Total downline recharge
- Referral commission earnings
- Pending vs credited earnings

---

**Last Updated:** December 2025

