<?php
/**
 * 芋头CMS - 内容列表（AJAX加载）
 */
$siteConfig = [];
$configs = $db->fetchAll("SELECT config_key, config_value FROM {$db->table('config')}");
foreach ($configs as $cfg) {
    $siteConfig[$cfg['config_key']] = $cfg['config_value'];
}
$siteUrl = rtrim($siteConfig['site_url'] ?? 'http://' . $_SERVER['HTTP_HOST'], '/');
$urlMode = $siteConfig['url_mode'] ?? 'dynamic';

$page = max(1, intval($_GET['page'] ?? 1));
$pageSize = 15;
$channelId = intval($_GET['channel_id'] ?? 0);
$search = isset($_GET['search']) ? htmlspecialchars(trim($_GET['search']), ENT_QUOTES, 'UTF-8') : '';
$type = trim($_GET['type'] ?? 'all');

$typeNames = [1 => '文章', 2 => '产品', 3 => '单页', 4 => '图集', 5 => '下载', 7 => '视频', 8 => '留言', 9 => '招聘'];
$typeTables = [1 => 'article', 2 => 'product', 3 => 'page', 4 => 'image', 5 => 'download', 7 => 'video', 8 => 'guestbook', 9 => 'recruit'];
$typeMap = [1=>'article', 2=>'product', 3=>'page', 4=>'image', 5=>'download', 7=>'video', 8=>'guestbook', 9=>'recruit'];

// 拼接搜索条件
$whereClauses = [];
$params = [];

if ($channelId > 0) {
    $allChannels = $db->fetchAll("SELECT * FROM {$db->table('channel')} ORDER BY parent_id ASC, list_order ASC, id ASC");
    $ids = [$channelId];
    foreach ($allChannels as $ch) {
        if ($ch['parent_id'] == $channelId) {
            $ids[] = $ch['id'];
            foreach ($allChannels as $ch2) {
                if ($ch2['parent_id'] == $ch['id']) {
                    $ids[] = $ch2['id'];
                }
            }
        }
    }
    $ids = array_unique($ids);
    $inClause = implode(',', $ids);
    $whereClauses[] = "channel_id IN ($inClause)";
}

if ($search !== '') {
    if ($channelId > 0) {
        $whereClauses[] = "(title LIKE ? OR page_title LIKE ? OR content LIKE ? OR page_content LIKE ?)";
        $params[] = '%' . $search . '%';
        $params[] = '%' . $search . '%';
        $params[] = '%' . $search . '%';
        $params[] = '%' . $search . '%';
    } else {
        $whereClauses[] = "(title LIKE ? OR page_title LIKE ? OR content LIKE ? OR page_content LIKE ?)";
        $params[] = '%' . $search . '%';
        $params[] = '%' . $search . '%';
        $params[] = '%' . $search . '%';
        $params[] = '%' . $search . '%';
    }
}

// 确定要查询哪些表
$tablesToQuery = [];
if ($type === 'all') {
    $tablesToQuery = $typeTables;
} else {
    if (isset($typeTables[$type])) {
        $tablesToQuery[$type] = $typeTables[$type];
    }
}

$allRows = [];
$channelMap = [];
$channels = $db->fetchAll("SELECT id, channel_name, channel_type FROM {$db->table('channel')}");
foreach ($channels as $c) {
    $channelMap[$c['id']] = $c['channel_name'];
}

foreach ($tablesToQuery as $t) {
    $where = '';
    if (!empty($whereClauses)) {
        $where = 'WHERE ' . implode(' AND ', $whereClauses);
        $cols = $db->fetchAll("DESCRIBE {$db->table($t)}");
        $colNames = array_column($cols, 'Field');
        $hasChannel = in_array('channel_id', $colNames);
        if (!$hasChannel) {
            $where = '';
            $params = [];
            if ($search !== '') {
                $where = "WHERE (title LIKE ? OR page_title LIKE ? OR content LIKE ? OR page_content LIKE ?)";
                $params = ['%' . $search . '%', '%' . $search . '%', '%' . $search . '%', '%' . $search . '%'];
            }
        }
    }

    try {
        $cols = $db->fetchAll("DESCRIBE {$db->table($t)}");
        $colNames = array_column($cols, 'Field');
        $selectFields = 'id, channel_id, title, status, create_time';
        if (in_array('page_title', $colNames)) $selectFields = 'id, channel_id, page_title as title, status, create_time';
        if (in_array('litpic', $colNames)) $selectFields .= ', litpic';
        if (in_array('view', $colNames)) $selectFields .= ', view';
        if (in_array('click', $colNames)) $selectFields .= ', click';

        $limit = ($t === 'page') ? '' : "LIMIT 1000";
        $rows = $db->fetchAll("SELECT $selectFields FROM {$db->table($t)} $where $limit");
        foreach ($rows as $r) {
            $r['_type'] = array_search($t, $typeTables);
            $allRows[] = $r;
        }
    } catch (Exception $e) {}
}

