<?php

function cmsNormalizeContentState($state, $supportsSchedule = false)
{
    $states = ['all', 'published', 'draft', 'trash'];
    if ($supportsSchedule) { $states[] = 'scheduled'; }
    return in_array($state, $states, true) ? $state : 'all';
}

function cmsContentStateCondition($alias, $state, $supportsSchedule = false)
{
    $alias = preg_match('/^[a-z][a-z0-9_]*$/i', (string) $alias) ? $alias . '.' : '';
    $state = cmsNormalizeContentState($state, $supportsSchedule);
    if ($state === 'trash') { return $alias . 'deleted_at > 0'; }
    $condition = $alias . 'deleted_at = 0';
    if ($state === 'published') { $condition .= ' AND ' . $alias . 'status = 1'; }
    if ($state === 'draft') {
        $condition .= ' AND ' . $alias . 'status = 0';
        if ($supportsSchedule) { $condition .= ' AND ' . $alias . 'scheduled_publish_at = 0'; }
    }
    if ($supportsSchedule && $state === 'scheduled') { $condition .= ' AND ' . $alias . 'status = 0 AND ' . $alias . 'scheduled_publish_at > 0'; }
    return $condition;
}

function cmsContentSaveStatus($value)
{
    return (string) $value === 'publish' ? 1 : 0;
}

function cmsEnsureContentWorkflowSchema($db, $table)
{
    return true;
}

function cmsApplyBatchContentWorkflow($db, $table, $action, array $ids)
{
    $ids = array_values(array_unique(array_filter(array_map('intval', $ids))));
    if (!$ids) { return ['success' => false, 'message' => '请选择要操作的内容']; }
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $fullTable = $db->table($table);
    $now = time();
    if ($action === 'delete') {
        $db->query("UPDATE {$fullTable} SET status=0, deleted_at=?, update_time=? WHERE id IN ({$placeholders}) AND deleted_at=0", array_merge([$now, $now], $ids));
        return ['success' => true, 'message' => '已移入回收站 ' . count($ids) . ' 项'];
    }
    if ($action === 'restore') {
        $db->query("UPDATE {$fullTable} SET status=0, deleted_at=0, update_time=? WHERE id IN ({$placeholders}) AND deleted_at>0", array_merge([$now], $ids));
        return ['success' => true, 'message' => '已恢复为隐藏状态 ' . count($ids) . ' 项'];
    }
    if ($action === 'purge') {
        $db->query("DELETE FROM {$fullTable} WHERE id IN ({$placeholders}) AND deleted_at>0", $ids);
        return ['success' => true, 'message' => '已永久删除 ' . count($ids) . ' 项'];
    }
    if ($action === 'show' || $action === 'hide') {
        $status = $action === 'show' ? 1 : 0;
        $db->query("UPDATE {$fullTable} SET status=?, update_time=? WHERE id IN ({$placeholders}) AND deleted_at=0", array_merge([$status, $now], $ids));
        return ['success' => true, 'message' => $status ? '已设为显示' : '已设为隐藏'];
    }
    return ['success' => false, 'message' => '不支持的操作'];
}

function cmsContentWorkflowCounts($db, $table)
{
    $fullTable = $db->table($table);
    $row = $db->fetch("SELECT COUNT(*) AS total, SUM(CASE WHEN status=1 AND deleted_at=0 THEN 1 ELSE 0 END) AS published, SUM(CASE WHEN status=0 AND deleted_at=0 THEN 1 ELSE 0 END) AS draft, SUM(CASE WHEN deleted_at>0 THEN 1 ELSE 0 END) AS trash FROM {$fullTable}");
    return [
        'total' => intval($row['published'] ?? 0) + intval($row['draft'] ?? 0),
        'published' => intval($row['published'] ?? 0),
        'draft' => intval($row['draft'] ?? 0),
        'trash' => intval($row['trash'] ?? 0),
    ];
}

