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

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
        requireAdminCsrfToken(true);
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $ajaxAct = $_POST['ajax_action'];

        if ($ajaxAct === 'delete') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择要删除的项']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("DELETE FROM {$db->table('download')} WHERE id IN ($placeholders) AND deleted_at>0", $ids);
            echo json_encode(['code'=>200,'msg'=>'已删除 '.count($ids).' 项']); exit;
        }

        if ($ajaxAct === 'show') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("UPDATE {$db->table('download')} SET status=1, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $ids));
            echo json_encode(['code'=>200,'msg'=>'已显示']); exit;
        }

        if ($ajaxAct === 'hide') {
            $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
            $ids = json_decode($idsRaw, true);
            if (!is_array($ids)) { $ids = []; }
            $ids = array_map('intval', $ids);
            if (empty($ids)) { echo json_encode(['code'=>400,'msg'=>'请选择']); exit; }
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->query("UPDATE {$db->table('download')} SET status=0, update_time=? WHERE id IN ($placeholders)", array_merge([time()], $ids));
            echo json_encode(['code'=>200,'msg'=>'已隐藏']); exit;
        }
    }


$action = isset($_GET['action']) ? $_GET['action'] : 'list';

function renderDownloadChannelSelect($channels, $parentId, $selected, $depth) {
    foreach ($channels as $ch) {
        if (intval($ch['parent_id']) === intval($parentId)) {
            $prefix = $depth > 0 ? str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $depth) . '└ ' : '';
            echo '<option value="' . intval($ch['id']) . '"' . ($selected == $ch['id'] ? ' selected' : '') . ' style="font-weight:' . ($depth == 0 ? '600' : '400') . '">' . $prefix . htmlspecialchars($ch['channel_name']) . '</option>';
            renderDownloadChannelSelect($channels, $ch['id'], $selected, $depth + 1);
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        requireAdminCsrfToken();
        $id = intval($_POST['id']);
        $data = [
            'title' => trim($_POST['title']),
            'file_path' => trim($_POST['file_path']),
            'channel_id' => intval($_POST['channel_id']),
            'content' => isset($_POST['content']) ? trim($_POST['content']) : '',
            'seo_title' => isset($_POST['seo_title']) ? trim($_POST['seo_title']) : '',
            'seo_keywords' => isset($_POST['seo_keywords']) ? trim($_POST['seo_keywords']) : '',
            'seo_description' => isset($_POST['seo_description']) ? trim($_POST['seo_description']) : '',
            'sort_order' => intval($_POST['sort_order']),
            'status' => cmsContentSaveStatus($_POST['save_mode'] ?? (isset($_POST['status']) ? 'publish' : 'draft')),
            'update_time' => time()
        ];
        if ($id > 0) {
            $db->update('download', $data, 'id = ? AND deleted_at = 0', [$id]);
            addLog('修改', '下载管理', '修改下载 ' . $data['title']);
        } else {
            $data['create_time'] = time();
            $db->insert('download', $data);
            addLog('添加', '下载管理', '添加下载 ' . $data['title']);
        }
        echo '<script>alert("保存成功");location.href="?act=download"</script>';
        exit;
    }
    if ($action === 'delete') {
        requireAdminCsrfToken(true);
        $id = intval($_POST['id']);
        $dl = $db->fetch("SELECT title FROM {$db->table('download')} WHERE id = ?", [$id]);
        $db->delete('download', 'id = ? AND deleted_at > 0', [$id]);
        addLog('删除', '下载管理', '删除下载 ' . ((isset($dl['title']) ? $dl['title'] : $id)));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'list') {
    $pageResult = cmsContentWorkflowPage($db, 'download', $state, $_GET['page'] ?? 1, 20);
    $downloads = $pageResult['rows'];
    $page = $pageResult['page'];
    $totalPages = $pageResult['total_pages'];
    $workflowCounts = cmsContentWorkflowCounts($db, 'download');
    $downloadChannels = $db->fetchAll("SELECT id, channel_name FROM {$db->table('channel')} WHERE channel_type = 5 ORDER BY list_order ASC, id ASC");
    $channelMap = array();
    foreach ($downloadChannels as $ch) { $channelMap[$ch['id']] = $ch['channel_name']; }
    ?>
    <div class="page-container fade-in download-manage-page">
        <div class="page-header">
            <div class="page-title">
                <div class="page-icon"><svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg></div>
                <div><h1>下载管理</h1><p style="font-size:12px;color:#64748b;margin:0;">管理下载文件、栏目归属与显示状态，不显示摘要卡。</p></div>
            </div>
            <div class="page-actions download-page-actions">
                <?php if ($state === 'trash'): ?>
                <button type="button" class="btn btn-secondary" onclick="batchAction('restore')">批量恢复</button>
                <button type="button" class="btn btn-danger" onclick="batchAction('purge')">永久删除</button>
                <?php else: ?>
                <button type="button" class="btn btn-secondary" onclick="batchAction('show')">批量显示</button>
                <button type="button" class="btn btn-secondary" onclick="batchAction('hide')">批量隐藏</button>
                <button type="button" class="btn btn-danger" onclick="batchAction('delete')">批量删除</button>
                <a href="?act=download&action=add" class="btn btn-primary">添加下载</a>
                <?php endif; ?>
            </div>
        </div>
        <?php cmsRenderContentWorkflowNav('download', $state, $workflowCounts); ?>
        <div class="content-card download-list-card">
        <?php if (empty($downloads)): ?>
        <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="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></div>
            <h3>暂无下载</h3>
            <p>添加第一个下载文件</p>
            <a href="?act=download&action=add" class="btn btn-primary">添加下载</a>
        </div>
        <?php else: ?>
        <div style="overflow-x:auto;">
        <table class="data-table download-data-table">
            <thead>
                <tr><th style="width:40px;"><input type="checkbox" id="checkAll" onchange="toggleCheckAll(this)" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></th><th style="width:50px;">ID</th><th>文件名称</th><th style="width:120px;">栏目</th><th style="width:250px;">下载地址</th><th style="width:60px;">排序</th><th style="width:100px;">状态</th><th style="width:250px;">操作</th></tr>
            </thead>
            <tbody>
                <?php foreach ($downloads as $item): ?>
                <tr>
                    <td style="text-align:center;"><input type="checkbox" class="row-check" value="<?php echo $item['id']; ?>" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></td>
                    <td class="id-cell"><?php echo $item['id']; ?></td>
                    <td>
                        <div style="font-weight:600;color:#334155;"><?php echo htmlspecialchars($item['title']); ?></div>
                    </td>
                    <td style="color:#64748b;font-size:13px;"><?php echo isset($channelMap[$item['channel_id']]) ? htmlspecialchars($channelMap[$item['channel_id']]) : '-'; ?></td>
                    <td style="font-family:monospace;font-size:12px;color:#64748b;word-break:break-all;max-width:250px;"><?php echo htmlspecialchars($item['file_path']); ?></td>
                    <td style="font-family:monospace;"><?php echo $item['sort_order']; ?></td>
                    <td>
                        <?php if ($item['status']): ?>
                        <span class="badge badge-success">显示</span>
                        <?php else: ?>
                        <span class="badge badge-secondary">隐藏</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div class="btn-group">
                            <?php if ($state !== 'trash'): ?>
                            <a href="?act=download&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="javascript:delDownload(<?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>
                            <?php else: ?>
                            <button type="button" class="btn btn-secondary" onclick="singleWorkflow('restore',<?php echo intval($item['id']); ?>)">恢复</button>
                            <button type="button" class="btn btn-danger" onclick="singleWorkflow('purge',<?php echo intval($item['id']); ?>)">永久删除</button>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>
    <?php cmsRenderContentWorkflowPagination('download', $state, $page, $totalPages); ?>
    </div>
    <style>
    .download-page-actions{display:flex;gap:10px;flex-wrap:wrap;}
    .download-list-card{border:1px solid #e2e8f0;border-radius:16px;overflow:hidden;box-shadow:0 10px 30px rgba(15,23,42,.05);}
    .download-data-table thead th{background:#f8fafc;color:#64748b;font-size:12px;font-weight:700;}
    .download-data-table tbody tr:hover{background:#fbfdff;}
    </style>
    <script>
    function delDownload(id) { if (confirm('确定删除?')) { fetch('?act=download&action=delete', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id+'&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>'}).then(r=>r.json()).then(d=>{alert(d.msg);if(d.code==200)location.reload();}); } }
    
    function toggleCheckAll(cb) { document.querySelectorAll('.row-check').forEach(function(c){c.checked=cb.checked;}); }
    function getSelectedIds() { var ids=[]; document.querySelectorAll('.row-check:checked').forEach(function(c){ids.push(c.value);}); return ids; }
    function singleWorkflow(action,id) { document.querySelectorAll('.row-check').forEach(function(c){ c.checked=String(c.value)===String(id); }); batchAction(action); }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) { alert('请先勾选要操作的项'); return; }
        if (action === 'delete' && !confirm('确定移入回收站？')) return;
        if (action === 'purge' && !confirm('永久删除后无法恢复，确定继续？')) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=download&action=batch', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try { var d = JSON.parse(xhr.responseText); alert(d.msg||'操作完成'); if(d.code==200) location.reload(); }
                catch(e) { alert('JSON解析失败'); }
            }
        };
        xhr.send('ajax_action=' + action + '&ids=' + encodeURIComponent(JSON.stringify(ids)) + '&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>');
    }

</script>
<?php
}

