<?php
session_start();
include 'layouts/dbconn.php';
require_once('fpdf/fpdf.php');

// Check if user is logged in and has admin rights
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    header('Location: login.php');
    exit();
}

// Get filter parameters
$action_filter = isset($_GET['action']) ? $conn->real_escape_string($_GET['action']) : '';
$user_filter = isset($_GET['user']) ? intval($_GET['user']) : 0;
$date_from = isset($_GET['date_from']) ? $conn->real_escape_string($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? $conn->real_escape_string($_GET['date_to']) : '';

// Build the query with filters
$query = "SELECT al.*, u.username, u.full_name 
          FROM admin_logs al
          LEFT JOIN users u ON al.user_id = u.user_id
          WHERE 1=1";

if (!empty($action_filter)) {
    $query .= " AND al.action LIKE '%$action_filter%'";
}

if ($user_filter > 0) {
    $query .= " AND al.user_id = $user_filter";
}

if (!empty($date_from)) {
    $query .= " AND DATE(al.created_at) >= '$date_from'";
}

if (!empty($date_to)) {
    $query .= " AND DATE(al.created_at) <= '$date_to'";
}

// Add sorting
$query .= " ORDER BY al.created_at DESC";

// Execute the query
$result = $conn->query($query);
$logs = [];

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $logs[] = $row;
    }
}

// Create custom PDF class with header and footer
class PDF extends FPDF {
    function Header() {
        // Logo
        // $this->Image('logo.png', 10, 6, 30);
        // Set font
        $this->SetFont('Arial', 'B', 15);
        // Title
        $this->Cell(0, 10, 'System Audit Logs', 0, 1, 'C');
        // Subtitle with current date
        $this->SetFont('Arial', 'I', 10);
        $this->Cell(0, 10, 'Generated on: ' . date('Y-m-d H:i:s'), 0, 1, 'C');
        // Line break
        $this->Ln(5);
    }

    function Footer() {
        // Position at 1.5 cm from bottom
        $this->SetY(-15);
        // Set font
        $this->SetFont('Arial', 'I', 8);
        // Page number
        $this->Cell(0, 10, 'Page ' . $this->PageNo() . '/{nb}', 0, 0, 'C');
    }
}

// Initialize PDF
$pdf = new PDF('L', 'mm', 'A4');
$pdf->AliasNbPages();
$pdf->AddPage();

// Set column widths
$col_date = 40;
$col_user = 40;
$col_action = 40;
$col_ip = 30;
$col_details = 120;

// Set column headers
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell($col_date, 10, 'Date & Time', 1, 0, 'C');
$pdf->Cell($col_user, 10, 'User', 1, 0, 'C');
$pdf->Cell($col_action, 10, 'Action', 1, 0, 'C');
$pdf->Cell($col_ip, 10, 'IP Address', 1, 0, 'C');
$pdf->Cell($col_details, 10, 'Details', 1, 1, 'C');

// Set content font
$pdf->SetFont('Arial', '', 9);

// Add data rows
foreach ($logs as $log) {
    // Date
    $pdf->Cell($col_date, 10, date('Y-m-d H:i:s', strtotime($log['created_at'])), 1, 0, 'L');
    
    // User
    $username = !empty($log['username']) ? $log['username'] : 'Unknown';
    $pdf->Cell($col_user, 10, $username, 1, 0, 'L');
    
    // Action
    $pdf->Cell($col_action, 10, $log['action'], 1, 0, 'L');
    
    // IP Address
    $pdf->Cell($col_ip, 10, $log['ip_address'], 1, 0, 'L');
    
    // Details (needs special handling for multi-line text)
    $details = $log['details'];
    $details = str_replace("\n", " | ", $details); // Replace line breaks with a separator
    
    // Calculate how many lines we need based on available width
    $lines = $pdf->GetStringWidth($details) / $col_details;
    $lines = ceil($lines) * 1.5; // Add some extra space
    $cell_height = max(5, $lines * 5); // Minimum height of 5mm
    
    // Check if we need to add a page
    if ($pdf->GetY() + $cell_height > $pdf->GetPageHeight() - 20) {
        $pdf->AddPage();
    }
    
    // Use MultiCell for details
    $pdf->MultiCell($col_details, $cell_height, $details, 1, 'L');
}

// Generate filename
$filename = 'audit_logs_' . date('Y-m-d') . '.pdf';

// Output PDF
$pdf->Output('D', $filename);
exit;
?>