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

$action = isset($_GET['action']) ? $_GET['action'] : 'list';
$typeNames = [1 => '图片', 2 => '文字', 3 => '代码'];

function uploadAdImageFile($file)
{
    if (empty($file) || !isset($file['error']) || $file['error'] === UPLOAD_ERR_NO_FILE) {
        return null;
    }

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errors = [
            UPLOAD_ERR_INI_SIZE => '上传图片超过服务器限制',
            UPLOAD_ERR_FORM_SIZE => '上传图片超过表单限制',
            UPLOAD_ERR_PARTIAL => '图片上传不完整',
            UPLOAD_ERR_NO_TMP_DIR => '服务器缺少临时目录',
            UPLOAD_ERR_CANT_WRITE => '服务器无法写入图片',
            UPLOAD_ERR_EXTENSION => '图片上传被扩展拦截',
        ];
        throw new Exception($errors[$file['error']] ?? '图片上传失败');
    }

    if ($file['size'] > 5 * 1024 * 1024) {
        throw new Exception('图片大小不能超过 5MB');
    }

    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    if (!in_array($mimeType, $allowedTypes, true)) {
        throw new Exception('仅支持 JPG、PNG、GIF、WebP 格式');
    }

    $uploadDir = dirname(__DIR__) . '/../uploads/' . date('Ymd') . '/';
    $saveResult = cmsStoreUploadedImage($file['tmp_name'], $file['name'], $uploadDir, 'ad', ['apply_watermark' => false]);
    if (!$saveResult['success']) { throw new Exception($saveResult['message'] ?? '图片保存失败'); }
    $newName = $saveResult['filename'];

    $siteUrl = rtrim(getSiteConfig('site_url', 'http://' . ($_SERVER['HTTP_HOST'] ?? 'localhost')), '/');
    return $siteUrl . '/uploads/' . date('Ymd') . '/' . $newName;
}

