<?php
// modules/itc_program.php — ITC Program v2 native.
// Fokus: materi admin/user, tracking durasi membaca/menonton, laporan keaktifan materi.

if (!isset($conn) || !($conn instanceof mysqli)) {
    if (function_exists('getConnection')) $conn = getConnection();
    elseif (function_exists('db')) $conn = db();
}
if (!($conn instanceof mysqli)) {
    echo "<div class='p-6 bg-red-50 text-red-700 rounded-xl'>Koneksi database aplikasi utama gagal.</div>";
    return;
}

if (!function_exists('e')) {
    function e($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('itc_rows')) {
    function itc_rows($res): array { $a=[]; if ($res instanceof mysqli_result) while($r=$res->fetch_assoc()) $a[]=$r; return $a; }
}
function itc_role(): string { return strtolower((string)($_SESSION['user_role'] ?? $_SESSION['user']['role'] ?? 'user')); }
function itc_admin(): bool { return in_array(itc_role(), ['admin','superadmin'], true); }
function itc_emp_id(): int { return (int)($_SESSION['employee_id'] ?? $_SESSION['user']['employee_id'] ?? $_SESSION['user_id'] ?? $_SESSION['user']['id'] ?? 0); }
function itc_name(): string { return (string)($_SESSION['full_name'] ?? $_SESSION['user']['full_name'] ?? $_SESSION['user']['name'] ?? $_SESSION['username'] ?? 'User'); }
function itc_nik(): string { return (string)($_SESSION['nik'] ?? $_SESSION['user']['nik'] ?? $_SESSION['username'] ?? ''); }
function itc_unit(): string { return (string)($_SESSION['unit'] ?? $_SESSION['user']['unit'] ?? ''); }
function itc_flash($type, $msg): void { $_SESSION['itc_flash'] = ['type'=>$type,'msg'=>$msg]; }
function itc_redirect($tab, $extra=[]): void { echo "<script>location.href='?".http_build_query(array_merge(['module'=>'itc_program','tab'=>$tab],$extra))."'</script>"; exit; }
function itc_col_exists(mysqli $conn, string $table, string $col): bool { $t=$conn->real_escape_string($table); $c=$conn->real_escape_string($col); $r=$conn->query("SHOW COLUMNS FROM `$t` LIKE '$c'"); return $r && $r->num_rows>0; }
function itc_table_exists(mysqli $conn, string $table): bool { $t=$conn->real_escape_string($table); $r=$conn->query("SHOW TABLES LIKE '$t'"); return $r && $r->num_rows>0; }
function itc_date_id($date): string { if(!$date) return '-'; return date('d/m/Y H:i', strtotime($date)); }
function itc_duration_text($sec): string { $sec=(int)$sec; $m=floor($sec/60); $s=$sec%60; if($m<=0) return $s.' detik'; return $m.' menit'.($s>0?' '.$s.' detik':''); }
function itc_upload_file($file): ?string {
    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) return null;
    $allowed = ['pdf','doc','docx','ppt','pptx','xls','xlsx','jpg','jpeg','png','mp4','zip'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed, true)) return null;
    $dir = __DIR__ . '/../uploads/itc_materi/'; if(!is_dir($dir)) mkdir($dir,0755,true);
    $name = 'materi_' . date('YmdHis') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
    if (move_uploaded_file($file['tmp_name'], $dir.$name)) return 'uploads/itc_materi/'.$name;
    return null;
}
function itc_youtube_embed($url): string {
    $url = trim((string)$url); if ($url==='') return '';
    if (preg_match('~(?:youtu\.be/|youtube\.com/(?:watch\?v=|embed/|shorts/))([A-Za-z0-9_-]{6,})~', $url, $m)) return 'https://www.youtube.com/embed/'.$m[1];
    return $url;
}
function itc_status_badge($status): string {
    $s = strtolower((string)$status); $cls = $s==='selesai'?'bg-green-100 text-green-700':($s==='sedang'?'bg-blue-100 text-blue-700':'bg-yellow-100 text-yellow-700');
    return "<span class='px-3 py-1 rounded-full text-xs font-bold $cls'>".e(ucfirst($s))."</span>";
}

if (!itc_table_exists($conn, 'itc_materials')) {
    echo "<div class='p-6 bg-yellow-50 border-l-4 border-yellow-500 rounded-xl text-yellow-800'>Database ITC Program belum terpasang. Jalankan <code>setup_itc_program.php</code>.</div>";
    return;
}

