<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */

namespace Core\Lib;

class ProductReviewService
{
    public static function ensureTable($db)
    {
        return true;
    }

    public static function statusMap()
    {
        return [
            0 => ['待审核', 'badge-warning'],
            1 => ['已显示', 'badge-success'],
            2 => ['已拒绝', 'badge-danger'],
        ];
    }

    public static function submit($db, $memberId, $orderId, $productId, $rating, $content, $needAudit = true)
    {
        self::ensureTable($db);
        $memberId = intval($memberId);
        $orderId = intval($orderId);
        $productId = intval($productId);
        $rating = max(1, min(5, intval($rating)));
        $content = trim((string) $content);

        if ($memberId <= 0 || $orderId <= 0 || $productId <= 0) {
            return ['code' => 400, 'msg' => '参数错误'];
        }
        if ($content === '') {
            return ['code' => 400, 'msg' => '请填写评价内容'];
        }

        $order = $db->fetch("SELECT id, status FROM {$db->table('order')} WHERE id = ? AND member_id = ?", [$orderId, $memberId]);
        if (!$order || intval($order['status']) !== 3) {
            return ['code' => 400, 'msg' => '只有已完成订单才能评价'];
        }

        $item = $db->fetch("SELECT id FROM {$db->table('order_product')} WHERE order_id = ? AND product_id = ? LIMIT 1", [$orderId, $productId]);
        if (!$item) {
            return ['code' => 400, 'msg' => '订单商品不存在'];
        }

        $exists = $db->fetch("SELECT id FROM {$db->table('product_review')} WHERE order_id = ? AND product_id = ? AND member_id = ? LIMIT 1", [$orderId, $productId, $memberId]);
        if ($exists) {
            return ['code' => 400, 'msg' => '该商品已评价'];
        }

        $now = time();
        $db->insert('product_review', [
            'product_id' => $productId,
            'order_id' => $orderId,
            'member_id' => $memberId,
            'rating' => $rating,
            'content' => $content,
            'status' => $needAudit ? 0 : 1,
            'create_time' => $now,
            'update_time' => $now,
            'audit_time' => $needAudit ? 0 : $now,
        ]);

        return ['code' => 200, 'msg' => $needAudit ? '评价已提交，等待审核' : '评价已发布'];
    }

    public static function updateStatus($db, $reviewId, $status, $reply = '')
    {
        self::ensureTable($db);
        $reviewId = intval($reviewId);
        $status = intval($status);
        $reply = trim((string) $reply);
        if ($reviewId <= 0 || !in_array($status, [0, 1, 2], true)) {
            return ['code' => 400, 'msg' => '参数错误'];
        }

        $review = $db->fetch("SELECT r.id, r.member_id, r.product_id, p.title AS product_title FROM {$db->table('product_review')} r LEFT JOIN {$db->table('product')} p ON p.id = r.product_id WHERE r.id = ?", [$reviewId]);
        if (!$review) {
            return ['code' => 404, 'msg' => '评价不存在'];
        }

        $db->update('product_review', [
            'status' => $status,
            'reply' => $reply,
            'audit_time' => time(),
            'update_time' => time(),
        ], 'id = ?', [$reviewId]);

        $productName = trim((string) ($review['product_title'] ?? ''));
        $productName = $productName !== '' ? $productName : '商品 #' . intval($review['product_id']);
        $notifications = [
            1 => ['评价审核通过', '您对“' . $productName . '”的评价已展示。'],
            2 => ['评价未通过审核', '您对“' . $productName . '”的评价未通过审核。'],
        ];
        if (function_exists('sendMemberMessage')) {
            try {
                if (isset($notifications[$status])) {
                    \sendMemberMessage(intval($review['member_id']), $notifications[$status][0], $notifications[$status][1]);
                }
                if ($reply !== '') {
                    \sendMemberMessage(intval($review['member_id']), '商家回复了您的评价', '商品“' . $productName . '”收到商家回复：' . $reply);
                }
            } catch (\Throwable $e) {
                error_log('Review notification failed: ' . $e->getMessage());
            }
        }

        return ['code' => 200, 'msg' => '评价状态已更新'];
    }

    public static function getVisibleStats($db, $productId)
    {
        self::ensureTable($db);
        $productId = intval($productId);
        if ($productId <= 0) {
            return ['total' => 0, 'avg_rating' => 0];
        }

        $row = $db->fetch("SELECT COUNT(*) AS total, AVG(rating) AS avg_rating FROM {$db->table('product_review')} WHERE product_id = ? AND status = 1", [$productId]);
        return [
            'total' => intval($row['total'] ?? 0),
            'avg_rating' => round(floatval($row['avg_rating'] ?? 0), 1),
        ];
    }

    public static function getVisibleList($db, $productId, $limit = 10)
    {
        self::ensureTable($db);
        $productId = intval($productId);
        $limit = max(1, min(50, intval($limit)));
        if ($productId <= 0) {
            return [];
        }

        return $db->fetchAll("SELECT r.*, m.username, m.nickname FROM {$db->table('product_review')} r LEFT JOIN {$db->table('member')} m ON m.id = r.member_id WHERE r.product_id = ? AND r.status = 1 ORDER BY r.id DESC LIMIT {$limit}", [$productId]);
    }
}
