<?php

function calculate_weighted_score($review_id)
{
    $db = \App\Core\Database::getInstance();

    $rows = $db->query("
        SELECT rs.score, rc.weight
        FROM review_scores rs
        JOIN review_criteria rc ON rc.id = rs.criteria_id
        WHERE rs.review_id = $review_id
    ")->fetchAll();

    $total = 0;
    $weight_sum = 0;

    foreach ($rows as $r) {
        $total += $r['score'] * $r['weight'];
        $weight_sum += $r['weight'];
    }

    return $weight_sum ? round($total / $weight_sum,2) : 0;
}
