<?php

function cmsArticleReviewStates()
{
    return ['draft', 'pending', 'approved', 'rejected'];
}

function cmsNormalizeArticleReviewState($state)
{
    $state = strtolower(trim((string) $state));
    return in_array($state, cmsArticleReviewStates(), true) ? $state : 'draft';
}

function cmsCanPublishArticles(array $access)
{
    if (!empty($access['super'])) { return true; }
    $permissions = (array) ($access['permissions'] ?? []);
    return in_array('article', $permissions, true)
        || in_array('article.publish', $permissions, true);
}

function cmsArticleReviewDecision($saveMode, $canPublish, $scheduleAt, $now = null)
{
    $now = $now === null ? time() : intval($now);
    $saveMode = strtolower(trim((string) $saveMode));
    $scheduleAt = max(0, intval($scheduleAt));
    if ($saveMode === 'draft') {
        return ['status' => 0, 'review_status' => 'draft', 'scheduled_publish_at' => 0];
    }
    if (!$canPublish || $saveMode === 'submit') {
        return ['status' => 0, 'review_status' => 'pending', 'scheduled_publish_at' => $scheduleAt > $now ? $scheduleAt : 0];
    }
    if ($saveMode === 'schedule' && $scheduleAt > $now) {
        return ['status' => 0, 'review_status' => 'approved', 'scheduled_publish_at' => $scheduleAt];
    }
    return ['status' => 1, 'review_status' => 'approved', 'scheduled_publish_at' => 0];
}

function cmsArticleReviewLabel($state)
{
    $labels = ['draft' => '草稿', 'pending' => '待审核', 'approved' => '已通过', 'rejected' => '已驳回'];
    return $labels[cmsNormalizeArticleReviewState($state)];
}
