# User Management API Documentation

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

---

## Table of Contents

1. [Get All Users](#get-all-users)
2. [Get Single User](#get-single-user)
3. [Update User](#update-user)
4. [Delete User](#delete-user)
5. [Get User Statistics](#get-user-statistics)

**Note:** All endpoints require admin authentication via Bearer token.

---

## Get All Users

Get list of all users with pagination and filtering options.

**Endpoint:** `GET /api/admin/user`

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Query Parameters:**
- `user_type` (optional, enum): Filter by user type - `"user"` or `"distributor"`
- `is_verified` (optional, boolean): Filter by verification status - `true` or `false`
- `search` (optional, string): Search by email, phone number, or name
- `per_page` (optional, integer, 1-100): Number of records per page (default: 15)

**Success Response (200):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "name": "John Doe",
            "email": "user@example.com",
            "phone_number": "1234567890",
            "user_type": "user",
            "wallet_balance": "500.00",
            "is_verified": true,
            "email_verified_at": "2025-12-04T06:30:00.000000Z",
            "created_at": "2025-12-04T06:20:00.000000Z",
            "updated_at": "2025-12-04T06:30:00.000000Z"
        }
    ],
    "pagination": {
        "current_page": 1,
        "per_page": 15,
        "total": 50,
        "last_page": 4
    }
}
```

**Examples:**

**Get All Users:**
```bash
curl -X GET https://api.alldigtalseva.com/api/admin/user \
  -H "Authorization: Bearer {admin_token}"
```

**Get Only Distributors:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/admin/user?user_type=distributor" \
  -H "Authorization: Bearer {admin_token}"
```

**Get Only Verified Users:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/admin/user?is_verified=true" \
  -H "Authorization: Bearer {admin_token}"
```

**Search Users:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/admin/user?search=john" \
  -H "Authorization: Bearer {admin_token}"
```

**Get Users with Pagination:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/admin/user?per_page=20" \
  -H "Authorization: Bearer {admin_token}"
```

**Combined Filters:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/admin/user?user_type=user&is_verified=true&search=example&per_page=10" \
  -H "Authorization: Bearer {admin_token}"
```

---

## Get Single User

Get detailed information about a specific user.

**Endpoint:** `GET /api/admin/user/{id}`

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Success Response (200):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "name": "John Doe",
        "email": "user@example.com",
        "phone_number": "1234567890",
        "user_type": "user",
        "wallet_balance": "500.00",
        "is_verified": true,
        "email_verified_at": "2025-12-04T06:30:00.000000Z",
        "created_at": "2025-12-04T06:20:00.000000Z",
        "updated_at": "2025-12-04T06:30:00.000000Z"
    }
}
```

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

**cURL Example:**
```bash
curl -X GET https://api.alldigtalseva.com/api/admin/user/1 \
  -H "Authorization: Bearer {admin_token}"
```

---

## Update User

Update user information. All fields are optional.

**Endpoint:** `PUT /api/admin/user/{id}` or `PATCH /api/admin/user/{id}`

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

**Request Body (all fields optional):**
```json
{
    "email": "updated@example.com",
    "phone_number": "9876543210",
    "name": "Updated Name",
    "user_type": "distributor",
    "wallet_balance": 1000.00,
    "is_verified": true,
    "password": "newpassword123"
}
```

**Parameters:**
- `email` (optional, string, email): User's email address (must be unique)
- `phone_number` (optional, string): User's phone number (must be unique)
- `name` (optional, string, max: 255): User's name
- `user_type` (optional, enum): `"user"` or `"distributor"`
- `wallet_balance` (optional, numeric, min: 0): Wallet balance amount
- `is_verified` (optional, boolean): Verification status
- `password` (optional, string, min: 6): New password (stored in plain text)

**Success Response (200):**
```json
{
    "success": true,
    "message": "User updated successfully",
    "data": {
        "id": 1,
        "name": "Updated Name",
        "email": "updated@example.com",
        "phone_number": "9876543210",
        "user_type": "distributor",
        "wallet_balance": "1000.00",
        "is_verified": true,
        "created_at": "2025-12-04T06:20:00.000000Z",
        "updated_at": "2025-12-04T08:00:00.000000Z"
    }
}
```

**Error Response (422) - Validation Error:**
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "email": ["The email has already been taken."],
        "phone_number": ["The phone number has already been taken."]
    }
}
```

