# Trending Offer API Documentation

This document describes the Trending Offer Management APIs for both admin and public endpoints. Trending offers are single-line text messages that can be displayed as scrolling text on the dashboard.

---

## Table of Contents

1. [Admin Trending Offer Management APIs](#admin-trending-offer-management-apis)
   - [Get All Trending Offers](#get-all-trending-offers)
   - [Get Single Trending Offer](#get-single-trending-offer)
   - [Add New Trending Offer](#add-new-trending-offer)
   - [Update Trending Offer](#update-trending-offer)
   - [Delete Trending Offer](#delete-trending-offer)
2. [Public Trending Offer API](#public-trending-offer-api)
   - [Get All Active Trending Offers](#get-all-active-trending-offers)

---

## Admin Trending Offer Management APIs

All admin endpoints require authentication using a Bearer token in the Authorization header.

**Base URL:** `/api/admin/trending-offer`

**Authentication:** Required (Admin Bearer Token)

---

### Get All Trending Offers

Get a list of all trending offers (both active and inactive) with admin details.

**Endpoint:** `GET /api/admin/trending-offer`

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

**Success Response (200):**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "text": "🎉 Special Offer: Get 50% off on all services this month! Use code SAVE50",
            "order": 1,
            "is_active": true,
            "created_by": 1,
            "created_at": "2025-12-06T15:14:00.000000Z",
            "updated_at": "2025-12-06T15:14:00.000000Z",
            "admin": {
                "id": 1,
                "username": "admin",
                "email": "admin@alldigtalseva.com"
            }
        },
        {
            "id": 2,
            "text": "💰 New users get ₹100 welcome bonus on signup! Start your digital journey today",
            "order": 2,
            "is_active": true,
            "created_by": 1,
            "created_at": "2025-12-06T15:14:00.000000Z",
            "updated_at": "2025-12-06T15:14:00.000000Z",
            "admin": {
                "id": 1,
                "username": "admin",
                "email": "admin@alldigtalseva.com"
            }
        }
    ]
}
```

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

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/admin/trending-offer" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Accept: application/json"
```

---

### Get Single Trending Offer

Get details of a specific trending offer by ID.

**Endpoint:** `GET /api/admin/trending-offer/{id}`

**URL Parameters:**
- `id` (required, integer): Trending Offer ID

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

**Success Response (200):**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "text": "🎉 Special Offer: Get 50% off on all services this month! Use code SAVE50",
        "order": 1,
        "is_active": true,
        "created_by": 1,
        "created_at": "2025-12-06T15:14:00.000000Z",
        "updated_at": "2025-12-06T15:14:00.000000Z",
        "admin": {
            "id": 1,
            "username": "admin",
            "email": "admin@alldigtalseva.com"
        }
    }
}
```

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

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

---

### Add New Trending Offer

Create a new trending offer text.

**Endpoint:** `POST /api/admin/trending-offer`

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

**Request Body:**
```json
{
    "text": "🎉 Special Offer: Get 50% off on all services this month! Use code SAVE50",
    "order": 1,
    "is_active": true
}
```

**Field Descriptions:**
- `text` (required, string): The scrolling text message to display
- `order` (optional, integer, min 0): Display order (default: 0). Lower numbers appear first
- `is_active` (optional, boolean): Whether the trending offer is active (default: true)

**Success Response (201):**
```json
{
    "success": true,
    "message": "Trending offer added successfully",
    "data": {
        "id": 1,
        "text": "🎉 Special Offer: Get 50% off on all services this month! Use code SAVE50",
        "order": 1,
        "is_active": true,
        "created_by": 1,
        "created_at": "2025-12-06T15:14:00.000000Z",
        "updated_at": "2025-12-06T15:14:00.000000Z",
        "admin": {
            "id": 1,
            "username": "admin",
            "email": "admin@alldigtalseva.com"
        }
    }
}
```

**Error Response (422) - Validation Error:**
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "text": [
            "The text field is required."
        ],
        "order": [
            "The order must be an integer."
        ]
    }
}
```

**cURL Example:**
```bash
curl -X POST "https://api.alldigtalseva.com/api/admin/trending-offer" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "text": "🎉 Special Offer: Get 50% off on all services this month! Use code SAVE50",
    "order": 1,
    "is_active": true
  }'
```

---

### Update Trending Offer

Update an existing trending offer.

**Endpoint:** `PUT /api/admin/trending-offer/{id}` or `PATCH /api/admin/trending-offer/{id}`

**URL Parameters:**
- `id` (required, integer): Trending Offer ID

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

**Request Body:**
```json
{
    "text": "Updated trending offer text",
    "order": 2,
    "is_active": false
}
```

**Field Descriptions:**
- All fields are optional (use `PUT` for full update, `PATCH` for partial update)
- Same validation rules as Add New Trending Offer

**Success Response (200):**
```json
{
    "success": true,
    "message": "Trending offer updated successfully",
    "data": {
        "id": 1,
        "text": "Updated trending offer text",
        "order": 2,
        "is_active": false,
        "created_by": 1,
        "created_at": "2025-12-06T15:14:00.000000Z",
        "updated_at": "2025-12-06T15:20:00.000000Z",
        "admin": {
            "id": 1,
            "username": "admin",
            "email": "admin@alldigtalseva.com"
        }
    }
}
```

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

**cURL Example:**
```bash
curl -X PUT "https://api.alldigtalseva.com/api/admin/trending-offer/1" \
  -H "Authorization: Bearer {admin_token}" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "text": "Updated trending offer text",
    "order": 2,
    "is_active": false
  }'
```

---

### Delete Trending Offer

Delete a trending offer.

**Endpoint:** `DELETE /api/admin/trending-offer/{id}`

**URL Parameters:**
- `id` (required, integer): Trending Offer ID

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

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

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

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

---

## Public Trending Offer API

Public endpoint for fetching active trending offers for dashboard scrolling text. No authentication required.

**Base URL:** `/api/trending-offer`

**Authentication:** Not required

---

### Get All Active Trending Offers

Get all active trending offers as a simple array of text strings. This endpoint is designed for scrolling text display on the dashboard.

**Endpoint:** `GET /api/trending-offer`

**Success Response (200):**
```json
{
    "success": true,
    "data": [
        "🎉 Special Offer: Get 50% off on all services this month! Use code SAVE50",
        "💰 New users get ₹100 welcome bonus on signup! Start your digital journey today",
        "📱 Refer your friends and earn ₹200 for each successful referral! Share the benefits",
        "⚡ Fast and secure document verification services available 24/7",
        "🎁 Recharge your wallet and get 10% cashback! Limited time offer",
        "✅ Verify your Farmer ID and BOCW ID in just 2 minutes! Quick and easy"
    ]
}
```

**Note:** 
- Only active trending offers (`is_active = true`) are returned
- Results are ordered by `order` field (ascending), then by creation date (descending)
- Returns a simple array of text strings (no IDs or metadata) for easy integration with scrolling text components

**cURL Example:**
```bash
curl -X GET "https://api.alldigtalseva.com/api/trending-offer" \
  -H "Accept: application/json"
```

**JavaScript/Fetch Example:**
```javascript
fetch('https://api.alldigtalseva.com/api/trending-offer')
  .then(response => response.json())
  .then(result => {
    if (result.success) {
      // result.data is an array of text strings
      const scrollingTexts = result.data;
      // Use these texts for scrolling display in dashboard
      displayScrollingText(scrollingTexts);
    }
  })
  .catch(error => console.error('Error:', error));
```

**React Example:**
```jsx
import { useEffect, useState } from 'react';

function ScrollingText() {
  const [texts, setTexts] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    fetch('https://api.alldigtalseva.com/api/trending-offer')
      .then(response => response.json())
      .then(result => {
        if (result.success) {
          setTexts(result.data);
        }
      });
  }, []);

  useEffect(() => {
    if (texts.length === 0) return;
    
    const interval = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % texts.length);
    }, 5000); // Change text every 5 seconds

    return () => clearInterval(interval);
  }, [texts]);

  if (texts.length === 0) return null;

  return (
    <div className="scrolling-text">
      <marquee behavior="scroll" direction="left">
        {texts[currentIndex]}
      </marquee>
    </div>
  );
}
```

**Angular Example:**
```typescript
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-scrolling-text',
  template: `
    <div class="scrolling-text">
      <marquee behavior="scroll" direction="left">
        {{ currentText }}
      </marquee>
    </div>
  `
})
export class ScrollingTextComponent implements OnInit {
  texts: string[] = [];
  currentIndex = 0;
  currentText = '';

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get<any>('https://api.alldigtalseva.com/api/trending-offer')
      .subscribe(result => {
        if (result.success) {
          this.texts = result.data;
          this.currentText = this.texts[0] || '';
          
          // Rotate texts every 5 seconds
          setInterval(() => {
            this.currentIndex = (this.currentIndex + 1) % this.texts.length;
            this.currentText = this.texts[this.currentIndex];
          }, 5000);
        }
      });
  }
}
```

**Vue.js Example:**
```vue
<template>
  <div class="scrolling-text">
    <marquee behavior="scroll" direction="left">
      {{ currentText }}
    </marquee>
  </div>
</template>

<script>
export default {
  data() {
    return {
      texts: [],
      currentIndex: 0,
      currentText: ''
    };
  },
  mounted() {
    fetch('https://api.alldigtalseva.com/api/trending-offer')
      .then(response => response.json())
      .then(result => {
        if (result.success) {
          this.texts = result.data;
          this.currentText = this.texts[0] || '';
          
          // Rotate texts every 5 seconds
          setInterval(() => {
            this.currentIndex = (this.currentIndex + 1) % this.texts.length;
            this.currentText = this.texts[this.currentIndex];
          }, 5000);
        }
      });
  }
};
</script>
```

---

## Integration Notes

### For Dashboard Integration

1. **Simple Array Response:**
   - The public API returns a simple array of text strings
   - No need to parse complex objects
   - Perfect for scrolling text components

2. **Display Order:**
   - Texts are automatically ordered by the `order` field (ascending)
   - Lower order numbers appear first
   - If order is the same, newer texts appear first

3. **Scrolling Implementation:**
   - Use HTML `<marquee>` tag for simple scrolling (deprecated but works)
   - Use CSS animations for modern scrolling
   - Use JavaScript to rotate between multiple texts
   - Consider using libraries like `react-marquee-slider` or `vue-marquee-text-component`

4. **CSS Scrolling Example:**
   ```css
   .scrolling-text {
     overflow: hidden;
     white-space: nowrap;
   }
   
   .scrolling-text-content {
     display: inline-block;
     animation: scroll 20s linear infinite;
   }
   
   @keyframes scroll {
     0% { transform: translateX(100%); }
     100% { transform: translateX(-100%); }
   }
   ```

### Best Practices

1. **Text Length:**
   - Keep texts concise (recommended: 50-100 characters)
   - Long texts may not display well on mobile devices
   - Consider truncating very long texts

2. **Order Management:**
   - Use order values like 1, 2, 3 for sequential display
   - Leave gaps (e.g., 10, 20, 30) for easy reordering
   - Lower numbers appear first

3. **Active Status:**
   - Set `is_active: false` to temporarily hide texts without deleting
   - Useful for seasonal promotions or A/B testing
   - Public API automatically filters inactive texts

4. **Emojis and Special Characters:**
   - Emojis are supported and can make texts more engaging
   - Use Unicode emojis for better compatibility
   - Test on different devices and browsers

5. **Performance:**
   - Cache the API response on the frontend
   - Refresh periodically (e.g., every 5-10 minutes)
   - Don't make API calls on every render

6. **Accessibility:**
   - Ensure scrolling text is readable
   - Provide pause/stop functionality for users
   - Consider screen reader compatibility

---

## Use Cases

1. **Dashboard Scrolling Banner:**
   - Display promotional messages
   - Show important announcements
   - Highlight special offers

2. **Notification Bar:**
   - System updates
   - Maintenance notices
   - Feature announcements

3. **Promotional Display:**
   - Limited-time offers
   - Discount codes
   - Referral programs

4. **Information Display:**
   - Service availability
   - New features
   - Tips and guides

---

## Error Codes

| Status Code | Description |
|------------|-------------|
| 200 | Success |
| 201 | Created successfully |
| 400 | Bad request |
| 401 | Unauthorized (Admin token required) |
| 404 | Resource not found |
| 422 | Validation error |

---

## Support

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


