<?php
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/functions.php';
startSession(); requireLogin();
$db = Database::getInstance();
$id = cleanInt($_GET['id'] ?? 0);

// FIX (07 Jul 2026): this exports PAN/Aadhaar/PF/ESI numbers — about as
// sensitive as data gets — and had no organization scoping at all, plus
// built its WHERE clause with string concatenation instead of bound
// parameters. Fixed both: scoped to the current org, and parameterized.
[$orgClause, $orgParams] = orgScopeClause($db, 'e.company_id');

if ($id) {
    // Export single employee — only if it belongs to this organization.
    $emps = $db->fetchAll(
        "SELECT e.*,d.name AS dept,des.name AS designation,g.name AS grade,l.name AS location
           FROM employees e
      LEFT JOIN departments d ON d.id=e.department_id
      LEFT JOIN designations des ON des.id=e.designation_id
      LEFT JOIN grades g ON g.id=e.grade_id
      LEFT JOIN locations l ON l.id=e.location_id
          WHERE e.id=? AND $orgClause",
        array_merge([$id], $orgParams)
    );
} else {
    // Export all employees (from list filters)
    $where  = [$orgClause];
    $params = $orgParams;
    if (!empty($_GET['dept']))   { $where[] = "e.department_id=?"; $params[] = (int)$_GET['dept']; }
    if (!empty($_GET['status'])) { $where[] = "e.status=?"; $params[] = $_GET['status']; }
    $whereStr = implode(' AND ', $where);
    $emps = $db->fetchAll(
        "SELECT e.*,d.name AS dept,des.name AS designation,g.name AS grade,l.name AS location
           FROM employees e
      LEFT JOIN departments d ON d.id=e.department_id
      LEFT JOIN designations des ON des.id=e.designation_id
      LEFT JOIN grades g ON g.id=e.grade_id
      LEFT JOIN locations l ON l.id=e.location_id
          WHERE $whereStr
          ORDER BY e.first_name",
        $params
    );
}

$filename = $id ? 'employee_'.$id.'_'.date('Ymd').'.csv' : 'employees_'.date('Ymd').'.csv';

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Pragma: no-cache');

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

// Header row
fputcsv($out, [
    'Employee ID','First Name','Last Name','Date of Birth','Gender','Blood Group',
    'Date of Joining','Department','Designation','Grade','Location',
    'Employment Type','Status','Mobile','Personal Email','Official Email',
    'PAN Number','Aadhaar','UAN','PF Number','ESI Number','Tax Regime'
]);

foreach ($emps as $e) {
    fputcsv($out, [
        $e['employee_id'], $e['first_name'], $e['last_name'],
        $e['date_of_birth'] ?? '', $e['gender'] ?? '', $e['blood_group'] ?? '',
        $e['date_of_joining'] ?? '', $e['dept'] ?? '', $e['designation'] ?? '',
        $e['grade'] ?? '', $e['location'] ?? '',
        $e['employment_type'] ?? '', $e['status'] ?? '',
        $e['mobile'] ?? '', $e['personal_email'] ?? '', $e['official_email'] ?? '',
        $e['pan_number'] ?? '', $e['aadhaar_number'] ?? '',
        $e['uan_number'] ?? '', $e['pf_number'] ?? '', $e['esi_number'] ?? '',
        $e['tax_regime'] ?? 'new'
    ]);
}

fclose($out);
exit;