**cURL Example:**
```bash
curl -X PUT https://api.alldigtalseva.com/api/admin/user/1 \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Updated Name",
    "user_type": "distributor",
    "wallet_balance": 1000.00
  }'
```

**Update Only Wallet Balance:**
```bash
curl -X PATCH https://api.alldigtalseva.com/api/admin/user/1 \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "wallet_balance": 1500.00
  }'
```

**Update Password:**
```bash
curl -X PUT https://api.alldigtalseva.com/api/admin/user/1 \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "password": "newpassword123"
  }'
```

---

## Delete User

Delete a user from the system.

**Endpoint:** `DELETE /api/admin/user/{id}`

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Success Response (200):**
```json
{
    "success": true,
    "message": "User deleted successfully"
}
```

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

**cURL Example:**
```bash
curl -X DELETE https://api.alldigtalseva.com/api/admin/user/1 \
  -H "Authorization: Bearer {admin_token}"
```

**Note:** Deleting a user will also delete all associated top-up requests (due to cascade delete).

---

## Get User Statistics

Get overall user statistics and counts.

**Endpoint:** `GET /api/admin/user/statistics`

**Headers:**
```
Authorization: Bearer {admin_token}
```

**Success Response (200):**
```json
{
    "success": true,
    "data": {
        "total_users": 100,
        "verified_users": 85,
        "unverified_users": 15,
        "regular_users": 80,
        "distributors": 20,
        "total_wallet_balance": "50000.00"
    }
}
```

**cURL Example:**
```bash
curl -X GET https://api.alldigtalseva.com/api/admin/user/statistics \
  -H "Authorization: Bearer {admin_token}"
```

**JavaScript/Fetch Example:**
```javascript
fetch('https://api.alldigtalseva.com/api/admin/user/statistics', {
  headers: {
    'Authorization': `Bearer ${adminToken}`
  }
})
.then(response => response.json())
.then(data => {
  if (data.success) {
    console.log('Total Users:', data.data.total_users);
    console.log('Verified Users:', data.data.verified_users);
    console.log('Total Wallet Balance:', data.data.total_wallet_balance);
  }
});
```

---

## Complete Examples

### Angular Service Example

**user-management.service.ts:**
```typescript
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UserManagementService {
  private apiUrl = 'https://api.alldigtalseva.com/api';
  private adminToken = localStorage.getItem('admin_token');

  constructor(private http: HttpClient) {}

  getUsers(filters?: any): Observable<any> {
    let params = new HttpParams();
    
    if (filters?.user_type) {
      params = params.set('user_type', filters.user_type);
    }
    if (filters?.is_verified !== undefined) {
      params = params.set('is_verified', filters.is_verified);
    }
    if (filters?.search) {
      params = params.set('search', filters.search);
    }
    if (filters?.per_page) {
      params = params.set('per_page', filters.per_page.toString());
    }

    return this.http.get<any>(`${this.apiUrl}/admin/user`, {
      params,
      headers: {
        'Authorization': `Bearer ${this.adminToken}`
      }
    });
  }

  getUser(id: number): Observable<any> {
    return this.http.get<any>(`${this.apiUrl}/admin/user/${id}`, {
      headers: {
        'Authorization': `Bearer ${this.adminToken}`
      }
    });
  }

  updateUser(id: number, data: any): Observable<any> {
    return this.http.put<any>(`${this.apiUrl}/admin/user/${id}`, data, {
      headers: {
        'Authorization': `Bearer ${this.adminToken}`,
        'Content-Type': 'application/json'
      }
    });
  }

  deleteUser(id: number): Observable<any> {
    return this.http.delete<any>(`${this.apiUrl}/admin/user/${id}`, {
      headers: {
        'Authorization': `Bearer ${this.adminToken}`
      }
    });
  }

  getStatistics(): Observable<any> {
    return this.http.get<any>(`${this.apiUrl}/admin/user/statistics`, {
      headers: {
        'Authorization': `Bearer ${this.adminToken}`
      }
    });
  }
}
```

