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

function cascade_delete_domain_data($pdo, $domainId)
{
    $domainId = (int)$domainId;
    if ($domainId <= 0) return;

    // 1. 删除内容的静态文件
    $contentStmt = $pdo->prepare('SELECT id, domain_id, template_id, path, static_file_path FROM contents WHERE domain_id = :did');
    $contentStmt->execute(array(':did' => $domainId));
    $contents = $contentStmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($contents as $c) {
        try { remove_content_static($c); } catch (Exception $e) {}
    }

    // 2. 收集内容ID，删除关联表
    $contentIds = array_map(function($c) { return (int)$c['id']; }, $contents);
    if (!empty($contentIds)) {
        $ph = implode(',', array_fill(0, count($contentIds), '?'));
        $pdo->prepare('DELETE FROM content_menu_relations WHERE content_id IN (' . $ph . ')')->execute($contentIds);
        $pdo->prepare('DELETE FROM content_tags WHERE content_id IN (' . $ph . ')')->execute($contentIds);
    }

    // 3. 删除内容
    $pdo->prepare('DELETE FROM contents WHERE domain_id = :did')->execute(array(':did' => $domainId));

    // 4. 删除菜单
    $pdo->prepare('DELETE FROM menus WHERE domain_id = :did')->execute(array(':did' => $domainId));

    // 5. 删除标签
    $pdo->prepare('DELETE FROM tags WHERE domain_id = :did')->execute(array(':did' => $domainId));

    // 6. 删除广告关联
    $pdo->prepare('DELETE FROM article_ad_domains WHERE domain_id = :did')->execute(array(':did' => $domainId));

    // 7. 删除任务关联
    $pdo->prepare('DELETE FROM article_generation_task_domains WHERE domain_id = :did')->execute(array(':did' => $domainId));

    // 8. 删除发布日志
    $pdo->prepare('DELETE FROM publish_logs WHERE domain_id = :did')->execute(array(':did' => $domainId));
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}
require_csrf();

$isBatch = !empty($_POST['batch']);

if ($isBatch) {
    $ids = isset($_POST['ids']) && is_array($_POST['ids']) ? $_POST['ids'] : array();
    $ids = array_filter(array_map('intval', $ids), function ($v) { return $v > 0; });
    $ids = array_values(array_unique($ids));

    if (empty($ids)) {
        redirect('/admin/domain/list.php?delete_status=invalid');
    }

    try {
        $pdo = db_connection();
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $findStmt = $pdo->prepare('SELECT id, domain FROM domains WHERE id IN (' . $placeholders . ')');
        $findStmt->execute($ids);
        $rows = $findStmt->fetchAll(PDO::FETCH_ASSOC);

        if (empty($rows)) {
            redirect('/admin/domain/list.php?delete_status=missing');
        }

        foreach ($ids as $did) {
            cascade_delete_domain_data($pdo, (int)$did);
        }

        $delStmt = $pdo->prepare('DELETE FROM domains WHERE id IN (' . $placeholders . ')');
        $delStmt->execute($ids);

        $names = array();
        foreach ($rows as $r) { $names[] = $r['domain']; }
        log_admin_action('domain_batch_delete', '批量删除 ' . count($rows) . ' 个域名（含关联数据）: ' . implode(', ', $names));

        redirect('/admin/domain/list.php?delete_status=success&deleted_domain=' . urlencode('共 ' . count($rows) . ' 个域名（' . implode(', ', $names) . '）'));
    } catch (Exception $e) {
        redirect('/admin/domain/list.php?delete_status=error');
    }
}

$domainId = isset($_POST['id']) ? (int)$_POST['id'] : 0;

if ($domainId <= 0) {
    redirect('/admin/domain/list.php?delete_status=invalid');
}

try {
    $pdo = db_connection();

    $findStmt = $pdo->prepare('SELECT domain FROM domains WHERE id = :id LIMIT 1');
    $findStmt->execute(array(':id' => $domainId));
    $row = $findStmt->fetch();

    if (!$row) {
        redirect('/admin/domain/list.php?delete_status=missing');
    }

    cascade_delete_domain_data($pdo, $domainId);

    $deleteStmt = $pdo->prepare('DELETE FROM domains WHERE id = :id LIMIT 1');
    $deleteStmt->execute(array(':id' => $domainId));
    log_admin_action('domain_delete', '删除域名 ID:' . $domainId . ' 域名:' . $row['domain'] . '（含关联数据）');

    redirect('/admin/domain/list.php?delete_status=success&deleted_domain=' . urlencode($row['domain']));
} catch (Exception $e) {
    redirect('/admin/domain/list.php?delete_status=error');
}