function normalizeAdPositionId($value)
{
    $value = trim((string) $value);
    return ctype_digit($value) ? intval($value) : 0;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
    requireAdminCsrfToken(true);
    while (ob_get_level() > 0) { ob_end_clean(); }
    header('Content-Type: application/json; charset=utf-8');

    $idsRaw = isset($_POST['ids']) ? $_POST['ids'] : '[]';
    $ids = json_decode($idsRaw, true);
    if (!is_array($ids)) {
        $ids = [];
    }
    $ids = array_values(array_unique(array_filter(array_map('intval', $ids))));

    if (empty($ids)) {
        echo json_encode(['code' => 400, 'msg' => '请先选择要操作的广告']);
        exit;
    }

    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $ajaxAct = $_POST['ajax_action'];

    if ($ajaxAct === 'delete') {
        $db->query("DELETE FROM {$db->table('ads')} WHERE id IN ($placeholders)", $ids);
        addLog('删除', '广告管理', '批量删除广告 ' . count($ids) . ' 条');
        echo json_encode(['code' => 200, 'msg' => '已删除 ' . count($ids) . ' 条广告']);
        exit;
    }

    if ($ajaxAct === 'show' || $ajaxAct === 'hide') {
        $isShow = $ajaxAct === 'show' ? 1 : 0;
        $db->query("UPDATE {$db->table('ads')} SET is_show = ? WHERE id IN ($placeholders)", array_merge([$isShow], $ids));
        addLog($isShow ? '显示' : '隐藏', '广告管理', ($isShow ? '批量显示' : '批量隐藏') . '广告 ' . count($ids) . ' 条');
        echo json_encode(['code' => 200, 'msg' => $isShow ? '已显示所选广告' : '已隐藏所选广告']);
        exit;
    }

    echo json_encode(['code' => 400, 'msg' => '不支持的操作']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAdminCsrfToken(in_array($action, ['delete', 'toggle'], true));
    if ($action === 'save') {
        $id = intval($_POST['id'] ?? 0);
        $adType = intval($_POST['ad_type'] ?? 1);
        $adType = isset($typeNames[$adType]) ? $adType : 1;
        $positionText = trim((string) ($_POST['ad_position'] ?? ''));

        try {
            $content = '';
            if ($adType === 1) {
                $uploadedUrl = uploadAdImageFile($_FILES['ad_image_file'] ?? null);
                $content = trim((string) ($_POST['ad_image_url'] ?? ''));
                if ($uploadedUrl !== null) {
                    $content = $uploadedUrl;
                }
                if ($content === '') {
                    throw new Exception('请上传广告图片或填写图片地址');
                }
            } elseif ($adType === 2) {
                $content = trim((string) ($_POST['ad_text'] ?? ''));
                if ($content === '') {
                    throw new Exception('请填写广告文字内容');
                }
            } else {
                $content = trim((string) ($_POST['ad_code'] ?? ''));
                if ($content === '') {
                    throw new Exception('请填写广告代码内容');
                }
            }
        } catch (Exception $e) {
            echo '<script>alert(' . json_encode($e->getMessage(), JSON_UNESCAPED_UNICODE) . ');history.back();</script>';
            exit;
        }

        $data = [
            'title' => trim((string) ($_POST['ad_name'] ?? '')),
            'ad_name' => trim((string) ($_POST['ad_name'] ?? '')),
            'position_id' => normalizeAdPositionId($positionText),
            'position' => $positionText,
            'ad_position' => $positionText,
            'ads_type' => $adType,
            'ad_type' => $typeNames[$adType],
            'content' => $content,
            'ad_code' => $adType === 3 ? $content : '',
            'link' => trim((string) ($_POST['ad_link'] ?? '')),
            'ad_link' => trim((string) ($_POST['ad_link'] ?? '')),
            'is_show' => isset($_POST['is_show']) ? 1 : 0,
            'status' => isset($_POST['is_show']) ? 1 : 0,
            'start_time' => !empty($_POST['start_time']) ? strtotime((string) $_POST['start_time']) : 0,
            'end_time' => !empty($_POST['end_time']) ? strtotime((string) $_POST['end_time']) : 0,
        ];

        if ($data['title'] === '') {
            echo '<script>alert("广告名称不能为空");history.back();</script>';
            exit;
        }

        if ($id > 0) {
            $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') {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $id = intval($_POST['id'] ?? 0);
        if ($id <= 0) {
            echo json_encode(['code' => 400, 'msg' => '无效的广告ID']);
            exit;
        }
        $ad = $db->fetch("SELECT title FROM {$db->table('ads')} WHERE id = ?", [$id]);
        $db->delete('ads', 'id = ?', [$id]);
        addLog('删除', '广告管理', '删除广告 ' . ($ad['title'] ?? $id));
        echo json_encode(['code' => 200, 'msg' => '删除成功']);
        exit;
    }

    if ($action === 'toggle') {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        $id = intval($_POST['id'] ?? 0);
        $isShow = intval($_POST['is_show'] ?? 0) ? 1 : 0;
        if ($id <= 0) {
            echo json_encode(['code' => 400, 'msg' => '无效的广告ID']);
            exit;
        }
        $db->update('ads', ['is_show' => $isShow, 'status' => $isShow], 'id = ?', [$id]);
        addLog($isShow ? '显示' : '隐藏', '广告管理', ($isShow ? '显示' : '隐藏') . '广告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 ($keyword !== '') {
        $where .= ' AND (title LIKE ? OR ad_position LIKE ? OR position LIKE ?)';
        $params[] = '%' . $keyword . '%';
        $params[] = '%' . $keyword . '%';
        $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 = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('ads')} WHERE {$where}", $params)['cnt'] ?? 0);
    $totalPages = max(1, (int) ceil($total / $pageSize));
    $totalAds = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('ads')}")['cnt'] ?? 0);
    $activeAds = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('ads')} WHERE is_show = 1")['cnt'] ?? 0);
    ?>
    <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">添加广告</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 $totalAds; ?> 个</span></div>
            <div class="page-context-item"><span class="page-context-label">展示中</span><span class="page-context-value"><?php echo $activeAds; ?> 个</span></div>
            <div class="page-context-item"><span class="page-context-label">支持类型</span><span class="page-context-value">图片、文字、代码</span></div>
            <div class="page-context-item"><span class="page-context-label">当前页</span><span class="page-context-value page-context-muted">第 <?php echo $page; ?> / <?php echo $totalPages; ?> 页</span></div>
        </div>
        <div class="filter-bar">
            <form method="get" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
                <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:220px;">
                <button type="submit" class="btn btn-sm btn-secondary">搜索</button>
                <?php if ($keyword !== ''): ?>
                <a href="?act=ads" class="btn btn-sm btn-ghost">清除</a>
                <?php endif; ?>
            </form>
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <button type="button" class="btn btn-sm btn-secondary" onclick="batchAction('show')">批量显示</button>
                <button type="button" class="btn btn-sm btn-secondary" onclick="batchAction('hide')">批量隐藏</button>
                <button type="button" class="btn btn-sm btn-ghost" style="color:#EF4444;" onclick="batchAction('delete')">批量删除</button>
            </div>
        </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: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:140px;">广告位置</th>
                        <th style="width:80px;">类型</th>
                        <th style="width:150px;">链接</th>
                        <th style="width:100px;">状态</th>
                        <th style="width:260px;">操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($lists as $item): ?>
                    <?php $positionLabel = trim((string) ($item['ad_position'] ?: ($item['position'] ?: ''))); ?>
                    <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;color:#334155;"><?php echo htmlspecialchars($item['title']); ?></td>
                        <td style="font-size:12px;color:#64748b;"><?php echo htmlspecialchars($positionLabel !== '' ? $positionLabel : ('位置ID:' . intval($item['position_id']))); ?></td>
                        <td><span class="badge badge-gray"><?php echo htmlspecialchars($typeNames[intval($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 !empty($item['link']) ? '<a href="' . htmlspecialchars($item['link']) . '" target="_blank" style="color:#2563eb;">查看</a>' : '-'; ?></td>
                        <td>
                            <?php if (!empty($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=ads&action=edit&id=<?php echo $item['id']; ?>" class="btn btn-primary">编辑</a>
                                <button type="button" class="btn btn-secondary" onclick="toggleAd(<?php echo $item['id']; ?>, <?php echo !empty($item['is_show']) ? 0 : 1; ?>)"><?php echo !empty($item['is_show']) ? '隐藏' : '显示'; ?></button>
                                <button type="button" class="btn btn-ghost" style="color:#EF4444;" onclick="delAd(<?php echo $item['id']; ?>)">删除</button>
                            </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>
    var adsCsrfToken = <?php echo json_encode(getAdminCsrfToken()); ?>;
    function delAd(id) {
        if (!confirm('确定删除该广告？')) return;
        fetch('?act=ads&action=delete', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'id=' + encodeURIComponent(id) + '&csrf_token=' + encodeURIComponent(adsCsrfToken)
        }).then(function(r) { return r.json(); }).then(function(d) {
            alert(d.msg || '操作完成');
            if (d.code === 200) location.reload();
        }).catch(function() {
            alert('删除失败');
        });
    }
    function toggleAd(id, isShow) {
        fetch('?act=ads&action=toggle', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'id=' + encodeURIComponent(id) + '&is_show=' + encodeURIComponent(isShow) + '&csrf_token=' + encodeURIComponent(adsCsrfToken)
        }).then(function(r) { return r.json(); }).then(function(d) {
            alert(d.msg || '操作完成');
            if (d.code === 200) location.reload();
        }).catch(function() {
            alert('更新失败');
        });
    }
    function toggleCheckAll(cb) {
        document.querySelectorAll('.row-check').forEach(function(item) {
            item.checked = cb.checked;
        });
    }
    function getSelectedIds() {
        var ids = [];
        document.querySelectorAll('.row-check:checked').forEach(function(item) {
            ids.push(item.value);
        });
        return ids;
    }
    function batchAction(action) {
        var ids = getSelectedIds();
        if (ids.length === 0) {
            alert('请先勾选要操作的广告');
            return;
        }
        var confirmText = action === 'delete'
            ? '确定删除选中的 ' + ids.length + ' 个广告？'
            : (action === 'show' ? '确定显示选中的 ' + ids.length + ' 个广告？' : '确定隐藏选中的 ' + ids.length + ' 个广告？');
        if (!confirm(confirmText)) return;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '?act=ads', 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('操作失败');
                }
            }
        };
        xhr.send('ajax_action=' + encodeURIComponent(action) + '&ids=' + encodeURIComponent(JSON.stringify(ids)) + '&csrf_token=' + encodeURIComponent(adsCsrfToken));
    }
    </script>
    <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>
    <?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' && !empty($_GET['id'])) {
        $row = $db->fetch("SELECT * FROM {$db->table('ads')} WHERE id = ?", [intval($_GET['id'])]);
        if ($row) {
            $positionText = trim((string) ($row['ad_position'] ?: ($row['position'] ?: '')));
            if ($positionText === '' && !empty($row['position_id'])) {
                $positionText = (string) intval($row['position_id']);
            }
            $editData = [
                'id' => $row['id'],
                'ad_name' => $row['title'] ?? '',
                'ad_position' => $positionText,
                'ad_type' => intval($row['ads_type'] ?: 1),
                'content' => $row['content'] ?? '',
                'link' => $row['link'] ?? '',
                'is_show' => intval($row['is_show'] ?? 1),
                'start_time' => !empty($row['start_time']) ? date('Y-m-d', $row['start_time']) : '',
                'end_time' => !empty($row['end_time']) ? date('Y-m-d', $row['end_time']) : ''
            ];
        }
    }

    $isEdit = $action === 'edit';
    $currentType = isset($typeNames[intval($editData['ad_type'])]) ? intval($editData['ad_type']) : 1;
    $imgUrl = $currentType === 1 ? (string) $editData['content'] : '';
    ?>
    <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">返回列表</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="csrf_token" value="<?php echo htmlspecialchars(getAdminCsrfToken()); ?>">
                <input type="hidden" name="id" value="<?php echo htmlspecialchars((string) $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;flex-wrap:wrap;">
                            <?php foreach ($typeNames as $typeId => $typeLabel): ?>
                            <label class="ad-type-btn<?php echo $currentType === $typeId ? ' active' : ''; ?>" data-type="<?php echo $typeId; ?>" 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="<?php echo $typeId; ?>" <?php echo $currentType === $typeId ? 'checked' : ''; ?> style="display:none;">
                                <span><?php echo $typeLabel; ?>广告</span>
                            </label>
                            <?php endforeach; ?>
                        </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 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($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 字</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($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($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 !empty($editData['is_show']) ? 'checked' : ''; ?> id="isShowCheck" style="display:none;">
                            <div id="isShowToggle" style="width:44px;height:24px;background:<?php echo !empty($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 !empty($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;flex-wrap:wrap;">
                        <button type="submit" class="btn btn-primary" style="padding:12px 32px;font-size:15px;">保存广告</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); }
    </style>
    <script>
    function switchAdType(type) {
        document.querySelectorAll('.ad-type-btn').forEach(function(btn) {
            var currentType = parseInt(btn.getAttribute('data-type'), 10);
            var input = btn.querySelector('input');
            var active = currentType === type;
            btn.classList.toggle('active', active);
            input.checked = active;
        });
        document.getElementById('typeImage').style.display = type === 1 ? '' : 'none';
        document.getElementById('typeText').style.display = type === 2 ? '' : 'none';
        document.getElementById('typeCode').style.display = type === 3 ? '' : 'none';
    }
    document.querySelectorAll('.ad-type-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            switchAdType(parseInt(btn.getAttribute('data-type'), 10));
        });
    });
    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;">';
        };
        reader.readAsDataURL(file);
    }
    function renderImagePlaceholder() {
        return '<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>';
    }
    function updateImagePreview(url) {
        var box = document.getElementById('imagePreviewBox');
        document.getElementById('ad_image_url').value = url;
        if (!url || url.trim() === '') {
            box.innerHTML = renderImagePlaceholder();
            return;
        }
        box.innerHTML = '<img src="' + encodeHTML(url) + '" style="width:100%;height:100%;object-fit:cover;">';
    }
    function encodeHTML(str) {
        return String(str).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) {
        var syncTextCount = function() {
            var count = document.getElementById('textCount');
            if (count) count.textContent = textArea.value.length + ' 字';
        };
        textArea.addEventListener('input', syncTextCount);
        syncTextCount();
    }
    </script>
    <?php
}
?>
