<?php
require_once __DIR__ . '/bootstrap.php';

function record_anomaly(PDO $pdo, $severity, $rule, $desc, $actor = null, $ip = null, $meta = []) {
    $stmt = $pdo->prepare("
        INSERT INTO audit_anomalies
        (severity, rule_key, description, actor_user_id, ip_address, meta)
        VALUES
        (:sev, :rule, :desc, :actor, :ip, :meta)
    ");
    $stmt->execute([
        ':sev'   => $severity,
        ':rule'  => $rule,
        ':desc'  => $desc,
        ':actor' => $actor,
        ':ip'    => $ip,
        ':meta'  => json_encode($meta)
    ]);
}

/* =========================
   RULE A — Excessive Actions
   ========================= */
$q = $pdo->query("
    SELECT actor_user_id, COUNT(*) cnt
    FROM audit_logs
    WHERE created_at >= NOW() - INTERVAL 10 MINUTE
    GROUP BY actor_user_id
    HAVING cnt > 50
");

foreach ($q as $row) {
    record_anomaly(
        $pdo,
        'high',
        'admin_action_spike',
        'Excessive admin actions detected',
        $row['actor_user_id'],
        null,
        ['count' => $row['cnt']]
    );
}

/* =========================
   RULE E — Logging Silence
   ========================= */
$q = $pdo->query("
    SELECT COUNT(*) c
    FROM audit_logs
    WHERE created_at >= NOW() - INTERVAL 15 MINUTE
");

if ($q->fetchColumn() == 0) {
    record_anomaly(
        $pdo,
        'high',
        'audit_silence',
        'No audit logs detected in last 15 minutes'
    );
}
