<?php
/**
 * GET /api/reviews/list.php?product_id=123
 * Public. Returns all reviews for a product, most recent first, plus the
 * average rating and count.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';

$productId = (int) ($_GET['product_id'] ?? 0);
if ($productId <= 0) {
    send_error('A valid product_id is required.', 422);
}

$pdo = Database::connect();

$stmt = $pdo->prepare('
    SELECT pr.rating, pr.comment, pr.created_at,
           COALESCE(pp.full_name, bp.business_name) AS reviewer_name
    FROM product_reviews pr
    JOIN users u ON u.id = pr.reviewer_id
    LEFT JOIN personal_profiles pp ON pp.user_id = u.id
    LEFT JOIN business_profiles bp ON bp.user_id = u.id
    WHERE pr.product_id = ?
    ORDER BY pr.created_at DESC
');
$stmt->execute([$productId]);
$reviews = $stmt->fetchAll();

$avg = 0;
if ($reviews) {
    $avg = round(array_sum(array_column($reviews, 'rating')) / count($reviews), 1);
}

send_json(true, 'OK', [
    'reviews' => $reviews,
    'average_rating' => $avg,
    'review_count' => count($reviews),
]);
