<?php
require_once '../config/database.php';

header('Content-Type: application/json');

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Check if user has permission to view security logs
if (!hasPermission('view_security_logs') && !hasRole('President')) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit;
}

try {
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
    $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
    $severity = $_GET['severity'] ?? '';
    $event_type = $_GET['event_type'] ?? '';
    
    $where_conditions = [];
    $params = [];
    
    if (!empty($severity)) {
        $where_conditions[] = "severity = ?";
        $params[] = $severity;
    }
    
    if (!empty($event_type)) {
        $where_conditions[] = "event_type = ?";
        $params[] = $event_type;
    }
    
    $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
    
    $query = "
        SELECT 
            sl.*,
            a.username,
            a.first_name,
            a.last_name
        FROM security_logs sl
        LEFT JOIN admins a ON sl.admin_id = a.id
        {$where_clause}
        ORDER BY sl.created_at DESC
        LIMIT ? OFFSET ?
    ";
    
    $params[] = $limit;
    $params[] = $offset;
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $logs = $stmt->fetchAll();
    
    // Get total count
    $count_query = "SELECT COUNT(*) as total FROM security_logs sl {$where_clause}";
    $count_stmt = $pdo->prepare($count_query);
    $count_stmt->execute(array_slice($params, 0, -2)); // Remove limit and offset
    $total = $count_stmt->fetch()['total'];
    
    echo json_encode([
        'success' => true,
        'data' => $logs,
        'total' => $total,
        'limit' => $limit,
        'offset' => $offset
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false, 
        'message' => 'Error fetching security logs: ' . $e->getMessage()
    ]);
}
?>
