<?php
declare(strict_types=1);
require_once __DIR__ . '/../Config/database.php';

class Audit {
    private PDO $db;
    public function __construct() { $this->db = Database::getConnection(); }

    public function log(int $userId, string $action): void {
        $ip = $_SERVER['REMOTE_ADDR'] ?? 'CLI';
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
        $stmt = $this->db->prepare("INSERT INTO audit_trail (user_id,action,ip_address,user_agent) VALUES (?,?,?,?)");
        $stmt->execute([$userId,$action,$ip,$ua]);
    }

    public function all(): array {
        $sql = "SELECT a.*,u.name AS user_name FROM audit_trail a 
                LEFT JOIN users u ON a.user_id=u.id 
                ORDER BY a.created_at DESC";
        return $this->db->query($sql)->fetchAll();
    }

    public function clear(): void {
        $this->db->exec("TRUNCATE TABLE audit_trail");
    }
}
