# Product Rating & Review System

## Overview

This document describes the Product Rating & Review System implementation for the e-commerce platform. The system allows customers to rate and review products, with moderation capabilities for administrators.

## Features

- **Star Ratings**: 1-5 star rating system
- **Text Reviews**: Optional title and body text
- **Moderation**: Admin approval workflow
- **Verified Purchases**: Optional requirement for verified purchase reviews
- **Rate Limiting**: Prevents spam and abuse
- **Helpful Votes**: Users can mark reviews as helpful
- **Auto-flagging**: Automatic detection of suspicious reviews
- **Rating Aggregation**: Automatic calculation of average ratings and counts

## Configuration

All configuration options are available in `config/reviews.php`. You can also set these via environment variables:

### Environment Variables

```env
# Require admin approval for all reviews
REVIEWS_REQUIRE_APPROVAL=true

# Only allow reviews from verified purchases
REVIEWS_VERIFIED_PURCHASE_ONLY=false

# Allow guest (unauthenticated) reviews
REVIEWS_ALLOW_GUEST_REVIEWS=false

# Hours after creation that users can edit their review
REVIEWS_EDIT_TIME_LIMIT_HOURS=24

# Days between reviews for same product by same user
REVIEWS_RATE_LIMIT_DAYS=30

# Maximum reviews per IP per minute
REVIEWS_THROTTLE_PER_IP=5

# Enable profanity filter
REVIEWS_ENABLE_PROFANITY_FILTER=false

# Auto-flag suspicious reviews
REVIEWS_AUTO_FLAG_SUSPICIOUS=true

# Suspicious review threshold
REVIEWS_SUSPICIOUS_COUNT=3
REVIEWS_SUSPICIOUS_MINUTES=60
```

## Database Schema

### `product_reviews` Table

- `id`: Primary key
- `product_id`: Foreign key to products
- `user_id`: Foreign key to users (nullable for guest reviews)
- `order_id`: Foreign key to orders (nullable, for verified purchase)
- `rating`: Integer 1-5
- `title`: String (nullable)
- `body`: Text (nullable)
- `is_approved`: Boolean (default: false)
- `helpful_count`: Integer (default: 0)
- `ip_address`: String (nullable)
- `user_agent`: String (nullable)
- `created_at`, `updated_at`: Timestamps

### `products` Table Additions

- `avg_rating`: Decimal(3,2) - Average rating from approved reviews
- `rating_count`: Integer - Count of approved reviews

## API Endpoints

### Public Endpoints

#### Get Product Reviews
```
GET /api/products/{id}/reviews?page=1&per_page=10
```

**Response:**
```json
{
  "success": true,
  "data": [
    {
      "id": 1,
      "rating": 5,
      "title": "Great product!",
      "body": "I really enjoyed this...",
      "user": {
        "id": 1,
        "name": "John Doe"
      },
      "helpful_count": 5,
      "created_at": "2025-12-03T10:00:00.000000Z"
    }
  ],
  "meta": {
    "current_page": 1,
    "last_page": 5,
    "per_page": 10,
    "total": 50
  }
}
```

#### Create Review
```
POST /api/products/{id}/reviews
Authorization: Bearer {token}
```

**Request Body:**
```json
{
  "rating": 5,
  "title": "Great product!",
  "body": "I really enjoyed this product...",
  "order_id": 123  // Optional, required if verified_purchase_only enabled
}
```

**Response:**
```json
{
  "success": true,
  "message": "Review submitted successfully.",
  "data": {
    "id": 1,
    "rating": 5,
    "title": "Great product!",
    "is_approved": true
  }
}
```

### Authenticated Endpoints

#### Update Review
```
PUT /api/reviews/{id}
Authorization: Bearer {token}
```

**Request Body:**
```json
{
  "rating": 4,
  "title": "Updated title",
  "body": "Updated review text"
}
```

#### Delete Review
```
DELETE /api/reviews/{id}
Authorization: Bearer {token}
```

