<?php

function product_reviews($product_id)
{
    return db_all('SELECT * FROM reviews WHERE product_id = ? AND status = 1 ORDER BY id DESC', [$product_id]);
}

// Ürünün ortalama puanını ve yorum sayısını onaylı yorumlardan yeniden hesaplar.
function review_refresh($product_id)
{
    $row = db_one('SELECT COALESCE(AVG(rating), 0) AS rating, COUNT(*) AS total FROM reviews WHERE product_id = ? AND status = 1', [$product_id]);
    db_update('products', ['rating' => round($row['rating'], 1), 'review_count' => $row['total']], $product_id);
}

function review_breakdown($reviews)
{
    $counts = array_fill_keys([5, 4, 3, 2, 1], 0);
    foreach ($reviews as $review) {
        $counts[(int) $review['rating']]++;
    }
    return $counts;
}

function customer_reviewed($product_id)
{
    return is_customer() && db_value('SELECT COUNT(*) FROM reviews WHERE product_id = ? AND customer_id = ?', [$product_id, customer_id()]);
}

function pending_review_count()
{
    return (int) db_value('SELECT COUNT(*) FROM reviews WHERE status = 0');
}
