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

require_once ROOT_PATH . 'core/db/db.php';
require_once ROOT_PATH . 'core/lib/license.php';
require_once ROOT_PATH . 'core/lib/license_guard.php';
require_once ROOT_PATH . 'core/lib/product_review_service.php';

$licenseObj = new \Core\Lib\License();
$readonlyMode = !\Core\Lib\LicenseGuard::canUseOrder($licenseObj);

$db = isset($db) && $db instanceof \Core\Db\DB ? $db : \Core\Db\DB::getInstance();
if (!function_exists('ytReviewReadonlyBanner')) {
    function ytReviewReadonlyBanner()
    {
        echo '<div style="margin-bottom:20px;padding:18px 20px;border:1px solid #fdba74;background:linear-gradient(135deg,#fff7ed 0%,#ffffff 100%);border-radius:14px;display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;">';
        echo '<div><div style="font-size:16px;font-weight:700;color:#9a3412;">商品评价当前为只读模式</div><div style="margin-top:6px;font-size:13px;color:#7c2d12;line-height:1.8;">免费版可查看评价记录，审核、拒绝、回复评价需升级专业版授权后使用。</div></div>';
        echo '<a href="?act=auth" style="display:inline-flex;align-items:center;justify-content:center;padding:11px 18px;border-radius:10px;background:linear-gradient(135deg,#ea580c 0%,#dc2626 100%);color:#fff;text-decoration:none;font-weight:700;white-space:nowrap;">升级授权</a>';
        echo '</div>';
    }
}
\Core\Lib\ProductReviewService::ensureTable($db);
$statusMap = \Core\Lib\ProductReviewService::statusMap();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
    requireAdminCsrfToken(true);
    if ($readonlyMode) {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['code' => 403, 'msg' => '当前为只读模式，升级专业版后可操作'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    while (ob_get_level() > 0) { ob_end_clean(); }
    header('Content-Type: application/json; charset=utf-8');
    $action = trim((string) $_POST['ajax_action']);
    $statusByAction = ['pending' => 0, 'approve' => 1, 'reject' => 2];
    if (!isset($statusByAction[$action])) {
        echo json_encode(['code' => 404, 'msg' => '未知操作'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $result = \Core\Lib\ProductReviewService::updateStatus($db, intval($_POST['id'] ?? 0), $statusByAction[$action], $_POST['reply'] ?? '');
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
    exit;
}

$page = max(1, intval($_GET['page'] ?? 1));
$pageSize = 15;
$offset = ($page - 1) * $pageSize;
$status = trim((string) ($_GET['status'] ?? 'all'));
$keyword = trim((string) ($_GET['keyword'] ?? ''));
$where = [];
$params = [];
if ($status !== 'all' && $status !== '') {
    $where[] = 'r.status = ?';
    $params[] = intval($status);
}
if ($keyword !== '') {
    $where[] = '(p.title LIKE ? OR m.username LIKE ? OR r.content LIKE ?)';
    $keywordLike = '%' . $keyword . '%';
    array_push($params, $keywordLike, $keywordLike, $keywordLike);
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
$total = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('product_review')} r LEFT JOIN {$db->table('product')} p ON p.id = r.product_id LEFT JOIN {$db->table('member')} m ON m.id = r.member_id {$whereSql}", $params)['cnt'] ?? 0);
$rows = $db->fetchAll("SELECT r.*, p.title AS product_title, m.username, m.nickname FROM {$db->table('product_review')} r LEFT JOIN {$db->table('product')} p ON p.id = r.product_id LEFT JOIN {$db->table('member')} m ON m.id = r.member_id {$whereSql} ORDER BY r.id DESC LIMIT {$offset}, {$pageSize}", $params);
$totalPages = max(1, (int) ceil($total / $pageSize));
$pendingCount = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('product_review')} WHERE status = 0")['cnt'] ?? 0);
$visibleCount = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('product_review')} WHERE status = 1")['cnt'] ?? 0);
?>
<div class="page-container fade-in">
    <div class="page-header">
    <?php if ($readonlyMode) { ytReviewReadonlyBanner(); } ?>
        <div>
            <h1 style="margin:0;font-size:20px;color:#0f172a;">商品评价</h1>
            <p style="margin:6px 0 0;color:#64748b;font-size:13px;">审核会员评价并回复，前台仅展示已通过评价。</p>
        </div>
        <div class="page-actions"><a href="?act=shop_config" class="btn btn-secondary">商城配置</a></div>
    </div>
    <div class="yt-review-stats">
        <a href="?act=review&status=0" class="yt-review-stat"><span>待审核</span><strong><?php echo $pendingCount; ?></strong></a>
        <a href="?act=review&status=1" class="yt-review-stat"><span>已显示</span><strong><?php echo $visibleCount; ?></strong></a>
    </div>
    <div class="content-card" style="margin-bottom:16px;padding:16px;">
        <form method="get" style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
            <input type="hidden" name="act" value="review">
            <select name="status" class="form-control" style="width:160px;">
                <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>全部状态</option>
                <?php foreach ($statusMap as $statusKey => $statusInfo): ?>
                <option value="<?php echo $statusKey; ?>" <?php echo $status !== 'all' && intval($status) === $statusKey ? 'selected' : ''; ?>><?php echo $statusInfo[0]; ?></option>
                <?php endforeach; ?>
            </select>
            <input type="text" name="keyword" class="form-control" style="width:260px;" value="<?php echo htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8'); ?>" placeholder="商品/会员/评价内容">
            <button type="submit" class="btn btn-primary">筛选</button>
            <a href="?act=review" class="btn btn-secondary">重置</a>
        </form>
    </div>
    <div class="content-card">
        <?php if (empty($rows)): ?>
        <div class="empty-state" style="padding:54px 20px;text-align:center;color:#94a3b8;">暂无商品评价</div>
        <?php else: ?>
        <table class="data-table">
            <thead><tr><th style="width:60px;">ID</th><th>商品/会员</th><th style="width:90px;">评分</th><th>评价内容</th><th style="width:100px;">状态</th><th style="width:150px;">时间</th><th style="width:230px;">操作</th></tr></thead>
            <tbody>
            <?php foreach ($rows as $row): ?>
            <?php $statusInfo = $statusMap[intval($row['status'] ?? 0)] ?? ['未知', 'badge-gray']; ?>
            <tr>
                <td class="id-cell"><?php echo intval($row['id']); ?></td>
                <td><div style="font-weight:600;color:#0f172a;max-width:260px;word-break:break-word;"><?php echo htmlspecialchars($row['product_title'] ?? ('商品ID ' . intval($row['product_id']))); ?></div><div style="margin-top:4px;color:#64748b;font-size:12px;">会员：<?php echo htmlspecialchars(($row['username'] ?? '') !== '' ? $row['username'] : ('ID ' . intval($row['member_id']))); ?></div></td>
                <td><?php echo str_repeat('★', max(1, min(5, intval($row['rating'])))); ?></td>
                <td style="max-width:360px;word-break:break-word;"><?php echo htmlspecialchars($row['content'] ?? '-'); ?><div style="margin-top:4px;color:#94a3b8;font-size:12px;">回复：<?php echo htmlspecialchars(($row['reply'] ?? '') !== '' ? $row['reply'] : '-'); ?></div></td>
                <td><span class="badge <?php echo $statusInfo[1]; ?>"><?php echo $statusInfo[0]; ?></span></td>
                <td style="color:#64748b;font-size:12px;"><?php echo !empty($row['create_time']) ? date('Y-m-d H:i', intval($row['create_time'])) : '-'; ?></td>
                <td><div class="btn-group" style="display:flex;gap:6px;flex-wrap:wrap;"><?php if ($readonlyMode): ?><a href="?act=auth" class="btn btn-secondary">升级后操作</a><?php else: ?><button type="button" class="btn btn-primary" onclick="updateReview(<?php echo intval($row['id']); ?>, 'approve')">通过</button><button type="button" class="btn btn-ghost" style="color:#dc2626;" onclick="updateReview(<?php echo intval($row['id']); ?>, 'reject')">拒绝</button><button type="button" class="btn btn-secondary" onclick="updateReview(<?php echo intval($row['id']); ?>, 'pending')">待审</button><?php endif; ?></div></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php if ($totalPages > 1): ?>
        <div class="pagination" style="padding:16px;text-align:center;">
            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
            <a href="?act=review&page=<?php echo $i; ?>&status=<?php echo urlencode($status); ?>&keyword=<?php echo urlencode($keyword); ?>" <?php echo $i === $page ? 'class="active"' : ''; ?>><?php echo $i; ?></a>
            <?php endfor; ?>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>
<style>.yt-review-stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:16px}.yt-review-stat{display:flex;justify-content:space-between;align-items:center;padding:16px 18px;background:#fff;border:1px solid #e2e8f0;border-radius:14px;text-decoration:none;color:#334155}.yt-review-stat span{font-size:13px;color:#64748b}.yt-review-stat strong{font-size:24px;color:#0f172a}</style>
<script>
var reviewCsrfToken = <?php echo json_encode(getAdminCsrfToken()); ?>;
function updateReview(id, action) {
    var reply = prompt('可填写后台回复：', '');
    if (reply === null) return;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '?act=review', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        try { var res = JSON.parse(xhr.responseText); alert(res.msg || '操作完成'); if (res.code === 200) location.reload(); }
        catch (e) { alert('操作失败'); }
    };
    xhr.send('ajax_action=' + encodeURIComponent(action) + '&id=' + encodeURIComponent(id) + '&reply=' + encodeURIComponent(reply) + '&csrf_token=' + encodeURIComponent(reviewCsrfToken));
}
</script>
