# Gift API Documentation

## Overview

The Gift API allows administrators to credit gifts (amounts) to users, and users can view their gifts through popup notifications. When an admin credits a gift, the amount is added to the user's wallet and a gift notification is created that the user can see.

---

## Base URL

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

---

## API Endpoints

### Admin Endpoints (Require Admin Token)

#### 1. Credit Gift to User

Admin can send a gift (amount) to a user. The amount will be credited to the user's wallet and a gift notification will be created.

**Endpoint:** `POST /admin/gift/credit`

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

**Request Body:**
```json
{
    "user_id": 1,
    "amount": 100.00,
    "message": "Congratulations! You received a special gift!"
}
```

**Request Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| user_id | integer | Yes | ID of the user to receive the gift |
| amount | decimal | Yes | Gift amount (minimum 0.01) |
| message | string | No | Optional message for the gift (max 500 characters) |

**Response (Success - 200):**
```json
{
    "success": true,
    "message": "Gift credited successfully",
    "data": {
        "user_id": 1,
        "amount": 100.00,
        "message": "Congratulations! You received a special gift!",
        "new_wallet_balance": 600.00
    }
}
```

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

**Response (Validation Error - 422):**
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "user_id": ["The user id field is required."],
        "amount": ["The amount must be at least 0.01."]
    }
}
```

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

**cURL Example:**
```bash
curl -X POST https://api.alldigtalseva.com/api/admin/gift/credit \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": 1,
    "amount": 100.00,
    "message": "Congratulations! You received a special gift!"
  }'
```

---

#### 2. Get All Gifts (Admin View)

Get list of all gifts sent to users with filtering options.

**Endpoint:** `GET /admin/gift`

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

**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| user_id | integer | No | Filter by user ID |
| is_read | string | No | Filter by read status: `true`, `false` |
| 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,
    "data": [
        {
            "id": 1,
            "user_id": 1,
            "amount": "100.00",
            "message": "Congratulations! You received a special gift!",
            "is_read": false,
            "read_at": null,
            "created_by": 1,
            "created_at": "2025-12-07T10:00:00.000000Z",
            "updated_at": "2025-12-07T10:00:00.000000Z",
            "user": {
                "id": 1,
                "email": "user@example.com",
                "phone_number": "1234567890",
                "name": "John Doe"
            },
            "admin": {
                "id": 1,
                "username": "admin"
            }
        }
    ],
    "pagination": {
        "current_page": 1,
        "per_page": 15,
        "total": 50,
        "last_page": 4
    }
}
```

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/admin/gift?user_id=1&is_read=false" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json"
```

---

### User Endpoints (Require User Token)

#### 3. Get Unread Gifts

Get all unread gifts for the authenticated user. This is used to show popup notifications.

**Endpoint:** `GET /gift/unread`

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

**Response (Success - 200):**
```json
{
    "success": true,
    "count": 2,
    "data": [
        {
            "id": 1,
            "amount": 100.00,
            "message": "Congratulations! You received a special gift!",
            "created_at": "2025-12-07T10:00:00.000000Z"
        },
        {
            "id": 2,
            "amount": 50.00,
            "message": "You received a gift!",
            "created_at": "2025-12-07T09:00:00.000000Z"
        }
    ]
}
```

**Response (Unauthorized - 401):**
```json
{
    "success": false,
    "message": "Unauthorized. Please login first."
}
```

**cURL Example:**
```bash
curl -X GET https://api.alldigtalseva.com/api/gift/unread \
  -H "Authorization: Bearer {user_token}" \
  -H "Content-Type: application/json"
```

---

#### 4. Mark Gift as Read

Mark a specific gift as read after the user has viewed the popup.

**Endpoint:** `POST /gift/{giftId}/read`

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

**URL Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| giftId | integer | Yes | ID of the gift to mark as read |

**Response (Success - 200):**
```json
{
    "success": true,
    "message": "Gift marked as read",
    "data": {
        "id": 1,
        "is_read": true,
        "read_at": "2025-12-07T10:05:00.000000Z"
    }
}
```

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

**Response (Already Read - 400):**
```json
{
    "success": false,
    "message": "Gift already marked as read"
}
```

**cURL Example:**
```bash
curl -X POST https://api.alldigtalseva.com/api/gift/1/read \
  -H "Authorization: Bearer {user_token}" \
  -H "Content-Type: application/json"
