<?php
// Export sederhana laporan keaktifan materi ITC Program.
declare(strict_types=1);
require_once __DIR__ . '/config/database.php';
if (file_exists(__DIR__ . '/config/master_auth.php')) require_once __DIR__ . '/config/master_auth.php';
if (function_exists('require_login')) require_login();
$conn = function_exists('getConnection') ? getConnection() : null;
if (!($conn instanceof mysqli)) exit('Koneksi database gagal.');
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="keaktifan_materi_itc_'.date('Ymd_His').'.xls"');
echo "<table border='1'>";
echo "<tr><th>Tanggal</th><th>User</th><th>NIK</th><th>Unit</th><th>Materi</th><th>Kode Materi</th><th>Durasi Detik</th><th>Durasi</th><th>Status</th><th>Role</th></tr>";
$res = $conn->query("SELECT a.*, m.title material_title, m.material_code FROM itc_material_activity a LEFT JOIN itc_materials m ON m.id=a.material_id ORDER BY a.last_seen_at DESC, a.id DESC");
function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function dur($s){ $s=(int)$s; $m=floor($s/60); $r=$s%60; return $m.' menit '.$r.' detik'; }
if ($res) while($r=$res->fetch_assoc()) {
    echo '<tr>';
    echo '<td>'.h($r['last_seen_at'] ?: $r['created_at']).'</td>';
    echo '<td>'.h($r['user_name']).'</td>';
    echo '<td>'.h($r['nik']).'</td>';
    echo '<td>'.h($r['unit_name']).'</td>';
    echo '<td>'.h($r['material_title']).'</td>';
    echo '<td>'.h($r['material_code']).'</td>';
    echo '<td>'.(int)$r['duration_seconds'].'</td>';
    echo '<td>'.h(dur($r['duration_seconds'])).'</td>';
    echo '<td>'.h($r['status']).'</td>';
    echo '<td>'.h($r['role_name']).'</td>';
    echo '</tr>';
}
echo '</table>';
