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

function redirect_back($status, $count = 0) {
    $base = '/admin/site-build/index.php?mode=tasklist';
    $params = array('batch_status' => $status, 'batch_action' => 'delete');
    if ($count > 0) { $params['batch_count'] = (int)$count; }
    redirect($base . '&' . http_build_query($params));
}

if (strtoupper(isset($_SERVER['REQUEST_METHOD']) ? (string)$_SERVER['REQUEST_METHOD'] : 'GET') !== 'POST') {
    redirect_back('error');
}

require_csrf();
$action = isset($_POST['batch_action']) ? trim((string)$_POST['batch_action']) : '';
$ids = isset($_POST['ids']) ? $_POST['ids'] : array();
if (!is_array($ids)) { $ids = array(); }
$ids = array_values(array_unique(array_filter(array_map('intval', $ids), function($id){ return $id > 0; })));

if ($action !== 'delete') {
    redirect_back('error');
}
if (empty($ids)) {
    redirect_back('empty');
}

$processed = 0;
try {
    foreach ($ids as $id) {
        if (find_article_generation_task_by_id($id)) {
            delete_article_generation_task($id);
            $processed++;
        }
    }
    redirect_back('success', $processed);
} catch (Exception $e) {
    redirect_back('error');
}
