<?php
include 'includes/session.php'; // Include session to access the user's session
include 'includes/dbh.php'; // Include your database connection file

if (isset($_GET['user_id'])) {
    $user_id = intval($_GET['user_id']); // Get the user ID from the URL

    // Prepare the SQL statement to fetch login history along with username and email
    $sql = "SELECT lh.*, u.name, u.email FROM login_history lh 
            JOIN users u ON lh.user_id = u.id 
            WHERE lh.user_id = ?"; // Assuming 'id' is the primary key in the 'users' table
    $stmt = $conn->prepare($sql); // Use $conn if you are using MySQLi
    $stmt->bind_param("i", $user_id); // Bind the user_id parameter as an integer
    $stmt->execute();
    $result = $stmt->get_result(); // Get the result set
    $user = $result->fetch_assoc();

    $email = $user['email'];
    $sanitized_email = preg_replace('/[^a-zA-Z0-9_-]/', '_', $email); // Sanitize email for filename

    // Set headers for CSV download
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $sanitized_email . '_login_history.csv"');

    // Open output stream
    $output = fopen('php://output', 'w');

    // Write column headings
    fputcsv($output, ['Username', 'Email', 'Login Time', 'Logged Out', 'Active Time (HH:MM:SS)', 'Reason']); // Adjust headings as necessary

    // Fetch and write each row of login history to the CSV
    while ($row = $result->fetch_assoc()) {
        // Convert 'logged_in' and 'logged_out' to timestamps and calculate the active time
        $login_time = strtotime($row['logged_in']);
        $logout_time = strtotime($row['logged_out']);

        // If the logout time is not null, calculate the active time
        if ($logout_time) {
            $active_time = $logout_time - $login_time; // Calculate the difference in seconds
            $formatted_active_time = gmdate("H:i:s", $active_time); // Format as HH:MM:SS
        } else {
            $formatted_active_time = 'N/A'; // If logout time is null, mark as N/A
        }

        // Write the row to the CSV file
        fputcsv($output, [
            $row['name'], // Username
            $row['email'], // Email
            $row['logged_in'], // Login time
            $row['logged_out'], // Logout time
            $formatted_active_time, // Active time
            $row['reason'] // Reason for logout
        ]);
    }

    fclose($output);
    exit();
} else {
    echo "No user ID provided.";
}
?>
