<?php
/**
 * Manual sweep trigger for the SSL renewal orchestrator. POST-only, root-only.
 * Fired by the "Run sweep now" button on the Network & SSL settings tab.
 *
 * Bypasses the orchestrator_enabled kill switch (the cron driver respects it,
 * but a manual operator-initiated sweep should still run regardless — this is
 * how an operator validates behavior before flipping the cron live).
 */
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'POST only']);
    exit;
}

// Permission gate — same group as the rest of server-settings actions.
check_api_permission('server-settings');

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

$MySQLMgmt = new mysqlmgmt();
$db = $MySQLMgmt->getMySQLConnection();
if (!$db) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

$started_at = microtime(true);

try {
    $orch = new ssl_renewal_orchestrator($db);
    $counts = $orch->runSweep(500);
    $elapsed = round(microtime(true) - $started_at, 2);
    error_log("ssl-orchestrator-sweep: manual sweep complete in {$elapsed}s — " . json_encode($counts));
    echo json_encode([
        'status' => 'success',
        'counts' => $counts,
        'elapsed_s' => $elapsed,
    ]);
} catch (Throwable $e) {
    error_log("ssl-orchestrator-sweep: exception — " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Sweep failed: ' . $e->getMessage(),
    ]);
}
