<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    json_response(false, 'Invalid request method.', [], 405);
}

$user = authenticate($pdo);

if (!can($user, 'admin_audit', 'view', $pdo)) {
    json_response(false, 'Access denied.', [], 403);
}

$stmt = $pdo->prepare("
    SELECT 
        a.created_at,
        CONCAT(u.first_name, ' ', u.last_name) AS full_name,
        a.role_key,
        a.module_key,
        a.action_type,
        a.record_id,
        a.ip_address
    FROM admin_audit_logs a
    JOIN users u ON u.id = a.user_id
    ORDER BY a.created_at DESC
    LIMIT 200
");

$stmt->execute();
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

json_response(true, 'Audit logs fetched.', [
    'logs' => $logs
]);