<?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('link')} 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('link')} 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('link')} 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';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'save') {
        $id = intval($_POST['id']);
        $data = [
            'link_name' => trim($_POST['link_name']),
            'link_url' => trim($_POST['link_url']),
            'link_logo' => trim($_POST['logo']),
            'sort_order' => intval($_POST['sort_order']),
            'status' => isset($_POST['is_show']) ? 1 : 0
        ];
        if (empty($data['link_name']) || empty($data['link_url'])) {
            echo '<script>alert("网站名称和网址不能为空");history.back();</script>';
            exit;
        }
        if ($id > 0) {
            $db->update('link', $data, 'id = ?', [$id]);
            addLog('编辑', '友情链接', '编辑链接 ' . $data['link_name']);
        } else {
            $data['create_time'] = time();
            $db->insert('link', $data);
            addLog('添加', '友情链接', '添加链接 ' . $data['link_name']);
        }
        echo '<script>alert("保存成功");location.href="?act=link"</script>';
        exit;
    }
    if ($action === 'delete') {
        $id = intval($_POST['id']);
        $l = $db->fetch("SELECT link_name FROM {$db->table('link')} WHERE id = ?", [$id]);
        $db->delete('link', 'id = ?', [$id]);
        addLog('删除', '友情链接', '删除链接 ' . (isset($l['link_name']) ? $l['link_name'] : $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
}

if ($action === 'list') {
    $links = $db->fetchAll("SELECT * FROM {$db->table('link')} ORDER BY sort_order ASC, id DESC");
    $totalLinks = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('link')}")['cnt'];
    $activeLinks = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('link')} WHERE is_show = 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="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $totalLinks; ?></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 $activeLinks; ?></div><div class="stat-label">展示中</div></div>
        </div>
    </div>
    <div class="filter-bar">
        <a href="?act=link&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($links)): ?>
        <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"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/><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=link&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:250px;">网址</th><th style="width:100px;">Logo</th><th style="width:60px;">排序</th><th style="width:100px;">状态</th><th style="width:250px;">操作</th></tr>
            </thead>
            <tbody>
                <?php foreach ($links as $item): ?>
                <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><tr>
                    <td class="id-cell"><?php echo $item['id']; ?></td>
                    <td style="font-weight:600;color:#334155;"><?php echo htmlspecialchars($item['link_name']); ?></td>
                    <td style="font-family:monospace;font-size:12px;color:#64748b;word-break:break-all;"><?php echo htmlspecialchars($item['link_url']); ?></td>
                    <td>
                        <?php if (!empty($item['link_logo'])): ?>
                        <img src="<?php echo htmlspecialchars($item['link_logo']); ?>" style="width:80px;height:32px;object-fit:contain;border-radius:4px;border:1px solid #e2e8f0;">
                        <?php else: ?>
                        <span style="color:#94a3b8;font-size:12px;">无Logo</span>
                        <?php endif; ?>
                    </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=link&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-sm btn-primary"><svg style="width:13px;height:13px;" 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:delLink(<?php echo $item['id']; ?>);" class="btn btn-sm btn-ghost" style="color:#EF4444;"><svg style="width:13px;height:13px;" 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 delLink(id) { if (confirm('确定删除?')) { fetch('?act=link&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=link&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') {
    $editData = ['id'=>'','link_name'=>'','link_url'=>'','logo'=>'','sort_order'=>100,'is_show'=>1];
    if ($action === 'edit' && isset($_GET['id'])) {
        $row = $db->fetch("SELECT * FROM {$db->table('link')} WHERE id = ?", [intval($_GET['id'])]);
        if ($row) { $editData = ['id'=>$row['id'],'link_name'=>isset($row['link_name'])?$row['link_name']:'', 'link_url'=>isset($row['link_url'])?$row['link_url']:'', 'logo'=>isset($row['link_logo'])?$row['link_logo']:'', 'sort_order'=>isset($row['sort_order'])?$row['sort_order']:100, 'is_show'=>isset($row['is_show'])?$row['is_show']:1]; }
    }
    $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=link" class="btn btn-secondary">&larr; 返回</a></div>
        </div>
        <form method="post" action="?act=link&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="link_name" class="form-control" value="<?php echo htmlspecialchars($editData['link_name']); ?>" placeholder="如：百度" required>
                    </div>
                    <div class="form-group">
                        <label>网址 <span class="required">*</span></label>
                        <input type="text" name="link_url" class="form-control" value="<?php echo htmlspecialchars($editData['link_url']); ?>" placeholder="https://www.example.com" required>
                    </div>
                    <div class="form-group">
                        <label>Logo URL</label>
                        <div style="display:flex;gap:12px;align-items:center;">
                            <input type="text" name="logo" id="linkLogo" class="form-control" value="<?php echo htmlspecialchars($editData['logo']); ?>" placeholder="Logo图片地址" 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="uploadLogo(this)"></label>
                        </div>
                        <div id="logoPreview" class="upload-preview" style="margin-top:12px;">
                            <?php if (!empty($editData['logo'])): ?>
                            <img src="<?php echo htmlspecialchars($editData['logo']); ?>" style="max-width:200px;max-height:80px;border-radius:4px;">
                            <?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;">输入Logo地址或上传</div></div>
                            <?php endif; ?>
                        </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="is_show" value="1" <?php echo $editData['is_show']?'checked':''; ?> id="stToggle" style="display:none;">
                                <div id="stSwitch" style="width:44px;height:24px;background:<?php echo $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 $editData['is_show']?'23px':'3px'; ?>;transition:all 0.2s;"></div></div>
                                <span id="stLabel" style="font-weight:500;color:<?php echo $editData['is_show']?'#10b981':'#64748b'; ?>;"><?php echo $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=link" 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('linkLogo') && document.getElementById('linkLogo').addEventListener('input', function(e) {
        var pv = document.getElementById('logoPreview');
        if (e.target.value) { pv.innerHTML = '<img src="'+e.target.value+'" style="max-width:200px;max-height:80px;border-radius:4px;">'; }
        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;">输入Logo地址或上传</div></div>'; }
    });
    function uploadLogo(input) {
        if (!input.files[0]) return;
        var fd = new FormData();
        fd.append('file', input.files[0]);
        fetch('?act=upload', {method:'POST',body:fd}).then(r=>r.json()).then(d=>{
            if (d.code == 200) {
                document.getElementById('linkLogo').value = d.data.url;
                document.getElementById('logoPreview').innerHTML = '<img src="'+d.data.url+'" style="max-width:200px;max-height:80px;border-radius:4px;">';
            } 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=link&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
}
?>

