<?php
include 'includes/db.php';
include 'includes/functions.php';
session_start();
header('Content-Type: application/json');
$photo = (int)($_POST['photo_id'] ?? 0);
$rating = (int)($_POST['rating'] ?? 0);
$ip = $_SERVER['REMOTE_ADDR'];
$sid = session_id();
if ($photo > 0 && $rating >= 1 && $rating <= 5) {
    if (!user_has_rated($pdo, $photo, $ip, $sid)) {
        $stmt = $pdo->prepare('INSERT INTO ratings (photo_id, rating, rater_ip, session_id) VALUES (?,?,?,?)');
        $stmt->execute([$photo, $rating, $ip, $sid]);
    }
    $avg = $pdo->prepare('SELECT AVG(rating) as avg, COUNT(*) as cnt FROM ratings WHERE photo_id = ?');
    $avg->execute([$photo]);
    $row = $avg->fetch();
    echo json_encode(['avg' => round($row['avg'],1), 'cnt' => $row['cnt']]);
} else {
    echo json_encode(['error' => 'ungültig']);
}
?>