<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */
$action = isset($_GET['action']) ? $_GET['action'] : 'list';
require_once ROOT_PATH . 'core/lib/content_workflow.php';
$pageTable = $db->table('page');
$state = cmsNormalizeContentState(trim((string) ($_GET['state'] ?? 'all')));
if (!isset($license) || !is_object($license)) {
    require_once ROOT_PATH . 'core/lib/license.php';
    $license = new \Core\Lib\License();
}
$canUseBuilder = $license->canUseBuilder();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        requireAdminCsrfToken();
        $id = intval($_POST['id']);
        $data = [
            'page_title' => trim($_POST['page_title']),
            'page_content' => $_POST['page_content'],
            'channel_id' => intval($_POST['channel_id']),
            'seo_title' => trim($_POST['seo_title']),
            'seo_keywords' => trim($_POST['seo_keywords']),
            'seo_description' => trim($_POST['seo_description']),
            'sort_order' => intval($_POST['sort_order']),
            'status' => cmsContentSaveStatus($_POST['save_mode'] ?? 'draft'),
            'update_time' => time()
        ];
        if ($id > 0) {
            $db->update('page', $data, 'id = ? AND deleted_at = 0', [$id]);
            addLog('修改', '单页管理', '修改单页 ' . $data['page_title']);
        } else {
            $data['create_time'] = time();
            $db->insert('page', $data);
            addLog('添加', '单页管理', '添加单页 ' . $data['page_title']);
        }
        echo '<script>alert(' . json_encode($data['status'] ? '单页已发布' : '草稿已保存', JSON_UNESCAPED_UNICODE) . ');location.href="?act=page&state=' . ($data['status'] ? 'published' : 'draft') . '"</script>';
        exit;
    }
    if ($action === 'delete') {
        requireAdminCsrfToken(true);
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $id = intval($_POST['id']);
        if ($id <= 0) {
            echo json_encode(['code' => 400, 'msg' => '参数错误']);
            exit;
        }
        $p = $db->fetch("SELECT page_title FROM {$db->table('page')} WHERE id = ?", [$id]);
        if (!$p) {
            echo json_encode(['code' => 404, 'msg' => '单页不存在']);
            exit;
        }
        $db->update('page', ['status' => 0, 'deleted_at' => time(), 'update_time' => time()], 'id = ? AND deleted_at = 0', [$id]);
        addLog('回收', '单页管理', '单页移入回收站 ' . (isset($p['page_title']) ? $p['page_title'] : $id));
        echo json_encode(['code' => 200, 'msg' => '已移入回收站']);
        exit;
    }
    if ($action === 'restore' || $action === 'purge') {
        requireAdminCsrfToken(true);
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $id = intval($_POST['id'] ?? 0);
        if ($action === 'restore') {
            $db->update('page', ['status' => 0, 'deleted_at' => 0, 'update_time' => time()], 'id = ? AND deleted_at > 0', [$id]);
            $message = '已恢复为草稿';
        } else {
            $db->query("DELETE FROM {$db->table('page')} WHERE id = ? AND deleted_at > 0", [$id]);
            $message = '已永久删除';
        }
        addLog($action === 'restore' ? '恢复' : '永久删除', '单页管理', $message . ' ID:' . $id);
        echo json_encode(['code' => 200, 'msg' => $message], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

if ($action === 'list') {
    $pageResult = cmsContentWorkflowPage($db, 'page', $state, $_GET['page'] ?? 1, 20);
    $pages = $pageResult['rows'];
    $page = $pageResult['page'];
    $totalPages = $pageResult['total_pages'];
    $activePageCount = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('page')} WHERE deleted_at = 0")['cnt'] ?? 0);
    $publishedPageCount = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('page')} WHERE deleted_at = 0 AND status = 1")['cnt'] ?? 0);
    $draftPageCount = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('page')} WHERE deleted_at = 0 AND status = 0")['cnt'] ?? 0);
    $trashPageCount = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('page')} WHERE deleted_at > 0")['cnt'] ?? 0);
    ?>
    <div class="page-container fade-in page-list-page">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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></div>
                <div><h1>单页管理</h1><p style="font-size:12px;color:#64748b;margin:0;">管理公司介绍、联系方式等单页内容，不显示摘要卡。</p></div>
            </div>
            <div class="page-actions">
                <a href="?act=page&action=add" class="btn btn-primary"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> 新增单页</a>
            </div>
        </div>
        <nav class="article-subnav page-list-subnav"><a class="article-subnav-link <?php echo $state==='all'?'is-active':''; ?>" href="?act=page&state=all">全部 <?php echo $activePageCount; ?></a><a class="article-subnav-link <?php echo $state==='published'?'is-active':''; ?>" href="?act=page&state=published">已发布 <?php echo $publishedPageCount; ?></a><a class="article-subnav-link <?php echo $state==='draft'?'is-active':''; ?>" href="?act=page&state=draft">草稿 <?php echo $draftPageCount; ?></a><a class="article-subnav-link <?php echo $state==='trash'?'is-active':''; ?>" href="?act=page&state=trash">回收站 <?php echo $trashPageCount; ?></a><span class="page-list-order-note">按排序值从小到大显示</span></nav>
        <div class="content-card">
            <?php if (empty($pages)): ?>
            <div class="empty-state">
                <div class="empty-icon"><svg style="width:40px;height:40px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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="10" y1="12" x2="14" y2="16"/><line x1="14" y1="12" x2="10" y2="16"/></svg></div>
                <h3>暂无单页</h3>
                <p>创建第一个单页</p>
                <a href="?act=page&action=add" class="btn btn-primary">创建单页</a>
            </div>
            <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr><th style="width:50px;">ID</th><th>页面标题</th><th style="width:90px;">状态</th><th style="width:80px;">排序</th><th style="width:300px;">操作</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($pages as $item): ?>
                    <tr>
                        <td class="id-cell"><?php echo $item['id']; ?></td>
                        <td style="font-weight:500;"><?php echo htmlspecialchars($item['page_title']); ?></td>
                        <td><?php if (intval($item['deleted_at'] ?? 0) > 0): ?><span class="badge badge-secondary">回收站</span><?php elseif (intval($item['status']) === 1): ?><span class="badge badge-success">已发布</span><?php else: ?><span class="badge badge-warning">草稿</span><?php endif; ?></td>
                        <td style="font-family:monospace;"><?php echo $item['sort_order']; ?></td>
                        <td>
                            <?php if ($state !== 'trash'): ?>
                            <a href="?act=page&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-primary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg> 编辑</a>
                            <?php if ($canUseBuilder): ?>
                    <a href="<?php echo htmlspecialchars(cmsBuildFrontendUrl('page', intval($item['id']), '', ['builder_edit' => 1, 'builder_window' => 1, 'builder_type' => 'page', 'builder_ref_id' => intval($item['id']), 'builder_token' => cmsBuildBuilderAccessToken('page', intval($item['id']), time() + 7200)]), ENT_QUOTES, 'UTF-8'); ?>" target="_blank" class="btn btn-secondary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg> 装修</a>
                            <?php else: ?>
                            <span class="btn btn-secondary" style="opacity:.55;cursor:not-allowed;" title="模板装修仅限专业版授权用户"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg> 装修需专业版</span>
                            <?php endif; ?>
                            <a href="/public/index.php?m=page&id=<?php echo $item['id']; ?>" target="_blank" class="btn btn-ghost"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg> 预览</a>
                            <a href="javascript:delPage(<?php echo $item['id']; ?>);" class="btn btn-ghost" style="color:#EF4444;">回收</a>
                            <?php else: ?><button class="btn btn-secondary" type="button" onclick="pageWorkflow('restore',<?php echo intval($item['id']); ?>)">恢复</button><button class="btn btn-danger" type="button" onclick="pageWorkflow('purge',<?php echo intval($item['id']); ?>)">永久删除</button><?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
        <?php cmsRenderContentWorkflowPagination('page', $state, $page, $totalPages); ?>
    </div>
    <style>
    .article-subnav{display:flex;gap:12px;margin-bottom:16px;flex-wrap:wrap}.article-subnav-link{padding:10px 16px;border-radius:12px;background:#fff;border:1px solid #e2e8f0;color:#475569;font-weight:600}.article-subnav-link.is-active{background:#eff6ff;border-color:#bfdbfe;color:#2563eb}
    .page-list-page .page-header{padding:16px 20px !important;margin-bottom:14px !important;border-radius:18px !important;box-shadow:0 14px 34px rgba(30,64,175,.16) !important}
    .page-list-subnav{align-items:center;margin-bottom:12px}
    .page-list-order-note{margin-left:auto;color:#64748b;font-size:12px;font-weight:600}
    @media (max-width: 768px){.page-list-order-note{width:100%;margin-left:0}}
    </style>
    <script>
    function delPage(id) {
        if (!confirm('确定移入回收站？')) return;
        fetch('?act=page&action=delete', {
            method:'POST',
            headers:{'Content-Type':'application/x-www-form-urlencoded'},
            body:'id='+id+'&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>'
        })
        .then(function(r){ return r.json(); })
        .then(function(d){
            alert(d.msg || '操作完成');
            if (d.code == 200) location.reload();
        })
        .catch(function(){
            alert('删除请求失败，请检查接口输出');
        });
    }
    function pageWorkflow(action,id){if(action==='purge'&&!confirm('永久删除后无法恢复，确定继续？'))return;fetch('?act=page&action='+action,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id+'&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>'}).then(function(r){return r.json();}).then(function(d){alert(d.msg);if(d.code===200)location.reload();});}
    </script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $defaults = ['id'=>'','page_title'=>'','page_content'=>'','seo_title'=>'','seo_keywords'=>'','seo_description'=>'','sort_order'=>100,'status'=>1,'channel_id'=>intval(isset($_GET['channel_id']) ? $_GET['channel_id'] : 0)];
    if ($action === 'edit' && isset($_GET['id'])) {
        $row = $db->fetch("SELECT * FROM {$db->table('page')} WHERE id = ? AND deleted_at = 0", [intval($_GET['id'])]);
        if (!$row) { echo '<script>alert("单页不存在或已在回收站");location.href="?act=page";</script>'; exit; }
        $editData = array_merge($defaults, $row);
    } else {
        $editData = $defaults;
    }
    $isEdit = $action === 'edit';
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></div>
                <div><h1><?php echo $isEdit ? '编辑单页' : '新增单页'; ?></h1><p style="font-size:12px;color:#64748b;margin:0;">填写页面内容</p></div>
            </div>
            <div class="page-actions"><a href="?act=page" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=page&action=save">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
            <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
            <div class="form-section">
                <div class="form-section-header"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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> 页面信息</div>
                <div class="form-section-body">
                    <div class="form-group">
                        <label>页面标题 <span class="required">*</span></label>
                        <input type="text" name="page_title" class="form-control" value="<?php echo htmlspecialchars($editData['page_title']); ?>" placeholder="请输入页面标题" required>
                    </div>
                    <div class="form-group">
                        <label>所属栏目</label>
                        <select name="channel_id" class="form-control" style="width:auto;">
                            <option value="0">-- 未分类 --</option>
                            <?php
                            $pageChannels = $db->fetchAll("SELECT id, channel_name, parent_id FROM {$db->table('channel')} WHERE channel_type = 3 ORDER BY parent_id ASC, list_order ASC, id ASC");
                            foreach ($pageChannels as $pc) {
                                $sel = ($editData['channel_id'] == $pc['id']) ? ' selected' : '';
                                echo '<option value="' . $pc['id'] . '"' . $sel . '>' . htmlspecialchars($pc['channel_name']) . '</option>';
                            }
                            ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>排序</label>
                        <input type="number" name="sort_order" class="form-control" value="<?php echo $editData['sort_order']; ?>" min="0" style="width:120px;">
                    </div>
                </div>
            </div>
            <div class="form-section">
                <div class="form-section-header"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="9" y1="21" x2="9" y2="9"/></svg> 页面内容</div>
                <div class="form-section-body cms-ueditor-wrap">
                    <textarea id="page_content_editor" name="page_content" data-cms-ueditor data-height="360" aria-label="页面内容"><?php echo htmlspecialchars(isset($editData['page_content']) ? $editData['page_content'] : '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                </div>
            </div>
            <div class="form-section">
                <div class="form-section-header"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg> SEO设置</div>
                <div class="form-section-body">
                    <div class="form-group"><label>SEO标题</label><input type="text" name="seo_title" class="form-control" value="<?php echo htmlspecialchars($editData['seo_title']); ?>" placeholder="留空使用页面标题"></div>
                    <div class="form-group"><label>关键词</label><input type="text" name="seo_keywords" class="form-control" value="<?php echo htmlspecialchars($editData['seo_keywords']); ?>" placeholder="多个关键词用逗号分隔"></div>
                    <div class="form-group"><label>描述</label><textarea name="seo_description" class="form-control" rows="3"><?php echo htmlspecialchars($editData['seo_description']); ?></textarea></div>
                </div>
            </div>
            <div class="form-actions"><button type="submit" name="save_mode" value="draft" class="btn btn-secondary btn-lg">保存草稿</button><button type="submit" name="save_mode" value="publish" class="btn btn-success btn-lg">发布单页</button><a href="?act=page" class="btn btn-secondary btn-lg">取消</a></div>
        </form>
    </div>
    <?php
}
?>
