<?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';
cmsEnsureContentWorkflowSchema($db, 'image');
$state = cmsNormalizeContentState(trim((string) ($_GET['state'] ?? 'all')));
cmsHandleContentWorkflowRequest($db, 'image', $action);
$keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$pageSize = 15;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        $id = intval($_POST['id']);
        $albumsInput = isset($_POST['albums']) && is_array($_POST['albums']) ? $_POST['albums'] : [];
        $data = [
            'channel_id' => intval($_POST['channel_id'] ?? 0),
            'title' => trim($_POST['title'] ?? ''),
            'litpic' => trim($_POST['litpic'] ?? ''),
            'albums' => json_encode($albumsInput),
            'sort_order' => intval($_POST['sort_order'] ?? 100),
            'status' => cmsContentSaveStatus($_POST['save_mode'] ?? (isset($_POST['status']) ? 'publish' : 'draft')),
            'update_time' => time()
        ];
        if ($id > 0) {
            $db->update('image', $data, 'id = ? AND deleted_at = 0', [$id]);
            addLog('修改', '图片管理', '修改图片 ' . $data['title']);
        } else {
            $data['create_time'] = time();
            $db->insert('image', $data);
            addLog('添加', '图片管理', '添加图片 ' . $data['title']);
        }
        echo '<script>alert("保存成功");location.href="?act=image"</script>';
        exit;
    }
    if ($action === 'delete') {
        $id = intval($_POST['id']);
        $img = $db->fetch("SELECT title FROM {$db->table('image')} WHERE id = ?", [$id]);
        $db->delete('image', 'id = ? AND deleted_at > 0', [$id]);
        addLog('删除', '图片管理', '删除图片 ' . ($img['title'] ?? $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'list') {
    $where = cmsContentStateCondition('', $state);
    $params = [];
    if (!empty($keyword)) {
        $where .= ' AND title LIKE ?';
        $params[] = '%' . $keyword . '%';
    }
    $total = intval($db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('image')} WHERE {$where}", $params)['cnt'] ?? 0);
    $totalPages = max(1, intval(ceil($total / $pageSize)));
    $page = min($page, $totalPages);
    $offset = ($page - 1) * $pageSize;
    $lists = $db->fetchAll("SELECT * FROM {$db->table('image')} WHERE {$where} ORDER BY id DESC LIMIT {$offset}, {$pageSize}", $params);
    $workflowCounts = cmsContentWorkflowCounts($db, 'image');
    ?>
    <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"><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=image&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> 添加图片</a>
            </div>
        </div>
        <?php cmsRenderContentWorkflowNav('image', $state, $workflowCounts); ?>
        <div class="filter-bar">
            <form method="get" style="display:flex;gap:12px;flex-wrap:wrap;align-items:center;">
                <input type="hidden" name="act" value="image">
                <input type="hidden" name="state" value="<?php echo htmlspecialchars($state); ?>">
                <input type="text" name="keyword" class="form-control" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="搜索图片标题..." style="width:200px;">
                <button type="submit" class="btn btn-primary">筛选</button>
                <?php if (!empty($keyword)): ?>
                <a href="?act=image&state=<?php echo urlencode($state); ?>" class="btn btn-secondary">重置</a>
                <?php endif; ?>
            </form>
        </div>
        <div class="content-card">
            <?php if (empty($lists)): ?>
            <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 21H3V3h18v18z"/><path d="M3 3l18 18"/><path d="M9.9 9.9a3 3 0 0 1 2.8 2.8L8.1 17"/><path d="M21 15l-3.5-3.5a3 3 0 0 0-2.8-2.8"/></svg></div>
                <h3>暂无图片</h3>
                <p>添加第一张图片吧</p>
                <a href="?act=image&action=add" class="btn btn-primary">添加图片</a>
            </div>
            <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr><th style="width:50px;">ID</th><th style="width:60px;">图片</th><th>图片标题</th><th style="width:140px;">上传时间</th><th style="width:70px;">状态</th><th style="width:200px;">操作</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($lists as $item): ?>
                    <tr data-id="<?php echo $item['id']; ?>">
                        <td class="id-cell"><?php echo $item['id']; ?></td>
                        <td>
                            <?php if ($item['litpic']): ?>
                            <img src="<?php echo htmlspecialchars($item['litpic']); ?>" style="width:44px;height:44px;object-fit:cover;border-radius:4px;cursor:pointer;" onclick="window.open(this.src)">
                            <?php else: ?>
                            <span style="color:#cbd5e1;">—</span>
                            <?php endif; ?>
                        </td>
                        <td style="font-weight:500;"><?php echo htmlspecialchars($item['title']); ?></td>
                        <td style="font-size:12px;color:#64748b;font-family:monospace;"><?php echo $item['create_time'] ? date('Y-m-d H:i', $item['create_time']) : '-'; ?></td>
                        <td>
                            <?php if ($item['status'] == 1): ?>
                            <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=image&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-sm btn-primary">编辑</a><a href="javascript:delImage(<?php echo $item['id']; ?>);" class="btn btn-sm btn-danger">回收</a><?php else: ?><button type="button" class="btn btn-secondary" onclick="imageWorkflow('restore',<?php echo intval($item['id']); ?>)">恢复</button><button type="button" class="btn btn-danger" onclick="imageWorkflow('purge',<?php echo intval($item['id']); ?>)">永久删除</button><?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
        <?php cmsRenderContentWorkflowPagination('image', $state, $page, $totalPages, ['keyword' => $keyword]); ?>
    </div>
    <script>
    function delImage(id) { imageWorkflow('delete', id); }
    function imageWorkflow(action,id){if(action==='delete'&&!confirm('确定移入回收站？'))return;if(action==='purge'&&!confirm('永久删除后无法恢复，确定继续？'))return;fetch('?act=image&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'=>'','channel_id'=>0,'title'=>'','litpic'=>'','sort_order'=>100,'status'=>1];
    if ($action === 'add' && isset($_GET['channel_id'])) {
        $defaults['channel_id'] = intval($_GET['channel_id']);
    }
    $editData = $defaults;
    if ($action === 'edit' && isset($_GET['id'])) {
        $row = $db->fetch("SELECT * FROM {$db->table('image')} WHERE id = ? AND deleted_at = 0", [intval($_GET['id'])]);
        if (!$row) { echo '<script>alert("内容不存在或已在回收站");location.href="?act=image";</script>'; exit; }
        if ($row) { $editData = $row; }
    }
    $isEdit = $action === 'edit';
    $channels = $db->fetchAll("SELECT id, parent_id, channel_name FROM {$db->table('channel')} WHERE channel_type = 4 ORDER BY list_order 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=image" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=image&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"><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 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
                                function renderImageChannelSelect($channels, $parentId = 0, $selected = 0, $depth = 0) {
                                    foreach ($channels as $ch) {
                                        if ($ch['parent_id'] == $parentId) {
                                            $prefix = $depth > 0 ? str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $depth) . '└ ' : '';
                                            echo '<option value="' . $ch['id'] . '"' . ($selected == $ch['id'] ? ' selected' : '') . ' style="font-weight:' . ($depth == 0 ? '600' : '400') . '">' . $prefix . htmlspecialchars($ch['channel_name']) . '</option>';
                                            renderImageChannelSelect($channels, $ch['id'], $selected, $depth + 1);
                                        }
                                    }
                                }
                                renderImageChannelSelect($channels, 0, $editData['channel_id']);
                                ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>相册图片 <span style="color:#94a3b8;font-weight:400;">(多选上传)</span></label>
                        <div id="albumsList" style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:10px;">
                            <?php
                            $existingAlbums = [];
                            if (!empty($editData['albums'])) {
                                $existingAlbums = json_decode($editData['albums'], true);
                                if (is_array($existingAlbums)) {
                                    foreach ($existingAlbums as $ai => $albumUrl): ?>
                            <div class="album-item" style="position:relative;height:80px;border:1px solid #e2e8f0;border-radius:6px;overflow:hidden;">
                                <img src="<?php echo htmlspecialchars($albumUrl); ?>" style="width:100%;height:100%;object-fit:cover;">
                                <input type="hidden" name="albums[]" value="<?php echo htmlspecialchars($albumUrl); ?>">
                                <button type="button" onclick="removeAlbum(this)" style="position:absolute;top:2px;right:2px;width:20px;height:20px;background:rgba(0,0,0,0.6);border:none;border-radius:50%;color:#fff;font-size:12px;cursor:pointer;line-height:20px;">×</button>
                            </div>
                            <?php endforeach; }
                            }
                            ?>
                        </div>
                        <div style="display:flex;gap:8px;flex-wrap:wrap;">
                            <button type="button" onclick="addAlbum()" class="btn btn-secondary btn-sm"><svg style="width:12px;height:12px;" 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> 添加图片</button>
                            <span style="font-size:12px;color:#94a3b8;line-height:28px;">支持 JPG/PNG/GIF/WebP</span>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>封面图</label>
                        <input type="text" name="litpic" id="litpicInput" class="form-control" value="<?php echo htmlspecialchars($editData['litpic'] ?? ''); ?>" placeholder="图片URL或上传">
                        <div style="display:flex;gap:8px;margin-top:8px;">
                            <button type="button" onclick="uploadImage()" class="btn btn-secondary btn-sm"><svg style="width:12px;height:12px;" 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> 上传封面</button>
                            <span id="litpicPreview" style="<?php echo !empty($editData['litpic']) ? '' : 'display:none'; ?>">
                                <img src="<?php echo htmlspecialchars($editData['litpic']); ?>" style="height:40px;border-radius:4px;" onclick="window.open(this.src)">
                            </span>
                        </div>
                    </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=image" class="btn btn-secondary btn-lg">取消</a></div>
        </form>
    </div>
    <script>
    var uploadCount = 0;
    function addAlbum() { var input = document.createElement('input'); input.type = 'file'; input.accept = 'image/*'; input.multiple = true; input.onchange = function() { var files = Array.from(input.files); if (!files.length) return; files.forEach(function(file) { var fd = new FormData(); fd.append('file', file); fd.append('upload_type', 'image'); fd.append('csrf_token', '<?php echo rawurlencode(getAdminCsrfToken()); ?>'); fetch('/admin/main.php?act=upload', {method:'POST', body:fd}).then(r=>r.json()).then(d=>{if(d.code==200){var url=d.data&&d.data.url?d.data.url:d.url; var div = document.createElement('div'); div.className='album-item'; div.style='position:relative;height:80px;border:1px solid #e2e8f0;border-radius:6px;overflow:hidden;'; div.innerHTML='<img src="'+url+'" style="width:100%;height:100%;object-fit:cover;"><input type="hidden" name="albums[]" value="'+url+'"><button type="button" onclick="removeAlbum(this, \'\') " style="position:absolute;top:2px;right:2px;width:20px;height:20px;background:rgba(0,0,0,0.6);border:none;border-radius:50%;color:#fff;font-size:12px;cursor:pointer;line-height:20px;">×</button>'; document.getElementById('albumsList').appendChild(div);}else{alert(d.msg||'上传失败');}}).catch(function(){alert('上传失败');}); }); }; input.click(); }
    function removeAlbum(btn, url) { btn.parentElement.remove(); }
    function uploadImage() { var input = document.createElement('input'); input.type = 'file'; input.accept = 'image/*'; input.onchange = function() { var file = input.files[0]; if (!file) return; var fd = new FormData(); fd.append('file', file); fd.append('upload_type', 'image'); fd.append('csrf_token', '<?php echo rawurlencode(getAdminCsrfToken()); ?>'); fetch('/admin/main.php?act=upload', {method:'POST', body:fd}).then(r=>r.json()).then(d=>{if(d.code==200){var imgUrl=d.data&&d.data.url?d.data.url:d.url; document.getElementById('litpicInput').value=imgUrl; document.getElementById('litpicPreview').style.display=''; document.getElementById('litpicPreview').querySelector('img').src=imgUrl;}else{alert(d.msg||'上传失败');}}).catch(function(){alert('上传失败');}); }; input.click(); }
    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'; }
    });
    </script>
    <?php
}
?>
<script>if (window.lucide && typeof window.lucide.createIcons === 'function') { window.lucide.createIcons(); }</script>
