<?php
require_once __DIR__.'/../../config/functions.php';
requireLogin();

// Auto-migrate database to add missing columns if they don't exist
try {
    $pdo->exec("ALTER TABLE takwim ADD COLUMN peringkat VARCHAR(100) DEFAULT NULL AFTER tajuk");
} catch(Exception $e) {}
try {
    $pdo->exec("ALTER TABLE takwim ADD COLUMN pengelola_keb VARCHAR(200) DEFAULT NULL AFTER peringkat");
} catch(Exception $e) {}
try {
    $pdo->exec("ALTER TABLE takwim ADD COLUMN bidang VARCHAR(100) DEFAULT NULL AFTER pengelola_keb");
} catch(Exception $e) {}
try {
    $pdo->exec("ALTER TABLE takwim ADD COLUMN subunit_id INT UNSIGNED DEFAULT NULL AFTER unit_id");
} catch(Exception $e) {}

// Export Takwim events to CSV
$filename = "TAKWIM_".date('Y').".csv";

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$filename);

$output = fopen('php://output', 'w');
// Write BOM for Excel UTF-8 compatibility
fputs($output, "\xEF\xBB\xBF");

// Write header (Matching user's latest structure)
$headers = [
    'ID',
    'NAMA PROG',
    'T_MULA',
    'T_AKHIR',
    'PERINGKAT',
    'PENGELOLA',
    'SUBUNIT',
    'UNIT',
    'PEGAWAI',
    'CATATAN',
    'MASA_MULA',
    'MASA_TAMAT',
    'SEMUA_HARI'
];
fputcsv($output, $headers);

// Fetch data
$stmt = $pdo->prepare("
    SELECT 
        t.id,
        t.tajuk,
        t.tarikh_mula,
        t.tarikh_tamat,
        t.masa_mula,
        t.masa_tamat,
        t.semua_hari,
        t.peringkat,
        t.pengelola_keb,
        su.nama_subunit,
        u.kod as kod_unit,
        p.nama as nama_pegawai,
        t.deskripsi as catatan
    FROM takwim t
    LEFT JOIN unit u ON t.unit_id = u.id
    LEFT JOIN subunit su ON t.subunit_id = su.id
    LEFT JOIN pegawai p ON t.pegawai_id = p.id
    WHERE t.status = 1
    ORDER BY t.tarikh_mula ASC
");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // Format dates to DD/MM/YYYY
    $t_mula = $row['tarikh_mula'] ? date('d/m/Y', strtotime($row['tarikh_mula'])) : '';
    $t_akhir = $row['tarikh_tamat'] ? date('d/m/Y', strtotime($row['tarikh_tamat'])) : '';
    
    $line = [
        $row['id'],
        $row['tajuk'],
        $t_mula,
        $t_akhir,
        $row['peringkat'] ?? '',
        $row['pengelola_keb'] ?? '',
        $row['nama_subunit'] ?? '',
        $row['kod_unit'] ?? '',
        $row['nama_pegawai'] ?? '',
        $row['catatan'] ?? '',
        $row['masa_mula'] ?? '',
        $row['masa_tamat'] ?? '',
        $row['semua_hari']
    ];
    fputcsv($output, $line);
}

fclose($output);
exit;
