<?php
// coaching_public.php - Link publik staf baru, tanpa login.
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/config/database.php';
$conn = getConnection();
if (!function_exists('e')) { function e($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); } }
if (!function_exists('date_id')) { function date_id($date): string { if (!$date) return '-'; $ts=strtotime((string)$date); if(!$ts) return (string)$date; $b=[1=>'Januari',2=>'Februari',3=>'Maret',4=>'April',5=>'Mei',6=>'Juni',7=>'Juli',8=>'Agustus',9=>'September',10=>'Oktober',11=>'November',12=>'Desember']; return date('d',$ts).' '.($b[(int)date('n',$ts)]??'').' '.date('Y',$ts); } }
if (!function_exists('avg_score_row')) { function avg_score_row(array $r): float { $keys=['understanding_score','repeat_explanation_score','follow_instruction_score','discipline_score','initiative_score','enthusiasm_score','responsibility_score','communication_score','ethic_score','professional_score']; $sum=0;$n=0; foreach($keys as $k){ $v=(int)($r[$k]??0); if($v>0){$sum+=$v;$n++;}} return $n?round($sum/$n,2):0; } }
$token = trim((string)($_GET['t'] ?? ''));
$orientation = null;
$logs = [];
if ($token !== '') {
    $stmt = $conn->prepare("SELECT * FROM coaching_orientations WHERE public_token = ? AND public_enabled = 1 LIMIT 1");
    if ($stmt) { $stmt->bind_param('s', $token); $stmt->execute(); $res=$stmt->get_result(); $orientation=$res?$res->fetch_assoc():null; $stmt->close(); }
    if ($orientation) {
        $stmt = $conn->prepare("SELECT * FROM coaching_daily_logs WHERE orientation_id = ? ORDER BY day_number ASC");
        $oid=(int)$orientation['id']; $stmt->bind_param('i',$oid); $stmt->execute(); $res=$stmt->get_result(); while($row=$res->fetch_assoc()) $logs[]=$row; $stmt->close();
    }
}
$submitted=0;$avg=0;$sum=0;$need=0; foreach($logs as $r){ if(($r['status']??'')==='submitted'){ $submitted++; $sum+=avg_score_row($r);} $need += ((int)($r['check_disappear']??0)+(int)($r['check_refuse_task']??0)+(int)($r['check_need_warning']??0)); } $avg=$submitted?round($sum/$submitted,2):0;
$category = $avg>=4.5?'Sangat Baik':($avg>=3.5?'Baik':($avg>=2.75?'Cukup':($avg>=2?'Kurang':'Bermasalah')));
$activity = $avg>=4?'Aktif':($avg>=3?'Cukup Aktif':($avg>=2?'Pasif':'Tidak Kooperatif')); if($need>=3) $activity='Perlu Pembinaan';
?>
<!doctype html><html lang="id"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Jadwal Coaching Orientasi</title><script src="https://cdn.tailwindcss.com"></script><link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap" rel="stylesheet"><style>body{font-family:Poppins,system-ui,sans-serif}</style></head>
<body class="bg-slate-100 text-slate-800">
<div class="max-w-6xl mx-auto p-4 md:p-8">
<?php if (!$orientation): ?>
  <div class="bg-white rounded-3xl shadow p-8 text-center"><div class="text-5xl mb-3">🔒</div><h1 class="text-2xl font-bold">Link coaching tidak valid / sudah dinonaktifkan</h1><p class="text-slate-500 mt-2">Silakan hubungi Clinical Instructor atau admin keperawatan.</p></div>
<?php else: ?>
  <div class="rounded-[32px] p-6 md:p-8 text-white shadow-xl mb-6" style="background:linear-gradient(135deg,#0f766e,#2563eb,#4f46e5)">
    <div class="flex flex-col md:flex-row md:items-end md:justify-between gap-5">
      <div><div class="inline-flex bg-white/15 rounded-full px-4 py-2 text-sm font-semibold mb-3">Coaching Orientasi 14 Hari</div><h1 class="text-3xl font-extrabold"><?= e($orientation['staff_name_manual']) ?></h1><p class="text-blue-50 mt-1">Unit: <?= e($orientation['unit_name']) ?> • Koordinator CI: <?= e($orientation['coach_name_manual']) ?></p><p class="text-blue-50">Periode: <?= e(date_id($orientation['start_date'])) ?> s/d <?= e(date_id($orientation['end_date'])) ?></p></div>
      <div class="bg-white/15 rounded-3xl px-5 py-4"><div class="text-sm text-blue-50">Progress</div><div class="text-3xl font-black"><?= $submitted ?>/14</div></div>
    </div>
  </div>
  <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
    <div class="bg-white rounded-3xl shadow p-5"><div class="text-slate-500 text-sm">Rata-rata skor</div><div class="text-3xl font-black text-indigo-700"><?= e($avg) ?>/5</div></div>
    <div class="bg-white rounded-3xl shadow p-5"><div class="text-slate-500 text-sm">Kategori</div><div class="text-2xl font-black text-emerald-700"><?= e($category) ?></div></div>
    <div class="bg-white rounded-3xl shadow p-5"><div class="text-slate-500 text-sm">Keaktifan</div><div class="text-2xl font-black text-amber-700"><?= e($activity) ?></div></div>
  </div>
  <div class="bg-white rounded-3xl shadow overflow-hidden">
    <div class="p-5 border-b"><h2 class="font-bold text-lg">Tabulasi Harian</h2><p class="text-sm text-slate-500">Staf dapat melihat materi, praktik, dan catatan yang sudah diinput oleh CI.</p></div>
    <div class="overflow-x-auto"><table class="min-w-full text-sm"><thead class="bg-slate-50 text-slate-600"><tr><th class="px-4 py-3 text-left">Hari</th><th class="px-4 py-3 text-left">Tanggal</th><th class="px-4 py-3 text-left">Coach Hari Ini</th><th class="px-4 py-3 text-left">Materi</th><th class="px-4 py-3 text-left">Praktik</th><th class="px-4 py-3 text-center">Skor</th><th class="px-4 py-3 text-left">Status</th></tr></thead><tbody class="divide-y">
    <?php foreach($logs as $r): $rowavg=avg_score_row($r); ?>
      <tr><td class="px-4 py-3 font-bold">Hari <?= (int)$r['day_number'] ?></td><td class="px-4 py-3"><?= e(date_id($r['log_date'])) ?></td><td class="px-4 py-3"><?= e(($r['daily_coach_name'] ?? '') ?: '-') ?></td><td class="px-4 py-3 max-w-md whitespace-pre-line"><?= e($r['materials_taught'] ?: '-') ?></td><td class="px-4 py-3 max-w-md whitespace-pre-line"><?= e($r['practice_done'] ?: '-') ?></td><td class="px-4 py-3 text-center font-bold"><?= $rowavg>0?e($rowavg):'-' ?></td><td class="px-4 py-3"><span class="rounded-full px-3 py-1 text-xs font-bold <?= ($r['status']==='submitted')?'bg-emerald-100 text-emerald-700':'bg-slate-100 text-slate-500' ?>"><?= e($r['status']==='submitted'?'Terisi':'Belum terisi') ?></span></td></tr>
    <?php endforeach; ?>
    </tbody></table></div>
  </div>
<?php endif; ?>
</div></body></html>
