<?php
session_start();
include '../db_config.php';
include '../functions.php';

// Check if admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    die("Access Denied");
}

// Set headers to force download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=employees_list_' . date('Y-m-d') . '.csv');

// Create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// Output the column headings
fputcsv($output, array('NIC', 'Full Name', 'Job Category', 'District', 'Divisional Secretariat', 'Phone', 'Address', 'DOB', 'Qualification', 'Status', 'Registered Date'));

// Fetch the data
$sql = "SELECT 
            u.nic, 
            ed.full_name, 
            ed.job_category, 
            ed.district, 
            ed.divisional_secretariat,
            ed.phone, 
            ed.address, 
            ed.dob, 
            ed.qualification, 
            ed.status,
            u.created_at
        FROM employee_login u 
        LEFT JOIN employee_details ed ON u.nic = ed.employee_nic 
        WHERE u.role = 'employee' 
        ORDER BY u.created_at DESC";

$result = $conn->query($sql);

// Loop over the rows, outputting them
while ($row = $result->fetch_assoc()) {
    fputcsv($output, $row);
}

fclose($output);
exit();
?>
