<?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'], '/');

$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);
    $whereClauses[] = 'channel_id IN (' . implode(',', array_map('intval', $ids)) . ')';
}

if ($search !== '') {
    $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;
} elseif (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 $channel) {
    $channelMap[$channel['id']] = $channel['channel_name'];
}

foreach ($tablesToQuery as $typeValue => $table) {
    $where = '';
    $queryParams = $params;

    if (!empty($whereClauses)) {
        $where = 'WHERE ' . implode(' AND ', $whereClauses);
        $cols = $db->fetchAll("DESCRIBE {$db->table($table)}");
        $colNames = array_column($cols, 'Field');

        if (!in_array('channel_id', $colNames, true)) {
            $where = '';
            $queryParams = [];
            if ($search !== '') {
                $where = 'WHERE (title LIKE ? OR page_title LIKE ? OR content LIKE ? OR page_content LIKE ?)';
                $queryParams = ['%' . $search . '%', '%' . $search . '%', '%' . $search . '%', '%' . $search . '%'];
            }
        }
    }

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

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

usort($allRows, function ($a, $b) {
    return ($b['create_time'] ?? 0) - ($a['create_time'] ?? 0);
});

$total = count($allRows);
$offset = ($page - 1) * $pageSize;
$paginatedRows = array_slice($allRows, $offset, $pageSize);
$totalPages = max(1, (int) ceil(max(1, $total) / $pageSize));
$page = min($page, $totalPages);
$rangeStart = $total > 0 ? $offset + 1 : 0;
$rangeEnd = min($offset + $pageSize, $total);
?>
<div class="list-meta-bar" data-total="<?php echo $total; ?>" data-page="<?php echo $page; ?>" data-pages="<?php echo $totalPages; ?>">
    <div class="list-meta-group">
        <span class="list-meta-title">列表结果</span>
        <span class="list-meta-pill is-active">共 <?php echo $total; ?> 条</span>
        <span class="list-meta-pill"><?php echo $rangeStart; ?> - <?php echo $rangeEnd; ?></span>
        <?php if ($search !== ''): ?>
        <span class="list-meta-pill">关键词：<?php echo htmlspecialchars($search, ENT_QUOTES, 'UTF-8'); ?></span>
        <?php endif; ?>
    </div>
    <div class="list-meta-group">
        <span class="list-meta-pill"><?php echo $channelId > 0 ? '当前栏目及子栏目' : '全部栏目'; ?></span>
        <span class="list-meta-pill"><?php echo $type !== 'all' && isset($typeNames[intval($type)]) ? $typeNames[intval($type)] : '全部类型'; ?></span>
    </div>
</div>

<table class="content-table">
    <thead>
        <tr>
            <th style="width:30px;" class="checkbox-cell"><input type="checkbox" id="checkAll"></th>
            <th style="width:44px;text-align:center;">ID</th>
            <th style="width:420px;">标题</th>
            <th style="width:88px;text-align:center;">类型</th>
            <th style="width:140px;">所属栏目</th>
            <th style="width:80px;text-align:center;">状态</th>
            <th style="width:140px;">发布时间</th>
            <th style="width:156px;text-align:center;">操作</th>
        </tr>
    </thead>
    <tbody>
        <?php if (empty($paginatedRows)): ?>
        <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>
        <?php else: ?>
            <?php foreach ($paginatedRows as $row): ?>
                <?php
                $typeVal = intval($row['_type'] ?? 1);
                $statusVal = intval($row['status'] ?? 0);
                $title = htmlspecialchars($row['title'] ?? '', ENT_QUOTES, 'UTF-8');
                $cid = intval($row['channel_id'] ?? 0);
                $channelName = htmlspecialchars($channelMap[$cid] ?? '未知栏目', ENT_QUOTES, 'UTF-8');
                $statusLabel = $statusVal === 1
                    ? '<span class="status-badge status-1">已发布</span>'
                    : '<span class="status-badge status-0">待审核</span>';
                $typeLabel = '<span class="type-badge type-' . $typeVal . '">' . htmlspecialchars($typeNames[$typeVal] ?? '未知', ENT_QUOTES, 'UTF-8') . '</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;
                ?>
        <tr data-id="<?php echo $id; ?>" data-type="<?php echo $typeVal; ?>">
            <td class="checkbox-cell"><input type="checkbox" class="row-check"></td>
            <td class="id-cell"><?php echo $id; ?></td>
            <td class="title-cell">
                <?php if ($litpic): ?>
                <img src="<?php echo htmlspecialchars($litpic, ENT_QUOTES, 'UTF-8'); ?>" class="row-thumb">
                <?php endif; ?>
                <a class="title-link" href="javascript:void(0)" onclick="window.open('<?php echo addslashes($viewUrl); ?>', '_blank')" title="预览"><?php echo $title; ?></a>
            </td>
            <td style="text-align:center;"><?php echo $typeLabel; ?></td>
            <td style="color:#64748b;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?php echo $channelName; ?></td>
            <td style="text-align:center;"><?php echo $statusLabel; ?></td>
            <td style="color:#94a3b8;font-size:12px;"><?php echo $time; ?></td>
            <td>
                <div class="action-cell">
                    <button class="btn-browse" onclick="window.open('<?php echo addslashes($viewUrl); ?>', '_blank')" title="浏览">浏览</button>
                    <button class="btn-edit" onclick="location.href='<?php echo addslashes($editUrl); ?>'" title="编辑">编辑</button>
                    <button class="btn-del" onclick="deleteItem(<?php echo $id; ?>, <?php echo $typeVal; ?>)" title="删除">删除</button>
                </div>
            </td>
        </tr>
            <?php endforeach; ?>
        <?php endif; ?>
    </tbody>
</table>

<?php if ($total > 0): ?>
<div class="content-pagination">
    <?php if ($page > 1): ?>
    <a href="javascript:goToPage(<?php echo $page - 1; ?>)">上一页</a>
    <?php endif; ?>

    <?php
    $start = max(1, $page - 2);
    $end = min($totalPages, $page + 2);
    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>';
    }
    ?>

    <?php if ($page < $totalPages): ?>
    <a href="javascript:goToPage(<?php echo $page + 1; ?>)">下一页</a>
    <?php endif; ?>
</div>
<?php endif; ?>