$isAdmin = itc_admin();
$employeeId = itc_emp_id();
$tab = $_GET['tab'] ?? 'dashboard';
$action = $_GET['action'] ?? '';

// POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pa = $_POST['itc_action'] ?? '';
    try {
        if ($pa === 'track_material') {
            header('Content-Type: application/json');
            $mid = (int)($_POST['material_id'] ?? 0);
            $duration = max(0, (int)($_POST['duration_seconds'] ?? 0));
            $status = $_POST['status'] === 'selesai' ? 'selesai' : ($duration > 0 ? 'sedang' : 'mulai');
            if ($mid <= 0) throw new Exception('material_id invalid');
            $emp = max(0, $employeeId);
            $name = itc_name(); $nik = itc_nik(); $unit = itc_unit(); $role = itc_role();
            $today = date('Y-m-d');
            $stmt = $conn->prepare("INSERT INTO itc_material_activity (material_id, employee_id, user_name, nik, unit_name, role_name, activity_date, duration_seconds, status, started_at, last_seen_at, finished_at)
                VALUES (?,?,?,?,?,?,?,?,?,NOW(),NOW(),IF(?='selesai',NOW(),NULL))
                ON DUPLICATE KEY UPDATE user_name=VALUES(user_name), nik=VALUES(nik), unit_name=VALUES(unit_name), role_name=VALUES(role_name), duration_seconds=GREATEST(duration_seconds, VALUES(duration_seconds)), status=IF(VALUES(status)='selesai','selesai',IF(status='selesai','selesai','sedang')), last_seen_at=NOW(), finished_at=IF(VALUES(status)='selesai',NOW(),finished_at)");
            $stmt->bind_param('iisssssiss', $mid, $emp, $name, $nik, $unit, $role, $today, $duration, $status, $status);
            $stmt->execute(); $stmt->close();
            $conn->query("UPDATE itc_materials SET view_count = view_count + 1 WHERE id=".$mid." AND NOT EXISTS (SELECT 1 FROM itc_material_activity WHERE material_id=".$mid." AND employee_id=".$emp." AND activity_date='".$conn->real_escape_string($today)."' AND duration_seconds > 3)");
            echo json_encode(['ok'=>true]); exit;
        }

        if ($pa === 'save_instructor' && $isAdmin) {
            $id=(int)($_POST['id']??0); $employee_id=(int)($_POST['employee_id']??0); $name=trim($_POST['name']??''); $profession=trim($_POST['profession']??''); $expertise=trim($_POST['expertise']??''); $phone=trim($_POST['phone']??''); $email=trim($_POST['email']??''); $status=$_POST['status']??'aktif';
            if($name==='') throw new Exception('Nama instruktur wajib diisi.');
            if($id>0){$stmt=$conn->prepare("UPDATE itc_instructors SET employee_id=NULLIF(?,0), name=?, profession=?, expertise=?, phone=?, email=?, status=? WHERE id=?"); $stmt->bind_param('issssssi',$employee_id,$name,$profession,$expertise,$phone,$email,$status,$id);} else {$code='INS-'.date('YmdHis'); $stmt=$conn->prepare("INSERT INTO itc_instructors (employee_id,instructor_code,name,profession,expertise,phone,email,status) VALUES (NULLIF(?,0),?,?,?,?,?,?,?)"); $stmt->bind_param('isssssss',$employee_id,$code,$name,$profession,$expertise,$phone,$email,$status);} $stmt->execute(); $stmt->close(); itc_flash('success','Instruktur berhasil disimpan.'); itc_redirect('instructors');
        }

        if ($pa === 'save_curriculum' && $isAdmin) {
            $id=(int)($_POST['id']??0); $title=trim($_POST['title']??''); $target_role=trim($_POST['target_role']??''); $target_unit=trim($_POST['target_unit']??''); $level=trim($_POST['competency_level']??''); $description=trim($_POST['description']??''); $min=(float)($_POST['min_score']??70); $valid=(int)($_POST['validity_months']??24); $status=$_POST['status']??'aktif';
            if($title==='') throw new Exception('Judul kurikulum wajib diisi.');
            if($id>0){$stmt=$conn->prepare("UPDATE itc_curriculum SET title=?,target_role=?,target_unit=?,competency_level=?,description=?,min_score=?,validity_months=?,status=? WHERE id=?"); $stmt->bind_param('sssssdisi',$title,$target_role,$target_unit,$level,$description,$min,$valid,$status,$id);} else {$code='KUR-'.date('YmdHis'); $stmt=$conn->prepare("INSERT INTO itc_curriculum (curriculum_code,title,target_role,target_unit,competency_level,description,min_score,validity_months,status) VALUES (?,?,?,?,?,?,?,?,?)"); $stmt->bind_param('ssssssdis',$code,$title,$target_role,$target_unit,$level,$description,$min,$valid,$status);} $stmt->execute(); $stmt->close(); itc_flash('success','Kurikulum berhasil disimpan.'); itc_redirect('curriculum');
        }

        if ($pa === 'save_material' && $isAdmin) {
            $id=(int)($_POST['id']??0); $curriculum_id=(int)($_POST['curriculum_id']??0); $title=trim($_POST['title']??''); $description=trim($_POST['description']??''); $material_type=$_POST['material_type']??'text'; $external_url=trim($_POST['external_url']??''); $content=trim($_POST['content']??''); $unit_name=trim($_POST['unit_name']??'Keperawatan'); $has_quiz=isset($_POST['has_quiz'])?1:0; $point_view=(int)($_POST['point_view']??1); $pass_score=(float)($_POST['pass_score']??70); $is_public=isset($_POST['is_public'])?1:0;
            if($title==='') throw new Exception('Judul materi wajib diisi.');
            $file_path=itc_upload_file($_FILES['material_file']??[]);
            if($id>0){
                if($file_path){$stmt=$conn->prepare("UPDATE itc_materials SET curriculum_id=NULLIF(?,0),title=?,description=?,material_type=?,file_path=?,external_url=?,content=?,unit_name=?,has_quiz=?,point_view=?,pass_score=?,is_public=? WHERE id=?"); $stmt->bind_param('isssssssiiiii',$curriculum_id,$title,$description,$material_type,$file_path,$external_url,$content,$unit_name,$has_quiz,$point_view,$pass_score,$is_public,$id);} 
                else {$stmt=$conn->prepare("UPDATE itc_materials SET curriculum_id=NULLIF(?,0),title=?,description=?,material_type=?,external_url=?,content=?,unit_name=?,has_quiz=?,point_view=?,pass_score=?,is_public=? WHERE id=?"); $stmt->bind_param('issssssiiiii',$curriculum_id,$title,$description,$material_type,$external_url,$content,$unit_name,$has_quiz,$point_view,$pass_score,$is_public,$id);} 
            } else { $code='MTR-'.date('YmdHis'); $stmt=$conn->prepare("INSERT INTO itc_materials (material_code,curriculum_id,title,description,material_type,file_path,external_url,content,unit_name,has_quiz,point_view,pass_score,is_public,created_by) VALUES (?,NULLIF(?,0),?,?,?,?,?,?,?,?,?,?,?,?)"); $stmt->bind_param('sisssssssiiiii',$code,$curriculum_id,$title,$description,$material_type,$file_path,$external_url,$content,$unit_name,$has_quiz,$point_view,$pass_score,$is_public,$employeeId); }
            $stmt->execute(); $stmt->close(); itc_flash('success','Materi berhasil disimpan.'); itc_redirect('materials');
        }

        if ($pa === 'save_schedule' && $isAdmin) {
            $ins=(int)($_POST['instructor_id']??0); $cur=(int)($_POST['curriculum_id']??0); $title=trim($_POST['title']??''); $date=$_POST['schedule_date']??date('Y-m-d'); $start=$_POST['start_time']?:null; $end=$_POST['end_time']?:null; $loc=trim($_POST['location']??''); $method=$_POST['method']??'offline'; $link=trim($_POST['link_online']??''); $quota=(int)($_POST['quota']??30); $notes=trim($_POST['notes']??''); $status=$_POST['status']??'aktif';
            if($title==='') throw new Exception('Judul jadwal wajib diisi.');
            $stmt=$conn->prepare("INSERT INTO itc_schedules (instructor_id,curriculum_id,title,schedule_date,start_time,end_time,location,method,link_online,quota,notes,status) VALUES (NULLIF(?,0),NULLIF(?,0),?,?,?,?,?,?,?,?,?,?)"); $stmt->bind_param('iissssssisss',$ins,$cur,$title,$date,$start,$end,$loc,$method,$link,$quota,$notes,$status); $stmt->execute(); $stmt->close(); itc_flash('success','Jadwal berhasil disimpan.'); itc_redirect('schedule');
        }
    } catch(Throwable $e){ itc_flash('error', $e->getMessage()); itc_redirect($tab); }
}

