<?php
$memberId = intval($_SESSION['member_id'] ?? 0);
cmsEnsureFavoriteTable($db);
$page = max(1, intval($_GET['p'] ?? 1));
$pageSize = 15;
$offset = ($page - 1) * $pageSize;
$total = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('favorite')} WHERE member_id = ?", [$memberId])['cnt'] ?? 0);
$totalPages = max(1, (int) ceil($total / $pageSize));
$favorites = $db->fetchAll("SELECT * FROM {$db->table('favorite')} WHERE member_id = ? ORDER BY id DESC LIMIT {$offset}, {$pageSize}", [$memberId]);
$types = [
    'product' => ['table' => 'product', 'label' => '产品'],
    'article' => ['table' => 'article', 'label' => '文章'],
    'download' => ['table' => 'download', 'label' => '下载'],
    'recruit' => ['table' => 'recruit', 'label' => '招聘'],
];
$contentIds = [];
foreach ($favorites as $favorite) {
    $type = (string) ($favorite['content_type'] ?? '');
    if (isset($types[$type])) { $contentIds[$type][] = intval($favorite['content_id']); }
}
$contentMap = [];
foreach ($contentIds as $type => $ids) {
    $ids = array_values(array_unique(array_filter($ids)));
    if (!$ids) { continue; }
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $rows = $db->fetchAll("SELECT id, title FROM {$db->table($types[$type]['table'])} WHERE id IN ({$placeholders})", $ids);
    foreach ($rows as $row) { $contentMap[$type][intval($row['id'])] = $row; }
}
$items = [];
foreach ($favorites as $favorite) {
    $type = (string) ($favorite['content_type'] ?? '');
    if (!isset($types[$type])) { continue; }
    $content = $contentMap[$type][intval($favorite['content_id'])] ?? null;
    if (!$content) { continue; }
    $items[] = $favorite + ['title' => (string) $content['title'], 'type_label' => $types[$type]['label'], 'url' => cmsBuildFrontendUrl($type, intval($content['id']))];
}
?>
<div class="page-header"><h1 class="page-title">我的收藏</h1></div>
<div class="page-content self-page">
    <?php if (!$items): ?><div class="self-empty">暂无收藏内容</div><?php endif; ?>
    <div class="self-list">
    <?php foreach ($items as $item): ?>
        <article class="self-card" id="favorite-<?php echo intval($item['id']); ?>">
            <div><span class="self-badge"><?php echo htmlspecialchars($item['type_label']); ?></span><h3><?php echo htmlspecialchars($item['title']); ?></h3><time><?php echo date('Y-m-d H:i', intval($item['create_time'])); ?></time></div>
            <div class="self-actions"><a href="<?php echo htmlspecialchars($item['url']); ?>" target="_blank">查看</a><button type="button" onclick="removeFavorite(<?php echo intval($item['id']); ?>,<?php echo intval($item['content_id']); ?>,<?php echo htmlspecialchars(json_encode($item['content_type']), ENT_QUOTES, 'UTF-8'); ?>)">取消收藏</button></div>
        </article>
    <?php endforeach; ?>
    </div>
    <?php if ($totalPages > 1): ?>
    <div class="self-pagination">
        <?php if ($page > 1): ?><a href="?page=favorites&p=<?php echo $page - 1; ?>">上一页</a><?php endif; ?>
        <span><?php echo $page; ?> / <?php echo $totalPages; ?></span>
        <?php if ($page < $totalPages): ?><a href="?page=favorites&p=<?php echo $page + 1; ?>">下一页</a><?php endif; ?>
    </div>
    <?php endif; ?>
</div>
<style>
.self-page{padding:22px}.self-list{display:grid;gap:12px}.self-card{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:18px 20px;border:1px solid #e2e8f0;border-radius:14px;background:#fff}.self-card h3{display:inline;margin:0 8px;color:#1e293b;font-size:15px}.self-card time{display:block;margin-top:8px;color:#94a3b8;font-size:12px}.self-badge{padding:4px 8px;border-radius:999px;background:#ecfdf5;color:#047857;font-size:11px}.self-actions{display:flex;gap:8px;white-space:nowrap}.self-actions a,.self-actions button,.self-pagination a{padding:8px 12px;border:1px solid #dbe4ee;border-radius:9px;background:#fff;color:#475569;cursor:pointer;text-decoration:none}.self-actions button{color:#dc2626}.self-empty{padding:60px;text-align:center;color:#94a3b8}.self-pagination{display:flex;align-items:center;justify-content:center;gap:12px;margin-top:20px;color:#64748b;font-size:13px}@media(max-width:640px){.self-card{align-items:flex-start;flex-direction:column}.self-actions{width:100%}.self-actions a,.self-actions button{flex:1;text-align:center}}
</style>
<script>
function removeFavorite(rowId, contentId, type) {
    if (!confirm('确定取消收藏吗？')) return;
    var body = new URLSearchParams({action:'remove',content_id:String(contentId),type:type,csrf_token:<?php echo json_encode(getMemberCsrfToken()); ?>});
    fetch('/api/favorite.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:body.toString()}).then(function(response){return response.json();}).then(function(result){
        if (result.code !== 200) { alert(result.msg || '操作失败'); return; }
        var row=document.getElementById('favorite-'+rowId); if(row) row.remove();
    }).catch(function(){alert('网络请求失败');});
}
</script>
