<?php
session_start();

// Validasi session
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=session");
    exit;
}

$userRole = strtoupper(trim($_SESSION['role'] ?? ''));
if ($userRole !== 'M' && $userRole !== 'A') {
    header("Location: ../../index.html?error=forbidden");
    exit;
}

// Set headers for Excel file download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=template_import_sdm.csv');

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

// Add BOM for UTF-8
fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

// Header columns
$headers = [
    'NIP',
    'Nama',
    'Email',
    'Jenis_Kelamin',
    'Jabatan',
    'Kantor',
    'No_HP',
    'Status'
];

fputcsv($output, $headers);

// Add example data
$examples = [
    [
        'NIP001',
        'Ahmad Fauzi',
        'ahmad.fauzi@acfedu.com',
        'Laki-laki',
        'Manager',
        'Kantor Pusat',
        '081234567890',
        'Aktif'
    ],
    [
        'NIP002',
        'Siti Nurhaliza',
        'siti.nurhaliza@acfedu.com',
        'Perempuan',
        'Staff',
        'Kantor Cabang A',
        '081234567891',
        'Aktif'
    ],
    [
        'NIP003',
        'Budi Santoso',
        'budi.santoso@acfedu.com',
        'Laki-laki',
        'Supervisor',
        'Kantor Pusat',
        '081234567892',
        'Aktif'
    ]
];

foreach ($examples as $example) {
    fputcsv($output, $example);
}

fclose($output);
exit;
?>