```

---

#### 5. Mark All Gifts as Read

Mark all unread gifts as read at once.

**Endpoint:** `POST /gift/mark-all-read`

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

**Response (Success - 200):**
```json
{
    "success": true,
    "message": "2 gift(s) marked as read",
    "data": {
        "marked_count": 2
    }
}
```

**cURL Example:**
```bash
curl -X POST https://api.alldigtalseva.com/api/gift/mark-all-read \
  -H "Authorization: Bearer {user_token}" \
  -H "Content-Type: application/json"
```

---

#### 6. Get All Gifts (User's Gift History)

Get all gifts received by the authenticated user with filtering options.

**Endpoint:** `GET /gift`

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

**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| is_read | string | No | Filter by read status: `true`, `false` |
| 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,
    "data": [
        {
            "id": 1,
            "user_id": 1,
            "amount": "100.00",
            "message": "Congratulations! You received a special gift!",
            "is_read": true,
            "read_at": "2025-12-07T10:05:00.000000Z",
            "created_by": 1,
            "created_at": "2025-12-07T10:00:00.000000Z",
            "updated_at": "2025-12-07T10:05:00.000000Z"
        }
    ],
    "pagination": {
        "current_page": 1,
        "per_page": 15,
        "total": 10,
        "last_page": 1
    }
}
```

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/gift?is_read=false" \
  -H "Authorization: Bearer {user_token}" \
  -H "Content-Type: application/json"
```

---

## JavaScript/Angular Examples

### Admin: Credit Gift

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

@Injectable({
  providedIn: 'root'
})
export class AdminGiftService {
  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'
    });
  }

  creditGift(userId: number, amount: number, message?: string): Observable<any> {
    return this.http.post(`${this.apiUrl}/admin/gift/credit`, {
      user_id: userId,
      amount: amount,
      message: message || 'You received a gift!'
    }, {
      headers: this.headers
    });
  }
}

// Usage in component
this.adminGiftService.creditGift(1, 100.00, 'Congratulations! You received a special gift!').subscribe(
  (response) => {
    if (response.success) {
      console.log('Gift credited successfully');
      console.log('New wallet balance:', response.data.new_wallet_balance);
    }
  },
  (error) => {
    console.error('Error:', error);
  }
);
```

### User: Get Unread Gifts

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

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

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

  getUnreadGifts(): Observable<any> {
    return this.http.get(`${this.apiUrl}/gift/unread`, {
      headers: this.headers
    });
  }

  markAsRead(giftId: number): Observable<any> {
    return this.http.post(`${this.apiUrl}/gift/${giftId}/read`, {}, {
      headers: this.headers
    });
  }

  markAllAsRead(): Observable<any> {
    return this.http.post(`${this.apiUrl}/gift/mark-all-read`, {}, {
      headers: this.headers
    });
  }
}

// Usage in component
// Check for unread gifts on app load
this.giftService.getUnreadGifts().subscribe(
  (response) => {
    if (response.success && response.count > 0) {
      // Show popup for each unread gift
      response.data.forEach((gift: any) => {
        this.showGiftPopup(gift);
      });
    }
  }
);

// Show gift popup
showGiftPopup(gift: any) {
  // Display popup with gift message and amount
  const message = `You received a gift of ₹${gift.amount}! ${gift.message}`;
  
  // After user views the popup, mark as read
  this.giftService.markAsRead(gift.id).subscribe(
    (response) => {
      if (response.success) {
        console.log('Gift marked as read');
      }
    }
  );
}
```

---

## React/Next.js Examples

### Admin: Credit Gift

```javascript
const creditGift = async (adminToken, userId, amount, message) => {
  try {
    const response = await fetch('https://api.alldigtalseva.com/api/admin/gift/credit', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${adminToken}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        user_id: userId,
        amount: amount,
        message: message || 'You received a gift!'
      }),
    });

    const data = await response.json();
    
    if (data.success) {
      return {
        success: true,
        data: data.data
      };
    } 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');
