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

    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)", $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' => isset($_POST['status']) ? 1 : 0,
            'update_time' => time()
        ];
        if ($id > 0) {
            $db->update('download', $data, 'id = ?', [$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 = ?', [$id]);
        addLog('删除', '下载管理', '删除下载 ' . ((isset($dl['title']) ? $dl['title'] : $id)));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'list') {
    $downloads = $db->fetchAll("SELECT * FROM {$db->table('download')} ORDER BY sort_order ASC");
    $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']; }
    $totalDownloads = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('download')}")['cnt'];
    $activeDownloads = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('download')} WHERE status = 1")['cnt'];
    ?>
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="background:#eff6ff;color:#2563eb;"><svg style="width:22px;height:22px;" 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"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $totalDownloads; ?></div><div class="stat-label">下载总数</div></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background:#ecfdf5;color:#10b981;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $activeDownloads; ?></div><div class="stat-label">展示中</div></div>
        </div>
    </div>
    <div class="filter-bar">
        <a href="?act=download&action=add" class="btn btn-primary"><svg style="width:14px;height:14px;" 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></i> 添加下载</a>
    </div>
    <div class="content-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: ?>
        <table class="data-table">
            <thead>
                <tr><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">
                            <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>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
    <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 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
}

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 = ?", [intval($_GET['id'])]);
    }
    $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;">
                            <script src="/public/ueditor/ueditor.config.js"></script>
                            <script src="/public/ueditor/ueditor.all.min.js"></script>
                            <script type="text/plain" id="download_content_editor" name="content" style="width:780px;height:360px;"></script>
                            <script>
                            (function(){
                                var editorContent = <?php echo json_encode(isset($editData['content']) ? $editData['content'] : '', JSON_UNESCAPED_UNICODE); ?>;
                                function initEditor(){
                                    if (!window.UE) { alert('UEditor资源加载失败'); return; }
                                    try { if (UE.instants && UE.instants['download_content_editor']) UE.instants['download_content_editor'].destroy(); } catch(e) {}
                                    window.downloadContentEditor = UE.getEditor('download_content_editor', {
                                        initialFrameWidth: 780,
                                        initialFrameHeight: 360,
                                        autoHeightEnabled: false,
                                        autoFloatEnabled: false,
                                        scaleEnabled: false,
                                        serverUrl: '/public/ueditor/php/controller.php'
                                    });
                                    downloadContentEditor.ready(function(){ downloadContentEditor.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-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" class="btn btn-success btn-lg">OK <?php echo $isEdit?'保存':'添加'; ?></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
}
?>

