<?php
// api/system_audit.php
// Provides campus-aware staff activity summaries and their audit records.

declare(strict_types=1);
ini_set('display_errors', '0');
error_reporting(E_ALL);
ob_start();
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

function auditRespond(int $status, array $data): void {
    while (ob_get_level() > 0) ob_end_clean();
    http_response_code($status);
    echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
    exit;
}

try {
    require_once __DIR__ . '/../config/database.php';
    require_once __DIR__ . '/session_auth.php';

    if (!isset($pdo) || !($pdo instanceof PDO)) {
        throw new RuntimeException('Database connection is not available.');
    }
    $viewer = rvu_current_user($pdo);
    if (!$viewer) auditRespond(401, ['message' => 'Your session is missing or expired. Please sign in again.']);

    $viewerRole = strtolower(trim((string)($viewer['role'] ?? '')));
    $isAdmin = in_array($viewerRole, ['admin', 'administrator', 'superadmin', 'super_admin'], true);
    $isStaff = $viewerRole === 'staff';
    if (!$isAdmin && !$isStaff) {
        auditRespond(403, ['message' => 'Only administrators and staff can view the system audit trail.']);
    }

    $viewerCampus = trim((string)($viewer['campus'] ?? ''));
    if ($isStaff && $viewerCampus === '') {
        auditRespond(403, ['message' => 'Your staff account has no campus assigned. Contact an administrator.']);
    }

    $view = strtolower(trim((string)($_GET['view'] ?? 'staff')));
    $q = trim((string)($_GET['q'] ?? ''));

    // The first view is a compact directory of staff with today's and this month's totals.
    if ($view === 'staff') {
        $where = ["LOWER(u.role) = 'staff'"];
        $params = [];
        $joinSql = 'LEFT JOIN system_audit_log a ON a.actor_id = u.id';
        $joinParams = [];
        if ($isStaff) {
            $joinSql .= ' AND a.campus = ?';
            $joinParams[] = $viewerCampus;
        }
        if ($isStaff) {
            $where[] = 'u.campus = ?';
            $params[] = $viewerCampus;
        }
        if ($q !== '') {
            $where[] = "(u.full_name ILIKE ? OR COALESCE(u.campus, '') ILIKE ? OR CAST(u.id AS TEXT) ILIKE ?)";
            $like = '%' . $q . '%';
            array_push($params, $like, $like, $like);
        }
        $whereSql = implode(' AND ', $where);
        $sql = "SELECT u.id AS actor_id,
                       u.full_name AS actor_name,
                       LOWER(u.role) AS actor_role,
                       COALESCE(NULLIF(u.campus, ''), 'Campus not assigned') AS campus,
                       COUNT(a.id)::INT AS total_actions,
                       COUNT(a.id) FILTER (WHERE a.created_at >= CURRENT_DATE)::INT AS today_actions,
                       COUNT(a.id) FILTER (WHERE a.created_at >= date_trunc('month', CURRENT_DATE))::INT AS month_actions,
                       MAX(a.created_at) AS last_activity
                FROM users u
                $joinSql
                WHERE $whereSql
                GROUP BY u.id, u.full_name, u.role, u.campus
                ORDER BY MAX(a.created_at) DESC NULLS LAST, u.full_name ASC";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array_merge($joinParams, $params));
        auditRespond(200, ['staff' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    }

    if ($view !== 'events') auditRespond(400, ['message' => 'Unknown audit view.']);

    $actorId = filter_var($_GET['actor_id'] ?? null, FILTER_VALIDATE_INT);
    if (!$actorId || $actorId < 1) auditRespond(400, ['message' => 'Choose a staff member to view their activity.']);

    // Staff viewers can only inspect colleagues assigned to the same campus,
    // and only the activity logged at that campus.
    if ($isStaff) {
        $access = $pdo->prepare("SELECT 1 FROM users WHERE id = ? AND LOWER(role) = 'staff' AND campus = ?");
        $access->execute([$actorId, $viewerCampus]);
        if (!$access->fetchColumn()) auditRespond(403, ['message' => 'You cannot view this staff member’s activity.']);
    }

    $period = strtolower(trim((string)($_GET['period'] ?? 'month')));
    if (!in_array($period, ['day', 'month', 'all'], true)) $period = 'month';
    $page = max(1, (int)($_GET['page'] ?? 1));
    $limit = min(100, max(1, (int)($_GET['limit'] ?? 30)));
    $conditions = ['a.actor_id = ?'];
    $params = [$actorId];
    if ($isStaff) {
        $conditions[] = 'a.campus = ?';
        $params[] = $viewerCampus;
    }
    if ($period === 'day') $conditions[] = 'a.created_at >= CURRENT_DATE';
    if ($period === 'month') $conditions[] = "a.created_at >= date_trunc('month', CURRENT_DATE)";
    if ($q !== '') {
        $conditions[] = '(a.action ILIKE ? OR a.entity ILIKE ? OR a.summary ILIKE ? OR COALESCE(a.campus, \'\') ILIKE ?)';
        $like = '%' . $q . '%';
        array_push($params, $like, $like, $like, $like);
    }
    $whereSql = implode(' AND ', $conditions);

    $count = $pdo->prepare('SELECT COUNT(*) FROM system_audit_log a WHERE ' . $whereSql);
    $count->execute($params);
    $total = (int)$count->fetchColumn();
    $pages = max(1, (int)ceil($total / $limit));
    $page = min($page, $pages);
    $offset = ($page - 1) * $limit;
    $stmt = $pdo->prepare(
        'SELECT a.id, a.actor_id, a.actor_name, a.actor_role, a.campus,
                a.entity, a.record_id, a.action, a.summary, a.ip_address, a.created_at
         FROM system_audit_log a WHERE ' . $whereSql .
        ' ORDER BY a.created_at DESC, a.id DESC LIMIT ' . $limit . ' OFFSET ' . $offset
    );
    $stmt->execute($params);
    auditRespond(200, [
        'records' => $stmt->fetchAll(PDO::FETCH_ASSOC),
        'total' => $total,
        'page' => $page,
        'pages' => $pages,
        'period' => $period,
    ]);
} catch (Throwable $e) {
    error_log('System audit API error: ' . $e->getMessage());
    auditRespond(500, ['message' => 'The audit trail could not be loaded. Check the API and database setup.']);
}
