<?php

class AuditLog
{
    private $pdo;

    public function __construct()
    {
        $this->pdo = $GLOBALS['pdo'];
    }

    public function record($actorId, $action, $entityType, $entityId = null, $details = [])
    {
        $sql = "INSERT INTO audit_logs (actor_id, action, entity_type, entity_id, details, created_at) VALUES (?,?,?,?,?,NOW())";
        $stmt = $this->pdo->prepare($sql);
        return $stmt->execute([
            $actorId,
            $action,
            $entityType,
            $entityId,
            json_encode($details)
        ]);
    }

    public function recent($limit = 20)
    {
        $stmt = $this->pdo->prepare("SELECT al.*, u.name as actor_name FROM audit_logs al LEFT JOIN users u ON al.actor_id = u.id ORDER BY al.id DESC LIMIT ?");
        $stmt->bindValue(1, (int)$limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}
