<?php
declare(strict_types=1);

// modules/data_staf_baru.php
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/app.php';

checkAuth();
$conn = getConnection();

if (!function_exists('e')) {
    function e($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

if (!$conn) {
    echo "<div class='bg-red-50 border-l-4 border-red-500 p-4 rounded'>
            <p class='text-red-700'>Koneksi database gagal.</p>
          </div>";
    return;
}



if (!function_exists('ensure_wawancara_signature_columns')) {
    function ensure_wawancara_signature_columns(mysqli $conn): void
    {
        $cols = [
            'pewawancara_1_nik' => "ALTER TABLE wawancara_staf_baru ADD COLUMN pewawancara_1_nik VARCHAR(50) NULL AFTER pewawancara_1_nama",
            'pewawancara_2_nik' => "ALTER TABLE wawancara_staf_baru ADD COLUMN pewawancara_2_nik VARCHAR(50) NULL AFTER pewawancara_2_nama",
            'pewawancara_3_nik' => "ALTER TABLE wawancara_staf_baru ADD COLUMN pewawancara_3_nik VARCHAR(50) NULL AFTER pewawancara_3_nama",
            'ttd_qr_signed_at'   => "ALTER TABLE wawancara_staf_baru ADD COLUMN ttd_qr_signed_at DATETIME NULL AFTER pewawancara_3_nik",
        ];

        foreach ($cols as $col => $sql) {
            $safeCol = $conn->real_escape_string($col);
            $check = $conn->query("SHOW COLUMNS FROM wawancara_staf_baru LIKE '{$safeCol}'");
            if ($check && $check->num_rows === 0) {
                try { $conn->query($sql); } catch (Throwable $e) { /* abaikan supaya modul tetap berjalan */ }
            }
            if ($check) { $check->close(); }
        }
    }
}

if (!function_exists('save_wawancara_signature_nik')) {
    function save_wawancara_signature_nik(mysqli $conn, int $id, array $nik): void
    {
        if ($id <= 0) { return; }
        ensure_wawancara_signature_columns($conn);
        $n1 = trim((string)($nik[1] ?? ''));
        $n2 = trim((string)($nik[2] ?? ''));
        $n3 = trim((string)($nik[3] ?? ''));
        $stmt = $conn->prepare("
            UPDATE wawancara_staf_baru
            SET pewawancara_1_nik = ?,
                pewawancara_2_nik = ?,
                pewawancara_3_nik = ?,
                ttd_qr_signed_at = COALESCE(ttd_qr_signed_at, NOW())
            WHERE id = ?
        ");
        if ($stmt) {
            $stmt->bind_param('sssi', $n1, $n2, $n3, $id);
            $stmt->execute();
            $stmt->close();
        }
    }
}

ensure_wawancara_signature_columns($conn);

$module = 'data_staf_baru';
$action = $_GET['action'] ?? 'list';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$error = '';

// Export Excel HARUS dibuka langsung ke file module ini, bukan melalui index.php,
// agar header download tidak bentrok dengan template/index yang sudah mencetak HTML.
$directModuleUrl = 'export_staf_baru_excel.php';
if (in_array((string)$action, ['excel', 'excel_gabungan'], true)) {
    ini_set('display_errors', '0');
    ini_set('display_startup_errors', '0');
}

if (!function_exists('safeLogActivity')) {
    function safeLogActivity(string $action, string $table, int $recordId, string $description): void
    {
        if (function_exists('logActivity')) {
            try {
                logActivity($action, $table, $recordId, $description);
            } catch (Throwable $e) {
                // abaikan
            }
        }
    }
}

$fields = [
    'penampilan',
    'etika',
    'komunikasi',
    'pendidikan_formal',
    'pengalaman_kerja',
    'kerjasama_tim',
    'komitmen',
    'pandangan_perusahaan',
    'bahasa_asing',
    'faktor_pendukung',
    'kompensasi'
];

$labels = [
    'penampilan' => 'Penampilan',
    'etika' => 'Etika/Sikap',
    'komunikasi' => 'Komunikasi',
    'pendidikan_formal' => 'Pendidikan Formal',
    'pengalaman_kerja' => 'Pengalaman Kerja',
    'kerjasama_tim' => 'Kerjasama Tim',
    'komitmen' => 'Komitmen',
    'pandangan_perusahaan' => 'Pandangan terhadap Perusahaan',
    'bahasa_asing' => 'Bahasa Asing',
    'faktor_pendukung' => 'Faktor Pendukung',
    'kompensasi' => 'Kompensasi'
];

$uraianLabels = [
    'penampilan' => 'Cara berpakaian, kerapihan, dan keadaan fisik secara umum',
    'etika' => 'Menunjukkan sikap sopan santun dalam tutur kata dan tingkah laku',
    'komunikasi' => 'Kemampuan mengungkapkan ide secara sistematis dan jelas sehingga dapat dipahami dengan benar oleh orang lain',
    'pendidikan_formal' => 'Tingkat pendidikan formal, kursus, dan seminar yang menunjang posisi yang dilamar',
    'pengalaman_kerja' => 'Kesesuaian pengalaman kerja sebelumnya dengan pekerjaan yang dilamar',
    'kerjasama_tim' => 'Kemampuan beradaptasi, bekerja sama dengan rekan kerja, dan sanggup bekerja dalam shift',
    'komitmen' => 'Kesanggupan bekerja dengan baik, mematuhi peraturan, dan menerima konsekuensi bila melakukan kesalahan',
    'pandangan_perusahaan' => 'Pandangan terhadap pekerjaan, perusahaan, pasien, dan konsumen rumah sakit',
    'bahasa_asing' => 'Kemampuan berbahasa asing yang dapat dimengerti orang lain',
    'faktor_pendukung' => 'Jarak tempat tinggal, kondisi keluarga, dan faktor pendukung lain',
    'kompensasi' => 'Besaran gaji dan jenis tunjangan yang diharapkan'
];

if (!function_exists('format_tanggal_id_safe')) {
    function format_tanggal_id_safe(?string $date): string
    {
        $date = trim((string)$date);
        if ($date === '' || $date === '0000-00-00') {
            return '-';
        }

        $bulan = [
            1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April',
            5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus',
            9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
        ];

        $ts = strtotime($date);
        if (!$ts) {
            return $date;
        }

        return date('d', $ts) . ' ' . $bulan[(int)date('n', $ts)] . ' ' . date('Y', $ts);
    }
}

if (!function_exists('nilai_akhir_wawancara')) {
    function nilai_akhir_wawancara(array $row): float
    {
        $nilai = [];
        for ($i = 1; $i <= 3; $i++) {
            $v = isset($row['rata_rata_' . $i]) ? (float)$row['rata_rata_' . $i] : 0.0;
            if ($v > 0) {
                $nilai[] = $v;
            }
        }

        if (!$nilai) {
            return 0.0;
        }

        return array_sum($nilai) / count($nilai);
    }
}

if (!function_exists('grading_wawancara')) {
    function grading_wawancara(float $nilai): array
    {
        if ($nilai >= 85) {
            return [
                'grade' => 'A',
                'label' => 'Sangat Direkomendasikan',
                'keputusan' => 'Dapat Diterima',
                'class' => 'grade-a'
            ];
        }

        if ($nilai >= 75) {
            return [
                'grade' => 'B',
                'label' => 'Direkomendasikan',
                'keputusan' => 'Dapat Diterima',
                'class' => 'grade-b'
            ];
        }

        if ($nilai >= 60) {
            return [
                'grade' => 'C',
                'label' => 'Dipertimbangkan',
                'keputusan' => 'Dipertimbangkan',
                'class' => 'grade-c'
            ];
        }

        return [
            'grade' => 'D',
            'label' => 'Tidak Direkomendasikan',
            'keputusan' => 'Tidak Disarankan',
            'class' => 'grade-d'
        ];
    }
}


if (!function_exists('grading_wawancara_dari_rekomendasi')) {
    /**
     * Print/export mengikuti kolom rekomendasi/keputusan_akhir di DB,
     * bukan menghitung ulang keputusan dari nilai.
     */
    function grading_wawancara_dari_rekomendasi(array $row, ?float $nilaiFallback = null): array
    {
        $raw = trim((string)($row['keputusan_akhir'] ?? ''));
        $key = strtolower($raw);
        $key = str_replace(['_', '-'], ' ', $key);
        $key = preg_replace('/\s+/', ' ', $key);

        if (in_array($key, ['diterima', 'dapat diterima', 'direkomendasikan'], true)) {
            return [
                'grade' => 'B',
                'label' => 'Direkomendasikan',
                'keputusan' => 'Diterima',
                'class' => 'grade-b'
            ];
        }

        if (in_array($key, ['dipertimbangkan', 'dipertimbangankan'], true)) {
            return [
                'grade' => 'C',
                'label' => 'Dipertimbangkan',
                'keputusan' => 'Dipertimbangkan',
                'class' => 'grade-c'
            ];
        }

        if (in_array($key, ['tidak disarankan', 'tidak direkomendasikan', 'ditolak'], true)) {
            return [
                'grade' => 'D',
                'label' => 'Tidak Direkomendasikan',
                'keputusan' => 'Tidak Disarankan',
                'class' => 'grade-d'
            ];
        }

        return grading_wawancara((float)($nilaiFallback ?? nilai_akhir_wawancara($row)));
    }
}

if (!function_exists('nilai_form_wawancara')) {
    /**
     * ADD memakai default 80.00.
     * EDIT mengambil nilai DB apa adanya agar tidak kembali menjadi default 80.
     */
    function nilai_form_wawancara(array $detailData, string $key, string $action): string
    {
        if ($action === 'edit') {
            if (array_key_exists($key, $detailData)) {
                $value = $detailData[$key];
                if ($value === null || $value === '') {
                    return '';
                }
                return number_format((float)$value, 2, '.', '');
            }
            return '';
        }

        if (array_key_exists($key, $detailData) && $detailData[$key] !== null && $detailData[$key] !== '') {
            return number_format((float)$detailData[$key], 2, '.', '');
        }

        return '80.00';
    }
}

if (!function_exists('skor_interviewer_aktif')) {
    function skor_interviewer_aktif(array $row): array
    {
        $aktif = [];
        for ($i = 1; $i <= 3; $i++) {
            $nama = trim((string)($row['pewawancara_' . $i . '_nama'] ?? ''));
            $rata = (float)($row['rata_rata_' . $i] ?? 0);
            $adaSkor = $rata > 0;

            if ($nama !== '' || $adaSkor) {
                $aktif[] = $i;
            }
        }

        return $aktif ?: [1, 2, 3];
    }
}

if (!function_exists('render_print_css_wawancara')) {
    function render_print_css_wawancara(): void
    {
        echo <<<HTML
<style>
    * { box-sizing: border-box; }
    body {
        font-family: Arial, Helvetica, sans-serif;
        color: #111827;
        background: #e5e7eb;
        margin: 0;
        padding: 18px;
        font-size: 12px;
    }
    .toolbar {
        max-width: 1120px;
        margin: 0 auto 12px auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 8px;
        background: #ffffff;
        border: 1px solid #d1d5db;
        padding: 10px 12px;
        border-radius: 12px;
    }
    .toolbar a,
    .toolbar button {
        border: 0;
        background: #2563eb;
        color: #ffffff;
        padding: 8px 12px;
        border-radius: 10px;
        text-decoration: none;
        font-weight: 700;
        cursor: pointer;
        font-size: 12px;
    }
    .toolbar .btn-light {
        background: #f3f4f6;
        color: #111827;
        border: 1px solid #d1d5db;
    }
    .page {
        width: 210mm;
        min-height: 297mm;
        margin: 0 auto 16px auto;
        background: #ffffff;
        padding: 12mm 12mm 10mm 12mm;
        border: 1px solid #d1d5db;
        page-break-after: always;
    }
    .page:last-child { page-break-after: auto; }
    .page.rekap-page {
        width: 297mm;
        min-height: 210mm;
        padding: 10mm 10mm 8mm 10mm;
    }
    .page.individu-page {
        width: 210mm;
        min-height: 297mm;
    }
    .doc-title {
        text-align: center;
        font-size: 15px;
        font-weight: 800;
        letter-spacing: .2px;
        margin: 4px 0 12px 0;
        text-transform: uppercase;
    }
    .identity {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 8px;
    }
    .identity td {
        padding: 3px 4px;
        vertical-align: top;
        border: 0;
        font-size: 12px;
    }
    .identity .label { width: 28mm; font-weight: 700; }
    .identity .colon { width: 4mm; text-align: center; }
    table.score {
        width: 100%;
        border-collapse: collapse;
        table-layout: fixed;
    }
    table.score th,
    table.score td {
        border: 1px solid #111827;
        padding: 4px 5px;
        vertical-align: top;
        font-size: 11px;
        line-height: 1.25;
    }
    table.score th {
        background: #f3f4f6;
        text-align: center;
        font-weight: 800;
    }
    .center { text-align: center; }
    .right { text-align: right; }
    .bold { font-weight: 800; }
    .muted { color: #4b5563; }
    .bg-soft { background: #f9fafb; }
    .summary-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 8px;
        margin: 10px 0;
    }
    .summary-card {
        border: 1px solid #d1d5db;
        border-radius: 10px;
        padding: 8px;
        background: #f9fafb;
    }
    .summary-card .label {
        font-size: 10px;
        color: #4b5563;
        margin-bottom: 3px;
    }
    .summary-card .value {
        font-size: 16px;
        font-weight: 800;
    }
    .grade-a { color: #047857; font-weight: 800; }
    .grade-b { color: #2563eb; font-weight: 800; }
    .grade-c { color: #b45309; font-weight: 800; }
    .grade-d { color: #b91c1c; font-weight: 800; }
    .section-title {
        font-weight: 800;
        margin: 10px 0 5px 0;
        font-size: 12px;
    }
    .signature-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 8px;
        margin-top: 10px;
    }
    .signature-box {
        border: 1px solid #111827;
        min-height: 34mm;
        padding: 6px;
        font-size: 11px;
    }
    .signature-date {
        text-align: right;
        margin-bottom: 16mm;
        min-height: 12px;
    }
    .signature-name {
        text-align: center;
        font-weight: 700;
        text-decoration: underline;
    }
    .note {
        font-size: 10px;
        color: #374151;
        margin-top: 6px;
    }
    .rekap-title {
        font-size: 14px;
        font-weight: 800;
        margin: 10px 0 8px 0;
        text-transform: uppercase;
    }
    table.rekap {
        width: 100%;
        border-collapse: collapse;
        table-layout: fixed;
    }
    table.rekap th,
    table.rekap td {
        border: 1px solid #111827;
        padding: 4px;
        font-size: 9.5px;
        line-height: 1.18;
        vertical-align: top;
        word-break: break-word;
    }
    table.rekap th {
        background: #f3f4f6;
        text-align: center;
        font-weight: 800;
    }
    @page portraitPage { size: A4 portrait; margin: 8mm; }
    @page landscapePage { size: A4 landscape; margin: 8mm; }
    @media print {
        @page { size: A4 portrait; margin: 8mm; }
        body {
            background: #ffffff;
            padding: 0;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        .toolbar { display: none !important; }
        .page {
            width: auto;
            min-height: auto;
            border: 0;
            margin: 0;
            padding: 0;
            box-shadow: none;
        }
        .page.rekap-page { page: landscapePage; }
        .page.individu-page { page: portraitPage; }
        .rekap-page .doc-title { font-size: 13px; margin-top: 0; margin-bottom: 7px; }
        .rekap-page .identity td { font-size: 10.5px; padding: 2px 3px; }
        .rekap-page .summary-grid { gap: 5px; margin: 6px 0; }
        .rekap-page .summary-card { padding: 5px 6px; border-radius: 6px; }
        .rekap-page .summary-card .value { font-size: 14px; }
        .rekap-page .rekap-title { font-size: 11.5px; margin: 6px 0 4px 0; }
        .rekap-page table.rekap th,
        .rekap-page table.rekap td { font-size: 8.8px; padding: 3px; }
        .no-break { page-break-inside: avoid; }
    }
</style>
HTML;
    }
}

if (!function_exists('render_print_individu_wawancara')) {
    function render_print_individu_wawancara(array $row, array $fields, array $labels, array $uraianLabels, string $module, bool $standalone = true): void
    {
        $nilaiAkhir = nilai_akhir_wawancara($row);
        $grade = grading_wawancara_dari_rekomendasi($row, $nilaiAkhir);
        $aktif = skor_interviewer_aktif($row);
        $tanggal = format_tanggal_id_safe((string)($row['tanggal_wawancara'] ?? ''));

        if ($standalone) {
            echo "<!DOCTYPE html><html lang='id'><head><meta charset='UTF-8'><title>Print Wawancara - " . e($row['nama_lengkap'] ?? '') . "</title>";
            render_print_css_wawancara();
            echo "</head><body>";
            echo "<div class='toolbar'><div><strong>Print Penilaian Wawancara Staf Baru</strong></div><div><a class='btn-light' href='?module=" . e($module) . "&action=detail&id=" . (int)$row['id'] . "'>← Kembali</a><button onclick='window.print()'>Print</button></div></div>";
        }

        echo "<section class='page individu-page'>";
        echo "<div class='doc-title'>PEDOMAN PENILAIAN WAWANCARA</div>";

        echo "<table class='identity'>";
        echo "<tr>";
        echo "<td class='label'>Nama Lengkap</td><td class='colon'>:</td><td>" . e($row['nama_lengkap'] ?? '-') . "</td>";
        echo "<td class='label'>Tanggal Wawancara</td><td class='colon'>:</td><td>" . e($tanggal) . "</td>";
        echo "</tr>";
        echo "<tr>";
        echo "<td class='label'>Pendidikan</td><td class='colon'>:</td><td>" . e($row['pendidikan'] ?? '-') . "</td>";
        echo "<td class='label'>Posisi Yang Dicari</td><td class='colon'>:</td><td>" . e($row['posisi_dicari'] ?? '-') . "</td>";
        echo "</tr>";
        echo "</table>";

        echo "<table class='score'>";
        echo "<thead>";
        echo "<tr>";
        echo "<th style='width:8mm' rowspan='2'>NO</th>";
        echo "<th style='width:37mm' rowspan='2'>ASPEK PENILAIAN</th>";
        echo "<th rowspan='2'>URAIAN</th>";
        echo "<th colspan='3'>PEWAWANCARA</th>";
        echo "</tr>";
        echo "<tr><th style='width:18mm'>1</th><th style='width:18mm'>2</th><th style='width:18mm'>3</th></tr>";
        echo "</thead><tbody>";

        $no = 1;
        foreach ($fields as $field) {
            echo "<tr>";
            echo "<td class='center'>" . $no++ . "</td>";
            echo "<td>" . e($labels[$field] ?? $field) . "</td>";
            echo "<td>" . nl2br(e($uraianLabels[$field] ?? '')) . "</td>";
            for ($i = 1; $i <= 3; $i++) {
                $nilai = (float)($row[$field . '_' . $i] ?? 0);
                echo "<td class='center'>" . ($nilai > 0 ? number_format($nilai, 0) : '') . "</td>";
            }
            echo "</tr>";
        }

        echo "<tr class='bg-soft bold'>";
        echo "<td colspan='3'>TOTAL NILAI</td>";
        for ($i = 1; $i <= 3; $i++) {
            $total = 0;
            foreach ($fields as $field) {
                $total += (float)($row[$field . '_' . $i] ?? 0);
            }
            echo "<td class='center'>" . ($total > 0 ? number_format($total, 0) : '') . "</td>";
        }
        echo "</tr>";

        echo "<tr class='bg-soft bold'>";
        echo "<td colspan='3'>NILAI RATA-RATA</td>";
        for ($i = 1; $i <= 3; $i++) {
            $rata = (float)($row['rata_rata_' . $i] ?? 0);
            echo "<td class='center'>" . ($rata > 0 ? number_format($rata, 2) : '') . "</td>";
        }
        echo "</tr>";
        echo "</tbody></table>";

        echo "<div class='note'>Catatan: range nilai 0 - 100</div>";

        echo "<div class='summary-grid no-break'>";
        echo "<div class='summary-card'><div class='label'>Nilai Akhir</div><div class='value'>" . number_format($nilaiAkhir, 2) . "</div></div>";
        echo "<div class='summary-card'><div class='label'>Grade</div><div class='value " . e($grade['class']) . "'>" . e($grade['grade']) . "</div></div>";
        echo "<div class='summary-card'><div class='label'>Kategori</div><div class='value " . e($grade['class']) . "' style='font-size:12px;'>" . e($grade['label']) . "</div></div>";
        echo "<div class='summary-card'><div class='label'>Keputusan Sistem</div><div class='value " . e($grade['class']) . "' style='font-size:12px;'>" . e($grade['keputusan']) . "</div></div>";
        echo "</div>";

        echo "<div class='section-title'>Kesimpulan dan Saran</div>";
        echo "<table class='score'>";
        echo "<thead><tr><th style='width:32mm'>Pewawancara</th><th style='width:35mm'>Kesimpulan</th><th>Saran / Komentar</th><th style='width:42mm'>Nama</th></tr></thead><tbody>";
        for ($i = 1; $i <= 3; $i++) {
            echo "<tr>";
            echo "<td class='bold'>Pewawancara " . $i . "</td>";
            echo "<td>" . e($row['kesimpulan_' . $i] ?? '-') . "</td>";
            echo "<td>" . nl2br(e($row['saran_komentar_' . $i] ?? '-')) . "</td>";
            echo "<td class='center'>" . e($row['pewawancara_' . $i . '_nama'] ?? '-') . "</td>";
            echo "</tr>";
        }
        echo "</tbody></table>";

        echo "<div class='section-title'>Tanda Tangan Pewawancara</div>";
        echo "<div class='signature-grid'>";
        for ($i = 1; $i <= 3; $i++) {
            echo "<div class='signature-box'>";
            echo "<div class='bold'>Pewawancara " . $i . "</div>";
            echo "<div class='signature-date'>Denpasar, " . e($tanggal) . "</div>";
            echo "<div class='signature-name'>(" . e($row['pewawancara_' . $i . '_nama'] ?: '................................') . ")</div>";
            echo "</div>";
        }
        echo "</div>";

        echo "<div class='note'>Catatan: kolom kesimpulan diisi keterangan Dapat Diterima / Dipertimbangkan / Tidak Disarankan.</div>";
        echo "</section>";

        if ($standalone) {
            echo "<script>if(new URLSearchParams(location.search).get('autoprint')==='1'){window.addEventListener('load',()=>setTimeout(()=>window.print(),400));}</script>";
            echo "</body></html>";
        }
    }
}

if (!function_exists('render_print_gabungan_wawancara')) {
    function render_print_gabungan_wawancara(array $rows, array $fields, array $labels, array $uraianLabels, string $module, string $tanggalFilter = ''): void
    {
        $tanggalJudul = $tanggalFilter !== '' ? format_tanggal_id_safe($tanggalFilter) : 'Semua Tanggal';
        $total = count($rows);
        $sum = 0.0;
        $gradeCounter = ['A' => 0, 'B' => 0, 'C' => 0, 'D' => 0];

        foreach ($rows as $row) {
            $nilai = nilai_akhir_wawancara($row);
            $sum += $nilai;
            $g = grading_wawancara_dari_rekomendasi($row, $nilai);
            $gradeCounter[$g['grade']]++;
        }

        $rataKelompok = $total > 0 ? $sum / $total : 0;
        $backUrl = '?module=' . e($module);

        echo "<!DOCTYPE html><html lang='id'><head><meta charset='UTF-8'><title>Print Rekap Wawancara Staf Baru</title>";
        render_print_css_wawancara();
        echo "</head><body>";
        echo "<div class='toolbar'><div><strong>Print Gabungan dan Rekap Wawancara</strong></div><div><a class='btn-light' href='{$backUrl}'>← Kembali</a><button onclick='window.print()'>Print Semua</button></div></div>";

        echo "<section class='page rekap-page'>";
        echo "<div class='doc-title'>REKAP HASIL WAWANCARA STAF BARU</div>";
        echo "<table class='identity'>";
        echo "<tr><td class='label'>Tanggal Wawancara</td><td class='colon'>:</td><td>" . e($tanggalJudul) . "</td><td class='label'>Jumlah Staf</td><td class='colon'>:</td><td>" . $total . " orang</td></tr>";
        echo "<tr><td class='label'>Rata-rata Kelompok</td><td class='colon'>:</td><td>" . number_format($rataKelompok, 2) . "</td><td class='label'>Dicetak</td><td class='colon'>:</td><td>" . date('d-m-Y H:i') . "</td></tr>";
        echo "</table>";

        echo "<div class='summary-grid no-break'>";
        foreach (['A' => 'Sangat Direkomendasikan', 'B' => 'Direkomendasikan', 'C' => 'Dipertimbangkan', 'D' => 'Tidak Direkomendasikan'] as $g => $label) {
            $tmp = grading_wawancara($g === 'A' ? 90 : ($g === 'B' ? 80 : ($g === 'C' ? 65 : 50)));
            echo "<div class='summary-card'><div class='label'>Grade {$g}</div><div class='value " . e($tmp['class']) . "'>" . (int)$gradeCounter[$g] . "</div><div class='label'>" . e($label) . "</div></div>";
        }
        echo "</div>";

        echo "<div class='rekap-title'>Daftar Staf yang Diwawancara</div>";
        echo "<table class='rekap'>";
        echo "<thead><tr>";
        echo "<th style='width:5%'>No</th>";
        echo "<th style='width:21%'>Nama</th>";
        echo "<th style='width:11%'>Pendidikan</th>";
        echo "<th style='width:13%'>Posisi</th>";
        echo "<th style='width:10%'>Tanggal</th>";
        echo "<th style='width:7%'>Nilai 1</th>";
        echo "<th style='width:7%'>Nilai 2</th>";
        echo "<th style='width:7%'>Nilai 3</th>";
        echo "<th style='width:7%'>Akhir</th>";
        echo "<th style='width:5%'>Grade</th>";
        echo "<th style='width:12%'>Keputusan</th>";
        echo "</tr></thead><tbody>";

        if (!$rows) {
            echo "<tr><td colspan='11' class='center'>Belum ada data wawancara pada filter ini.</td></tr>";
        } else {
            $no = 1;
            foreach ($rows as $row) {
                $nilai = nilai_akhir_wawancara($row);
                $grade = grading_wawancara_dari_rekomendasi($row, $nilai);
                echo "<tr>";
                echo "<td class='center'>" . $no++ . "</td>";
                echo "<td>" . e($row['nama_lengkap'] ?? '-') . "</td>";
                echo "<td>" . e($row['pendidikan'] ?? '-') . "</td>";
                echo "<td>" . e($row['posisi_dicari'] ?? '-') . "</td>";
                echo "<td class='center'>" . e(format_tanggal_id_safe((string)($row['tanggal_wawancara'] ?? ''))) . "</td>";
                for ($i = 1; $i <= 3; $i++) {
                    $r = (float)($row['rata_rata_' . $i] ?? 0);
                    echo "<td class='center'>" . ($r > 0 ? number_format($r, 2) : '-') . "</td>";
                }
                echo "<td class='center bold'>" . number_format($nilai, 2) . "</td>";
                echo "<td class='center " . e($grade['class']) . "'>" . e($grade['grade']) . "</td>";
                echo "<td class='" . e($grade['class']) . "'>" . e($grade['label']) . "</td>";
                echo "</tr>";
            }
        }

        echo "</tbody></table>";
        echo "<div class='note'>Grading: A ≥ 85, B 75 - 84,99, C 60 - 74,99, D &lt; 60.</div>";
        echo "</section>";

        foreach ($rows as $row) {
            render_print_individu_wawancara($row, $fields, $labels, $uraianLabels, $module, false);
        }

        echo "<script>if(new URLSearchParams(location.search).get('autoprint')==='1'){window.addEventListener('load',()=>setTimeout(()=>window.print(),400));}</script>";
        echo "</body></html>";
    }
}



if (!function_exists('excel_text_wawancara')) {
    function excel_text_wawancara($value): string
    {
        $value = (string)($value ?? '');
        if ($value !== '' && preg_match('/^[=+\-@]/', $value)) {
            $value = "'" . $value;
        }
        return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('excel_filename_safe')) {
    function excel_filename_safe(string $value): string
    {
        $value = preg_replace('/[^A-Za-z0-9_\-]+/', '_', $value);
        $value = trim((string)$value, '_');
        return $value !== '' ? $value : 'data';
    }
}

if (!function_exists('send_excel_headers_wawancara')) {
    function send_excel_headers_wawancara(string $filename): void
    {
        while (ob_get_level() > 0) {
            ob_end_clean();
        }
        header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        header('Pragma: public');
        echo "\xEF\xBB\xBF";
    }
}

if (!function_exists('render_excel_style_wawancara')) {
    function render_excel_style_wawancara(): void
    {
        echo <<<HTML
<style>
    body { font-family: Arial, Helvetica, sans-serif; font-size: 11pt; }
    table { border-collapse: collapse; }
    td, th { border: 1px solid #000000; padding: 6px; vertical-align: top; }
    .title { font-size: 16pt; font-weight: bold; text-align: center; }
    .subtitle { font-size: 12pt; font-weight: bold; text-align: center; }
    .section { background: #D9EAF7; font-weight: bold; text-align: center; }
    .head { background: #EAF2F8; font-weight: bold; text-align: center; }
    .center { text-align: center; }
    .right { text-align: right; }
    .bold { font-weight: bold; }
    .muted { color: #666666; }
    .grade-a { color: #047857; font-weight: bold; }
    .grade-b { color: #2563EB; font-weight: bold; }
    .grade-c { color: #B45309; font-weight: bold; }
    .grade-d { color: #B91C1C; font-weight: bold; }
    .text { mso-number-format:"\@"; }
    .num { mso-number-format:"0.00"; }
</style>
HTML;
    }
}

if (!function_exists('render_excel_individu_wawancara')) {
    function render_excel_individu_wawancara(array $row, array $fields, array $labels, array $uraianLabels): void
    {
        $nilaiAkhir = nilai_akhir_wawancara($row);
        $grade = grading_wawancara_dari_rekomendasi($row, $nilaiAkhir);
        $tanggal = format_tanggal_id_safe((string)($row['tanggal_wawancara'] ?? ''));

        echo "<table style='width:100%;'>";
        echo "<tr><td colspan='8' class='title'>HASIL PENILAIAN WAWANCARA STAF BARU</td></tr>";
        echo "<tr><td colspan='8' class='subtitle'>RS BaliMéd Denpasar</td></tr>";
        echo "<tr><td colspan='8'>&nbsp;</td></tr>";
        echo "<tr><td class='bold text'>Nama Lengkap</td><td colspan='3' class='text'>" . excel_text_wawancara($row['nama_lengkap'] ?? '-') . "</td><td class='bold text'>Tanggal Wawancara</td><td colspan='3' class='text'>" . excel_text_wawancara($tanggal) . "</td></tr>";
        echo "<tr><td class='bold text'>Pendidikan</td><td colspan='3' class='text'>" . excel_text_wawancara($row['pendidikan'] ?? '-') . "</td><td class='bold text'>Posisi Dicari</td><td colspan='3' class='text'>" . excel_text_wawancara($row['posisi_dicari'] ?? '-') . "</td></tr>";
        echo "<tr><td class='bold text'>Nilai Akhir</td><td class='num center bold'>" . number_format($nilaiAkhir, 2, '.', '') . "</td><td class='bold text'>Grade</td><td class='center " . excel_text_wawancara($grade['class']) . "'>" . excel_text_wawancara($grade['grade']) . "</td><td class='bold text'>Kategori</td><td colspan='3' class='" . excel_text_wawancara($grade['class']) . "'>" . excel_text_wawancara($grade['label']) . "</td></tr>";
        echo "<tr><td colspan='8'>&nbsp;</td></tr>";
        echo "<tr class='head'><th>No</th><th>Aspek Penilaian</th><th>Uraian</th><th>Nilai 1</th><th>Nilai 2</th><th>Nilai 3</th><th>Rata-rata</th><th>Keterangan</th></tr>";

        $no = 1;
        foreach ($fields as $field) {
            $n1 = (float)($row[$field . '_1'] ?? 0);
            $n2 = (float)($row[$field . '_2'] ?? 0);
            $n3 = (float)($row[$field . '_3'] ?? 0);
            $vals = [];
            if ($n1 > 0) $vals[] = $n1;
            if ($n2 > 0) $vals[] = $n2;
            if ($n3 > 0) $vals[] = $n3;
            $avg = $vals ? array_sum($vals) / count($vals) : 0;
            $gRow = grading_wawancara($avg);
            echo "<tr>";
            echo "<td class='center'>" . $no++ . "</td>";
            echo "<td class='text'>" . excel_text_wawancara($labels[$field] ?? $field) . "</td>";
            echo "<td class='text'>" . excel_text_wawancara($uraianLabels[$field] ?? '') . "</td>";
            echo "<td class='center num'>" . number_format($n1, 2, '.', '') . "</td>";
            echo "<td class='center num'>" . number_format($n2, 2, '.', '') . "</td>";
            echo "<td class='center num'>" . number_format($n3, 2, '.', '') . "</td>";
            echo "<td class='center num bold'>" . number_format($avg, 2, '.', '') . "</td>";
            echo "<td class='text'>" . excel_text_wawancara($gRow['label']) . "</td>";
            echo "</tr>";
        }

        echo "<tr class='section'><td colspan='8'>HASIL PEWAWANCARA</td></tr>";
        echo "<tr class='head'><th colspan='2'>Komponen</th><th colspan='2'>Pewawancara 1</th><th colspan='2'>Pewawancara 2</th><th colspan='2'>Pewawancara 3</th></tr>";
        echo "<tr><td colspan='2' class='bold text'>Nama Pewawancara</td><td colspan='2' class='text'>" . excel_text_wawancara($row['pewawancara_1_nama'] ?? '-') . "</td><td colspan='2' class='text'>" . excel_text_wawancara($row['pewawancara_2_nama'] ?? '-') . "</td><td colspan='2' class='text'>" . excel_text_wawancara($row['pewawancara_3_nama'] ?? '-') . "</td></tr>";
        echo "<tr><td colspan='2' class='bold text'>Rata-rata</td><td colspan='2' class='center num bold'>" . number_format((float)($row['rata_rata_1'] ?? 0), 2, '.', '') . "</td><td colspan='2' class='center num bold'>" . number_format((float)($row['rata_rata_2'] ?? 0), 2, '.', '') . "</td><td colspan='2' class='center num bold'>" . number_format((float)($row['rata_rata_3'] ?? 0), 2, '.', '') . "</td></tr>";
        echo "<tr><td colspan='2' class='bold text'>Kesimpulan</td><td colspan='2' class='text'>" . excel_text_wawancara($row['kesimpulan_1'] ?? '-') . "</td><td colspan='2' class='text'>" . excel_text_wawancara($row['kesimpulan_2'] ?? '-') . "</td><td colspan='2' class='text'>" . excel_text_wawancara($row['kesimpulan_3'] ?? '-') . "</td></tr>";
        echo "<tr><td colspan='2' class='bold text'>Saran/Komentar</td><td colspan='2' class='text'>" . excel_text_wawancara($row['saran_komentar_1'] ?? '-') . "</td><td colspan='2' class='text'>" . excel_text_wawancara($row['saran_komentar_2'] ?? '-') . "</td><td colspan='2' class='text'>" . excel_text_wawancara($row['saran_komentar_3'] ?? '-') . "</td></tr>";
        echo "<tr><td colspan='2' class='bold text'>Keputusan Akhir</td><td colspan='6' class='text bold'>" . excel_text_wawancara($row['keputusan_akhir'] ?? $grade['label']) . "</td></tr>";
        echo "<tr><td colspan='2' class='bold text'>Catatan Akhir</td><td colspan='6' class='text'>" . excel_text_wawancara($row['catatan_akhir'] ?? '-') . "</td></tr>";
        echo "<tr><td colspan='8'>&nbsp;</td></tr>";
        echo "<tr><td colspan='2' class='center text'>Pewawancara 1</td><td colspan='3' class='center text'>Pewawancara 2</td><td colspan='3' class='center text'>Pewawancara 3</td></tr>";
        echo "<tr><td colspan='2' style='height:70px;'>&nbsp;</td><td colspan='3'>&nbsp;</td><td colspan='3'>&nbsp;</td></tr>";
        echo "<tr><td colspan='2' class='center text bold'>" . excel_text_wawancara($row['pewawancara_1_nama'] ?? '') . "</td><td colspan='3' class='center text bold'>" . excel_text_wawancara($row['pewawancara_2_nama'] ?? '') . "</td><td colspan='3' class='center text bold'>" . excel_text_wawancara($row['pewawancara_3_nama'] ?? '') . "</td></tr>";
        echo "</table>";
    }
}

if (!function_exists('render_excel_gabungan_wawancara')) {
    function render_excel_gabungan_wawancara(array $rows, array $fields, array $labels, array $uraianLabels, string $tanggalFilter = ''): void
    {
        $tanggalJudul = $tanggalFilter !== '' ? format_tanggal_id_safe($tanggalFilter) : 'Semua Tanggal';
        $total = count($rows);
        $sum = 0.0;
        $gradeCounter = ['A' => 0, 'B' => 0, 'C' => 0, 'D' => 0];
        foreach ($rows as $row) {
            $nilai = nilai_akhir_wawancara($row);
            $sum += $nilai;
            $g = grading_wawancara_dari_rekomendasi($row, $nilai);
            $gradeCounter[$g['grade']]++;
        }
        $rataKelompok = $total > 0 ? $sum / $total : 0;

        echo "<table style='width:100%;'>";
        echo "<tr><td colspan='11' class='title'>REKAP HASIL WAWANCARA STAF BARU</td></tr>";
        echo "<tr><td colspan='11' class='subtitle'>RS BaliMéd Denpasar</td></tr>";
        echo "<tr><td colspan='11'>&nbsp;</td></tr>";
        echo "<tr><td class='bold text'>Tanggal Wawancara</td><td colspan='2' class='text'>" . excel_text_wawancara($tanggalJudul) . "</td><td class='bold text'>Jumlah Staf</td><td colspan='2' class='center'>" . $total . " orang</td><td class='bold text'>Rata-rata Kelompok</td><td colspan='2' class='center num bold'>" . number_format($rataKelompok, 2, '.', '') . "</td><td class='bold text'>Dicetak</td><td class='text'>" . date('d-m-Y H:i') . "</td></tr>";
        echo "<tr><td class='bold text'>Grade A</td><td class='center grade-a'>" . (int)$gradeCounter['A'] . "</td><td class='text'>Sangat Direkomendasikan</td><td class='bold text'>Grade B</td><td class='center grade-b'>" . (int)$gradeCounter['B'] . "</td><td class='text'>Direkomendasikan</td><td class='bold text'>Grade C</td><td class='center grade-c'>" . (int)$gradeCounter['C'] . "</td><td class='text'>Dipertimbangkan</td><td class='bold text'>Grade D</td><td class='center grade-d'>" . (int)$gradeCounter['D'] . "</td></tr>";
        echo "<tr><td colspan='11'>&nbsp;</td></tr>";
        echo "<tr><td colspan='11' class='section'>DAFTAR STAF YANG DIWAWANCARA</td></tr>";
        echo "<tr class='head'><th>No</th><th>Nama</th><th>Pendidikan</th><th>Posisi</th><th>Tanggal</th><th>Nilai 1</th><th>Nilai 2</th><th>Nilai 3</th><th>Akhir</th><th>Grade</th><th>Keputusan/Grading</th></tr>";
        if (!$rows) {
            echo "<tr><td colspan='11' class='center'>Belum ada data wawancara pada filter ini.</td></tr>";
        } else {
            $no = 1;
            foreach ($rows as $row) {
                $nilai = nilai_akhir_wawancara($row);
                $grade = grading_wawancara_dari_rekomendasi($row, $nilai);
                echo "<tr>";
                echo "<td class='center'>" . $no++ . "</td>";
                echo "<td class='text'>" . excel_text_wawancara($row['nama_lengkap'] ?? '-') . "</td>";
                echo "<td class='text'>" . excel_text_wawancara($row['pendidikan'] ?? '-') . "</td>";
                echo "<td class='text'>" . excel_text_wawancara($row['posisi_dicari'] ?? '-') . "</td>";
                echo "<td class='text center'>" . excel_text_wawancara(format_tanggal_id_safe((string)($row['tanggal_wawancara'] ?? ''))) . "</td>";
                for ($i = 1; $i <= 3; $i++) {
                    $r = (float)($row['rata_rata_' . $i] ?? 0);
                    echo "<td class='center num'>" . ($r > 0 ? number_format($r, 2, '.', '') : '-') . "</td>";
                }
                echo "<td class='center num bold'>" . number_format($nilai, 2, '.', '') . "</td>";
                echo "<td class='center " . excel_text_wawancara($grade['class']) . "'>" . excel_text_wawancara($grade['grade']) . "</td>";
                echo "<td class='text " . excel_text_wawancara($grade['class']) . "'>" . excel_text_wawancara($grade['label']) . "</td>";
                echo "</tr>";
            }
        }
        echo "<tr><td colspan='11' class='muted'>Grading: A ≥ 85, B 75 - 84,99, C 60 - 74,99, D &lt; 60.</td></tr>";
        echo "</table>";

        if ($rows) {
            foreach ($rows as $row) {
                echo "<br><br>";
                render_excel_individu_wawancara($row, $fields, $labels, $uraianLabels);
            }
        }
    }
}

/**
 * Helper simpan insert/update
 */
function buildInterviewData(array $fields): array
{
    $nama_lengkap       = trim((string)($_POST['nama_lengkap'] ?? ''));
    $pendidikan         = trim((string)($_POST['pendidikan'] ?? ''));
    $posisi_dicari      = trim((string)($_POST['posisi_dicari'] ?? ''));
    $tanggal_wawancara  = trim((string)($_POST['tanggal_wawancara'] ?? ''));
    $keputusan_akhir    = trim((string)($_POST['keputusan_akhir'] ?? ''));
    $catatan_akhir      = trim((string)($_POST['catatan_akhir'] ?? ''));

    $scores = [];
    $rataList = [];
    $kesimpulanList = [];
    $saranList = [];
    $pewawancaraList = [];
    $pewawancaraNikList = [];

    foreach ($fields as $field) {
        for ($i = 1; $i <= 3; $i++) {
            $scores[$field . '_' . $i] = (float)($_POST[$field . '_' . $i] ?? 0);
        }
    }

    for ($i = 1; $i <= 3; $i++) {
        $total = 0;
        foreach ($fields as $field) {
            $total += (float)($scores[$field . '_' . $i] ?? 0);
        }

        $rata = $total / count($fields);
        $rataList[$i] = $rata;

        if ($rata >= 80) {
            $kesimpulanList[$i] = 'Diterima';
        } elseif ($rata >= 60) {
            $kesimpulanList[$i] = 'Dipertimbangkan';
        } else {
            $kesimpulanList[$i] = 'Tidak Disarankan';
        }

        $saranList[$i] = trim((string)($_POST['saran_' . $i] ?? ''));
        $pewawancaraList[$i] = trim((string)($_POST['pewawancara_' . $i] ?? ''));
        $pewawancaraNikList[$i] = trim((string)($_POST['pewawancara_' . $i . '_nik'] ?? ''));
    }

    return [
        'nama_lengkap' => $nama_lengkap,
        'pendidikan' => $pendidikan,
        'posisi_dicari' => $posisi_dicari,
        'tanggal_wawancara' => $tanggal_wawancara,
        'keputusan_akhir' => $keputusan_akhir,
        'catatan_akhir' => $catatan_akhir,
        'scores' => $scores,
        'rata' => $rataList,
        'kesimpulan' => $kesimpulanList,
        'saran' => $saranList,
        'pewawancara' => $pewawancaraList,
        'pewawancara_nik' => $pewawancaraNikList,
    ];
}

// HANDLE POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // ADD
    if ($action === 'add') {
        $payload = buildInterviewData($fields);

        if ($payload['nama_lengkap'] === '' || $payload['tanggal_wawancara'] === '') {
            $error = 'Nama lengkap dan tanggal wawancara wajib diisi.';
        } else {
            $dibuat_oleh = (int)($_SESSION['user_id'] ?? 0);

            $sql = "
                INSERT INTO wawancara_staf_baru (
                    nama_lengkap, pendidikan, posisi_dicari, tanggal_wawancara,

                    penampilan_1, penampilan_2, penampilan_3,
                    etika_1, etika_2, etika_3,
                    komunikasi_1, komunikasi_2, komunikasi_3,
                    pendidikan_formal_1, pendidikan_formal_2, pendidikan_formal_3,
                    pengalaman_kerja_1, pengalaman_kerja_2, pengalaman_kerja_3,
                    kerjasama_tim_1, kerjasama_tim_2, kerjasama_tim_3,
                    komitmen_1, komitmen_2, komitmen_3,
                    pandangan_perusahaan_1, pandangan_perusahaan_2, pandangan_perusahaan_3,
                    bahasa_asing_1, bahasa_asing_2, bahasa_asing_3,
                    faktor_pendukung_1, faktor_pendukung_2, faktor_pendukung_3,
                    kompensasi_1, kompensasi_2, kompensasi_3,

                    rata_rata_1, rata_rata_2, rata_rata_3,
                    kesimpulan_1, kesimpulan_2, kesimpulan_3,
                    saran_komentar_1, saran_komentar_2, saran_komentar_3,
                    pewawancara_1_nama, pewawancara_2_nama, pewawancara_3_nama,

                    keputusan_akhir, catatan_akhir, dibuat_oleh
                ) VALUES (
                    ?, ?, ?, ?,

                    ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?,

                    ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?,

                    ?, ?, ?
                )
            ";

            $stmt = $conn->prepare($sql);

            if (!$stmt) {
                $error = 'Gagal menyiapkan query simpan: ' . $conn->error;
            } else {
                $types =
                    "ssss" .
                    str_repeat("d", 33) .
                    "ddd" .
                    "sss" .
                    "sss" .
                    "sss" .
                    "ssi";

                $s = $payload['scores'];
                $r = $payload['rata'];
                $k = $payload['kesimpulan'];
                $sa = $payload['saran'];
                $p = $payload['pewawancara'];

                $stmt->bind_param(
                    $types,
                    $payload['nama_lengkap'],
                    $payload['pendidikan'],
                    $payload['posisi_dicari'],
                    $payload['tanggal_wawancara'],

                    $s['penampilan_1'], $s['penampilan_2'], $s['penampilan_3'],
                    $s['etika_1'], $s['etika_2'], $s['etika_3'],
                    $s['komunikasi_1'], $s['komunikasi_2'], $s['komunikasi_3'],
                    $s['pendidikan_formal_1'], $s['pendidikan_formal_2'], $s['pendidikan_formal_3'],
                    $s['pengalaman_kerja_1'], $s['pengalaman_kerja_2'], $s['pengalaman_kerja_3'],
                    $s['kerjasama_tim_1'], $s['kerjasama_tim_2'], $s['kerjasama_tim_3'],
                    $s['komitmen_1'], $s['komitmen_2'], $s['komitmen_3'],
                    $s['pandangan_perusahaan_1'], $s['pandangan_perusahaan_2'], $s['pandangan_perusahaan_3'],
                    $s['bahasa_asing_1'], $s['bahasa_asing_2'], $s['bahasa_asing_3'],
                    $s['faktor_pendukung_1'], $s['faktor_pendukung_2'], $s['faktor_pendukung_3'],
                    $s['kompensasi_1'], $s['kompensasi_2'], $s['kompensasi_3'],

                    $r[1], $r[2], $r[3],
                    $k[1], $k[2], $k[3],
                    $sa[1], $sa[2], $sa[3],
                    $p[1], $p[2], $p[3],

                    $payload['keputusan_akhir'],
                    $payload['catatan_akhir'],
                    $dibuat_oleh
                );

                if ($stmt->execute()) {
                    $new_id = (int)$conn->insert_id;
                    save_wawancara_signature_nik($conn, $new_id, $payload['pewawancara_nik'] ?? []);
                    safeLogActivity('create', 'wawancara_staf_baru', $new_id, "Menambah data wawancara: {$payload['nama_lengkap']}");
                    echo "<script>alert('Data berhasil ditambahkan!'); window.location.href='?module={$module}';</script>";
                    exit;
                } else {
                    $error = 'Gagal menyimpan data: ' . $stmt->error;
                }

                $stmt->close();
            }
        }
    }

    // EDIT
    if ($action === 'edit' && $id > 0) {
        $payload = buildInterviewData($fields);

        if ($payload['nama_lengkap'] === '' || $payload['tanggal_wawancara'] === '') {
            $error = 'Nama lengkap dan tanggal wawancara wajib diisi.';
        } else {
            $sql = "
                UPDATE wawancara_staf_baru SET
                    nama_lengkap=?, pendidikan=?, posisi_dicari=?, tanggal_wawancara=?,

                    penampilan_1=?, penampilan_2=?, penampilan_3=?,
                    etika_1=?, etika_2=?, etika_3=?,
                    komunikasi_1=?, komunikasi_2=?, komunikasi_3=?,
                    pendidikan_formal_1=?, pendidikan_formal_2=?, pendidikan_formal_3=?,
                    pengalaman_kerja_1=?, pengalaman_kerja_2=?, pengalaman_kerja_3=?,
                    kerjasama_tim_1=?, kerjasama_tim_2=?, kerjasama_tim_3=?,
                    komitmen_1=?, komitmen_2=?, komitmen_3=?,
                    pandangan_perusahaan_1=?, pandangan_perusahaan_2=?, pandangan_perusahaan_3=?,
                    bahasa_asing_1=?, bahasa_asing_2=?, bahasa_asing_3=?,
                    faktor_pendukung_1=?, faktor_pendukung_2=?, faktor_pendukung_3=?,
                    kompensasi_1=?, kompensasi_2=?, kompensasi_3=?,

                    rata_rata_1=?, rata_rata_2=?, rata_rata_3=?,
                    kesimpulan_1=?, kesimpulan_2=?, kesimpulan_3=?,
                    saran_komentar_1=?, saran_komentar_2=?, saran_komentar_3=?,
                    pewawancara_1_nama=?, pewawancara_2_nama=?, pewawancara_3_nama=?,

                    keputusan_akhir=?, catatan_akhir=?
                WHERE id=?
            ";

            $stmt = $conn->prepare($sql);

            if (!$stmt) {
                $error = 'Gagal menyiapkan query update: ' . $conn->error;
            } else {
                $types =
                    "ssss" .
                    str_repeat("d", 33) .
                    "ddd" .
                    "sss" .
                    "sss" .
                    "sss" .
                    "ssi";

                $s = $payload['scores'];
                $r = $payload['rata'];
                $k = $payload['kesimpulan'];
                $sa = $payload['saran'];
                $p = $payload['pewawancara'];

                $stmt->bind_param(
                    $types,
                    $payload['nama_lengkap'],
                    $payload['pendidikan'],
                    $payload['posisi_dicari'],
                    $payload['tanggal_wawancara'],

                    $s['penampilan_1'], $s['penampilan_2'], $s['penampilan_3'],
                    $s['etika_1'], $s['etika_2'], $s['etika_3'],
                    $s['komunikasi_1'], $s['komunikasi_2'], $s['komunikasi_3'],
                    $s['pendidikan_formal_1'], $s['pendidikan_formal_2'], $s['pendidikan_formal_3'],
                    $s['pengalaman_kerja_1'], $s['pengalaman_kerja_2'], $s['pengalaman_kerja_3'],
                    $s['kerjasama_tim_1'], $s['kerjasama_tim_2'], $s['kerjasama_tim_3'],
                    $s['komitmen_1'], $s['komitmen_2'], $s['komitmen_3'],
                    $s['pandangan_perusahaan_1'], $s['pandangan_perusahaan_2'], $s['pandangan_perusahaan_3'],
                    $s['bahasa_asing_1'], $s['bahasa_asing_2'], $s['bahasa_asing_3'],
                    $s['faktor_pendukung_1'], $s['faktor_pendukung_2'], $s['faktor_pendukung_3'],
                    $s['kompensasi_1'], $s['kompensasi_2'], $s['kompensasi_3'],

                    $r[1], $r[2], $r[3],
                    $k[1], $k[2], $k[3],
                    $sa[1], $sa[2], $sa[3],
                    $p[1], $p[2], $p[3],

                    $payload['keputusan_akhir'],
                    $payload['catatan_akhir'],
                    $id
                );

                if ($stmt->execute()) {
                    save_wawancara_signature_nik($conn, $id, $payload['pewawancara_nik'] ?? []);
                    safeLogActivity('update', 'wawancara_staf_baru', $id, "Mengubah data wawancara: {$payload['nama_lengkap']}");
                    echo "<script>alert('Data berhasil diubah!'); window.location.href='?module={$module}';</script>";
                    exit;
                } else {
                    $error = 'Gagal mengubah data: ' . $stmt->error;
                }

                $stmt->close();
            }
        }
    }
}

// DELETE
if ($action === 'delete' && $id > 0) {
    $stmt = $conn->prepare("DELETE FROM wawancara_staf_baru WHERE id = ?");
    if ($stmt) {
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            safeLogActivity('delete', 'wawancara_staf_baru', $id, "Menghapus data wawancara ID: {$id}");
            echo "<script>alert('Data berhasil dihapus!'); window.location.href='?module={$module}';</script>";
            exit;
        } else {
            $error = 'Gagal menghapus data: ' . $stmt->error;
        }
        $stmt->close();
    } else {
        $error = 'Gagal menyiapkan query hapus.';
    }
}

// Get data detail / edit
$detailData = null;
if (($action === 'detail' || $action === 'edit') && $id > 0) {
    $stmt = $conn->prepare("SELECT * FROM wawancara_staf_baru WHERE id = ? LIMIT 1");
    if ($stmt) {
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $detailData = $result ? $result->fetch_assoc() : null;
        $stmt->close();
    }
}


if ($action === 'excel' && $id > 0) {
    $stmt = $conn->prepare("SELECT * FROM wawancara_staf_baru WHERE id = ? LIMIT 1");
    if ($stmt) {
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $excelData = $result ? $result->fetch_assoc() : null;
        $stmt->close();

        if ($excelData) {
            $name = excel_filename_safe((string)($excelData['nama_lengkap'] ?? 'staf_baru'));
            send_excel_headers_wawancara('Penilaian_Staf_Baru_' . $name . '.xls');
            echo "<html><head><meta charset='UTF-8'>";
            render_excel_style_wawancara();
            echo "</head><body>";
            render_excel_individu_wawancara($excelData, $fields, $labels, $uraianLabels);
            echo "</body></html>";
            exit;
        }
    }

    echo "<div style='font-family:Arial;padding:20px'>Data tidak ditemukan. <a href='?module=" . e($module) . "'>Kembali</a></div>";
    exit;
}

if ($action === 'excel_gabungan') {
    $tanggalExcel = trim((string)($_GET['tanggal'] ?? ''));
    $rowsExcel = [];

    if ($tanggalExcel !== '') {
        $stmt = $conn->prepare("SELECT * FROM wawancara_staf_baru WHERE tanggal_wawancara = ? ORDER BY nama_lengkap ASC");
        if ($stmt) {
            $stmt->bind_param("s", $tanggalExcel);
            $stmt->execute();
            $result = $stmt->get_result();
            while ($result && ($row = $result->fetch_assoc())) {
                $rowsExcel[] = $row;
            }
            $stmt->close();
        }
    } else {
        $result = $conn->query("SELECT * FROM wawancara_staf_baru ORDER BY tanggal_wawancara DESC, nama_lengkap ASC");
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $rowsExcel[] = $row;
            }
        }
    }

    $suffix = $tanggalExcel !== '' ? excel_filename_safe($tanggalExcel) : 'Semua_Tanggal';
    send_excel_headers_wawancara('Rekap_Wawancara_Staf_Baru_' . $suffix . '.xls');
    echo "<html><head><meta charset='UTF-8'>";
    render_excel_style_wawancara();
    echo "</head><body>";
    render_excel_gabungan_wawancara($rowsExcel, $fields, $labels, $uraianLabels, $tanggalExcel);
    echo "</body></html>";
    exit;
}

if ($action === 'print' && $id > 0) {
    $stmt = $conn->prepare("SELECT * FROM wawancara_staf_baru WHERE id = ? LIMIT 1");
    if ($stmt) {
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $printData = $result ? $result->fetch_assoc() : null;
        $stmt->close();

        if ($printData) {
            render_print_individu_wawancara($printData, $fields, $labels, $uraianLabels, $module, true);
            exit;
        }
    }

    echo "<div style='font-family:Arial;padding:20px'>Data tidak ditemukan. <a href='?module=" . e($module) . "'>Kembali</a></div>";
    exit;
}

if ($action === 'print_gabungan') {
    $tanggalPrint = trim((string)($_GET['tanggal'] ?? ''));

    if ($tanggalPrint !== '') {
        $stmt = $conn->prepare("SELECT * FROM wawancara_staf_baru WHERE tanggal_wawancara = ? ORDER BY nama_lengkap ASC");
        if ($stmt) {
            $stmt->bind_param("s", $tanggalPrint);
            $stmt->execute();
            $result = $stmt->get_result();
            $rowsPrint = [];
            while ($result && ($row = $result->fetch_assoc())) {
                $rowsPrint[] = $row;
            }
            $stmt->close();
            render_print_gabungan_wawancara($rowsPrint, $fields, $labels, $uraianLabels, $module, $tanggalPrint);
            exit;
        }
    }

    $result = $conn->query("SELECT * FROM wawancara_staf_baru ORDER BY tanggal_wawancara DESC, nama_lengkap ASC");
    $rowsPrint = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $rowsPrint[] = $row;
        }
    }

    render_print_gabungan_wawancara($rowsPrint, $fields, $labels, $uraianLabels, $module, '');
    exit;
}

$filterTanggal = trim((string)($_GET['tanggal'] ?? ''));

$daftarTanggalWawancara = [];
$resultTanggal = $conn->query("
    SELECT tanggal_wawancara, COUNT(*) AS total
    FROM wawancara_staf_baru
    WHERE tanggal_wawancara IS NOT NULL AND tanggal_wawancara <> '0000-00-00'
    GROUP BY tanggal_wawancara
    ORDER BY tanggal_wawancara DESC
");
if ($resultTanggal) {
    while ($rowTanggal = $resultTanggal->fetch_assoc()) {
        $daftarTanggalWawancara[] = $rowTanggal;
    }
}

// Get all data
$data = [];
if ($filterTanggal !== '') {
    $stmtData = $conn->prepare("SELECT * FROM wawancara_staf_baru WHERE tanggal_wawancara = ? ORDER BY created_at DESC");
    if ($stmtData) {
        $stmtData->bind_param("s", $filterTanggal);
        $stmtData->execute();
        $result = $stmtData->get_result();
        while ($result && ($row = $result->fetch_assoc())) {
            $data[] = $row;
        }
        $stmtData->close();
    }
} else {
    $result = $conn->query("SELECT * FROM wawancara_staf_baru ORDER BY created_at DESC");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }
}

// Data lengkap khusus export Excel sisi browser.
// Export tidak lagi memakai header PHP / file root, supaya aman dari redirect hosting dan template index.php.
$dataExcelAll = [];
$resultExcelAll = $conn->query("SELECT * FROM wawancara_staf_baru ORDER BY tanggal_wawancara DESC, nama_lengkap ASC");
if ($resultExcelAll) {
    while ($rowExcelAll = $resultExcelAll->fetch_assoc()) {
        $dataExcelAll[] = $rowExcelAll;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Staf Baru</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        body { font-family: 'Poppins', sans-serif; background: #f8fafc; }
    </style>
</head>
<body class="p-6">
    <div class="mb-6 flex flex-col lg:flex-row lg:justify-between lg:items-center gap-4">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">Data Wawancara Staf Baru</h1>
            <p class="text-sm text-gray-500 mt-1">Export Excel rekap dipisah dari export per staf agar tampilan lebih rapi dan mudah digunakan.</p>
        </div>

        <div class="flex flex-col md:flex-row gap-2 md:items-center">
            <form method="GET" class="flex gap-2 items-center">
                <input type="hidden" name="module" value="<?= e($module) ?>">
                <select name="tanggal" class="px-3 py-2 border border-gray-300 rounded-lg text-sm bg-white">
                    <option value="">Semua tanggal</option>
                    <?php foreach ($daftarTanggalWawancara as $tgl): ?>
                        <option value="<?= e($tgl['tanggal_wawancara']) ?>" <?= $filterTanggal === $tgl['tanggal_wawancara'] ? 'selected' : '' ?>>
                            <?= e(format_tanggal_id_safe($tgl['tanggal_wawancara'])) ?> (<?= (int)$tgl['total'] ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" class="px-4 py-2 bg-gray-700 text-white rounded-lg text-sm hover:bg-gray-800">
                    Filter
                </button>
            </form>

            <div class="flex flex-col md:flex-row gap-2 md:items-center rounded-xl border border-emerald-200 bg-emerald-50 px-3 py-2">
                <div class="text-xs font-semibold text-emerald-800 md:mr-1 whitespace-nowrap">Rekap Excel</div>
                <select id="excelTanggalRekap" class="px-3 py-2 border border-emerald-300 rounded-lg text-sm bg-white min-w-[210px]">
                    <option value="">Semua tanggal</option>
                    <?php foreach ($daftarTanggalWawancara as $tgl): ?>
                        <option value="<?= e($tgl['tanggal_wawancara']) ?>" <?= $filterTanggal === $tgl['tanggal_wawancara'] ? 'selected' : '' ?>>
                            <?= e(format_tanggal_id_safe($tgl['tanggal_wawancara'])) ?> (<?= (int)$tgl['total'] ?> staf)
                        </option>
                    <?php endforeach; ?>
                </select>
                <button type="button" onclick="excelRekapByTanggal()" class="px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm hover:bg-emerald-700 whitespace-nowrap">
                    <i class="fas fa-table mr-2"></i>Export Rekap
                </button>
            </div>

            <button onclick="showForm()" class="bg-gradient-to-r from-blue-600 to-indigo-600 text-white px-4 py-2 rounded-lg hover:from-blue-700 hover:to-indigo-700 transition-all text-sm">
                <i class="fas fa-plus mr-2"></i> Input Wawancara Baru
            </button>
        </div>
    </div>

    <?php if ($error !== ''): ?>
    <div class="mb-4 bg-red-50 border-l-4 border-red-500 p-4 rounded">
        <p class="text-red-700"><?= e($error) ?></p>
    </div>
    <?php endif; ?>

    <?php if ($action === 'add' || ($action === 'edit' && $detailData)): ?>
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
        <h2 class="text-lg font-semibold mb-4"><?= $action === 'add' ? 'Form Wawancara Staf Baru' : 'Edit Wawancara Staf Baru' ?></h2>
        <form method="POST" action="?module=<?= e($module) ?>&action=<?= e($action) ?><?= $action === 'edit' ? '&id=' . (int)$id : '' ?>" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-gray-50 rounded-lg">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Nama Lengkap *</label>
                    <input type="text" name="nama_lengkap" required value="<?= e($detailData['nama_lengkap'] ?? '') ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Pendidikan</label>
                    <input type="text" name="pendidikan" value="<?= e($detailData['pendidikan'] ?? '') ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Posisi Dicari</label>
                    <input type="text" name="posisi_dicari" value="<?= e($detailData['posisi_dicari'] ?? '') ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Tanggal Wawancara *</label>
                    <input type="date" name="tanggal_wawancara" required value="<?= e($detailData['tanggal_wawancara'] ?? date('Y-m-d')) ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                </div>
            </div>

            <div class="overflow-x-auto">
                <table class="w-full border-collapse">
                    <thead>
                        <tr class="bg-gray-100">
                            <th class="border p-2 text-left">Aspek Penilaian</th>
                            <th class="border p-2 text-center">Pewawancara 1</th>
                            <th class="border p-2 text-center">Pewawancara 2</th>
                            <th class="border p-2 text-center">Pewawancara 3</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($labels as $key => $label): ?>
                        <tr>
                            <td class="border p-2 font-medium"><?= e($label) ?></td>
                            <td class="border p-2">
                                <input type="number" name="<?= e($key) ?>_1" min="0" max="100" step="0.01" value="<?= e(nilai_form_wawancara($detailData, $key . '_1', $action)) ?>" class="w-20 text-center border rounded">
                            </td>
                            <td class="border p-2">
                                <input type="number" name="<?= e($key) ?>_2" min="0" max="100" step="0.01" value="<?= e(nilai_form_wawancara($detailData, $key . '_2', $action)) ?>" class="w-20 text-center border rounded">
                            </td>
                            <td class="border p-2">
                                <input type="number" name="<?= e($key) ?>_3" min="0" max="100" step="0.01" value="<?= e(nilai_form_wawancara($detailData, $key . '_3', $action)) ?>" class="w-20 text-center border rounded">
                            </td>
                        </tr>
                        <?php endforeach; ?>

                        <tr class="bg-blue-50">
                            <td class="border p-2 font-medium">Nama Pewawancara</td>
                            <td class="border p-2">
                                <input type="text" name="pewawancara_1" value="<?= e($detailData['pewawancara_1_nama'] ?? ($_SESSION['full_name'] ?? '')) ?>" class="w-full px-2 py-1 border rounded text-sm">
                            </td>
                            <td class="border p-2">
                                <input type="text" name="pewawancara_2" value="<?= e($detailData['pewawancara_2_nama'] ?? '') ?>" class="w-full px-2 py-1 border rounded text-sm">
                            </td>
                            <td class="border p-2">
                                <input type="text" name="pewawancara_3" value="<?= e($detailData['pewawancara_3_nama'] ?? '') ?>" class="w-full px-2 py-1 border rounded text-sm">
                            </td>
                        </tr>

                        <tr class="bg-emerald-50">
                            <td class="border p-2 font-medium">NIK / Passcode TTD QR</td>
                            <td class="border p-2">
                                <input type="text" name="pewawancara_1_nik" value="<?= e($detailData['pewawancara_1_nik'] ?? ($_SESSION['nik'] ?? $_SESSION['emp_id'] ?? $_SESSION['employee_id'] ?? '')) ?>" class="w-full px-2 py-1 border rounded text-sm" placeholder="NIK Pewawancara 1">
                            </td>
                            <td class="border p-2">
                                <input type="text" name="pewawancara_2_nik" value="<?= e($detailData['pewawancara_2_nik'] ?? '') ?>" class="w-full px-2 py-1 border rounded text-sm" placeholder="NIK Pewawancara 2">
                            </td>
                            <td class="border p-2">
                                <input type="text" name="pewawancara_3_nik" value="<?= e($detailData['pewawancara_3_nik'] ?? '') ?>" class="w-full px-2 py-1 border rounded text-sm" placeholder="NIK Pewawancara 3">
                            </td>
                        </tr>

                        <tr>
                            <td class="border p-2 font-medium">Saran/Komentar</td>
                            <td class="border p-2">
                                <textarea name="saran_1" rows="2" class="w-full px-2 py-1 border rounded text-sm"><?= e($detailData['saran_komentar_1'] ?? '') ?></textarea>
                            </td>
                            <td class="border p-2">
                                <textarea name="saran_2" rows="2" class="w-full px-2 py-1 border rounded text-sm"><?= e($detailData['saran_komentar_2'] ?? '') ?></textarea>
                            </td>
                            <td class="border p-2">
                                <textarea name="saran_3" rows="2" class="w-full px-2 py-1 border rounded text-sm"><?= e($detailData['saran_komentar_3'] ?? '') ?></textarea>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-gray-50 rounded-lg">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Keputusan Akhir</label>
                    <select name="keputusan_akhir" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                        <option value="Diterima" <?= (($detailData['keputusan_akhir'] ?? '') === 'Diterima') ? 'selected' : '' ?>>Diterima</option>
                        <option value="Dipertimbangkan" <?= (($detailData['keputusan_akhir'] ?? 'Dipertimbangkan') === 'Dipertimbangkan') ? 'selected' : '' ?>>Dipertimbangkan</option>
                        <option value="Tidak Disarankan" <?= (($detailData['keputusan_akhir'] ?? '') === 'Tidak Disarankan') ? 'selected' : '' ?>>Tidak Disarankan</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Catatan Akhir</label>
                    <textarea name="catatan_akhir" rows="2" class="w-full px-4 py-2 border border-gray-300 rounded-lg"><?= e($detailData['catatan_akhir'] ?? '') ?></textarea>
                </div>
            </div>

            <div class="flex justify-end space-x-2">
                <a href="?module=<?= e($module) ?>" class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">Batal</a>
                <button type="submit" class="px-6 py-2 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-lg hover:from-blue-700 hover:to-indigo-700">
                    <?= $action === 'add' ? 'Simpan Hasil Wawancara' : 'Update Hasil Wawancara' ?>
                </button>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <?php if ($action === 'detail' && $detailData): ?>
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-lg font-semibold">Detail Wawancara</h2>
            <div class="space-x-2">
                <a href="javascript:void(0)" onclick="excelIndividuById(<?= (int)$detailData['id'] ?>)" class="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700">
                    <i class="fas fa-user mr-2"></i>Excel Per Orang
                </a>
                <a href="javascript:void(0)" onclick="excelRekapByTanggal('<?= e((string)$detailData['tanggal_wawancara']) ?>')" class="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700">
                    <i class="fas fa-table mr-2"></i>Rekap Tanggal Ini
                </a>
                <a href="?module=<?= e($module) ?>&action=edit&id=<?= (int)$detailData['id'] ?>" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                    <i class="fas fa-edit mr-2"></i>Edit
                </a>
                <a href="?module=<?= e($module) ?>" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                    Kembali
                </a>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-gray-50 rounded-lg mb-6">
            <div><strong>Nama:</strong> <?= e($detailData['nama_lengkap']) ?></div>
            <div><strong>Pendidikan:</strong> <?= e($detailData['pendidikan']) ?></div>
            <div><strong>Posisi Dicari:</strong> <?= e($detailData['posisi_dicari']) ?></div>
            <div><strong>Tanggal Wawancara:</strong> <?= e($detailData['tanggal_wawancara']) ?></div>
            <div><strong>Keputusan Akhir:</strong> <?= e($detailData['keputusan_akhir']) ?></div>
            <div><strong>Catatan:</strong> <?= e($detailData['catatan_akhir']) ?></div>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full border-collapse">
                <thead>
                    <tr class="bg-gray-100">
                        <th class="border p-2 text-left">Aspek Penilaian</th>
                        <th class="border p-2 text-center">Pewawancara 1</th>
                        <th class="border p-2 text-center">Pewawancara 2</th>
                        <th class="border p-2 text-center">Pewawancara 3</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($labels as $key => $label): ?>
                    <tr>
                        <td class="border p-2 font-medium"><?= e($label) ?></td>
                        <td class="border p-2 text-center"><?= e($detailData[$key . '_1'] ?? 0) ?></td>
                        <td class="border p-2 text-center"><?= e($detailData[$key . '_2'] ?? 0) ?></td>
                        <td class="border p-2 text-center"><?= e($detailData[$key . '_3'] ?? 0) ?></td>
                    </tr>
                    <?php endforeach; ?>

                    <tr class="bg-blue-50">
                        <td class="border p-2 font-medium">Rata-rata</td>
                        <td class="border p-2 text-center font-semibold"><?= number_format((float)($detailData['rata_rata_1'] ?? 0), 2) ?></td>
                        <td class="border p-2 text-center font-semibold"><?= number_format((float)($detailData['rata_rata_2'] ?? 0), 2) ?></td>
                        <td class="border p-2 text-center font-semibold"><?= number_format((float)($detailData['rata_rata_3'] ?? 0), 2) ?></td>
                    </tr>

                    <tr>
                        <td class="border p-2 font-medium">Kesimpulan</td>
                        <td class="border p-2 text-center"><?= e($detailData['kesimpulan_1'] ?? '-') ?></td>
                        <td class="border p-2 text-center"><?= e($detailData['kesimpulan_2'] ?? '-') ?></td>
                        <td class="border p-2 text-center"><?= e($detailData['kesimpulan_3'] ?? '-') ?></td>
                    </tr>

                    <tr>
                        <td class="border p-2 font-medium">Pewawancara</td>
                        <td class="border p-2 text-center"><?= e($detailData['pewawancara_1_nama'] ?? '-') ?></td>
                        <td class="border p-2 text-center"><?= e($detailData['pewawancara_2_nama'] ?? '-') ?></td>
                        <td class="border p-2 text-center"><?= e($detailData['pewawancara_3_nama'] ?? '-') ?></td>
                    </tr>

                    <tr>
                        <td class="border p-2 font-medium">NIK TTD QR</td>
                        <td class="border p-2 text-center"><?= e($detailData['pewawancara_1_nik'] ?? '-') ?></td>
                        <td class="border p-2 text-center"><?= e($detailData['pewawancara_2_nik'] ?? '-') ?></td>
                        <td class="border p-2 text-center"><?= e($detailData['pewawancara_3_nik'] ?? '-') ?></td>
                    </tr>

                    <tr>
                        <td class="border p-2 font-medium">Saran / Komentar</td>
                        <td class="border p-2"><?= e($detailData['saran_komentar_1'] ?? '-') ?></td>
                        <td class="border p-2"><?= e($detailData['saran_komentar_2'] ?? '-') ?></td>
                        <td class="border p-2"><?= e($detailData['saran_komentar_3'] ?? '-') ?></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <div class="bg-white rounded-xl shadow-lg overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 border-b border-gray-200">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">No</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nama</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Pendidikan</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Posisi</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tgl Wawancara</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Rata-rata</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Grade</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Keputusan</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    <?php $no = 1; ?>
                    <?php foreach ($data as $d): ?>
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 text-sm text-gray-600"><?= $no++ ?></td>
                        <td class="px-6 py-4 text-sm font-medium text-gray-900"><?= e($d['nama_lengkap']) ?></td>
                        <td class="px-6 py-4 text-sm text-gray-600"><?= e($d['pendidikan']) ?></td>
                        <td class="px-6 py-4 text-sm text-gray-600"><?= e($d['posisi_dicari']) ?></td>
                        <td class="px-6 py-4 text-sm text-gray-600"><?= function_exists('formatTanggal') ? formatTanggal($d['tanggal_wawancara']) : e($d['tanggal_wawancara']) ?></td>
                        <td class="px-6 py-4 text-sm font-semibold">
                            <?php
                            $rata = nilai_akhir_wawancara($d);
                            $gradeRow = grading_wawancara($rata);
                            echo number_format($rata, 2);
                            ?>
                        </td>
                        <td class="px-6 py-4">
                            <span class="px-2 py-1 text-xs rounded-full bg-slate-100 text-slate-800 font-bold" title="<?= e($gradeRow['label']) ?>">
                                <?= e($gradeRow['grade']) ?>
                            </span>
                        </td>
                        <td class="px-6 py-4">
                            <?php
                            $color = 'yellow';
                            if (($d['keputusan_akhir'] ?? '') === 'Diterima') $color = 'green';
                            elseif (($d['keputusan_akhir'] ?? '') === 'Tidak Disarankan') $color = 'red';
                            ?>
                            <span class="px-2 py-1 text-xs rounded-full bg-<?= $color ?>-100 text-<?= $color ?>-800">
                                <?= e($d['keputusan_akhir']) ?>
                            </span>
                        </td>
                        <td class="px-6 py-4 text-sm space-x-3 whitespace-nowrap">
                            <a href="javascript:void(0)" onclick="excelIndividuById(<?= (int)$d['id'] ?>)" class="text-emerald-600 hover:text-emerald-800" title="Export Excel Per Orang">
                                <i class="fas fa-file-excel"></i>
                            </a>
                            <a href="?module=<?= e($module) ?>&action=detail&id=<?= (int)$d['id'] ?>" class="text-blue-600 hover:text-blue-800" title="Detail">
                                <i class="fas fa-eye"></i>
                            </a>
                            <a href="?module=<?= e($module) ?>&action=edit&id=<?= (int)$d['id'] ?>" class="text-yellow-600 hover:text-yellow-800" title="Edit">
                                <i class="fas fa-edit"></i>
                            </a>
                            <a href="?module=<?= e($module) ?>&action=delete&id=<?= (int)$d['id'] ?>" onclick="return confirm('Yakin hapus data ini?')" class="text-red-600 hover:text-red-800" title="Hapus">
                                <i class="fas fa-trash"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>

                    <?php if (empty($data)): ?>
                    <tr>
                        <td colspan="9" class="px-6 py-8 text-center text-gray-500">Belum ada data wawancara.</td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <script>
        function showForm() {
            window.location.href = '?module=<?= e($module) ?>&action=add';
        }

        const WAWANCARA_ROWS = <?= json_encode($dataExcelAll, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>;
        const WAWANCARA_FIELDS = <?= json_encode($fields, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>;
        const WAWANCARA_LABELS = <?= json_encode($labels, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>;
        const WAWANCARA_URAIAN = <?= json_encode($uraianLabels, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE) ?>;

        function escExcel(value) {
            return String(value ?? '')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;');
        }

        function num(value) {
            const n = parseFloat(value ?? 0);
            return Number.isFinite(n) ? n : 0;
        }

        function fmt2(value) {
            return num(value).toFixed(2);
        }

        function tanggalIndo(dateString) {
            if (!dateString || dateString === '0000-00-00') return '-';
            const parts = String(dateString).split('-');
            if (parts.length !== 3) return dateString;
            const bulan = ['', 'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
            const m = parseInt(parts[1], 10);
            return parseInt(parts[2], 10) + ' ' + (bulan[m] || parts[1]) + ' ' + parts[0];
        }

        function nilaiAkhir(row) {
            const vals = [1, 2, 3]
                .map(i => num(row['rata_rata_' + i]))
                .filter(v => v > 0);
            if (!vals.length) return 0;
            return vals.reduce((a, b) => a + b, 0) / vals.length;
        }

        function gradeInfo(nilai) {
            if (nilai >= 85) return { grade: 'A', label: 'Sangat Direkomendasikan', keputusan: 'Dapat Diterima' };
            if (nilai >= 75) return { grade: 'B', label: 'Direkomendasikan', keputusan: 'Dapat Diterima' };
            if (nilai >= 60) return { grade: 'C', label: 'Dipertimbangkan', keputusan: 'Dipertimbangkan' };
            return { grade: 'D', label: 'Tidak Direkomendasikan', keputusan: 'Tidak Disarankan' };
        }

        const BALIMED_LOGO_URL = 'https://balimedhospital.co.id/wp-content/uploads/elementor/thumbs/logo-dark-o9cm6tnx14hcrnest1hge1pwnqj0yaumij7qohadlm.png';

        function logoHeader(colspanLeft, colspanTitle, colspanRight, title) {
            return `<tr>
                <td colspan="${colspanLeft}" class="logo-cell"><img src="${BALIMED_LOGO_URL}" class="logo-img"></td>
                <td colspan="${colspanTitle}" class="title">${title}</td>
                <td colspan="${colspanRight}" class="logo-cell">&nbsp;</td>
            </tr>`;
        }

        function excelCss(orientation = 'portrait') {
            const isLandscape = orientation === 'landscape';
            return `
                <style>
                    @page {
                        size: A4 ${isLandscape ? 'landscape' : 'portrait'};
                        margin: ${isLandscape ? '0.30in 0.25in 0.30in 0.25in' : '0.35in 0.30in 0.35in 0.30in'};
                        mso-page-orientation: ${isLandscape ? 'landscape' : 'portrait'};
                    }
                    body { font-family: Arial, sans-serif; font-size: ${isLandscape ? '9.5pt' : '9pt'}; color: #000; }
                    table { border-collapse: collapse; width: 100%; table-layout: fixed; }
                    td, th { border: 0.5pt solid #444444; padding: 3px 4px; vertical-align: middle; }
                    .noborder td, .noborder th { border: 0; }
                    .logo-cell { border:0; text-align:left; vertical-align:middle; }
                    .logo-img { width: 105px; height:auto; }
                    .title { font-size: ${isLandscape ? '15pt' : '13pt'}; font-weight: bold; text-align: center; border:0; }
                    .subtitle { font-size: ${isLandscape ? '10.5pt' : '10pt'}; text-align: center; border:0; }
                    .section-title { font-size: ${isLandscape ? '12pt' : '11pt'}; font-weight: bold; text-align: center; background: #ffffff; border: 0; padding-top: 6px; padding-bottom: 2px; }
                    .head { background: #d9eaf7; font-weight: bold; text-align: center; }
                    .soft { background: #f2f2f2; font-weight: bold; }
                    .center { text-align: center; }
                    .right { text-align: right; }
                    .bold { font-weight: bold; }
                    .small { font-size: 7.5pt; }
                    .wrap { white-space: normal; mso-wrap-style: square; }
                    .nowrap { white-space: nowrap; }
                    .blue { color: #1d4ed8; font-weight: bold; }
                    .green { color: #047857; font-weight: bold; }
                    .orange { color: #b45309; font-weight: bold; }
                    .red { color: #b91c1c; font-weight: bold; }
                    .qrbox { height: 78px; text-align: center; vertical-align: middle; }
                    .qrimg { width: 58px; height: 58px; }
                    .signature-name { font-weight: bold; text-align:center; }
                    .page-gap { height: 12px; border: 0; }
                </style>`;
        }

        function qrPasscode(row, idx) {
            const nik = String(row['pewawancara_' + idx + '_nik'] || '').trim();
            const nama = String(row['pewawancara_' + idx + '_nama'] || '').trim();
            if (!nik && !nama) return '';
            return 'TTD-WAWANCARA-STAF-BARU|ID:' + (row.id || '-') + '|NIK:' + nik + '|NAMA:' + nama + '|STAF:' + (row.nama_lengkap || '-') + '|TGL:' + (row.tanggal_wawancara || '-');
        }

        function qrImg(passcode) {
            if (!passcode) return '<span class="small">Belum ada NIK</span>';
            const url = 'https://api.qrserver.com/v1/create-qr-code/?size=110x110&margin=1&data=' + encodeURIComponent(passcode);
            return '<img class="qrimg" src="' + url + '" alt="QR TTD">';
        }

        function renderRekap(rows, tanggalFilter) {
            const total = rows.length;
            const avg = total ? rows.reduce((s, r) => s + nilaiAkhir(r), 0) / total : 0;
            const counts = { A: 0, B: 0, C: 0, D: 0 };
            rows.forEach(r => counts[gradeInfo(nilaiAkhir(r)).grade]++);
            const tanggalText = tanggalFilter ? tanggalIndo(tanggalFilter) : 'Semua Tanggal';
            const now = new Date();
            const printed = String(now.getDate()).padStart(2, '0') + '-' + String(now.getMonth() + 1).padStart(2, '0') + '-' + now.getFullYear() + ' ' + String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0');

            let html = `
                <table class="noborder" style="width:100%;">
                    <colgroup>
                        <col style="width:5%"><col style="width:17%"><col style="width:12%"><col style="width:18%"><col style="width:10%"><col style="width:8%"><col style="width:8%"><col style="width:8%"><col style="width:7%"><col style="width:5%"><col style="width:12%">
                    </colgroup>
                    ${logoHeader(2, 7, 2, 'REKAP HASIL WAWANCARA STAF BARU')}
                    <tr><td colspan="11" class="subtitle">RS BaliMéd Denpasar</td></tr>
                    <tr><td colspan="11" style="border:0;height:6px;">&nbsp;</td></tr>
                    <tr>
                        <td colspan="2" class="bold">Tanggal Wawancara</td><td colspan="3">: ${escExcel(tanggalText)}</td>
                        <td colspan="2" class="bold">Jumlah Staf</td><td colspan="4">: ${total} orang</td>
                    </tr>
                    <tr>
                        <td colspan="2" class="bold">Rata-rata Kelompok</td><td colspan="3">: ${fmt2(avg)}</td>
                        <td colspan="2" class="bold">Dicetak</td><td colspan="4">: ${printed}</td>
                    </tr>
                    <tr><td colspan="11">&nbsp;</td></tr>
                    <tr class="head"><td colspan="2">Grade A</td><td colspan="3">Grade B</td><td colspan="2">Grade C</td><td colspan="4">Grade D</td></tr>
                    <tr class="center bold"><td colspan="2" class="green">${counts.A}</td><td colspan="3" class="blue">${counts.B}</td><td colspan="2" class="orange">${counts.C}</td><td colspan="4" class="red">${counts.D}</td></tr>
                    <tr class="center"><td colspan="2">Sangat Direkomendasikan</td><td colspan="3">Direkomendasikan</td><td colspan="2">Dipertimbangkan</td><td colspan="4">Tidak Direkomendasikan</td></tr>
                    <tr><td colspan="11">&nbsp;</td></tr>
                    <tr><td colspan="11" class="bold">DAFTAR STAF YANG DIWAWANCARA</td></tr>
                    <tr class="head">
                        <th>No</th><th>Nama</th><th>Pendidikan</th><th>Posisi</th><th>Tanggal</th>
                        <th>Nilai 1</th><th>Nilai 2</th><th>Nilai 3</th><th>Akhir</th><th>Grade</th><th>Keputusan</th>
                    </tr>`;
            rows.forEach((r, idx) => {
                const akhir = nilaiAkhir(r);
                const g = gradeInfo(akhir);
                html += `<tr>
                    <td class="center">${idx + 1}</td>
                    <td class="wrap">${escExcel(r.nama_lengkap)}</td>
                    <td>${escExcel(r.pendidikan)}</td>
                    <td>${escExcel(r.posisi_dicari)}</td>
                    <td class="center nowrap">${tanggalIndo(r.tanggal_wawancara)}</td>
                    <td class="center">${fmt2(r.rata_rata_1)}</td>
                    <td class="center">${fmt2(r.rata_rata_2)}</td>
                    <td class="center">${fmt2(r.rata_rata_3)}</td>
                    <td class="center bold">${fmt2(akhir)}</td>
                    <td class="center blue">${g.grade}</td>
                    <td>${escExcel(g.label)}</td>
                </tr>`;
            });
            html += `<tr><td colspan="11">Grading: A ≥ 85, B 75 - 84,99, C 60 - 74,99, D &lt; 60.</td></tr>`;
            html += `<tr><td colspan="11" class="page-gap">&nbsp;</td></tr></table>`;
            return html;
        }

        function renderIndividu(row) {
            const akhir = nilaiAkhir(row);
            const g = gradeInfo(akhir);
            const q1 = qrPasscode(row, 1);
            const q2 = qrPasscode(row, 2);
            const q3 = qrPasscode(row, 3);
            let html = `
                <table style="width:100%;">
                    <colgroup>
                        <col style="width:4%"><col style="width:16%"><col style="width:29%"><col style="width:9%"><col style="width:9%"><col style="width:9%"><col style="width:9%"><col style="width:15%">
                    </colgroup>
                    ${logoHeader(2, 4, 2, 'HASIL PENILAIAN WAWANCARA STAF BARU')}
                    <tr><td colspan="8" class="subtitle">RS BaliMéd Denpasar</td></tr>
                    <tr><td colspan="8" style="border:0;height:6px;">&nbsp;</td></tr>
                    <tr>
                        <td colspan="2" class="bold">Nama Lengkap</td><td colspan="2">${escExcel(row.nama_lengkap)}</td>
                        <td colspan="2" class="bold">Tanggal Wawancara</td><td colspan="2" class="center">${tanggalIndo(row.tanggal_wawancara)}</td>
                    </tr>
                    <tr>
                        <td colspan="2" class="bold">Pendidikan</td><td colspan="2">${escExcel(row.pendidikan)}</td>
                        <td colspan="2" class="bold">Posisi Dicari</td><td colspan="2">${escExcel(row.posisi_dicari)}</td>
                    </tr>
                    <tr>
                        <td colspan="2" class="bold">Nilai Akhir</td><td class="center bold">${fmt2(akhir)}</td><td class="bold center">Grade</td>
                        <td class="center bold">${g.grade}</td><td class="bold">Kategori</td><td colspan="2">${escExcel(g.label)}</td>
                    </tr>
                    <tr class="head">
                        <th>No</th>
                        <th>Aspek Penilaian</th>
                        <th>Uraian</th>
                        <th>Nilai 1</th>
                        <th>Nilai 2</th>
                        <th>Nilai 3</th>
                        <th>Rata-rata</th>
                        <th>Keterangan</th>
                    </tr>`;
            WAWANCARA_FIELDS.forEach((field, idx) => {
                const n1 = num(row[field + '_1']);
                const n2 = num(row[field + '_2']);
                const n3 = num(row[field + '_3']);
                const vals = [n1, n2, n3].filter(v => v > 0);
                const avg = vals.length ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;
                html += `<tr>
                    <td class="center">${idx + 1}</td>
                    <td>${escExcel(WAWANCARA_LABELS[field] || field)}</td>
                    <td class="wrap">${escExcel(WAWANCARA_URAIAN[field] || '')}</td>
                    <td class="center">${fmt2(n1)}</td>
                    <td class="center">${fmt2(n2)}</td>
                    <td class="center">${fmt2(n3)}</td>
                    <td class="center bold">${fmt2(avg)}</td>
                    <td>${escExcel(gradeInfo(avg).label)}</td>
                </tr>`;
            });
            html += `
                    <tr class="soft"><td colspan="3">Rata-rata Pewawancara</td><td class="center">${fmt2(row.rata_rata_1)}</td><td class="center">${fmt2(row.rata_rata_2)}</td><td class="center">${fmt2(row.rata_rata_3)}</td><td class="center bold">${fmt2(akhir)}</td><td></td></tr>
                    <tr><td colspan="3" class="bold">Kesimpulan Pewawancara</td><td>${escExcel(row.kesimpulan_1)}</td><td>${escExcel(row.kesimpulan_2)}</td><td>${escExcel(row.kesimpulan_3)}</td><td colspan="2">${escExcel(g.label)}</td></tr>
                    <tr><td colspan="3" class="bold">Saran/Komentar</td><td colspan="2">${escExcel(row.saran_komentar_1)}</td><td colspan="2">${escExcel(row.saran_komentar_2)}</td><td>${escExcel(row.saran_komentar_3 || row.catatan_akhir)}</td></tr>
                    <tr><td colspan="3" class="bold">Keputusan Akhir</td><td colspan="5" class="bold">${escExcel(row.keputusan_akhir || g.keputusan)}</td></tr>
                    <tr><td colspan="8">&nbsp;</td></tr>
                    <tr class="head"><td colspan="8">TANDA TANGAN DIGITAL PEWAWANCARA / QR PASSCODE NIK</td></tr>
                    <tr class="center bold"><td colspan="3">Pewawancara 1</td><td colspan="2">Pewawancara 2</td><td colspan="3">Pewawancara 3</td></tr>
                    <tr class="qrbox"><td colspan="3">${qrImg(q1)}</td><td colspan="2">${qrImg(q2)}</td><td colspan="3">${qrImg(q3)}</td></tr>
                    <tr class="signature-name"><td colspan="3">${escExcel(row.pewawancara_1_nama || '-')}</td><td colspan="2">${escExcel(row.pewawancara_2_nama || '-')}</td><td colspan="3">${escExcel(row.pewawancara_3_nama || '-')}</td></tr>
                    <tr class="center small"><td colspan="3">NIK: ${escExcel(row.pewawancara_1_nik || '-')}</td><td colspan="2">NIK: ${escExcel(row.pewawancara_2_nik || '-')}</td><td colspan="3">NIK: ${escExcel(row.pewawancara_3_nik || '-')}</td></tr>
                    <tr class="center small"><td colspan="8">QR berisi passcode: ID wawancara, NIK pewawancara, nama pewawancara, nama staf, dan tanggal wawancara.</td></tr>
                </table>`;
            return html;
        }

        function downloadExcel(html, filename, orientation = 'portrait') {
            const fullHtml = `<!DOCTYPE html><html><head><meta charset="UTF-8">${excelCss(orientation)}</head><body>${html}</body></html>`;
            const blob = new Blob(['\ufeff', fullHtml], { type: 'application/vnd.ms-excel;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            setTimeout(() => URL.revokeObjectURL(url), 1000);
        }

        function excelRekapByTanggal(tanggalManual = null) {
            const el = document.getElementById('excelTanggalRekap');
            const tanggal = tanggalManual !== null ? tanggalManual : (el ? el.value : '');
            const rows = tanggal ? WAWANCARA_ROWS.filter(r => r.tanggal_wawancara === tanggal) : WAWANCARA_ROWS.slice();
            if (!rows.length) {
                alert('Tidak ada data wawancara pada tanggal yang dipilih.');
                return;
            }
            const suffix = tanggal ? tanggal : 'semua_tanggal';
            downloadExcel(renderRekap(rows, tanggal), 'Rekap_Wawancara_Staf_Baru_' + suffix + '.xls', 'landscape');
        }

        function excelGabunganDetailByTanggal(tanggalManual = null) {
            const el = document.getElementById('excelTanggalRekap');
            const tanggal = tanggalManual !== null ? tanggalManual : (el ? el.value : '');
            const rows = tanggal ? WAWANCARA_ROWS.filter(r => r.tanggal_wawancara === tanggal) : WAWANCARA_ROWS.slice();
            if (!rows.length) {
                alert('Tidak ada data wawancara pada tanggal yang dipilih.');
                return;
            }
            let html = renderRekap(rows, tanggal);
            rows.forEach(row => { html += renderIndividu(row); });
            const suffix = tanggal ? tanggal : 'semua_tanggal';
            downloadExcel(html, 'Rekap_Detail_Wawancara_Staf_Baru_' + suffix + '.xls', 'landscape');
        }

        function excelIndividuById(id) {
            const row = WAWANCARA_ROWS.find(r => parseInt(r.id, 10) === parseInt(id, 10));
            if (!row) {
                alert('Data staf tidak ditemukan.');
                return;
            }
            const safeName = String(row.nama_lengkap || 'staf_baru').replace(/[^a-zA-Z0-9_-]+/g, '_');
            downloadExcel(renderIndividu(row), 'Penilaian_Staf_Baru_' + safeName + '.xls', 'portrait');
        }
    </script>
</body>
</html>