### React Hook Example

**useUserManagement.ts:**
```typescript
import { useState, useEffect } from 'react';

export function useUserManagement(adminToken: string) {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState(null);

  const fetchUsers = async (filters = {}) => {
    setLoading(true);
    const params = new URLSearchParams();
    
    Object.keys(filters).forEach(key => {
      if (filters[key] !== undefined && filters[key] !== null) {
        params.append(key, filters[key]);
      }
    });

    try {
      const response = await fetch(
        `https://api.alldigtalseva.com/api/admin/user?${params}`,
        {
          headers: {
            'Authorization': `Bearer ${adminToken}`
          }
        }
      );
      const data = await response.json();
      
      if (data.success) {
        setUsers(data.data);
        setPagination(data.pagination);
      }
    } catch (error) {
      console.error('Failed to fetch users:', error);
    } finally {
      setLoading(false);
    }
  };

  const updateUser = async (id: number, userData: any) => {
    const response = await fetch(
      `https://api.alldigtalseva.com/api/admin/user/${id}`,
      {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${adminToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
      }
    );
    return response.json();
  };

  const deleteUser = async (id: number) => {
    const response = await fetch(
      `https://api.alldigtalseva.com/api/admin/user/${id}`,
      {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${adminToken}`
        }
      }
    );
    return response.json();
  };

  return {
    users,
    loading,
    pagination,
    fetchUsers,
    updateUser,
    deleteUser
  };
}
```

---

## Important Notes

1. **Authentication**: All endpoints require admin Bearer token in Authorization header.

2. **Password Update**: 
   - Password is stored in plain text (not encrypted) as per requirements
   - Minimum length: 6 characters

3. **Wallet Balance**: 
   - Can be updated directly by admin
   - Stored as decimal with 2 decimal places

4. **User Types**:
   - `"user"` - Regular user
   - `"distributor"` - Distributor user

5. **Search Functionality**:
   - Searches in email, phone_number, and name fields
   - Case-insensitive partial matching

6. **Pagination**:
   - Default: 15 records per page
   - Maximum: 100 records per page
   - Minimum: 1 record per page

7. **Deletion**:
   - Deleting a user will cascade delete all associated top-up requests
   - This action cannot be undone

---

## Response Codes

| Status Code | Description |
|------------|-------------|
| 200 | Success |
| 201 | Created |
| 401 | Unauthorized - Invalid or missing admin token |
| 404 | Not Found - User not found |
| 422 | Validation Error - Invalid input data |
| 500 | Server Error - Internal server error |

---

## Common Use Cases

### 1. View All Users with Pagination
```bash
GET /api/admin/user?per_page=20
```

### 2. Search for a Specific User
```bash
GET /api/admin/user?search=john@example.com
```

### 3. Get All Unverified Users
```bash
GET /api/admin/user?is_verified=false
```

### 4. Get All Distributors
```bash
GET /api/admin/user?user_type=distributor
```

### 5. Update User Wallet Balance
```bash
PUT /api/admin/user/1
{
  "wallet_balance": 2000.00
}
```

### 6. Verify a User
```bash
PUT /api/admin/user/1
{
  "is_verified": true
}
```

### 7. Change User Type
```bash
PUT /api/admin/user/1
{
  "user_type": "distributor"
}
```

---

**Last Updated:** December 4, 2025

