<?php
require_once __DIR__ . '/DB.php';

class Rating {
    public static function add(int $imageId, int $userId, int $rating): void {
        if ($rating < 1 || $rating > 10 || $rating == 7) {
            throw new Exception("Invalid rating");
        }

        $db = DB::get();
        $stmt = $db->prepare("
            INSERT INTO image_ratings (image_id, rater_user_id, rating, created_at)
            VALUES (?, ?, ?, NOW())
            ON DUPLICATE KEY UPDATE rating = VALUES(rating), created_at = VALUES(created_at)
        ");
        $stmt->execute([$imageId, $userId, $rating]);

        $db->prepare("
            UPDATE images 
            SET avg_rating = (SELECT AVG(rating) FROM image_ratings WHERE image_id = ?)
            WHERE id = ?
        ")->execute([$imageId, $imageId]);
    }
}