if ($action === 'add' || $action === 'edit') {
    $editData = ['id'=>'','channel_id'=>0,'title'=>'','file_path'=>'','content'=>'','seo_title'=>'','seo_keywords'=>'','seo_description'=>'','sort_order'=>100,'status'=>1];
    if ($action === 'edit' && isset($_GET['id'])) {
        $editData = $db->fetch("SELECT * FROM {$db->table('download')} WHERE id = ? AND deleted_at = 0", [intval($_GET['id'])]);
        if (!$editData) { echo '<script>alert("内容不存在或已在回收站");location.href="?act=download";</script>'; exit; }
    }
    $isEdit = $action === 'edit';
    $downloadChannels = $db->fetchAll("SELECT id, parent_id, channel_name FROM {$db->table('channel')} WHERE channel_type = 5 ORDER BY list_order ASC, id ASC");
    ?>
    <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=download" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=download&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-row">
                        <div class="form-group" style="flex:1;">
                            <label>文件名称 <span class="required">*</span></label>
                            <input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($editData['title']); ?>" placeholder="请输入文件名称" required>
                        </div>
                        <div class="form-group" style="width:220px;">
                            <label>所属栏目</label>
                            <select name="channel_id" class="form-control" style="padding:6px 8px;">
                                <option value="0">-- 请选择下载栏目 --</option>
                                <?php renderDownloadChannelSelect($downloadChannels, 0, $editData['channel_id'], 0); ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>文件URL <span class="required">*</span></label>
                        <input type="text" name="file_path" class="form-control" value="<?php echo htmlspecialchars($editData['file_path']); ?>" placeholder="http:// 或 /uploads/xxx.zip" required>
                    </div>
                    <div class="form-group">
                        <label>下载说明</label>
                        <div class="cms-ueditor-wrap" style="margin-top:6px;">
                            <textarea id="download_content_editor" name="content" data-cms-ueditor data-height="360" aria-label="下载说明"><?php echo htmlspecialchars(isset($editData['content']) ? $editData['content'] : '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group" style="flex:1;">
                            <label>SEO标题</label>
                            <input type="text" name="seo_title" class="form-control" value="<?php echo htmlspecialchars(isset($editData['seo_title']) ? $editData['seo_title'] : ''); ?>" placeholder="可选">
                        </div>
                        <div class="form-group" style="flex:1;">
                            <label>SEO关键词</label>
                            <input type="text" name="seo_keywords" class="form-control" value="<?php echo htmlspecialchars(isset($editData['seo_keywords']) ? $editData['seo_keywords'] : ''); ?>" placeholder="可选">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>SEO描述</label>
                        <textarea name="seo_description" class="form-control" rows="3" placeholder="可选"><?php echo htmlspecialchars(isset($editData['seo_description']) ? $editData['seo_description'] : ''); ?></textarea>
                    </div>
                    <div class="form-row">
                        <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 class="form-group">
                            <label>&nbsp;</label>
                            <label style="display:flex;align-items:center;gap:12px;cursor:pointer;padding-top:8px;">
                                <input type="checkbox" name="status" value="1" <?php echo $editData['status']?'checked':''; ?> id="stToggle" style="display:none;">
                                <div id="stSwitch" style="width:44px;height:24px;background:<?php echo $editData['status']?'#10b981':'#cbd5e1'; ?>;border-radius:12px;position:relative;transition:all 0.2s;"><div style="width:18px;height:18px;background:#fff;border-radius:50%;position:absolute;top:3px;left:<?php echo $editData['status']?'23px':'3px'; ?>;transition:all 0.2s;"></div></div>
                                <span id="stLabel" style="font-weight:500;color:<?php echo $editData['status']?'#10b981':'#64748b'; ?>;"><?php echo $editData['status']?'显示':'隐藏'; ?></span>
                            </label>
                        </div>
                    </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=download" class="btn btn-secondary btn-lg">取消</a></div>
        </form>
    </div>
    <script>
    document.getElementById('stToggle') && document.getElementById('stToggle').addEventListener('change', function() {
        var sw = document.getElementById('stSwitch');
        var lb = document.getElementById('stLabel');
        if (this.checked) { sw.style.background = '#10b981'; sw.querySelector('div').style.left = '23px'; lb.textContent = '显示'; lb.style.color = '#10b981'; }
        else { sw.style.background = '#cbd5e1'; sw.querySelector('div').style.left = '3px'; lb.textContent = '隐藏'; lb.style.color = '#64748b'; }
    });
    
    function toggleCheckAll(cb) { document.querySelectorAll('.row-check').forEach(function(c){c.checked=cb.checked;}); }
    function getSelectedIds() { var ids=[]; document.querySelectorAll('.row-check:checked').forEach(function(c){ids.push(c.value);}); return ids; }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) { alert('请先勾选要操作的项'); return; }
        if (action === 'delete') {
            if (!confirm('确定删除选中的 ' + ids.length + ' 项？')) return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=download&action=batch', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                try { var d = JSON.parse(xhr.responseText); alert(d.msg||'操作完成'); if(d.code==200) location.reload(); }
                catch(e) { alert('JSON解析失败'); }
            }
        };
        xhr.send('ajax_action=' + action + '&ids=' + encodeURIComponent(JSON.stringify(ids)) + '&csrf_token=<?php echo rawurlencode(getAdminCsrfToken()); ?>');
    }

</script>
    <?php
}
?>
