<?php
/**
 * Heritage Voice — ratings.php
 * POST /api/ratings              Đánh giá audio point
 * GET  /api/ratings/{point_id}   Lấy rating của 1 điểm nghe
 * GET  /api/ratings/{point_id}/me Rating của user hiện tại
 */
function rating_add(): void {
    $u = require_auth();
    $b = body();
    $point_id = $b['audio_point_id'] ?? '';
    $site_id  = $b['site_id']        ?? '';
    $rating   = (int)($b['rating']   ?? 0);
    $comment  = trim($b['comment']   ?? '');
    if (!$point_id || !$site_id)      json_error('Thiếu audio_point_id hoặc site_id');
    if ($rating < 1 || $rating > 5)   json_error('Rating phải từ 1-5 sao');
    db()->prepare("INSERT INTO audio_ratings(user_id,audio_point_id,site_id,rating,comment,created_at)
        VALUES(:u,:p,:s,:r,:c,NOW())
        ON DUPLICATE KEY UPDATE rating=VALUES(rating),comment=VALUES(comment),created_at=NOW()")
        ->execute([':u'=>$u['id'],':p'=>$point_id,':s'=>$site_id,':r'=>$rating,':c'=>$comment?:null]);
    json_ok(['rating'=>$rating], 'Cảm ơn bạn đã đánh giá!');
}
function rating_get(string $point_id): void {
    // Aggregate
    $stmt = db()->prepare("
        SELECT AVG(rating) AS avg_rating, COUNT(*) AS total,
               SUM(rating=5) AS star5, SUM(rating=4) AS star4,
               SUM(rating=3) AS star3, SUM(rating=2) AS star2,
               SUM(rating=1) AS star1
        FROM audio_ratings WHERE audio_point_id=:p
    ");
    $stmt->execute([':p' => $point_id]);
    $row = $stmt->fetch();

    // Reviews có comment
    $stmt2 = db()->prepare("
        SELECT r.rating, r.comment, r.created_at,
               u.display_name, u.avatar_url
        FROM audio_ratings r
        LEFT JOIN users u ON u.id = r.user_id
        WHERE r.audio_point_id = :p
          AND r.comment IS NOT NULL
          AND r.comment != ''
        ORDER BY r.created_at DESC
        LIMIT 20
    ");
    $stmt2->execute([':p' => $point_id]);
    $reviews = $stmt2->fetchAll();

    json_ok([
        'avg_rating'   => $row['avg_rating'] ? round((float)$row['avg_rating'],1) : null,
        'total'        => (int)$row['total'],
        'distribution' => [
            5=>(int)$row['star5'], 4=>(int)$row['star4'], 3=>(int)$row['star3'],
            2=>(int)$row['star2'], 1=>(int)$row['star1'],
        ],
        'reviews' => array_map(fn($r) => [
            'rating'       => (int)$r['rating'],
            'comment'      => $r['comment'],
            'created_at'   => $r['created_at'],
            'display_name' => $r['display_name'] ?? 'Người dùng',
            'avatar_url'   => $r['avatar_url']   ?? null,
        ], $reviews),
    ]);
}
function rating_me(string $point_id): void {
    $u = require_auth();
    $stmt = db()->prepare("SELECT rating, comment FROM audio_ratings WHERE user_id=:u AND audio_point_id=:p");
    $stmt->execute([':u'=>$u['id'],':p'=>$point_id]);
    $row = $stmt->fetch();
    json_ok($row ? ['rating'=>(int)$row['rating'],'comment'=>$row['comment']] : null);
}
