<?php
/**
 * Disk-usage admin API. Root-only; auto-prepend has already enforced
 * that via permission_manager (this file is registered there as
 * api_permissions['disk-usage'] = ['root']) but we re-check here
 * defense-in-depth.
 *
 *   GET  ?action=snapshot  -> JSON of the latest cached snapshot
 *   POST ?action=refresh   -> take a fresh snapshot synchronously and
 *                             return it
 *
 * The cleanup buttons surfaced on the page POST to /api/disk-cleanup.php
 * (which already exists for the critical-disk banner). This endpoint
 * is read-only / refresh-only.
 */

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

if (!defined('AUTH_USER') || AUTH_USER !== 'root') {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'root only']);
    exit;
}

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

try {
    $mysql = new mysqlmgmt();
    $db = $mysql->getMySQLConnection();
    if (!$db) {
        throw new RuntimeException('MySQL connection failed');
    }
    $db->query("USE whp");

    $action = $_REQUEST['action'] ?? 'snapshot';

    if ($action === 'snapshot') {
        $row = whp_du_load_snapshot($db);
        if ($row === null) {
            echo json_encode([
                'success'     => true,
                'snapshot_at' => null,
                'snapshot'    => null,
                'message'     => 'No snapshot recorded yet. Click Refresh.',
            ]);
            exit;
        }
        echo json_encode([
            'success'     => true,
            'snapshot_at' => $row['snapshot_at'],
            'duration_ms' => $row['duration_ms'],
            'snapshot'    => $row['payload'],
        ]);
        exit;
    }

    if ($action === 'refresh') {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            echo json_encode(['success' => false, 'error' => 'method not allowed']);
            exit;
        }
        $start = microtime(true);
        $payload = whp_du_collect_snapshot();
        $duration_ms = (int) round((microtime(true) - $start) * 1000);
        whp_du_save_snapshot($db, $payload, $duration_ms);
        echo json_encode([
            'success'     => true,
            'snapshot_at' => date('Y-m-d H:i:s'),
            'duration_ms' => $duration_ms,
            'snapshot'    => $payload,
        ]);
        exit;
    }

    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'unknown action: ' . $action]);
} catch (\Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
