<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */
$action = isset($_GET['action']) ? $_GET['action'] : 'list';

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']),
            'update_time' => time()
        ];
        if ($id > 0) {
            $db->update('page', $data, 'id = ?', [$id]);
            addLog('修改', '单页管理', '修改单页 ' . $data['page_title']);
        } else {
            $data['create_time'] = time();
            $db->insert('page', $data);
            addLog('添加', '单页管理', '添加单页 ' . $data['page_title']);
        }
        echo '<script>alert("保存成功");location.href="?act=page"</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->delete('page', 'id = ?', [$id]);
        addLog('删除', '单页管理', '删除单页 ' . (isset($p['page_title']) ? $p['page_title'] : $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'list') {
    $pages = $db->fetchAll("SELECT * FROM {$db->table('page')} ORDER BY sort_order ASC");
    ?>
    <div class="page-container fade-in">
        <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>
        <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:80px;">排序</th><th style="width:250px;">操作</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 style="font-family:monospace;"><?php echo $item['sort_order']; ?></td>
                        <td>
                            <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>
                            <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;"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg> 删除</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
    <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('删除请求失败，请检查接口输出');
        });
    }
    </script>
    <?php
}

// 检查 page 表是否有 channel_id 字段，没有则添加
$cols = $db->fetchAll("SHOW COLUMNS FROM {$db->table('page')}");
$colNames = array_column($cols, 'Field');
if (!in_array('channel_id', $colNames)) {
    $db->query("ALTER TABLE {$db->table('page')} ADD COLUMN channel_id INT UNSIGNED NOT NULL DEFAULT 0 AFTER sort_order");
}

if ($action === 'add' || $action === 'edit') {
    $defaults = ['id'=>'','page_title'=>'','page_content'=>'','seo_title'=>'','seo_keywords'=>'','seo_description'=>'','sort_order'=>100,'channel_id'=>intval(isset($_GET['channel_id']) ? $_GET['channel_id'] : 0)];
    if ($action === 'edit' && isset($_GET['id'])) {
        $editData = array_merge($defaults, $db->fetch("SELECT * FROM {$db->table('page')} WHERE id = ?", [intval($_GET['id'])]));
    } 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">
                    <script src="/public/ueditor/ueditor.config.js"></script>
                    <script src="/public/ueditor/ueditor.all.min.js"></script>
                    <script type="text/plain" id="page_content_editor" name="page_content" style="width:780px;height:360px;"></script>
                    <script>
                    (function(){
                        var editorContent = <?php echo json_encode(isset($editData['page_content']) ? $editData['page_content'] : '', JSON_UNESCAPED_UNICODE); ?>;
                        function initEditor(){
                            if (!window.UE) { alert('UEditor资源加载失败'); return; }
                            try { if (UE.instants && UE.instants['page_content_editor']) UE.instants['page_content_editor'].destroy(); } catch(e) {}
                            window.pageContentEditor = UE.getEditor('page_content_editor', {
                                initialFrameWidth: 780,
                                initialFrameHeight: 360,
                                autoHeightEnabled: false,
                                autoFloatEnabled: false,
                                scaleEnabled: false,
                                serverUrl: '/public/ueditor/php/controller.php'
                            });
                            pageContentEditor.ready(function(){ pageContentEditor.setContent(editorContent || ''); });
                        }
                        if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initEditor); else setTimeout(initEditor, 0);
                    })();
                    </script>
                    <style>
                    .cms-ueditor-wrap{overflow:visible !important;padding:20px !important;box-sizing:border-box;height:500px !important;margin:0 !important;display:block;}
                    .cms-ueditor-wrap .edui-editor{display:block !important;width:780px !important;max-width:780px !important;box-sizing:border-box;}
                    .cms-ueditor-wrap .edui-editor-toolbarbox,.cms-ueditor-wrap .edui-editor-iframeholder{width:780px !important;max-width:780px !important;box-sizing:border-box;}
                    </style>
                </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" class="btn btn-success btn-lg">OK <?php echo $isEdit?'保存':'创建'; ?></button><a href="?act=page" class="btn btn-secondary btn-lg">取消</a></div>
        </form>
    </div>
    <?php
}
?>

