<?php
/**
 * license-php/lib/AuditLogger.php
 * Audit logger for Presensi License Server.
 * Records all activation, verification, and admin actions.
 */

class AuditLogger {
    private PDO $pdo;

    public function __construct(PDO $pdo) {
        $this->pdo = $pdo;
    }

    /**
     * Records an audit log entry.
     */
    public function log(?string $licenseId, string $action, ?string $domain, array $metadata = []): array {
        $id = 'log_' . bin2hex(random_bytes(8));
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
        $ip = trim(explode(',', $ip)[0]);
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown UA';
        $createdAt = gmdate('Y-m-d\TH:i:s.v\Z');

        $stmt = $this->pdo->prepare("
            INSERT INTO license_audit_logs (id, license_id, action, domain, ip_address, user_agent, metadata, created_at)
            VALUES (:id, :license_id, :action, :domain, :ip_address, :user_agent, :metadata, :created_at)
        ");

        $stmt->execute([
            ':id'          => $id,
            ':license_id'  => $licenseId,
            ':action'      => $action,
            ':domain'      => $domain ?: '-',
            ':ip_address'  => (string)$ip,
            ':user_agent'  => substr((string)$ua, 0, 500),
            ':metadata'    => json_encode($metadata, JSON_UNESCAPED_SLASHES),
            ':created_at'  => $createdAt
        ]);

        return [
            'id'          => $id,
            'license_id'  => $licenseId,
            'action'      => $action,
            'domain'      => $domain ?: '-',
            'ip_address'  => $ip,
            'user_agent'  => $ua,
            'metadata'    => $metadata,
            'created_at'  => $createdAt
        ];
    }

    /**
     * Retrieve audit logs with optional filters.
     */
    public function getLogs(int $limit = 100, ?string $action = null, ?string $licenseId = null): array {
        $sql = "SELECT id, license_id, action, domain, ip_address, user_agent, metadata, created_at FROM license_audit_logs WHERE 1=1";
        $params = [];

        if ($action) {
            $sql .= " AND action = :action";
            $params[':action'] = $action;
        }
        if ($licenseId) {
            $sql .= " AND license_id = :license_id";
            $params[':license_id'] = $licenseId;
        }

        $sql .= " ORDER BY created_at DESC LIMIT " . (int)$limit;

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($rows as &$row) {
            if (!empty($row['metadata'])) {
                $row['metadata'] = json_decode($row['metadata'], true) ?: [];
            } else {
                $row['metadata'] = [];
            }
        }
        return $rows;
    }
}
