<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));
$slotOptions = article_ad_slot_options();
$typeOptions = article_ad_type_options();
$statusOptions = article_ad_status_options();
$domains = array();
$domainLoadError = '';
$created = isset($_GET['created']) && $_GET['created'] === '1';
$adId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$isEdit = $adId > 0;
$error = '';
$success = '';
$form = array(
    'name' => '',
    'slot' => 'article_top',
    'ad_type' => 'text',
    'content_html' => '',
    'image_url' => '',
    'link_url' => '',
    'status' => 'enabled',
    'sort_order' => 0,
    'domain_ids' => array()
);

try {
    $domains = list_enabled_domain_options();
    $publishedCounts = count_published_contents_by_domain_ids();
    usort($domains, function ($a, $b) use ($publishedCounts) {
        $aPub = isset($publishedCounts[(int)$a['id']]) ? $publishedCounts[(int)$a['id']] : 0;
        $bPub = isset($publishedCounts[(int)$b['id']]) ? $publishedCounts[(int)$b['id']] : 0;
        if ($aPub > 0 && $bPub === 0) return -1;
        if ($aPub === 0 && $bPub > 0) return 1;
        if ($aPub !== $bPub) return $bPub - $aPub;
        return (int)$b['id'] - (int)$a['id'];
    });
} catch (Exception $e) {
    $domainLoadError = $e->getMessage();
}

