<?php
require_once __DIR__ . '/../config/user_functions.php';

// JSON-based activity logger with 90-day autoclean
function log_action($user, $action, $target, $details='') {
    $file = __DIR__ . DIRECTORY_SEPARATOR . 'activity_log.json';
    if (!file_exists($file)) {
        file_put_contents($file, json_encode([]));
    }
    $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $entry = [
        'timestamp' => gmdate('Y-m-d H:i:s'),
        'user' => $user ?: 'system',
        'action' => $action,
        'target' => $target,
        'details' => $details,
        'ip' => $ip
    ];
    $fp = fopen($file, 'c+');
    if ($fp) {
        flock($fp, LOCK_EX);
        $size = filesize($file);
        $json = $size > 0 ? fread($fp, $size) : '[]';
        $arr = json_decode($json, true);
        if (!is_array($arr)) $arr = [];
        $arr[] = $entry;
        // Auto-clean (keep last 90 days)
        $cutoff = strtotime('-90 days');
        $arr = array_values(array_filter($arr, function($e) use ($cutoff) {
            $ts = strtotime($e['timestamp'] ?? '');
            return $ts >= $cutoff;
        }));
        ftruncate($fp, 0);
        rewind($fp);
        fwrite($fp, json_encode($arr, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        fflush($fp);
        flock($fp, LOCK_UN);
        fclose($fp);
    }
}
?>