creditGift(adminToken, 1, 100.00, 'Congratulations! You received a special gift!').then(result => {
  if (result.success) {
    console.log('Gift credited successfully');
    console.log('New wallet balance:', result.data.new_wallet_balance);
  }
});
```

### User: Get Unread Gifts and Show Popup

```javascript
const getUnreadGifts = async (userToken) => {
  try {
    const response = await fetch('https://api.alldigtalseva.com/api/gift/unread', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${userToken}`,
        'Content-Type': 'application/json',
      },
    });

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

const markAsRead = async (userToken, giftId) => {
  try {
    const response = await fetch(`https://api.alldigtalseva.com/api/gift/${giftId}/read`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${userToken}`,
        'Content-Type': 'application/json',
      },
    });

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

// Usage in component
useEffect(() => {
  const userToken = localStorage.getItem('user_token');
  
  // Check for unread gifts on app load
  getUnreadGifts(userToken).then(result => {
    if (result.success && result.count > 0) {
      // Show popup for each unread gift
      result.data.forEach(gift => {
        showGiftPopup(gift, userToken);
      });
    }
  });
}, []);

const showGiftPopup = (gift, userToken) => {
  // Display popup with gift message and amount
  const message = `You received a gift of ₹${gift.amount}! ${gift.message}`;
  
  // Show popup (using your UI library)
  // After user views/closes popup, mark as read
  markAsRead(userToken, gift.id).then(result => {
    if (result.success) {
      console.log('Gift marked as read');
    }
  });
};
```

---

## Complete Flow Example

### Step 1: Admin Credits Gift

```javascript
// Admin credits ₹100 to user ID 1
POST /api/admin/gift/credit
{
  "user_id": 1,
  "amount": 100.00,
  "message": "Congratulations! You received a special gift!"
}

// Response: Gift credited, user's wallet balance updated
```

### Step 2: User Checks for Unread Gifts

```javascript
// User checks for unread gifts (on app load or periodically)
GET /api/gift/unread

// Response: Returns unread gifts
{
  "success": true,
  "count": 1,
  "data": [
    {
      "id": 1,
      "amount": 100.00,
      "message": "Congratulations! You received a special gift!",
      "created_at": "2025-12-07T10:00:00.000000Z"
    }
  ]
}
```

### Step 3: User Views Popup

```javascript
// Show popup to user
// Popup displays: "You received a gift of ₹100.00! Congratulations! You received a special gift!"

// After user views/closes popup, mark as read
POST /api/gift/1/read

// Response: Gift marked as read
{
  "success": true,
  "message": "Gift marked as read"
}
```

---

## Integration Checklist

- [ ] Admin can credit gifts to users
- [ ] Gift amount is added to user's wallet
- [ ] User can fetch unread gifts
- [ ] Show popup notification when unread gifts exist
- [ ] Mark gift as read after user views popup
- [ ] Display gift message and amount in popup
- [ ] Handle multiple unread gifts
- [ ] Update wallet balance display after gift
- [ ] Test gift credit flow
- [ ] Test popup display
- [ ] Test mark as read functionality

---

## Best Practices

1. **Check for Unread Gifts**: Check for unread gifts when user logs in or app loads
2. **Show Popup Immediately**: Display popup as soon as unread gifts are detected
3. **Mark as Read**: Mark gift as read after user views/closes the popup
4. **Handle Multiple Gifts**: If multiple unread gifts exist, show them one by one or in a list
5. **Update Wallet**: Refresh wallet balance after receiving a gift
6. **Error Handling**: Handle errors gracefully when fetching or marking gifts

---

## Support

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

---

**Last Updated:** December 2025