if ($isEdit) {
    try {
        $existing = find_article_ad_by_id($adId);
        if (!$existing) {
            $error = '未找到对应广告。';
            $isEdit = false;
        } else {
            $form = array_merge($form, $existing);
            $form['domain_ids'] = list_article_ad_domain_ids($adId);
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_csrf();
    $form = normalize_article_ad_data($_POST);
    try {
        if ($isEdit) {
            update_article_ad($adId, $form);
            $success = '广告已保存成功。请前往「内容管理」对相关页面重新静态发布后才会显示。';
        } else {
            $newId = create_article_ad($form);
            redirect('/admin/ad/edit.php?id=' . $newId . '&created=1');
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

if ($created && $success === '') {
    $success = '广告创建成功。请前往「内容管理」对相关页面重新静态发布后才会显示。';
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - <?php echo $isEdit ? '编辑广告' : '新增广告'; ?></title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('ads', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div><h1><?php echo $isEdit ? '编辑广告' : '新增广告'; ?></h1><p>配置文章页广告位、内容类型与排序规则。</p></div>
                <div class="topbar-actions"><a class="btn-ghost" href="/admin/ad/list.php">返回列表</a></div>
            </header>
            <section class="page-card">
                <?php if ($error !== ''): ?><div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);"><strong style="color:#dc2626;">保存失败</strong><p style="margin:0; color:#b91c1c;"><?php echo e($error); ?></p></div><?php endif; ?>
                <?php if ($success !== ''): ?><div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);"><strong style="color:#15803d;">保存成功</strong><p style="margin:0; color:#166534;"><?php echo e($success); ?> <a href="/content.php" style="color:#15803d; text-decoration:underline; margin-left:6px;">前往内容管理 →</a></p></div><?php endif; ?>
                <?php if ($domainLoadError !== ''): ?><div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);"><strong style="color:#dc2626;">域名读取失败</strong><p style="margin:0; color:#b91c1c;"><?php echo e($domainLoadError); ?></p></div><?php endif; ?>
                <form method="post" action="/admin/ad/edit.php<?php echo $isEdit ? '?id=' . $adId : ''; ?>">
                    <?php echo csrf_field(); ?>
                    <div class="form-grid">
                        <div class="input-group"><span>* 广告名称</span><input class="input" type="text" name="name" value="<?php echo e($form['name']); ?>" placeholder="如：文章顶部品牌横幅"></div>
                        <div class="input-group"><span>* 广告位置</span><select class="select" name="slot"><?php foreach ($slotOptions as $key => $label): ?><option value="<?php echo e($key); ?>"<?php echo $form['slot'] === $key ? ' selected' : ''; ?>><?php echo e($label); ?></option><?php endforeach; ?></select></div>
                        <div class="input-group"><span>* 广告类型</span><select class="select" name="ad_type"><?php foreach ($typeOptions as $key => $label): ?><option value="<?php echo e($key); ?>"<?php echo $form['ad_type'] === $key ? ' selected' : ''; ?>><?php echo e($label); ?></option><?php endforeach; ?></select></div>
                        <div class="input-group"><span>* 状态</span><select class="select" name="status"><?php foreach ($statusOptions as $key => $label): ?><option value="<?php echo e($key); ?>"<?php echo $form['status'] === $key ? ' selected' : ''; ?>><?php echo e($label); ?></option><?php endforeach; ?></select></div>
                        <div class="input-group"><span>排序值</span><input class="input" type="number" name="sort_order" value="<?php echo (int)$form['sort_order']; ?>" placeholder="数值越大越靠前"></div>
                        <div class="input-group"><span>图片地址</span><input class="input" type="text" name="image_url" value="<?php echo e($form['image_url']); ?>" placeholder="图片广告时必填"></div>
                        <div class="input-group"><span>跳转链接</span><input class="input" type="text" name="link_url" value="<?php echo e($form['link_url']); ?>" placeholder="图片广告可填写目标链接"></div>
                        <div class="input-group" style="grid-column:1 / -1;">
                            <span>投放域名</span>
                            <?php if (!empty($domains)): ?>
                            <div style="display:flex; gap:8px; margin:8px 0 10px;">
                                <button type="button" class="btn-ghost" style="font-size:12px; padding:4px 12px;" onclick="document.querySelectorAll('.ad-domain-cb').forEach(function(c){c.checked=true;})">全选</button>
                                <button type="button" class="btn-ghost" style="font-size:12px; padding:4px 12px;" onclick="document.querySelectorAll('.ad-domain-cb').forEach(function(c){c.checked=false;})">取消全选</button>
                                <button type="button" class="btn-ghost" style="font-size:12px; padding:4px 12px;" onclick="document.querySelectorAll('.ad-domain-cb[data-pub=\'1\']').forEach(function(c){c.checked=true;});document.querySelectorAll('.ad-domain-cb[data-pub=\'0\']').forEach(function(c){c.checked=false;})">仅选已发布</button>
                            </div>
                            <div style="display:grid; grid-template-columns:repeat(auto-fill,minmax(300px,1fr)); gap:6px; max-height:360px; overflow-y:auto; padding:12px; border:1px solid var(--line); border-radius:12px; background:#fafbfc;">
                                <?php foreach ($domains as $item):
                                    $domId = (int)$item['id'];
                                    $pubCnt = isset($publishedCounts[$domId]) ? (int)$publishedCounts[$domId] : 0;
                                    $checked = in_array($domId, $form['domain_ids'], true);
                                ?>
                                <label style="display:flex; align-items:center; gap:8px; padding:7px 10px; border-radius:8px; cursor:pointer; font-size:13px; background:<?php echo $checked ? 'rgba(79,70,229,0.06)' : '#fff'; ?>; border:1px solid <?php echo $checked ? 'rgba(79,70,229,0.25)' : 'rgba(0,0,0,0.05)'; ?>; transition:all .15s;">
                                    <input class="ad-domain-cb" type="checkbox" name="domain_ids[]" value="<?php echo $domId; ?>" data-pub="<?php echo $pubCnt > 0 ? '1' : '0'; ?>"<?php echo $checked ? ' checked' : ''; ?>>
                                    <span style="flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;"><?php echo e($item['domain']); ?>（<?php echo e($item['site_name']); ?>）</span>
                                    <?php if ($pubCnt > 0): ?>
                                    <span style="flex-shrink:0; font-size:11px; padding:1px 7px; border-radius:6px; background:rgba(34,197,94,0.1); color:#15803d;">已发布 <?php echo $pubCnt; ?></span>
                                    <?php endif; ?>
                                </label>
                                <?php endforeach; ?>
                            </div>
                            <?php else: ?>
                            <div style="color:#94a3b8; font-size:13px; margin-top:6px;">当前暂无可选启用域名。</div>
                            <?php endif; ?>
                            <div style="font-size:12px; color:#94a3b8; margin-top:6px;">留空表示所有域名都可投放；勾选后仅在选中的域名文章页展示。已发布站点优先显示。</div>
                        </div>
                        <div class="input-group" style="grid-column:1 / -1;"><span>广告内容</span><textarea class="input" name="content_html" rows="10" placeholder="文本支持 HTML 代码；JS 广告可直接粘贴脚本代码。\n例如：<div class='ad-box'>...</div> 或 <script>...</script>"><?php echo e($form['content_html']); ?></textarea></div>
                    </div>
                    <div class="topbar-actions" style="justify-content:flex-start; margin-top:18px;"><button class="btn-primary" type="submit"><?php echo $isEdit ? '保存广告' : '创建广告'; ?></button><a class="btn-ghost" href="/admin/ad/list.php">取消</a></div>
                </form>
            </section>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
</body>
</html>
