<?php
// Task 20: AJAX endpoint to bulk-disable multiple sites.
// Root-only, CSRF-validated POST.
// Accepts: site_ids[] (array of integer site IDs), reason (string), note (optional string).
// Returns JSON: { "results": { "<site_id>": { "ok": bool, "error": ?string }, ... } }

header('Content-Type: application/json');

if (!is_root_user()) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'forbidden']);
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method_not_allowed']);
    exit;
}
if (!validate_csrf_token()) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'csrf']);
    exit;
}

require_once('/docker/whp/web/libs/site_disable.php');

$ids    = isset($_POST['site_ids']) ? (array)$_POST['site_ids'] : [];
$reason = (string)($_POST['reason'] ?? '');
$note   = isset($_POST['note']) && $_POST['note'] !== '' ? (string)$_POST['note'] : null;
$actor  = defined('AUTH_USER') ? AUTH_USER : 'unknown';

if (empty($ids)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'no_site_ids']);
    exit;
}

$results = [];
foreach ($ids as $id) {
    $site_id = (int)$id;
    if ($site_id <= 0) {
        $results[$site_id] = ['ok' => false, 'error' => 'invalid_site_id'];
        continue;
    }
    $results[$site_id] = disable_site($site_id, $reason, $actor, $note);
}

echo json_encode(['results' => $results]);
