<?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('ads')} 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('ads')} 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('ads')} 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']);
        $ad_type = intval(isset($_POST['ad_type']) ? $_POST['ad_type'] : 1);
        $content = '';
        if ($ad_type == 1) {
            // 图片：content存图片URL
            $content = trim(isset($_POST['ad_image_url']) ? $_POST['ad_image_url'] : '');
        } elseif ($ad_type == 2) {
            // 文字：content存文字内容
            $content = trim(isset($_POST['ad_text']) ? $_POST['ad_text'] : '');
        } else {
            // 代码
            $content = trim(isset($_POST['ad_code']) ? $_POST['ad_code'] : '');
        }
        $data = [
            'title' => trim($_POST['ad_name']),
            'position_id' => intval($_POST['ad_position']),
            'ads_type' => $ad_type,
            'content' => $content,
            'link' => trim($_POST['ad_link']),
            'is_show' => isset($_POST['is_show']) ? 1 : 0,
            'start_time' => strtotime(isset($_POST['start_time']) ? $_POST['start_time'] : '1970-01-01'),
            'end_time' => strtotime(isset($_POST['end_time']) ? $_POST['end_time'] : '2099-12-31'),
            'create_time' => time()
        ];
        if ($id > 0) {
            unset($data['create_time']);
            $db->update('ads', $data, 'id = ?', [$id]);
            addLog('修改', '广告管理', '修改广告 ' . $data['title']);
        } else {
            $data['create_time'] = time();
            $db->insert('ads', $data);
            addLog('添加', '广告管理', '添加广告 ' . $data['title']);
        }
        echo '<script>alert("保存成功");location.href="?act=ads";</script>';
        exit;
    }
    if ($action === 'delete') {
        $id = intval($_POST['id']);
        $ad = $db->fetch("SELECT title FROM {$db->table('ads')} WHERE id = ?", [$id]);
        $db->delete('ads', 'id = ?', [$id]);
        addLog('删除', '广告管理', '删除广告 ' . (isset($ad['title']) ? $ad['title'] : $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }
    if ($action === 'toggle') {
        header('Content-Type: application/json');
        $id = intval(isset($_POST['id']) ? $_POST['id'] : 0);
        $is_show = intval(isset($_POST['is_show']) ? $_POST['is_show'] : 0);
        $db->update('ads', ['is_show' => $is_show], 'id = ?', [$id]);
        echo json_encode(['code' => 200, 'msg' => '更新成功']);
        exit;
    }
}

if ($action === 'list') {
    $keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $pageSize = 15;
    $where = '1=1';
    $params = [];
    if (!empty($keyword)) {
        $where .= ' AND title LIKE ?';
        $params[] = '%' . $keyword . '%';
    }
    $offset = ($page - 1) * $pageSize;
    $lists = $db->fetchAll("SELECT * FROM {$db->table('ads')} WHERE {$where} ORDER BY id DESC LIMIT {$offset}, {$pageSize}", $params);
    $total = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('ads')} WHERE {$where}", $params)['cnt'];
    $totalPages = ceil($total / $pageSize);
    $totalAds = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('ads')}")['cnt'];
    $activeAds = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('ads')} WHERE is_show = 1")['cnt'];
    $typeNames = [1 => '图片', 2 => '文字', 3 => '代码'];
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div>
                <h2><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 11l18-5v12L3 13v-2z"/><path d="M11.6 16.8a3 3 0 1 1-5.8-1.6"/></svg> 广告管理</h2>
                <p style="font-size:13px;color:var(--text-light);margin:4px 0 0 0;">管理网站广告位，支持图片、文字、代码三种类型</p>
            </div>
            <div><a href="?act=ads&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>
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-header"><div class="stat-label">广告总数</div><div class="stat-icon blue"><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>
                <div class="stat-value"><?php echo $totalAds; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-header"><div class="stat-label">展示中</div><div class="stat-icon green"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></div></div>
                <div class="stat-value"><?php echo $activeAds; ?></div>
            </div>
        </div>
        <div class="filter-bar">
            <form method="get" style="display:flex;gap:8px;align-items:center;">
                <input type="hidden" name="act" value="ads">
                <input type="text" name="keyword" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="搜索广告名称" style="padding:8px 12px;border:1px solid var(--border);border-radius:var(--radius);font-size:13px;width:200px;">
                <button type="submit" class="btn btn-sm btn-secondary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg></i> 搜索</button>
                <?php if ($keyword): ?>
                <a href="?act=ads" class="btn btn-sm btn-ghost"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg> 清除</a>
                <?php endif; ?>
            </form>
        </div>
        <div class="content-card">
            <?php if (empty($lists)): ?>
            <div class="empty-state"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 11l18-5v12L3 13v-2z"/><path d="M11.6 16.8a3 3 0 1 1-5.8-1.6"/></svg><h3>暂无广告</h3><p>点击添加按钮创建第一个广告</p></div>
            <?php else: ?>
            <table class="data-table">
                <thead>
                    <tr>
                        <th style="width:50px;">ID</th>
                        <th>标题</th>
                        <th style="width:80px;">类型</th>
                        <th style="width:120px;">广告位置</th>
                        <th style="width:150px;">链接</th>
                        <th style="width:60px;">排序</th>
                        <th style="width:100px;">状态</th>
                        <th style="width:250px;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($lists as $item): ?>
                    <?php
                    $flags = !empty($item['flag']) ? explode(',', $item['flag']) : [];
                    ?>
                    <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['title']); ?></td>
                        <td style="font-size:12px;color:#64748b;"><?php echo htmlspecialchars($item['position_id'] ?: '-'); ?></td>
                        <td><span class="badge badge-gray"><?php echo isset($typeNames[$item['ads_type']]) ? $typeNames[$item['ads_type']] : '图片'; ?></span></td>
                        <td style="font-size:12px;color:#64748b;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?php echo $item['link'] ? '<a href="'.$item['link'].'" target="_blank" style="color:#2563eb;">查看</a>' : '-'; ?></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-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:delLink(<?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 if ($totalPages > 1): ?>
            <div style="padding:16px;text-align:center;">
                <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                <a href="?act=ads&page=<?php echo $p; ?>&keyword=<?php echo urlencode($keyword); ?>" class="btn btn-sm <?php echo $p == $page ? 'btn-primary' : 'btn-secondary'; ?>" style="margin:0 2px;"><?php echo $p; ?></a>
                <?php endfor; ?>
            </div>
            <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
    <script>
    function delAd(id) { if(confirm('确定删除该广告？')) { fetch('?act=ads&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=ads&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
    exit;
}

if ($action === 'add' || $action === 'edit') {
    $editData = ['id'=>'','ad_name'=>'','ad_position'=>'','ad_type'=>1,'content'=>'','link'=>'','is_show'=>1,'start_time'=>'','end_time'=>''];
    if ($action === 'edit' && isset($_GET['id']) && intval($_GET['id']) > 0) {
        $row = $db->fetch("SELECT * FROM {$db->table('ads')} WHERE id = ?", [intval($_GET['id'])]);
        if ($row) {
            $editData = ['id'=>$row['id'],'ad_name'=>isset($row['title']) ? $row['title'] : '','ad_position'=>isset($row['position_id']) ? $row['position_id'] : '','ad_type'=>isset($row['ads_type']) ? $row['ads_type'] : 1,'content'=>isset($row['content']) ? $row['content'] : '','link'=>isset($row['link']) ? $row['link'] : '','is_show'=>isset($row['is_show']) ? $row['is_show'] : 1,'start_time'=>$row['start_time'] ? date('Y-m-d', $row['start_time']) : '','end_time'=>$row['end_time'] ? date('Y-m-d', $row['end_time']) : ''];
        }
    }
    $isEdit = $action === 'edit';
    $currentType = $editData['ad_type'];
    ?>
    <div class="page-container fade-in">
        <div class="page-header">
            <div>
                <h2><svg style="width:22px;height:22px;color:var(--primary);margin-right:8px;" 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> <?php echo $isEdit ? '编辑广告' : '添加广告'; ?></h2>
                <p style="font-size:13px;color:var(--text-light);margin:4px 0 0 0;">支持图片广告、文字广告、代码广告三种类型</p>
            </div>
            <div><a href="?act=ads" class="btn btn-secondary"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg> 返回列表</a></div>
        </div>
        <div class="content-card">
            <form method="post" action="?act=ads&action=save" id="adForm" enctype="multipart/form-data">
                <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
                <div style="padding:20px;">
                    <!-- 基本信息 -->
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px;">
                        <div class="form-group">
                            <label style="font-size:13px;font-weight:500;color:var(--text);margin-bottom:6px;display:block;">广告名称 <span style="color:red;">*</span></label>
                            <input type="text" name="ad_name" value="<?php echo htmlspecialchars($editData['ad_name']); ?>" placeholder="请输入广告名称" required style="width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:var(--radius);font-size:14px;box-sizing:border-box;">
                        </div>
                        <div class="form-group">
                            <label style="font-size:13px;font-weight:500;color:var(--text);margin-bottom:6px;display:block;">广告位置</label>
                            <input type="text" name="ad_position" value="<?php echo htmlspecialchars($editData['ad_position']); ?>" placeholder="如：首页横幅、侧边栏广告、弹窗" style="width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:var(--radius);font-size:14px;box-sizing:border-box;">
                        </div>
                    </div>

                    <!-- 广告类型切换 -->
                    <div class="form-group">
                        <label style="font-size:13px;font-weight:500;color:var(--text);margin-bottom:8px;display:block;">广告类型</label>
                        <div style="display:flex;gap:8px;">
                            <label class="ad-type-btn <?php echo $currentType == 1 ? 'active' : ''; ?>" onclick="switchAdType(1)" style="padding:10px 20px;border:2px solid var(--border);border-radius:var(--radius);cursor:pointer;font-size:14px;font-weight:500;transition:0.2s;display:flex;align-items:center;gap:6px;">
                                <input type="radio" name="ad_type" value="1" <?php echo $currentType == 1 ? 'checked' : ''; ?> style="display:none;"><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> 图片广告
                            </label>
                            <label class="ad-type-btn <?php echo $currentType == 2 ? 'active' : ''; ?>" onclick="switchAdType(2)" style="padding:10px 20px;border:2px solid var(--border);border-radius:var(--radius);cursor:pointer;font-size:14px;font-weight:500;transition:0.2s;display:flex;align-items:center;gap:6px;">
                                <input type="radio" name="ad_type" value="2" <?php echo $currentType == 2 ? 'checked' : ''; ?> style="display:none;"><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> 文字广告
                            </label>
                            <label class="ad-type-btn <?php echo $currentType == 3 ? 'active' : ''; ?>" onclick="switchAdType(3)" style="padding:10px 20px;border:2px solid var(--border);border-radius:var(--radius);cursor:pointer;font-size:14px;font-weight:500;transition:0.2s;display:flex;align-items:center;gap:6px;">
                                <input type="radio" name="ad_type" value="3" <?php echo $currentType == 3 ? 'checked' : ''; ?> style="display:none;"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg> 代码广告
                            </label>
                        </div>
                    </div>

                    <!-- 图片广告内容区 -->
                    <div id="typeImage" style="<?php echo $currentType != 1 ? 'display:none;' : ''; ?>margin-bottom:20px;">
                        <div class="form-group">
                            <label style="font-size:13px;font-weight:500;color:var(--text);margin-bottom:8px;display:block;">广告图片</label>
                            <div style="display:grid;grid-template-columns:240px 1fr;gap:16px;align-items:start;">
                                <div>
                                    <div id="imagePreviewBox" style="width:240px;height:160px;border:2px dashed #d1d5db;border-radius:var(--radius-lg);overflow:hidden;cursor:pointer;background:#fafafa;display:flex;flex-direction:column;align-items:center;justify-content:center;transition:0.15s;" onclick="document.getElementById('ad_image_file').click();" onmouseover="this.style.borderColor='#165DFF';" onmouseout="this.style.borderColor='#d1d5db';">
                                        <?php
                                        $imgUrl = ($currentType == 1) ? (isset($editData['content']) ? $editData['content'] : '') : '';
                                        if ($imgUrl): ?>
                                        <img src="<?php echo htmlspecialchars($imgUrl); ?>" style="width:100%;height:100%;object-fit:cover;" id="imgPreviewTag">
                                        <?php else: ?>
                                        <div style="text-align:center;color:#9ca3af;" id="imgPlaceholder">
                                            <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:13px;">点击上传图片</div>
                                            <div style="font-size:11px;margin-top:2px;">JPG/PNG/GIF/WebP</div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <input type="file" name="ad_image_file" id="ad_image_file" accept="image/*" style="display:none;" onchange="previewLocalImage(this);">
                                    <input type="hidden" name="ad_image_url" id="ad_image_url" value="<?php echo htmlspecialchars($imgUrl); ?>">
                                </div>
                                <div>
                                    <div style="font-size:13px;font-weight:500;color:var(--text);margin-bottom:8px;">或输入图片地址</div>
                                    <input type="text" id="imgUrlInput" value="<?php echo htmlspecialchars($imgUrl); ?>" placeholder="http://..." oninput="updateImagePreview(this.value);" style="width:100%;padding:9px 12px;border:1px solid var(--border);border-radius:var(--radius);font-size:13px;box-sizing:border-box;margin-bottom:8px;">
                                    <div style="font-size:12px;color:var(--text-light);">支持本地图片上传或填入外部图片URL</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 文字广告内容区 -->
                    <div id="typeText" style="<?php echo $currentType != 2 ? 'display:none;' : ''; ?>margin-bottom:20px;">
                        <div class="form-group">
                            <label style="font-size:13px;font-weight:500;color:var(--text);margin-bottom:8px;display:block;">广告文字内容</label>
                            <textarea name="ad_text" id="ad_text_area" placeholder="输入广告文字内容，如：限时优惠，全场8折" style="width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:var(--radius);font-size:14px;resize:vertical;min-height:100px;box-sizing:border-box;"><?php echo $currentType == 2 ? htmlspecialchars(isset($editData['content']) ? $editData['content'] : '') : ''; ?></textarea>
                            <div style="margin-top:8px;display:flex;justify-content:space-between;align-items:center;">
                                <div style="font-size:12px;color:var(--text-light);">支持换行和基本样式</div>
                                <div style="font-size:12px;color:#9ca3af;" id="textCount">0/100字</div>
                            </div>
                        </div>
                    </div>

                    <!-- 代码广告内容区 -->
                    <div id="typeCode" style="<?php echo $currentType != 3 ? 'display:none;' : ''; ?>margin-bottom:20px;">
                        <div class="form-group">
                            <label style="font-size:13px;font-weight:500;color:var(--text);margin-bottom:8px;display:block;">广告代码（HTML/JS）</label>
                            <textarea name="ad_code" id="ad_code_area" placeholder="粘贴HTML或JavaScript代码，如：统计代码、联盟广告代码等" style="width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:var(--radius);font-size:13px;font-family:monospace;resize:vertical;min-height:120px;background:#1f293b;color:#10b981;box-sizing:border-box;"><?php echo $currentType == 3 ? htmlspecialchars(isset($editData['content']) ? $editData['content'] : '') : ''; ?></textarea>
                            <div style="margin-top:6px;font-size:12px;color:var(--text-light);">粘贴第三方广告代码、统计脚本等</div>
                        </div>
                    </div>

                    <!-- 广告链接 -->
                    <div class="form-group">
                        <label style="font-size:13px;font-weight:500;color:var(--text);margin-bottom:6px;display:block;">广告链接（点击跳转地址）</label>
                        <input type="text" name="ad_link" value="<?php echo htmlspecialchars(isset($editData['link']) ? $editData['link'] : ''); ?>" placeholder="http:// 或留空" style="width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:var(--radius);font-size:14px;box-sizing:border-box;">
                    </div>

                    <!-- 时间设置 -->
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:20px;">
                        <div class="form-group">
                            <label style="font-size:13px;font-weight:500;color:var(--text);margin-bottom:6px;display:block;">开始时间</label>
                            <input type="date" name="start_time" value="<?php echo htmlspecialchars($editData['start_time']); ?>" style="width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:var(--radius);font-size:14px;box-sizing:border-box;">
                        </div>
                        <div class="form-group">
                            <label style="font-size:13px;font-weight:500;color:var(--text);margin-bottom:6px;display:block;">结束时间</label>
                            <input type="date" name="end_time" value="<?php echo htmlspecialchars($editData['end_time']); ?>" style="width:100%;padding:10px 12px;border:1px solid var(--border);border-radius:var(--radius);font-size:14px;box-sizing:border-box;">
                        </div>
                    </div>

                    <!-- 显示状态 -->
                    <div class="form-group">
                        <label style="display:flex;align-items:center;gap:12px;cursor:pointer;">
                            <input type="checkbox" name="is_show" value="1" <?php echo $editData['is_show'] ? 'checked' : ''; ?> id="isShowCheck" style="display:none;">
                            <div id="isShowToggle" style="width:44px;height:24px;background:<?php echo $editData['is_show'] ? '#10b981' : '#cbd5e1'; ?>;border-radius:12px;position:relative;transition:0.2s;cursor:pointer;">
                                <div style="width:18px;height:18px;background:#fff;border-radius:50%;position:absolute;top:3px;left:<?php echo $editData['is_show'] ? '23px' : '3px'; ?>;transition:0.2s;box-shadow:0 1px 3px rgba(0,0,0,0.2);"></div>
                            </div>
                            <span style="font-size:14px;color:var(--text);">立即展示该广告</span>
                        </label>
                    </div>

                    <!-- 提交按钮 -->
                    <div style="display:flex;gap:12px;margin-top:8px;">
                        <button type="submit" class="btn btn-primary" style="padding:12px 32px;font-size:15px;"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> 保存广告</button>
                        <a href="?act=ads" class="btn btn-secondary" style="padding:12px 24px;font-size:15px;text-decoration:none;">取消</a>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <style>
    .ad-type-btn { background:#fff; color:var(--text); }
    .ad-type-btn.active { background:var(--primary-bg); color:var(--primary); border-color:var(--primary); }
    .opacity-60 { opacity: 0.6; }
    </style>
    <script>
    function switchAdType(type) {
        document.querySelectorAll('.ad-type-btn').forEach(function(b, i) {
            b.classList.toggle('active', (i + 1) == type);
            b.querySelector('input').checked = (i + 1) == type;
        });
        document.getElementById('typeImage').style.display = type == 1 ? '' : 'none';
        document.getElementById('typeText').style.display = type == 2 ? '' : 'none';
        document.getElementById('typeCode').style.display = type == 3 ? '' : 'none';
        // 更新textarea placeholder
        if (type == 1) {
            document.querySelector('textarea[name="ad_code"]') && (document.querySelector('textarea[name="ad_code"]').value = '');
        } else if (type == 2) {
            document.querySelector('textarea[name="ad_code"]') && (document.querySelector('textarea[name="ad_code"]').value = '');
        } else {
            document.querySelector('textarea[name="ad_code"]') && (document.querySelector('textarea[name="ad_code"]').value = '');
        }
    }
    function previewLocalImage(input) {
        var file = input.files[0];
        if (!file) return;
        var reader = new FileReader();
        reader.onload = function(e) {
            var box = document.getElementById('imagePreviewBox');
            box.innerHTML = '<img src="' + e.target.result + '" style="width:100%;height:100%;object-fit:cover;">';
            document.getElementById('ad_image_url').value = e.target.result;
            document.getElementById('imgUrlInput').value = '';
        };
        reader.readAsDataURL(file);
    }
    function updateImagePreview(url) {
        var box = document.getElementById('imagePreviewBox');
        document.getElementById('ad_image_url').value = url;
        document.getElementById('ad_image_file').value = '';
        if (!url || url.trim() === '') {
            box.innerHTML = '<div style="text-align:center;color:#9ca3af;" id="imgPlaceholder"><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:13px;">点击上传图片</div><div style="font-size:11px;margin-top:2px;">JPG/PNG/GIF/WebP</div></div>';
            return;
        }
        var img = new Image();
        img.onload = function() {
            box.innerHTML = '<img src="' + encodeHTML(url) + '" style="width:100%;height:100%;object-fit:cover;">';
        };
        img.onerror = function() {
            box.innerHTML = '<div style="text-align:center;color:#dc2626;font-size:13px;padding:20px;">图片加载失败<br><span style="font-size:11px;">' + encodeHTML(url.substring(0,50)) + '</span></div>';
        };
        img.src = url;
    }
    function encodeHTML(s) {
        return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }
    // 状态开关
    var isShowCheck = document.getElementById('isShowCheck');
    var isShowToggle = document.getElementById('isShowToggle');
    isShowToggle.addEventListener('click', function() {
        isShowCheck.checked = !isShowCheck.checked;
        var on = isShowCheck.checked;
        isShowToggle.style.background = on ? '#10b981' : '#cbd5e1';
        isShowToggle.querySelector('div').style.left = on ? '23px' : '3px';
    });
    // 文字计数
    var textArea = document.getElementById('ad_text_area');
    if (textArea) {
        textArea.addEventListener('input', function() {
            var cnt = document.getElementById('textCount');
            if (cnt) cnt.textContent = this.value.length + '/100字';
        });
        textArea.dispatchEvent(new Event('input'));
    }
    
    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=ads&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
}
?>


