# Grievance Pagination API Usage Guide

## API Endpoints Added

### 1. Paginated Grievance Search by Ration Card
- **Endpoint**: `GET /api/grievance/paginated`
- **Purpose**: Search grievances by ration card number with pagination support

### 2. General Paginated Grievance List
- **Endpoint**: `GET /api/grievance/paginated-all`
- **Purpose**: Get all grievances with pagination (optional status filtering)

## API Parameters

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `ration_card_number` | string | No | null | Search by ration card number |
| `status` | string | No | null | Filter by status (OPEN, IN_PROGRESS, CLOSED, etc.) |
| `per_page` | integer | No | 15 | Items per page (1-100) |
| `page` | integer | No | 1 | Page number |

## Usage Examples

### Example 1: Search by Ration Card Number
```bash
GET /api/grievance/paginated?ration_card_number=RC123456&per_page=10&page=1
```

### Example 2: Search by Ration Card with Status Filter
```bash
GET /api/grievance/paginated?ration_card_number=RC123456&status=OPEN&per_page=15&page=1
```

### Example 3: Get All Open Grievances (Paginated)
```bash
GET /api/grievance/paginated-all?status=OPEN&per_page=20&page=1
```

### Example 4: Get All Grievances (No Filters)
```bash
GET /api/grievance/paginated-all?per_page=25&page=2
```

## Response Structure

```json
{
    "status": 200,
    "message": "Grievances for ration card 'RC123456' retrieved successfully",
    "data": {
        "grievances": [
            {
                "id": 1,
                "voter_id": "V001",
                "ration_card_number": "RC123456",
                "title": "Ration card not received",
                "description": "Applied for ration card 3 months ago but still not received",
                "status": "OPEN",
                "meeting_date": "2024-12-01",
                "reported_at": "2024-11-20T10:30:00.000000Z",
                "target_resolve_by": "2024-12-15",
                "closed_at": null,
                "created_at": "2024-11-20T10:30:00.000000Z",
                "updated_at": "2024-11-20T10:30:00.000000Z",
                "voter": {
                    "voter_id_number": "V001",
                    "name": "John Doe",
                    "mobile_number": "9876543210",
                    "ration_card_number": "RC123456"
                },
                "ration_card": {
                    "ration_card_number": "RC123456",
                    "head_name": "John Doe",
                    "mobile_number": "9876543210"
                }
            }
        ],
        "pagination": {
            "current_page": 1,
            "last_page": 3,
            "per_page": 10,
            "total": 25,
            "from": 1,
            "to": 10,
            "has_more_pages": true,
            "prev_page_url": null,
            "next_page_url": "http://localhost/api/grievance/paginated?page=2"
        },
        "search_criteria": {
            "ration_card_number": "RC123456",
            "status": null
        },
        "status_counts": {
            "OPEN": 15,
            "IN_PROGRESS": 8,
            "CLOSED": 12,
            "UNRESOLVED": 3,
            "HOLD": 2
        }
    }
}
```

## How Ration Card Search Works

The search functionality looks for grievances in **three different ways**:

1. **Direct Match**: Grievances where `ration_card_number` field matches directly
2. **Through Voter**: Grievances linked to voters who have the specified ration card number
3. **Through Ration Card Relationship**: Grievances linked through the ration card relationship

## Testing with Sample Data

### Step 1: Create Test Data
You can use the existing grievance creation endpoint to add test data:

```bash
POST /api/grievance/create
Content-Type: application/json

{
    "voter_id": "V001",
    "ration_card_number": "RC123456",
    "title": "Ration card not received",
    "description": "Applied for ration card 3 months ago but still not received",
    "status": "OPEN",
    "target_resolve_by": "2024-12-15"
}
```

### Step 2: Test the Pagination Endpoints

#### Test Case 1: Search by Ration Card
```bash
curl -X GET "http://localhost:8000/api/grievance/paginated?ration_card_number=RC123456&per_page=5"
```

#### Test Case 2: Get All Grievances with Pagination
```bash
curl -X GET "http://localhost:8000/api/grievance/paginated-all?status=OPEN&per_page=10&page=1"
```

## Frontend Implementation Examples

### JavaScript/Axios Example
```javascript
// Search by ration card number
async function searchGrievancesByRationCard(rationCardNumber, page = 1, perPage = 15) {
    try {
        const response = await axios.get('/api/grievance/paginated', {
            params: {
                ration_card_number: rationCardNumber,
                per_page: perPage,
                page: page
            }
        });
        return response.data;
    } catch (error) {
        console.error('Error fetching grievances:', error);
    }
}

// Get all grievances paginated
async function getAllGrievancesPaginated(status = null, page = 1, perPage = 15) {
    try {
        const params = { per_page: perPage, page: page };
        if (status) params.status = status;
        
        const response = await axios.get('/api/grievance/paginated-all', { params });
        return response.data;
    } catch (error) {
        console.error('Error fetching grievances:', error);
    }
}
```

### PHP/Laravel Example (for testing in another controller)
```php
use Illuminate\Support\Facades\Http;

// Test the pagination endpoint
$response = Http::get('http://localhost:8000/api/grievance/paginated', [
    'ration_card_number' => 'RC123456',
    'per_page' => 10,
    'page' => 1
]);

$data = $response->json();
```

## Error Handling

The API handles various error scenarios:

1. **Invalid Status**: Returns 400 error if invalid status is provided
2. **Database Errors**: Returns 500 error with error message
3. **No Results**: Returns empty array with proper pagination metadata
4. **Invalid Per Page**: Automatically limits to 1-100 range

## Performance Considerations

1. **Per Page Limit**: Maximum 100 items per page to prevent memory issues
2. **Indexed Queries**: Ensure database indexes on `ration_card_number`, `status`, and date fields
3. **Eager Loading**: Relationships (voter, rationCard) are eager loaded to prevent N+1 queries

## Next Steps

1. Test the endpoints with your existing data
2. Add frontend pagination controls
3. Implement search functionality in your UI
4. Consider adding more filters (date ranges, etc.) if needed