<?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=employers_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('ID', 'Company Name', 'Email (Username)', 'Business Reg No', 'Contact No', 'Address', 'Status', 'Registered Date'));

// Fetch the data
$sql = "SELECT 
            u.id, 
            ed.company_name, 
            u.username, 
            ed.business_reg_no, 
            ed.contact_no, 
            ed.address, 
            ed.status,
            u.created_at
        FROM employer_login u 
        LEFT JOIN employer_details ed ON u.id = ed.user_id 
        WHERE u.role = 'employer' 
        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();
?>