$flash = $_SESSION['itc_flash'] ?? null; unset($_SESSION['itc_flash']);
$stats = [
    'materials'=>(int)($conn->query("SELECT COUNT(*) c FROM itc_materials")->fetch_assoc()['c']??0),
    'views'=>(int)($conn->query("SELECT COALESCE(SUM(duration_seconds),0) c FROM itc_material_activity")->fetch_assoc()['c']??0),
    'quiz'=>(int)($conn->query("SELECT COUNT(*) c FROM itc_materials WHERE has_quiz=1")->fetch_assoc()['c']??0),
    'active_users'=>(int)($conn->query("SELECT COUNT(DISTINCT employee_id) c FROM itc_material_activity WHERE employee_id>0")->fetch_assoc()['c']??0),
];
$curr = itc_rows($conn->query("SELECT id,title FROM itc_curriculum WHERE status='aktif' ORDER BY title ASC"));
$units = itc_rows($conn->query("SELECT DISTINCT name FROM units WHERE is_active=1 ORDER BY name ASC"));
$employees = itc_rows($conn->query("SELECT e.id,e.full_name,e.nik FROM employees e WHERE e.is_active = 1 ORDER BY e.full_name ASC LIMIT 1000"));
$instructors = itc_rows($conn->query("SELECT id,name FROM itc_instructors WHERE status='aktif' ORDER BY name ASC"));
?>
<style>
.itc-wrap{font-family:Poppins,Arial,sans-serif}.itc-hero{background:linear-gradient(135deg,#2563eb,#7c3aed);border-radius:28px;color:#fff;padding:28px;margin-bottom:22px;box-shadow:0 20px 45px rgba(37,99,235,.22);position:relative;overflow:hidden}.itc-hero:after{content:'';position:absolute;right:-40px;top:-50px;width:210px;height:210px;background:rgba(255,255,255,.12);border-radius:999px}.itc-tabs{display:flex;gap:10px;flex-wrap:wrap;margin-bottom:18px}.itc-tab{padding:11px 16px;border-radius:999px;background:white;border:1px solid #e2e8f0;color:#334155;text-decoration:none;font-weight:700}.itc-tab.active{background:#0f172a;color:white}.itc-card{background:white;border:1px solid #e2e8f0;border-radius:22px;box-shadow:0 12px 28px rgba(15,23,42,.06);padding:18px}.itc-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:16px}.itc-stat{border-radius:20px;padding:18px;background:linear-gradient(135deg,#eff6ff,#eef2ff);border:1px solid #dbeafe}.itc-material-card{border-radius:20px;background:#fff;border:1px solid #e2e8f0;box-shadow:0 14px 34px rgba(15,23,42,.06);padding:18px;position:relative;overflow:hidden}.itc-material-card:before{content:'';position:absolute;left:0;top:0;height:6px;width:100%;background:linear-gradient(90deg,#2563eb,#7c3aed)}.itc-btn{display:inline-flex;align-items:center;gap:8px;border-radius:12px;padding:10px 14px;font-weight:800;text-decoration:none;border:0;cursor:pointer}.itc-btn-primary{background:#2563eb;color:#fff}.itc-btn-dark{background:#0f172a;color:#fff}.itc-btn-green{background:#059669;color:#fff}.itc-btn-soft{background:#eef2ff;color:#3730a3}.itc-table{width:100%;border-collapse:collapse}.itc-table th{background:#f1f5f9;text-align:left;padding:12px;font-size:13px}.itc-table td{padding:12px;border-bottom:1px solid #e2e8f0;vertical-align:top}.itc-input,.itc-select,.itc-textarea{width:100%;border:1px solid #cbd5e1;border-radius:12px;padding:11px;background:#fff}.itc-textarea{min-height:90px}.itc-chip{display:inline-flex;padding:5px 9px;border-radius:999px;font-size:12px;font-weight:800;background:#eef2ff;color:#3730a3}.itc-viewer{background:white;border-radius:22px;padding:22px;box-shadow:0 14px 34px rgba(15,23,42,.08)}.itc-video{width:100%;aspect-ratio:16/9;border:0;border-radius:18px;box-shadow:0 12px 30px rgba(15,23,42,.14)}
</style>
<div class="itc-wrap">
  <div class="itc-hero">
    <div class="relative z-10">
      <div class="text-sm uppercase tracking-wider font-bold opacity-90">ITC Program</div>
      <h1 class="text-3xl font-extrabold mt-1">Internal Training Centre RS BaliMéd</h1>
      <p class="mt-2 text-blue-50">Materi, kurikulum, jadwal instruktur, bank soal, tryout, hasil ujian, sertifikat, dan laporan keaktifan membaca/menonton materi.</p>
    </div>
  </div>
  <?php if($flash): ?><div class="mb-4 p-4 rounded-xl <?= $flash['type']==='success'?'bg-green-50 text-green-700':'bg-red-50 text-red-700' ?> font-bold"><?= e($flash['msg']) ?></div><?php endif; ?>
  <?php $tabs=['dashboard'=>'Dashboard','materials'=>'Materi','activity'=>'Keaktifan Materi','instructors'=>'Instruktur/Lector','curriculum'=>'Kurikulum','schedule'=>'Jadwal Mengajar','questions'=>'Bank Soal','tryouts'=>'Tryout','results'=>'Hasil Ujian','certificates'=>'Sertifikat']; ?>
  <div class="itc-tabs"><?php foreach($tabs as $k=>$v): if(!$isAdmin && in_array($k,['instructors','curriculum','schedule','questions','tryouts','results','certificates'],true)) continue; ?><a class="itc-tab <?= $tab===$k?'active':'' ?>" href="?module=itc_program&tab=<?= e($k) ?>"><?= e($v) ?></a><?php endforeach; ?></div>

<?php if($tab==='dashboard'): ?>
  <div class="itc-grid mb-5">
    <div class="itc-stat"><div class="text-slate-500 font-semibold">Total Materi</div><div class="text-4xl font-extrabold"><?= $stats['materials'] ?></div></div>
    <div class="itc-stat"><div class="text-slate-500 font-semibold">Total Durasi Dibaca/Ditonton</div><div class="text-4xl font-extrabold"><?= e(itc_duration_text($stats['views'])) ?></div></div>
    <div class="itc-stat"><div class="text-slate-500 font-semibold">Materi Berquiz</div><div class="text-4xl font-extrabold"><?= $stats['quiz'] ?></div></div>
    <div class="itc-stat"><div class="text-slate-500 font-semibold">User Aktif Membaca</div><div class="text-4xl font-extrabold"><?= $stats['active_users'] ?></div></div>
  </div>
  <div class="itc-card"><h2 class="text-xl font-extrabold mb-3">Aksi Cepat</h2><a class="itc-btn itc-btn-primary" href="?module=itc_program&tab=materials">Buka Materi</a> <?php if($isAdmin): ?><a class="itc-btn itc-btn-green" href="?module=itc_program&tab=activity">Laporan Keaktifan</a><?php endif; ?></div>

<?php elseif($tab==='materials'):
  $q=trim($_GET['q']??''); $unit=trim($_GET['unit']??'');
  $where = $isAdmin ? '1=1' : 'm.is_public=1';
  if($q!==''){ $safe='%'.$q.'%'; $where.=" AND (m.title LIKE '".$conn->real_escape_string($safe)."' OR m.material_code LIKE '".$conn->real_escape_string($safe)."' OR m.description LIKE '".$conn->real_escape_string($safe)."')"; }
  if($unit!==''){ $where.=" AND m.unit_name='".$conn->real_escape_string($unit)."'"; }
  $materials = itc_rows($conn->query("SELECT m.*, c.title curriculum_title FROM itc_materials m LEFT JOIN itc_curriculum c ON c.id=m.curriculum_id WHERE $where ORDER BY m.id DESC"));
?>
  <?php if($isAdmin): ?>
  <div class="itc-grid mb-5"><div class="itc-stat"><div>Total Materi</div><div class="text-3xl font-extrabold"><?= $stats['materials'] ?></div></div><div class="itc-stat"><div>Total Views</div><div class="text-3xl font-extrabold"><?= (int)($conn->query("SELECT COUNT(*) c FROM itc_material_activity")->fetch_assoc()['c']??0) ?></div></div><div class="itc-stat"><div>Materi Berquiz</div><div class="text-3xl font-extrabold"><?= $stats['quiz'] ?></div></div></div>
  <details class="itc-card mb-4"><summary class="font-extrabold cursor-pointer text-lg">+ Tambah Materi Baru</summary><form method="POST" enctype="multipart/form-data" class="grid grid-cols-1 md:grid-cols-2 gap-3 mt-4"><input type="hidden" name="itc_action" value="save_material"><input class="itc-input md:col-span-2" name="title" placeholder="Judul materi"><textarea class="itc-textarea md:col-span-2" name="description" placeholder="Deskripsi singkat"></textarea><select class="itc-select" name="curriculum_id"><option value="0">Tanpa kurikulum</option><?php foreach($curr as $c): ?><option value="<?= (int)$c['id'] ?>"><?= e($c['title']) ?></option><?php endforeach; ?></select><select class="itc-select" name="material_type"><option value="text">Text</option><option value="video">Video/YouTube</option><option value="link">Link</option><option value="file">File</option></select><input class="itc-input" name="unit_name" placeholder="Unit" value="Keperawatan"><input class="itc-input" name="external_url" placeholder="URL YouTube / link eksternal"><input class="itc-input" type="file" name="material_file"><textarea class="itc-textarea md:col-span-2" name="content" placeholder="Isi materi / catatan"></textarea><label><input type="checkbox" name="has_quiz"> Materi berquiz</label><input class="itc-input" type="number" name="point_view" value="1" placeholder="Poin view"><input class="itc-input" type="number" name="pass_score" value="70" placeholder="Nilai lulus quiz"><label><input type="checkbox" name="is_public" checked> Tampil untuk user</label><button class="itc-btn itc-btn-primary md:col-span-2">Simpan Materi</button></form></details>
  <?php endif; ?>
  <div class="itc-card mb-4"><form class="flex flex-wrap gap-3"><input type="hidden" name="module" value="itc_program"><input type="hidden" name="tab" value="materials"><input class="itc-input" style="max-width:520px" name="q" value="<?= e($q) ?>" placeholder="Cari judul, kode, atau deskripsi..."><select class="itc-select" style="max-width:220px" name="unit"><option value="">Semua Unit</option><?php foreach($units as $u): ?><option <?= $unit===$u['name']?'selected':'' ?>><?= e($u['name']) ?></option><?php endforeach; ?></select><button class="itc-btn itc-btn-primary">Cari</button><a class="itc-btn itc-btn-soft" href="?module=itc_program&tab=materials">Reset</a></form></div>
  <div class="itc-grid"><?php foreach($materials as $m): ?><div class="itc-material-card"><div class="flex justify-between gap-2"><span class="itc-chip"><?= e($m['material_code'] ?: 'MTR') ?></span><span class="text-xs text-slate-500"><i class="fas fa-eye"></i> <?= (int)$m['view_count'] ?></span></div><h3 class="font-extrabold text-lg mt-3"><?= e($m['title']) ?></h3><p class="text-sm text-slate-500 mt-1"><?= e(mb_strimwidth((string)($m['description']??$m['content']),0,120,'...')) ?></p><div class="mt-3 text-sm"><div><i class="fas fa-building"></i> <?= e($m['unit_name'] ?: '-') ?></div><div><?= (int)$m['has_quiz']?'<span class="text-purple-700 font-bold">Quiz tersedia</span>':'<span class="text-slate-500">Tanpa quiz</span>' ?></div><div><i class="fas fa-star text-green-600"></i> Poin View: <?= (int)$m['point_view'] ?></div></div><div class="mt-4"><a class="itc-btn itc-btn-primary" href="?module=itc_program&tab=view_material&id=<?= (int)$m['id'] ?>">Buka Materi</a></div></div><?php endforeach; if(!$materials): ?><div class="itc-card">Belum ada materi.</div><?php endif; ?></div>

<?php elseif($tab==='view_material'):
  $id=(int)($_GET['id']??0); $stmt=$conn->prepare("SELECT * FROM itc_materials WHERE id=? LIMIT 1"); $stmt->bind_param('i',$id); $stmt->execute(); $mat=$stmt->get_result()->fetch_assoc(); $stmt->close(); if(!$mat){echo '<div class="itc-card">Materi tidak ditemukan.</div>'; } else { $embed=itc_youtube_embed($mat['external_url']??''); ?>
  <div class="itc-viewer"><a class="itc-btn itc-btn-soft mb-4" href="?module=itc_program&tab=materials">← Kembali</a><div class="flex justify-between gap-4 flex-wrap"><div><span class="itc-chip"><?= e($mat['material_code']) ?></span> <span class="itc-chip"><?= e($mat['unit_name']) ?></span><h2 class="text-3xl font-extrabold mt-3"><?= e($mat['title']) ?></h2><p class="text-slate-600 mt-2"><?= nl2br(e($mat['description'])) ?></p></div><div class="itc-card bg-slate-50"><div class="text-sm text-slate-500">Durasi membaca saat ini</div><div id="itcTimer" class="text-3xl font-extrabold text-purple-700">00:00</div><div class="text-xs text-slate-500">Log ID: auto</div><button id="itcFinishBtn" class="itc-btn itc-btn-green mt-3">Selesai Membaca</button></div></div><hr class="my-5">
    <?php if($embed && preg_match('~youtube\.com/embed~',$embed)): ?><iframe class="itc-video" src="<?= e($embed) ?>" allowfullscreen></iframe><?php elseif($mat['file_path']): ?><a class="itc-btn itc-btn-primary" target="_blank" href="<?= e($mat['file_path']) ?>">Buka File Terlampir</a><?php elseif($mat['external_url']): ?><a class="itc-btn itc-btn-primary" target="_blank" href="<?= e($mat['external_url']) ?>">Buka Link Materi</a><?php endif; ?>
    <?php if($mat['content']): ?><div class="prose max-w-none mt-5 whitespace-pre-wrap"><?= e($mat['content']) ?></div><?php endif; ?>
  </div><script>
  (function(){let sec=0;const mid=<?= (int)$mat['id'] ?>;const timer=document.getElementById('itcTimer');function fmt(s){let m=Math.floor(s/60),ss=s%60;return String(m).padStart(2,'0')+':'+String(ss).padStart(2,'0')}function post(status){const fd=new FormData();fd.append('itc_action','track_material');fd.append('material_id',mid);fd.append('duration_seconds',sec);fd.append('status',status||'sedang');fetch('?module=itc_program',{method:'POST',body:fd,credentials:'same-origin'}).catch(()=>{});} setInterval(()=>{sec++; timer.textContent=fmt(sec); if(sec%10===0)post('sedang');},1000); post('mulai'); document.getElementById('itcFinishBtn').onclick=function(){post('selesai'); alert('Aktivitas membaca/menonton tersimpan.');}; window.addEventListener('beforeunload',()=>post('sedang'));})();
  </script><?php } ?>

<?php elseif($tab==='activity' && $isAdmin):
  $rows=itc_rows($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 LIMIT 300")); ?>
  <div class="itc-card"><div class="flex justify-between items-center mb-3"><div><h2 class="text-xl font-extrabold">Riwayat Aktivitas Membaca Materi</h2><p class="text-slate-500">Pengukur berapa lama user melihat, menonton, dan membaca materi.</p></div><a class="itc-btn itc-btn-green" href="itc_program_export.php?type=activity">Export Excel</a></div><div class="overflow-x-auto"><table class="itc-table"><thead><tr><th>Tanggal</th><th>User</th><th>NIK</th><th>Unit</th><th>Materi</th><th>Durasi</th><th>Status</th><th>Role</th></tr></thead><tbody><?php foreach($rows as $r): ?><tr><td><?= e(itc_date_id($r['last_seen_at'] ?: $r['created_at'])) ?></td><td><b><?= e($r['user_name']) ?></b></td><td><?= e($r['nik']) ?></td><td><?= e($r['unit_name']) ?></td><td><b><?= e($r['material_title']) ?></b><div class="text-xs text-slate-500"><?= e($r['material_code']) ?></div></td><td><?= e(itc_duration_text($r['duration_seconds'])) ?></td><td><?= itc_status_badge($r['status']) ?></td><td><span class="itc-chip"><?= e($r['role_name']) ?></span></td></tr><?php endforeach; ?></tbody></table></div></div>

<?php elseif($tab==='instructors' && $isAdmin): ?>
  <details class="itc-card mb-4"><summary class="font-extrabold cursor-pointer">+ Tambah Instruktur/Lector</summary><form method="POST" class="grid grid-cols-1 md:grid-cols-2 gap-3 mt-4"><input type="hidden" name="itc_action" value="save_instructor"><select class="itc-select" name="employee_id"><option value="0">Manual / tidak terhubung karyawan</option><?php foreach($employees as $e): ?><option value="<?= (int)$e['id'] ?>"><?= e($e['full_name'].' - '.$e['nik']) ?></option><?php endforeach; ?></select><input class="itc-input" name="name" placeholder="Nama instruktur"><input class="itc-input" name="profession" placeholder="Profesi"><input class="itc-input" name="phone" placeholder="Telepon"><input class="itc-input" name="email" placeholder="Email"><textarea class="itc-textarea md:col-span-2" name="expertise" placeholder="Keahlian / bidang ajar"></textarea><button class="itc-btn itc-btn-primary md:col-span-2">Simpan</button></form></details><div class="itc-card"><table class="itc-table"><tr><th>Nama</th><th>Profesi</th><th>Keahlian</th><th>Status</th></tr><?php foreach(itc_rows($conn->query("SELECT * FROM itc_instructors ORDER BY id DESC")) as $r): ?><tr><td><b><?= e($r['name']) ?></b><div class="text-xs"><?= e($r['instructor_code']) ?></div></td><td><?= e($r['profession']) ?></td><td><?= e($r['expertise']) ?></td><td><?= e($r['status']) ?></td></tr><?php endforeach; ?></table></div>

<?php elseif($tab==='curriculum' && $isAdmin): ?>
  <details class="itc-card mb-4"><summary class="font-extrabold cursor-pointer">+ Tambah Kurikulum</summary><form method="POST" class="grid grid-cols-1 md:grid-cols-2 gap-3 mt-4"><input type="hidden" name="itc_action" value="save_curriculum"><input class="itc-input md:col-span-2" name="title" placeholder="Judul kurikulum"><input class="itc-input" name="target_role" placeholder="Target role"><input class="itc-input" name="target_unit" placeholder="Target unit"><input class="itc-input" name="competency_level" placeholder="Level kompetensi"><input class="itc-input" type="number" name="min_score" value="70"><textarea class="itc-textarea md:col-span-2" name="description" placeholder="Deskripsi"></textarea><button class="itc-btn itc-btn-primary md:col-span-2">Simpan</button></form></details><div class="itc-card"><table class="itc-table"><tr><th>Kode</th><th>Judul</th><th>Target</th><th>Nilai Lulus</th></tr><?php foreach(itc_rows($conn->query("SELECT * FROM itc_curriculum ORDER BY id DESC")) as $r): ?><tr><td><?= e($r['curriculum_code']) ?></td><td><b><?= e($r['title']) ?></b><div><?= e($r['description']) ?></div></td><td><?= e($r['target_role'].' / '.$r['target_unit']) ?></td><td><?= e($r['min_score']) ?></td></tr><?php endforeach; ?></table></div>

<?php elseif($tab==='schedule' && $isAdmin): ?>
  <details class="itc-card mb-4"><summary class="font-extrabold cursor-pointer">+ Jadwal Mengajar Instruktur</summary><form method="POST" class="grid grid-cols-1 md:grid-cols-2 gap-3 mt-4"><input type="hidden" name="itc_action" value="save_schedule"><input class="itc-input md:col-span-2" name="title" placeholder="Judul kegiatan"><select class="itc-select" name="instructor_id"><option value="0">Pilih instruktur</option><?php foreach($instructors as $i): ?><option value="<?= (int)$i['id'] ?>"><?= e($i['name']) ?></option><?php endforeach; ?></select><select class="itc-select" name="curriculum_id"><option value="0">Kurikulum</option><?php foreach($curr as $c): ?><option value="<?= (int)$c['id'] ?>"><?= e($c['title']) ?></option><?php endforeach; ?></select><input class="itc-input" type="date" name="schedule_date" value="<?= date('Y-m-d') ?>"><input class="itc-input" type="time" name="start_time"><input class="itc-input" type="time" name="end_time"><input class="itc-input" name="location" placeholder="Lokasi"><select class="itc-select" name="method"><option>offline</option><option>online</option><option>hybrid</option></select><input class="itc-input" name="link_online" placeholder="Link online"><button class="itc-btn itc-btn-primary md:col-span-2">Simpan Jadwal</button></form></details><div class="itc-card"><table class="itc-table"><tr><th>Tanggal</th><th>Judul</th><th>Instruktur</th><th>Lokasi/Metode</th></tr><?php foreach(itc_rows($conn->query("SELECT s.*, i.name instructor_name FROM itc_schedules s LEFT JOIN itc_instructors i ON i.id=s.instructor_id ORDER BY s.schedule_date DESC LIMIT 200")) as $r): ?><tr><td><?= e(date('d/m/Y',strtotime($r['schedule_date']))) ?><div><?= e(substr($r['start_time'],0,5).' - '.substr($r['end_time'],0,5)) ?></div></td><td><b><?= e($r['title']) ?></b></td><td><?= e($r['instructor_name']) ?></td><td><?= e($r['location'].' / '.$r['method']) ?></td></tr><?php endforeach; ?></table></div>

<?php elseif(in_array($tab,['questions','tryouts','results','certificates'],true)): ?>
  <div class="itc-card"><h2 class="text-xl font-extrabold mb-2"><?= e($tabs[$tab]) ?></h2><p class="text-slate-600">Bagian ini tetap disiapkan sebagai menu ITC. Tahap berikutnya bisa kita detailkan sesuai alur ujian/sertifikat yang dipakai.</p></div>
<?php else: ?>
  <div class="itc-card">Tab tidak ditemukan atau tidak punya akses.</div>
<?php endif; ?>
</div>
