<?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'])) {
        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('slide')} 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('slide')} SET is_show=1, status=1 WHERE id IN ($placeholders)", $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('slide')} SET is_show=0, status=0 WHERE id IN ($placeholders)", $ids);
            echo json_encode(['code'=>200,'msg'=>'已隐藏']); exit;
        }
    }


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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        $id = intval($_POST['id']);
        $data = [
            'group_id' => intval($_POST['group_id']),
            'title' => trim($_POST['title']),
            'litpic' => trim($_POST['litpic']),
            'link' => trim($_POST['link']),
            'target' => trim($_POST['target']) ?: '_self',
            'sort_order' => intval($_POST['sort_order']),
            'is_show' => isset($_POST['is_show']) ? 1 : 0,
            'status' => isset($_POST['is_show']) ? 1 : 0,
            'create_time' => time()
        ];
        if (empty($data['title']) || empty($data['litpic'])) {
            echo '<script>alert("请填写标题和图片");history.back();</script>';
            exit;
        }
        if ($id > 0) {
            $db->update('slide', $data, 'id = ?', [$id]);
            addLog('修改', '幻灯片管理', '修改幻灯片 ' . $data['title']);
            echo '<script>alert("保存成功");location.href="?act=slide";</script>';
        } else {
            $db->insert('slide', $data);
            addLog('添加', '幻灯片管理', '添加幻灯片 ' . $data['title']);
            echo '<script>alert("添加成功");location.href="?act=slide";</script>';
        }
        exit;
    }
    if ($action === 'delete') {
        $id = intval($_POST['id']);
        $s = $db->fetch("SELECT title FROM {$db->table('slide')} WHERE id = ?", [$id]);
        $db->delete('slide', 'id = ?', [$id]);
        addLog('删除', '幻灯片管理', '删除幻灯片 ' . ($s['title'] ?? $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'list') {
    $lists = $db->fetchAll("SELECT s.*, g.group_name FROM {$db->table('slide')} s LEFT JOIN {$db->table('slide_group')} g ON s.group_id=g.id ORDER BY s.sort_order ASC, s.id DESC");
    $totalSlides = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('slide')}")['cnt'];
    $activeSlides = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('slide')} WHERE is_show = 1")['cnt'];
    $groups = $db->fetchAll("SELECT * FROM {$db->table('slide_group')} 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"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></div>
                <div><h1>幻灯片管理</h1><p style="font-size:12px;color:#64748b;margin:0;">后台页面已改为轻量列表，摘要卡不再显示。</p></div>
            </div>
            <div class="page-actions"><a href="?act=slide&action=add" class="btn btn-primary">添加幻灯片</a></div>
        </div>
        <div class="page-context-bar">
            <div class="page-context-item"><span class="page-context-label">幻灯片总数</span><span class="page-context-value"><?php echo $totalSlides; ?> 张</span></div>
            <div class="page-context-item"><span class="page-context-label">展示中</span><span class="page-context-value"><?php echo $activeSlides; ?> 张</span></div>
            <div class="page-context-item"><span class="page-context-label">分组数量</span><span class="page-context-value"><?php echo count($groups); ?> 个</span></div>
            <div class="page-context-item"><span class="page-context-label">支持操作</span><span class="page-context-value page-context-muted">显示、隐藏、删除</span></div>
        </div>
        <div class="filter-bar">
            <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-ghost" style="color:#EF4444;" onclick="batchAction('delete')">批量删除</button>
        </div>
        <div class="content-card">
            <?php if (empty($lists)): ?>
            <div class="empty-state">
                <div class="empty-icon"><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"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></div>
                <h3>暂无幻灯片</h3>
                <p>添加第一张幻灯片</p>
                <a href="?act=slide&action=add" class="btn btn-primary">添加幻灯片</a>
            </div>
            <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr><th style="width:44px;text-align:center;"><input type="checkbox" onclick="toggleCheckAll(this)" style="accent-color:#2563eb;width:16px;height:16px;cursor:pointer;"></th><th style="width:50px;">ID</th><th>标题</th><th style="width:100px;">图片</th><th style="width:200px;">链接</th><th style="width:80px;">分组</th><th style="width:60px;">排序</th><th style="width:100px;">状态</th><th style="width:250px;">操作</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($lists 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 style="font-weight:600;"><?php echo htmlspecialchars($item['title']); ?></td>
                        <td>
                            <?php if ($item['litpic']): ?>
                            <img src="<?php echo htmlspecialchars($item['litpic']); ?>" style="width:60px;height:30px;object-fit:cover;border-radius:4px;">
                            <?php else: ?>
                            <span style="color:#cbd5e1;font-size:12px;">无图</span>
                            <?php endif; ?>
                        </td>
                        <td style="font-family:monospace;font-size:12px;color:#64748b;"><?php echo $item['link'] ? '<a href="'.$item['link'].'" target="_blank" style="color:#2563eb;">查看</a>' : '-'; ?></td>
                        <td style="font-size:12px;color:#64748b;"><?php echo htmlspecialchars($item['group_name'] ?? '-'); ?></td>
                        <td style="font-family:monospace;"><?php echo $item['sort_order']; ?></td>
                        <td>
                            <?php if ($item['is_show']): ?>
                            <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=slide&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:delSlide(<?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>
    </div>
    <style>
    .page-context-bar{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:16px;}
    .page-context-item{background:#fff;border:1px solid #e2e8f0;border-radius:14px;padding:14px 16px;}
    .page-context-label{display:block;font-size:12px;color:#94a3b8;margin-bottom:6px;}
    .page-context-value{display:block;font-size:14px;font-weight:700;color:#1e293b;line-height:1.6;}
    .page-context-muted{color:#475569;font-weight:600;}
    @media (max-width: 1200px){.page-context-bar{grid-template-columns:repeat(2,minmax(0,1fr));}}
    @media (max-width: 768px){.page-context-bar{grid-template-columns:1fr;}}
    </style>
    <script>
    function delSlide(id) { if (confirm('确定删除?')) { fetch('?act=slide&action=delete', {method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:'id='+id}).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=slide&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)));
    }

</script>
    <?php
}

if ($action === 'add' || $action === 'edit') {
    $groups = $db->fetchAll("SELECT * FROM {$db->table('slide_group')} ORDER BY sort_order ASC");
    $editData = ['id'=>'','group_id'=>1,'title'=>'','litpic'=>'','link'=>'','target'=>'_self','sort_order'=>100,'is_show'=>1];
    if ($action === 'edit' && isset($_GET['id'])) {
        $editData = $db->fetch("SELECT * FROM {$db->table('slide')} WHERE id = ?", [intval($_GET['id'])]);
    }
    $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=slide" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=slide&action=save">
            <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="title" class="form-control" value="<?php echo htmlspecialchars($editData['title']); ?>" placeholder="幻灯片标题" required></div>
                    <div class="form-group"><label>图片URL <span class="required">*</span></label><div style="display:flex;gap:12px;align-items:center;"><input type="text" name="litpic" id="slideLitpic" class="form-control" value="<?php echo htmlspecialchars($editData['litpic']); ?>" placeholder="http://..." style="flex:1;"><label class="btn btn-secondary" style="cursor:pointer;"><svg style="width:14px;height:14px;" 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="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg> 上传<input type="file" accept="image/*" style="display:none;" onchange="uploadLitpic(this)"></label></div><div id="slidePreview" class="upload-preview" style="margin-top:12px;"><?php if (!empty($editData['litpic'])): ?><img src="<?php echo htmlspecialchars($editData['litpic']); ?>" style="width:220px;height:110px;object-fit:cover;border-radius:6px;"><?php else: ?><div class="placeholder"><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"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg><div style="font-size:12px;margin-top:4px;">输入图片地址或上传</div></div><?php endif; ?></div></div>
                    <div class="form-group"><label>链接地址</label><input type="text" name="link" class="form-control" value="<?php echo htmlspecialchars($editData['link']); ?>" placeholder="http://..."></div>
                    <div class="form-row">
                        <div class="form-group"><label>分组</label><select name="group_id" class="form-control"><?php foreach ($groups as $g): ?><option value="<?php echo $g['id']; ?>"<?php echo $editData['group_id'] == $g['id'] ? ' selected' : ''; ?>><?php echo htmlspecialchars($g['group_name']); ?></option><?php endforeach; ?></select></div>
                        <div class="form-group"><label>打开方式</label><select name="target" class="form-control"><option value="_self"<?php echo $editData['target']=='_self' ? ' selected' : ''; ?>>本窗口</option><option value="_blank"<?php echo $editData['target']=='_blank' ? ' selected' : ''; ?>>新窗口</option></select></div>
                    </div>
                    <div class="form-row">
                        <div class="form-group"><label>排序</label><input type="number" name="sort_order" class="form-control" value="<?php echo intval($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="is_show" value="1" <?php echo !empty($editData['is_show']) ? 'checked' : ''; ?> id="stToggle" style="display:none;"><div id="stSwitch" style="width:44px;height:24px;background:<?php echo !empty($editData['is_show']) ? '#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 !empty($editData['is_show']) ? '23px' : '3px'; ?>;transition:all 0.2s;"></div></div><span id="stLabel" style="font-weight:500;color:<?php echo !empty($editData['is_show']) ? '#10b981' : '#64748b'; ?>;"><?php echo !empty($editData['is_show']) ? '显示' : '隐藏'; ?></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=slide" 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'; }
    });
    document.getElementById('slideLitpic') && document.getElementById('slideLitpic').addEventListener('input', function(e) {
        var pv = document.getElementById('slidePreview');
        if (e.target.value) { pv.innerHTML = '<img src="'+e.target.value+'" style="width:220px;height:110px;object-fit:cover;border-radius:6px;">'; }
        else { pv.innerHTML = '<div class="placeholder"><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"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg><div style="font-size:12px;margin-top:4px;">输入图片地址或上传</div></div>'; }
    });
    function uploadLitpic(input) {
        if (!input.files[0]) return;
        var fd = new FormData();
        fd.append('file', input.files[0]);
        fd.append('csrf_token', '<?php echo rawurlencode(getAdminCsrfToken()); ?>');
        fetch('?act=upload', {method:'POST',body:fd}).then(r=>r.json()).then(d=>{
            if (d.code == 200) {
                document.getElementById('slideLitpic').value = d.data.url;
                document.getElementById('slidePreview').innerHTML = '<img src="'+d.data.url+'" style="width:220px;height:110px;object-fit:cover;border-radius:6px;">';
            } else { alert(d.msg); }
        });
    }
    
    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=slide&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)));
    }

</script>
    <?php
}
?>