#### Mark Review as Helpful
```
POST /api/reviews/{id}/helpful
Authorization: Bearer {token}
```

## Admin Endpoints

All admin endpoints require authentication and admin/staff role.

#### List Reviews
```
GET /admin/reviews?product_id=1&is_approved=0&rating=5&search=keyword
```

#### Approve/Unapprove Review
```
PATCH /admin/reviews/{id}/approve
```

**Request Body:**
```json
{
  "is_approved": true
}
```

#### Delete Review
```
DELETE /admin/reviews/{id}
```

#### Export Reviews to CSV
```
GET /admin/reviews/export-csv?product_id=1&is_approved=1
```

## Frontend Components

### Star Rating Component

```blade
<x-star-rating :rating="4.5" size="lg" :showNumber="true" />
```

**Props:**
- `rating`: Float (0-5)
- `size`: String ('sm', 'md', 'lg', 'xl')
- `showNumber`: Boolean

### Review Form Partial

```blade
@include('partials.review-form', ['product' => $product])
```

### Review List Partial

```blade
@include('partials.review-list', ['reviews' => $reviews, 'product' => $product])
```

## Usage Examples

### Display Product Rating

```blade
@if($product->rating_count > 0)
    <x-star-rating :rating="$product->avg_rating" size="lg" :showNumber="true" />
    <p>{{ $product->rating_count }} reviews</p>
@endif
```

### Check if User Can Review

```php
$user = auth()->user();
$canReview = $user && !ProductReview::where('product_id', $product->id)
    ->where('user_id', $user->id)
    ->where('created_at', '>=', now()->subDays(30))
    ->exists();
```

### Recalculate Product Rating

```php
$product->recalculateRating();
// Returns: ['avg_rating' => 4.5, 'rating_count' => 10]
```

## Events

The system fires the following events:

- `ReviewCreated`: When a new review is created
- `ReviewApproved`: When a review is approved by admin
- `ReviewDeleted`: When a review is deleted

These events automatically trigger rating recalculation via the `RecalculateRatingOnReviewChange` listener.

## Jobs

### RecalculateProductRating

This job recalculates the average rating and count for a product. It's automatically dispatched when reviews are created, approved, or deleted.

## Security Features

1. **Rate Limiting**: Prevents users from submitting multiple reviews for the same product within the configured time period
2. **IP Tracking**: Stores IP address and user agent for spam detection
3. **Auto-flagging**: Automatically flags reviews from the same IP within a short time window
4. **Authorization**: Users can only edit/delete their own reviews (within time limit)
5. **Throttling**: API endpoints are throttled to prevent abuse

## Testing

Run the test suite:

```bash
php artisan test --filter ProductReviewTest
php artisan test --filter ReviewCreationTest
php artisan test --filter ReviewManagementTest
php artisan test --filter ReviewApiTest
```

## Deployment

1. **Run Migrations:**
   ```bash
   php artisan migrate
   ```

2. **Configure Settings:**
   Update `config/reviews.php` or set environment variables

3. **Clear Cache:**
   ```bash
   php artisan config:clear
   php artisan cache:clear
   ```

4. **Queue Workers (if using queues):**
   ```bash
   php artisan queue:work
   ```

## Troubleshooting

### Ratings Not Updating

- Check if reviews are approved (only approved reviews count)
- Verify event listeners are registered in `EventServiceProvider`
- Check queue workers are running if using queues

### Reviews Not Appearing

- Check `is_approved` status
- Verify user has permission to view reviews
- Check if product exists and is active

### Rate Limiting Issues

- Adjust `REVIEWS_RATE_LIMIT_DAYS` in config
- Check IP-based rate limiting if guest reviews enabled

## Future Enhancements

- Photo/video attachments in reviews
- Review helpfulness algorithm
- Review sorting options (newest, highest rated, most helpful)
- Review replies/threading
- Review moderation queue notifications
- Integration with email notifications
- Review analytics dashboard