function cmsContentWorkflowPage($db, $table, $state, $page, $pageSize = 20, $orderBy = 'sort_order ASC, id DESC')
{
    $pageSize = max(1, min(100, intval($pageSize)));
    $page = max(1, intval($page));
    $orderBy = preg_match('/^[a-z0-9_.,\s]+$/i', (string) $orderBy) ? $orderBy : 'sort_order ASC, id DESC';
    $fullTable = $db->table($table);
    $condition = cmsContentStateCondition('', $state);
    $total = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$fullTable} WHERE {$condition}")['cnt'] ?? 0);
    $totalPages = max(1, intval(ceil($total / $pageSize)));
    $page = min($page, $totalPages);
    $offset = ($page - 1) * $pageSize;

    return [
        'rows' => $db->fetchAll("SELECT * FROM {$fullTable} WHERE {$condition} ORDER BY {$orderBy} LIMIT {$offset}, {$pageSize}"),
        'total' => $total,
        'page' => $page,
        'page_size' => $pageSize,
        'total_pages' => $totalPages,
    ];
}

function cmsRenderContentWorkflowPagination($act, $state, $page, $totalPages, array $extra = [])
{
    $page = max(1, intval($page));
    $totalPages = max(1, intval($totalPages));
    if ($totalPages <= 1) { return; }
    $base = array_merge(['act' => $act, 'state' => cmsNormalizeContentState($state)], $extra);
    $url = function ($targetPage) use ($base) {
        return '?' . http_build_query(array_merge($base, ['page' => intval($targetPage)]), '', '&', PHP_QUERY_RFC3986);
    };
    echo '<nav class="pagination cms-content-pagination" aria-label="内容分页">';
    if ($page > 1) { echo '<a href="' . htmlspecialchars($url($page - 1), ENT_QUOTES, 'UTF-8') . '">&laquo; 上一页</a>'; }
    for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++) {
        echo '<a href="' . htmlspecialchars($url($i), ENT_QUOTES, 'UTF-8') . '"' . ($i === $page ? ' class="active" aria-current="page"' : '') . '>' . $i . '</a>';
    }
    if ($page < $totalPages) { echo '<a href="' . htmlspecialchars($url($page + 1), ENT_QUOTES, 'UTF-8') . '">下一页 &raquo;</a>'; }
    echo '</nav>';
}

function cmsRenderContentWorkflowNav($act, $state, array $counts, $publishedLabel = '已显示', $draftLabel = '已隐藏')
{
    $items = ['all' => ['全部', $counts['total']], 'published' => [$publishedLabel, $counts['published']], 'draft' => [$draftLabel, $counts['draft']], 'trash' => ['回收站', $counts['trash']]];
    echo '<nav class="article-subnav cms-workflow-nav" aria-label="内容状态">';
    foreach ($items as $key => $item) {
        echo '<a class="article-subnav-link cms-workflow-link' . ($state === $key ? ' is-active' : '') . '"' . ($state === $key ? ' aria-current="page"' : '') . ' href="?act=' . rawurlencode($act) . '&state=' . $key . '">' . htmlspecialchars($item[0]) . ' ' . intval($item[1]) . '</a>';
    }
    echo '</nav><style>.cms-workflow-nav{display:flex;align-items:center;gap:12px;margin:0 0 12px;flex-wrap:wrap}.cms-workflow-link{display:inline-flex;align-items:center;min-height:40px;padding:10px 16px;border:1px solid #e2e8f0;border-radius:12px;background:#fff;color:#475569;font-weight:600;text-decoration:none;box-sizing:border-box}.cms-workflow-link:hover{border-color:#bfdbfe;color:#2563eb}.cms-workflow-link.is-active{background:#eff6ff;border-color:#bfdbfe;color:#2563eb}</style>';
}

function cmsHandleContentWorkflowRequest($db, $table, $action)
{
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { return false; }
    $workflowAction = isset($_POST['ajax_action']) ? trim((string) $_POST['ajax_action']) : trim((string) $action);
    if (!in_array($workflowAction, ['delete', 'restore', 'purge', 'show', 'hide'], true)) { return false; }
    if (function_exists('requireAdminCsrfToken')) { requireAdminCsrfToken(true); }
    $ids = isset($_POST['ajax_action']) ? json_decode((string) ($_POST['ids'] ?? '[]'), true) : [intval($_POST['id'] ?? 0)];
    $ids = is_array($ids) ? $ids : [];
    while (ob_get_level() > 0) { ob_end_clean(); }
    header('Content-Type: application/json; charset=utf-8');
    $result = cmsApplyBatchContentWorkflow($db, $table, $workflowAction, $ids);
    echo json_encode(['code' => $result['success'] ? 200 : 400, 'msg' => $result['message']], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}
