<?php
// Include necessary files and start session if not already started
session_start();
include '../../assets/constant/config.php';

// Check if an ID is provided in the query parameter
if (isset($_GET['id'])) {
    try {
        // Connect to the database
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Prepare and execute SQL query to fetch payslip data based on the provided ID
        $stmt = $conn->prepare("SELECT * FROM `payroll` WHERE id = :id");
        $stmt->bindParam(':id', $_GET['id']);
        $stmt->execute();
        $payroll = $stmt->fetch();

        // Generate the payslip content (you need to adjust this based on your payslip format)
        $content = "Payslip for " . $payroll['user_name'] . "\n";
        $content .= "Date: " . $payroll['payroll_date'] . "\n";
        // Add more data as needed

        // Set response headers for file download
        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename="payslip_' . $_GET['id'] . '.txt"');

        // Output the payslip content
        echo $content;
    } catch (PDOException $e) {
        // Handle database connection or query errors
        echo "Connection failed: " . $e->getMessage();
    }
} else {
    // If ID is not provided, redirect back to the previous page or handle it accordingly
    header("Location: {$_SERVER['HTTP_REFERER']}");
    exit;
}

?>