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

require_once __DIR__ . '/../core/db/db.php';
require_once __DIR__ . '/../core/lib/common.php';
require_once __DIR__ . '/../core/lib/shop_config.php';
require_once __DIR__ . '/../core/lib/product_review_service.php';

$db = \Core\Db\DB::getInstance();
\Core\Lib\ProductReviewService::ensureTable($db);
$action = trim((string) ($_POST['action'] ?? $_GET['action'] ?? ''));

if ($action === 'list') {
    if (!\Core\Lib\ShopConfig::enabled($db, 'review_enabled')) {
        echo json_encode(['code' => 200, 'data' => ['list' => [], 'total' => 0]], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $productId = intval($_GET['product_id'] ?? 0);
    $page = max(1, intval($_GET['page'] ?? 1));
    $pageSize = max(1, min(20, intval($_GET['page_size'] ?? 10)));
    $offset = ($page - 1) * $pageSize;
    if ($productId <= 0) {
        echo json_encode(['code' => 400, 'msg' => '参数错误'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $total = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('product_review')} WHERE product_id = ? AND status = 1", [$productId])['cnt'] ?? 0);
    $rows = $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 {$offset}, {$pageSize}", [$productId]);
    echo json_encode(['code' => 200, 'data' => ['list' => $rows, 'total' => $total]], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'submit') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['code' => 405, 'msg' => '璇锋敹鍒板悎鍙厑璁?POST'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    requireMemberCsrfToken(true);
    if (!\Core\Lib\ShopConfig::enabled($db, 'review_enabled')) {
        echo json_encode(['code' => 403, 'msg' => '商品评价暂未开启'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $memberId = intval($_SESSION['member_id'] ?? 0);
    if ($memberId <= 0) {
        echo json_encode(['code' => 401, 'msg' => '请先登录'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $needAudit = \Core\Lib\ShopConfig::enabled($db, 'review_audit');
    $result = \Core\Lib\ProductReviewService::submit(
        $db,
        $memberId,
        intval($_POST['order_id'] ?? 0),
        intval($_POST['product_id'] ?? 0),
        intval($_POST['rating'] ?? 5),
        $_POST['content'] ?? '',
        $needAudit
    );
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode(['code' => 404, 'msg' => '未知操作'], JSON_UNESCAPED_UNICODE);