// 按 create_time 降序排列
usort($allRows, function($a, $b) {
    return ($b['create_time'] ?? 0) - ($a['create_time'] ?? 0);
});

// 搜索过滤
if ($search !== '') {
    $s = strtolower($search);
    $allRows = array_filter($allRows, function($r) use ($s) {
        $title = strtolower($r['title'] ?? '');
        $content = strtolower($r['content'] ?? '');
        return strpos($title, $s) !== false || strpos($content, $s) !== false;
    });
    $allRows = array_values($allRows);
}

$total = count($allRows);
$offset = ($page - 1) * $pageSize;
$paginatedRows = array_slice($allRows, $offset, $pageSize);
$totalPages = ceil($total / $pageSize);

if (empty($paginatedRows)) {
    echo '<tr><td colspan="8" class="table-loading"><svg viewBox="0 0 24 24" width="40" height="40" fill="none" stroke="#cbd5e1" stroke-width="1.5" style="display:block;margin:0 auto 12px;"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>暂无内容</td></tr>';
} else {
    foreach ($paginatedRows as $row) {
        $typeVal = $row['_type'] ?? 1;
        $statusVal = $row['status'] ?? 0;
        $title = htmlspecialchars($row['title'] ?? '');
        $cid = intval($row['channel_id'] ?? 0);
        $channelName = $channelMap[$cid] ?? '未知栏目';
        $statusLabel = $statusVal == 1 ? '<span class="status-badge status-1">已发布</span>' : '<span class="status-badge status-0">待审核</span>';
        $typeLabel = '<span class="type-badge type-' . $typeVal . '">' . ($typeNames[$typeVal] ?? '未知') . '</span>';
        $time = date('Y-m-d H:i', $row['create_time'] ?? time());
        $id = intval($row['id']);
        $litpic = $row['litpic'] ?? '';

        $m = $typeMap[$typeVal] ?? 'article';
        $viewUrl = $siteUrl . '/public/index.php?m=' . $m . '&id=' . $id;
        $editUrl = '?act=' . ($typeTables[$typeVal] ?? 'article') . '&action=edit&id=' . $id;

        echo '<tr data-id="' . $id . '" data-type="' . $typeVal . '">';
        echo '<td class="checkbox-cell"><input type="checkbox" class="row-check"></td>';
        echo '<td class="id-cell">' . $id . '</td>';
        echo '<td class="title-cell">';
        if ($litpic) echo '<img src="' . htmlspecialchars($litpic) . '" style="width:32px;height:32px;object-fit:cover;border-radius:4px;margin-right:8px;vertical-align:middle;">';
        echo '<a href="javascript:void(0)" onclick="window.open(\'' . addslashes($viewUrl) . '\', \'_blank\')" title="在新窗口预览">' . $title . '</a></td>';
        echo '<td style="width:80px;text-align:center;">' . $typeLabel . '</td>';
        echo '<td style="width:80px;color:#64748b;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">' . htmlspecialchars($channelName) . '</td>';
        echo '<td style="width:70px;text-align:center;">' . $statusLabel . '</td>';
        echo '<td style="width:130px;color:#94a3b8;font-size:12px;">' . $time . '</td>';
        echo '<td>';
        echo '<div class="action-cell">';
        echo '<button class="btn-browse" onclick="window.open(\'' . addslashes($viewUrl) . '\', \'_blank\')" title="浏览">浏览</button>';
        echo '<button class="btn-edit" onclick="location.href=\'' . addslashes($editUrl) . '\'" title="编辑">编辑</button>';
        echo '<button class="btn-del" onclick="deleteItem(' . $id . ', ' . $typeVal . ')" title="删除">删除</button>';
        echo '</div></td>';
        echo '</tr>';
    }
}

// 分页
if ($totalPages > 1) {
    $start = max(1, $page - 2);
    $end = min($totalPages, $page + 2);
    echo '<script>window._contentPagination = ' . json_encode(['total' => $total, 'page' => $page, 'totalPages' => $totalPages]) . ';</script>';
    echo '<div class="content-pagination">';
    if ($page > 1) echo '<a href="javascript:goToPage(' . ($page - 1) . ')">上一页</a>';
    if ($start > 1) { echo '<a href="javascript:goToPage(1)">1</a>'; if ($start > 2) echo '<span>...</span>'; }
    for ($i = $start; $i <= $end; $i++) {
        $active = $i === $page ? 'active' : '';
        echo '<a href="javascript:goToPage(' . $i . ')" class="' . $active . '">' . $i . '</a>';
    }
    if ($end < $totalPages) { if ($end < $totalPages - 1) echo '<span>...</span>'; echo '<a href="javascript:goToPage(' . $totalPages . ')">' . $totalPages . '</a>'; }
    if ($page < $totalPages) echo '<a href="javascript:goToPage(' . ($page + 1) . ')">下一页</a>';
    echo '</div>';
} elseif ($total > 0) {
    echo '<div style="padding:12px;text-align:center;color:#94a3b8;font-size:12px;">共 ' . $total . ' 条记录</div>';
}
?>