<?php
declare(strict_types=1);

ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);

// AUTH dari master HR
require_once __DIR__ . '/config/master_auth.php';

// DB aplikasi lama tetap dipakai
require_once __DIR__ . '/config/database.php';

// config app lama tetap dipakai
if (file_exists(__DIR__ . '/config/app.php')) {
    require_once __DIR__ . '/config/app.php';
}

require_login();
$masterUser = current_user();

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

/*
|--------------------------------------------------------------------------
| EXPORT DOCX ANALISIS KUNJUNGAN
|--------------------------------------------------------------------------
*/
if (
    isset($_GET['module'], $_GET['action']) &&
    $_GET['module'] === 'analisis_kunjungan' &&
    $_GET['action'] === 'export_docx'
) {
    require_once __DIR__ . '/modules/analisis_kunjungan/functions.php';

    $vendorAutoload = __DIR__ . '/vendor/autoload.php';
    if (file_exists($vendorAutoload)) {
        require_once $vendorAutoload;
    }

    if (function_exists('checkAuth')) {
        checkAuth();
    }

    if (!function_exists('ak_docx_writer_available') || !ak_docx_writer_available()) {
        exit('Library PhpWord belum terpasang atau vendor/autoload.php tidak ditemukan.');
    }

    $conn = getConnection();
    $analysisYear = (int)($_GET['year'] ?? date('Y'));
    $exportData = ak_build_export_data($conn, $analysisYear);

    $phpWord = new \PhpOffice\PhpWord\PhpWord();
    $phpWord->setDefaultFontName('Times New Roman');
    $phpWord->setDefaultFontSize(12);

    $section = $phpWord->addSection([
        'marginTop'    => 1000,
        'marginBottom' => 1000,
        'marginLeft'   => 1200,
        'marginRight'  => 1000,
    ]);

    $titleStyle   = ['bold' => true, 'size' => 14];
    $headingStyle = ['bold' => true, 'size' => 12];
    $normalStyle  = ['size' => 12];
    $centerStyle  = ['align' => 'center'];
    $justifyStyle = ['align' => 'both'];
    $tableStyleName = 'MainTable';

    $phpWord->addTableStyle($tableStyleName, [
        'borderSize' => 6,
        'borderColor' => '666666',
        'cellMargin' => 60,
    ], [
        'bgColor' => 'D9EAF7',
    ]);

    $section->addText('LAPORAN ANALISIS REKAM MEDIS TERKAIT JUMLAH KUNJUNGAN PASIEN PER UNIT DI DIV. KEPERAWATAN', $titleStyle, $centerStyle);
    $section->addText('TAHUN ' . $analysisYear, $titleStyle, $centerStyle);
    $section->addTextBreak(1);

    $section->addText('BAB I', $headingStyle, $centerStyle);
    $section->addText('PENDAHULUAN', $headingStyle, $centerStyle);
    $section->addTextBreak(1);

    $pendahuluan = "Mengingat pentingnya data dan informasi sebagai dasar pengambilan keputusan dan pelaksanaan fungsi manajemen, rumah sakit perlu memanfaatkan data pelayanan secara optimal. Salah satu pendekatan yang digunakan adalah analisis kunjungan pasien per unit pelayanan keperawatan dan rasio pasien terhadap jumlah perawat. Analisis ini membantu memetakan beban kerja, kecenderungan kunjungan, dan kebutuhan penyesuaian SDM keperawatan.";
    $section->addText($pendahuluan, $normalStyle, $justifyStyle);
    $section->addTextBreak(1);

    $section->addText('BAB II', $headingStyle, $centerStyle);
    $section->addText('PEMBAHASAN', $headingStyle, $centerStyle);
    $section->addTextBreak(1);

    $section->addText('Ringkasan Umum', ['bold' => true], ['align' => 'left']);
    $section->addText($exportData['summary_text'], $normalStyle, $justifyStyle);
    $section->addTextBreak(1);

    $overallLabels = [];
    $overallValues = [];
    foreach ($exportData['overall_totals'] as $row) {
        if ((int)($row['total_visits'] ?? 0) > 0) {
            $overallLabels[] = $row['period_label'];
            $overallValues[] = (int)$row['total_visits'];
        }
    }

    $ratioLabels = [];
    $ratioValues = [];
    foreach ($exportData['dashboard_rows'] as $row) {
        $ratioLabels[] = $row['unit_name'];
        $ratioValues[] = (float)$row['ratio'];
    }

    $visitChartPath = ak_create_line_chart_png($overallLabels, $overallValues, 'Grafik Total Kunjungan Bulanan');
    $ratioChartPath = ak_create_bar_chart_png($ratioLabels, $ratioValues, 'Grafik Rata-rata Kunjungan / Perawat');

    if ($visitChartPath && file_exists($visitChartPath)) {
        $section->addText('Grafik 1. Tren Kunjungan Bulanan', ['bold' => true], ['align' => 'left']);
        $section->addImage($visitChartPath, [
            'width' => 520,
            'height' => 220,
            'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER
        ]);
        $section->addTextBreak(1);
    }

    if ($ratioChartPath && file_exists($ratioChartPath)) {
        $section->addText('Grafik 2. Rata-rata Kunjungan per Perawat per Unit', ['bold' => true], ['align' => 'left']);
        $section->addImage($ratioChartPath, [
            'width' => 520,
            'height' => 220,
            'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER
        ]);
        $section->addTextBreak(1);
    }

    $section->addText('Tabel 1. Rekap Kunjungan dan Rasio Per Unit', ['bold' => true], ['align' => 'left']);
    $table = $section->addTable($tableStyleName);
    $table->addRow();
    $table->addCell(800)->addText('No', ['bold' => true]);
    $table->addCell(2800)->addText('Unit', ['bold' => true]);
    $table->addCell(1800)->addText('Total Kunjungan', ['bold' => true]);
    $table->addCell(1800)->addText('Jumlah Perawat', ['bold' => true]);
    $table->addCell(2200)->addText('Rata-rata Kunjungan / Perawat', ['bold' => true]);

    foreach ($exportData['dashboard_rows'] as $i => $row) {
        $table->addRow();
        $table->addCell(800)->addText((string)($i + 1));
        $table->addCell(2800)->addText($row['unit_name']);
        $table->addCell(1800)->addText(number_format((int)$row['total_visits'], 0, ',', '.'));
        $table->addCell(1800)->addText(number_format((int)$row['nurse_count'], 0, ',', '.'));
        $table->addCell(2200)->addText(number_format((float)$row['ratio'], 2, ',', '.'));
    }

    $section->addTextBreak(1);

    foreach ($exportData['unit_analysis'] as $unitItem) {
        $section->addText('Analisis Unit: ' . $unitItem['unit_name'], ['bold' => true], ['align' => 'left']);
        $section->addText($unitItem['note'], $normalStyle, $justifyStyle);

        $detailTable = $section->addTable($tableStyleName);
        $detailTable->addRow();
        $detailTable->addCell(900)->addText('No', ['bold' => true]);
        $detailTable->addCell(2200)->addText('Periode', ['bold' => true]);
        $detailTable->addCell(1800)->addText('Kunjungan', ['bold' => true]);
        $detailTable->addCell(1800)->addText('Perawat', ['bold' => true]);
        $detailTable->addCell(2200)->addText('Rasio', ['bold' => true]);

        foreach ($unitItem['detail'] as $i => $detail) {
            $detailTable->addRow();
            $detailTable->addCell(900)->addText((string)($i + 1));
            $detailTable->addCell(2200)->addText($detail['period_label']);
            $detailTable->addCell(1800)->addText(number_format((int)$detail['visit_total'], 0, ',', '.'));
            $detailTable->addCell(1800)->addText(number_format((int)$detail['nurse_count'], 0, ',', '.'));
            $detailTable->addCell(2200)->addText(number_format((float)$detail['ratio'], 2, ',', '.'));
        }

        $section->addTextBreak(1);
    }

    $section->addText('BAB III', $headingStyle, $centerStyle);
    $section->addText('ANALISIS RASIO PERAWAT', $headingStyle, $centerStyle);
    $section->addTextBreak(1);

    $bab3 = "Rasio pasien terhadap perawat menjadi indikator penting untuk menggambarkan beban kerja pelayanan. Total jumlah perawat yang digunakan dalam analisis ini adalah " .
        number_format((int)$exportData['total_nurses'], 0, ',', '.') .
        " orang. Unit dengan rasio rata-rata tertinggi adalah {$exportData['highest_ratio_unit']} dengan nilai " .
        number_format((float)$exportData['highest_ratio_value'], 2, ',', '.') .
        ". Data ini perlu menjadi dasar evaluasi distribusi SDM dan penjadwalan layanan.";
    $section->addText($bab3, $normalStyle, $justifyStyle);
    $section->addTextBreak(1);

    $section->addText('BAB IV', $headingStyle, $centerStyle);
    $section->addText('KESIMPULAN DAN REKOMENDASI', $headingStyle, $centerStyle);
    $section->addTextBreak(1);

    $section->addText($exportData['conclusion'], $normalStyle, $justifyStyle);
    $section->addTextBreak(2);

    $day   = date('d');
    $month = function_exists('ak_month_name_id') ? ak_month_name_id((int)date('n')) : date('F');
    $year  = date('Y');

    $section->addText('Denpasar, ' . $day . ' ' . $month . ' ' . $year, $normalStyle, ['align' => 'right']);
    $section->addText('Kepala Divisi Keperawatan', $normalStyle, ['align' => 'right']);
    $section->addTextBreak(3);
    $section->addText('Ns. Gusti Ngurah Agung, S.Kep', ['bold' => true], ['align' => 'right']);

    $filename = 'Laporan_Analisis_Kunjungan_Keperawatan_' . $analysisYear . '.docx';
    $tempFile = tempnam(sys_get_temp_dir(), 'ak_docx_');

    $writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
    $writer->save($tempFile);

    while (ob_get_level()) {
        ob_end_clean();
    }

    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($tempFile));

    readfile($tempFile);
    @unlink($tempFile);
    exit;
}

/**
 * Adapter user master -> format lama aplikasi
 */
$user = [
    'id'            => $masterUser['employee_id'] ?? null,
    'user_id'       => $masterUser['employee_id'] ?? null,
    'employee_id'   => $masterUser['employee_id'] ?? null,
    'nik'           => $masterUser['nik'] ?? ($masterUser['employee_code'] ?? ''),
    'employee_code' => $masterUser['employee_code'] ?? '',
    'full_name'     => $masterUser['nama'] ?? '',
    'nama'          => $masterUser['nama'] ?? '',
    'unit'          => $masterUser['unit_name'] ?? '',
    'unit_name'     => $masterUser['unit_name'] ?? '',
    'jabatan'       => $masterUser['position_name'] ?? '',
    'position_name' => $masterUser['position_name'] ?? '',
    'role'          => $masterUser['role'] ?? 'user',
    'email'         => $masterUser['email'] ?? '',
    'username'      => $masterUser['username'] ?? '',
];

$role = strtolower((string)($user['role'] ?? 'user'));

/**
 * Adapter session lama supaya modul-modul lama tetap kompatibel
 */
$_SESSION['user_id']      = $user['id'] ?? null;
$_SESSION['user_role']    = $user['role'] ?? 'user';
$_SESSION['access_scope'] = in_array(($user['role'] ?? ''), ['admin', 'superadmin'], true) ? 'full' : 'limited';
$_SESSION['full_name']    = $user['full_name'] ?? ($user['nama'] ?? '');
$_SESSION['nik']          = $user['nik'] ?? '';
$_SESSION['username']     = $user['username'] ?? '';
$_SESSION['email']        = $user['email'] ?? '';
$_SESSION['unit']         = $user['unit'] ?? ($user['unit_name'] ?? '');
$_SESSION['jabatan']      = $user['jabatan'] ?? ($user['position_name'] ?? '');

$_SESSION['user'] = [
    'logged_in'   => true,
    'id'          => $user['id'] ?? null,
    'user_id'     => $user['id'] ?? null,
    'employee_id' => $user['employee_id'] ?? null,
    'role'        => $user['role'] ?? 'user',
    'name'        => $user['full_name'] ?? ($user['nama'] ?? ''),
    'full_name'   => $user['full_name'] ?? ($user['nama'] ?? ''),
    'nama'        => $user['nama'] ?? '',
    'nik'         => $user['nik'] ?? '',
    'unit'        => $user['unit'] ?? ($user['unit_name'] ?? ''),
    'email'       => $user['email'] ?? '',
];

/**
 * Permission module per role
 */
function allowedModulesByRole(string $role): array
{
    $role = strtolower(trim($role));

    $viewerOnly = [
        'dashboard',
        'laporan_katim',
        'laporan_harian_poliklinik',
        'permasalahan_tindak_lanjut',
        'penugasan_manajemen_keperawatan',
        'user_profile',
        'activity_log',
        'struktur_organisasi',
        'google_drive_reader',
        'rdk',
        'coaching',
    ];

    $allModules = [
        'dashboard',
        'manage_user',
        'data_perawat',
        'data_perawat_per_unit',
        'data_staf_baru',
        'jadwal_orientasi_staf_baru',
        'rotasi_perawat',
        'beban_kerja',
        'kalender_kegiatan_keperawatan',
        'kegiatan_harian',
        'patient_safety',
        'laporan_rka',
        'laporan_katim',
        'permasalahan_tindak_lanjut',
        'penugasan_manajemen_keperawatan',
        'daftar_spo',
        'generator_surat',
        'distribusi_alat',
        'p3k',
        'laporan_bulanan',
        'analisis_kunjungan',
        'bpjs_margin_operasi',
        'laporan_harian_poliklinik',
        'import_poliklinik_doctors',
        'user_profile',
        'activity_log',
        'struktur_organisasi',
        'google_drive_reader',
        'rdk',
        'coaching',
    ];

    if (in_array($role, ['admin', 'superadmin'], true)) {
        return $allModules;
    }

    if ($role === 'viewer') {
        return $viewerOnly;
    }

    return [
        'dashboard',
        'laporan_katim',
        'penugasan_manajemen_keperawatan',
        'laporan_harian_poliklinik',
        'user_profile',
        'activity_log',
        'struktur_organisasi',
        'google_drive_reader',
        'rdk',
        'coaching',
    ];
}

function canAccessModule(string $role, string $module): bool
{
    return in_array($module, allowedModulesByRole($role), true);
}

/**
 * Module aktif
 */
$module = trim((string)($_GET['module'] ?? 'dashboard'));
if ($module === '') {
    $module = 'dashboard';
}

/**
 * Helper role
 */
if (!function_exists('hasRole')) {
    function hasRole($roles): bool
    {
        if (!is_array($roles)) {
            $roles = [$roles];
        }

        $currentRole = strtolower((string)($_SESSION['user_role'] ?? $_SESSION['user']['role'] ?? ''));

        if ($currentRole === 'superadmin') {
            return true;
        }

        $roles = array_map(static fn($r) => strtolower((string)$r), $roles);
        return in_array($currentRole, $roles, true);
    }
}

/**
 * Koneksi DB aplikasi lama
 */
$conn = null;

if (function_exists('getConnection')) {
    $conn = getConnection();
} elseif (class_exists('Database')) {
    $database = new Database();
    $conn = $database->getConnection();
} elseif (function_exists('db')) {
    $conn = db();
}

if (!$conn) {
    die('Koneksi database aplikasi gagal.');
}

function scalarQuery($conn, string $sql, int $default = 0): int
{
    try {
        if ($conn instanceof mysqli) {
            $result = $conn->query($sql);
            if (!$result) return $default;
            $row = $result->fetch_assoc();
            if (!$row) return $default;
            return (int)array_values($row)[0];
        }

        if ($conn instanceof PDO) {
            $stmt = $conn->query($sql);
            if (!$stmt) return $default;
            return (int)$stmt->fetchColumn();
        }
    } catch (Throwable $e) {
        return $default;
    }

    return $default;
}

function moduleFileMap(): array
{
    return [
        'manage_user' => 'modules/manage_user.php',
        'data_perawat' => 'modules/data_perawat.php',
        'data_perawat_per_unit' => 'modules/data_perawat_per_unit.php',
        'data_staf_baru' => 'modules/data_staf_baru.php',
        'jadwal_orientasi_staf_baru' => 'modules/jadwal_orientasi_staf_baru.php',
        'rotasi_perawat' => 'modules/rotasi_perawat.php',
        'beban_kerja' => 'modules/beban_kerja.php',
        'kegiatan_harian' => 'modules/kegiatan_harian/index.php',
        'patient_safety' => 'modules/patient_safety/index.php',
        'laporan_katim' => 'modules/laporan_katim/index.php',
        'permasalahan_tindak_lanjut' => 'modules/permasalahan_tindak_lanjut/index.php',
        'penugasan_manajemen_keperawatan' => 'modules/penugasan_manajemen_keperawatan/index.php',
        'kalender_kegiatan_keperawatan' => 'modules/kalender_kegiatan_keperawatan.php',
        'daftar_spo' => 'modules/daftar_spo.php',
        'generator_surat' => 'modules/generator_surat.php',
        'distribusi_alat' => 'modules/distribusi_alat/index.php',
        'p3k' => 'modules/p3k.php',
        'laporan_bulanan' => 'modules/laporan/index.php',
        'analisis_kunjungan' => 'modules/analisis_kunjungan/index.php',
        'bpjs_margin_operasi' => 'modules/bpjs_margin_operasi/index.php',
        'laporan_harian_poliklinik' => 'modules/laporan_harian_poliklinik.php',
        'import_poliklinik_doctors' => 'modules/import_poliklinik_doctors.php',
        'user_profile' => 'modules/user_profile.php',
        'activity_log' => 'modules/activity_log.php',
        'struktur_organisasi' => 'modules/struktur_organisasi.php',
        'google_drive_reader' => 'modules/google_drive_frame.php',
        'rdk' => 'modules/rdk/index.php',
        'coaching' => 'modules/coaching/index.php',
        
    ];
}

function moduleExists(string $module): bool
{
    if ($module === 'dashboard') {
        return true;
    }

    $map = moduleFileMap();
    if (!isset($map[$module])) {
        return false;
    }

    return file_exists(__DIR__ . '/' . $map[$module]);
}

function loadModule(string $module): void
{
    if ($module === 'dashboard') {
        return;
    }

    $validModules = moduleFileMap();

    if (!isset($validModules[$module])) {
        echo "<div class='bg-yellow-50 border-l-4 border-yellow-500 p-4 rounded'><p class='text-yellow-700'>Module tidak dikenal: " . e($module) . "</p></div>";
        return;
    }

    $file = __DIR__ . '/' . $validModules[$module];
    if (!file_exists($file)) {
        echo "<div class='bg-red-50 border-l-4 border-red-500 p-4 rounded'><p class='text-red-700'>File module tidak ditemukan: " . e($validModules[$module]) . "</p></div>";
        return;
    }

    include $file;
}

if (!canAccessModule((string)$role, $module) || !moduleExists($module)) {
    $module = 'dashboard';
}

if (
    isset($_GET['module'], $_GET['page']) &&
    $_GET['module'] === 'laporan_bulanan' &&
    $_GET['page'] === 'export_word'
) {
    $exportFile = __DIR__ . '/modules/laporan/export_word.php';
    if (file_exists($exportFile)) {
        require $exportFile;
        exit;
    }
    exit('File export laporan tidak ditemukan.');
}

if (
    isset($_GET['module'], $_GET['action']) &&
    $_GET['module'] === 'bpjs_margin_operasi' &&
    $_GET['action'] === 'export'
) {
    $exportFile = __DIR__ . '/modules/bpjs_margin_operasi/index.php';
    if (file_exists($exportFile)) {
        require $exportFile;
        exit;
    }
    exit('File export Analisa Margin Operasi BPJS tidak ditemukan.');
}

// Statistik dashboard
$totalPerawat = scalarQuery(
    $conn,
    "SELECT COUNT(*) FROM employees WHERE profession IN ('perawat', 'bidan') AND employment_status = 'aktif'",
    0
);

$totalUnit = scalarQuery(
    $conn,
    "SELECT COUNT(*) FROM units WHERE is_active = 1",
    0
);

$bulan = (int)date('n');
$tahun = (int)date('Y');

$totalSurat = scalarQuery(
    $conn,
    "SELECT COUNT(*) FROM letters WHERE MONTH(letter_date) = {$bulan} AND YEAR(letter_date) = {$tahun}",
    0
);

$totalInsiden = scalarQuery(
    $conn,
    "SELECT COUNT(*) FROM patient_incidents WHERE MONTH(incident_date) = {$bulan} AND YEAR(incident_date) = {$tahun}",
    0
);

if (!defined('APP_NAME')) {
    define('APP_NAME', 'Sistem Keperawatan RS BaliMed');
}
if (!defined('LOGO_URL')) {
    define('LOGO_URL', 'https://balimedhospital.co.id/wp-content/uploads/elementor/thumbs/logo-dark-o9cm6tnx14hcrnest1hge1pwnqj0yaumij7qohadlm.png');
}

$logoutUrl = 'logout.php';
if (!file_exists(__DIR__ . '/logout.php') && file_exists(__DIR__ . '/auth/logout.php')) {
    $logoutUrl = 'auth/logout.php';
}

$globalNotifCount = 0;
$shouldPlayGlobalNotif = false;

try {
    if ($conn instanceof mysqli) {
        $notifRes = $conn->query("
            SELECT COUNT(*) AS total
            FROM permasalahan_unit
            WHERE is_read_admin = 0
        ");
        if ($notifRes instanceof mysqli_result) {
            $notifRow = $notifRes->fetch_assoc();
            $globalNotifCount = (int)($notifRow['total'] ?? 0);
        }
    } elseif ($conn instanceof PDO) {
        $notifStmt = $conn->query("
            SELECT COUNT(*) AS total
            FROM permasalahan_unit
            WHERE is_read_admin = 0
        ");
        if ($notifStmt) {
            $notifRow = $notifStmt->fetch(PDO::FETCH_ASSOC);
            $globalNotifCount = (int)($notifRow['total'] ?? 0);
        }
    }
} catch (Throwable $e) {
    $globalNotifCount = 0;
}

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

$lastNotifCount = (int)($_SESSION['last_permasalahan_notif_count'] ?? 0);
if ($globalNotifCount > $lastNotifCount) {
    $shouldPlayGlobalNotif = true;
}
$_SESSION['last_permasalahan_notif_count'] = $globalNotifCount;
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= e(APP_NAME) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&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>
        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            font-family: 'Poppins', sans-serif;
            background:
                radial-gradient(circle at top left, rgba(59,130,246,0.10), transparent 30%),
                radial-gradient(circle at top right, rgba(168,85,247,0.12), transparent 28%),
                linear-gradient(180deg, #f8fbff 0%, #f1f5f9 100%);
            overflow: hidden;
            color: #0f172a;
        }

        .main-content {
            height: 100vh;
            overflow-y: auto;
        }

        .top-bar {
            background: rgba(255,255,255,0.88);
            backdrop-filter: blur(12px);
            border-bottom: 1px solid rgba(226,232,240,0.9);
            padding: 1rem 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 40;
            box-shadow: 0 10px 30px rgba(15, 23, 42, 0.06);
            gap: 1rem;
            flex-wrap: wrap;
        }

        .brand-wrap {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .brand-logo {
            width: 48px;
            height: 48px;
            background: white;
            border-radius: 16px;
            padding: 6px;
            box-shadow: 0 10px 25px rgba(59,130,246,0.15);
            border: 1px solid rgba(226,232,240,0.8);
            object-fit: contain;
        }

        .page-title {
            font-size: 1.45rem;
            font-weight: 800;
            color: #0f172a;
            line-height: 1.2;
        }

        .page-subtitle {
            font-size: 0.82rem;
            color: #64748b;
            margin-top: 0.15rem;
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 0.9rem;
            flex-wrap: wrap;
            justify-content: flex-end;
        }

        .date-display {
            font-size: 0.88rem;
            color: #475569;
            display: flex;
            align-items: center;
            gap: 0.55rem;
            background: white;
            border: 1px solid #e2e8f0;
            padding: 0.7rem 1rem;
            border-radius: 999px;
            box-shadow: 0 4px 15px rgba(15, 23, 42, 0.04);
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 0.8rem;
            background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
            padding: 0.7rem 1rem;
            border-radius: 999px;
            border: 1px solid #e2e8f0;
            box-shadow: 0 8px 22px rgba(15, 23, 42, 0.05);
        }

        .user-avatar {
            width: 2.5rem;
            height: 2.5rem;
            background: linear-gradient(135deg, #3b82f6, #7c3aed);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
            font-size: 0.95rem;
            box-shadow: 0 10px 20px rgba(99,102,241,0.25);
        }

        .user-details {
            line-height: 1.25;
        }

        .user-name {
            font-weight: 700;
            font-size: 0.88rem;
            color: #0f172a;
        }

        .user-role {
            font-size: 0.72rem;
            color: #64748b;
        }

        .logout-btn {
            display: inline-flex;
            align-items: center;
            gap: 0.55rem;
            padding: 0.78rem 1.1rem;
            border-radius: 999px;
            font-weight: 600;
            color: white;
            text-decoration: none;
            background: linear-gradient(135deg, #ef4444, #dc2626);
            box-shadow: 0 12px 24px rgba(239,68,68,0.24);
            transition: all 0.2s ease;
            white-space: nowrap;
        }

        .logout-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 16px 28px rgba(239,68,68,0.30);
        }
        .notif-bell {
            position: relative;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 52px;
            height: 52px;
            border-radius: 18px;
            background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
            border: 1px solid #e2e8f0;
            box-shadow: 0 8px 22px rgba(15, 23, 42, 0.05);
            color: #0f172a;
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .notif-bell:hover {
            transform: translateY(-1px);
            box-shadow: 0 14px 28px rgba(15, 23, 42, 0.09);
            background: #ffffff;
        }

        .notif-badge {
            position: absolute;
            top: -6px;
            right: -6px;
            min-width: 24px;
            height: 24px;
            padding: 0 6px;
            border-radius: 999px;
            background: linear-gradient(135deg, #ef4444, #dc2626);
            color: #ffffff;
            font-size: 11px;
            font-weight: 700;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 10px 20px rgba(239, 68, 68, 0.28);
            z-index: 2;
        }

        .notif-bell.has-unread {
            animation: bellPulse 1.4s infinite;
        }

        @keyframes bellPulse {
            0%   { box-shadow: 0 0 0 0 rgba(239,68,68,0.35); }
            70%  { box-shadow: 0 0 0 12px rgba(239,68,68,0); }
            100% { box-shadow: 0 0 0 0 rgba(239,68,68,0); }
        }

        .content-area {
            padding: 2rem;
            width: 100%;
            max-width: 100%;
            overflow-x: auto;
        }

        .welcome-banner {
            position: relative;
            overflow: hidden;
            border-radius: 28px;
            background:
                linear-gradient(135deg, rgba(37,99,235,0.96), rgba(124,58,237,0.92)),
                linear-gradient(135deg, #2563eb, #7c3aed);
            color: white;
            padding: 1.75rem;
            box-shadow: 0 20px 45px rgba(59,130,246,0.20);
            margin-bottom: 1.75rem;
        }

        .welcome-banner::before,
        .welcome-banner::after {
            content: '';
            position: absolute;
            border-radius: 999px;
            background: rgba(255,255,255,0.08);
        }

        .welcome-banner::before {
            width: 220px;
            height: 220px;
            top: -90px;
            right: -60px;
        }

        .welcome-banner::after {
            width: 140px;
            height: 140px;
            bottom: -50px;
            left: -35px;
        }

        .module-shell {
            width: 100%;
            max-width: 100%;
            min-width: 0;
            display: block;
        }

        .module-shell > * {
            width: 100%;
            max-width: 100%;
        }

        .stat-card {
            position: relative;
            overflow: hidden;
            border-radius: 24px;
            padding: 1.25rem;
            color: #0f172a;
            border: 1px solid rgba(255,255,255,0.65);
            box-shadow: 0 14px 34px rgba(15, 23, 42, 0.06);
            transition: all 0.25s ease;
        }

        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 22px 42px rgba(15, 23, 42, 0.10);
        }

        .stat-card .icon-wrap {
            width: 58px;
            height: 58px;
            border-radius: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.35rem;
            color: white;
            box-shadow: 0 12px 24px rgba(15,23,42,0.12);
        }

        .bg-stat-blue { background: linear-gradient(135deg, #eff6ff, #dbeafe); }
        .bg-stat-green { background: linear-gradient(135deg, #ecfdf5, #d1fae5); }
        .bg-stat-purple { background: linear-gradient(135deg, #f5f3ff, #ede9fe); }
        .bg-stat-rose { background: linear-gradient(135deg, #fff1f2, #ffe4e6); }

        .menu-card {
            position: relative;
            overflow: hidden;
            border-radius: 24px;
            padding: 1.1rem;
            transition: all 0.25s ease;
            border: 1px solid rgba(226,232,240,0.9);
            background: rgba(255,255,255,0.92);
            box-shadow: 0 12px 28px rgba(15,23,42,0.05);
        }

        .menu-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(15,23,42,0.11);
        }

        .menu-card::after {
            content: '';
            position: absolute;
            inset: auto -20px -20px auto;
            width: 90px;
            height: 90px;
            background: rgba(255,255,255,0.18);
            border-radius: 999px;
        }

        .menu-icon {
            width: 56px;
            height: 56px;
            border-radius: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.2rem;
            box-shadow: 0 14px 24px rgba(15,23,42,0.12);
            flex-shrink: 0;
        }

        .content-section-title {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            font-size: 1.1rem;
            font-weight: 700;
            color: #0f172a;
            margin-bottom: 1rem;
        }

        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #e2e8f0;
        }

        ::-webkit-scrollbar-thumb {
            background: #94a3b8;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #64748b;
        }

        @media (max-width: 768px) {
            .top-bar {
                padding: 1rem;
            }

            .content-area {
                padding: 1rem;
            }

            .page-title {
                font-size: 1.15rem;
            }

            .brand-wrap {
                width: 100%;
            }

            .user-menu {
                width: 100%;
                justify-content: flex-start;
            }
        }
    </style>
</head>
<body>
    <main class="main-content">
        <div class="top-bar">
            <div class="brand-wrap">
                <img src="<?= e(LOGO_URL) ?>" alt="Logo BaliMed" class="brand-logo">
                <div>
                    <h1 class="page-title">
                        <?php
                        $titles = [
                            'dashboard' => 'Dashboard',
                            'manage_user' => 'Manage User',
                            'data_perawat' => 'Data Perawat',
                            'data_perawat_per_unit' => 'Data Perawat per Unit',
                            'data_staf_baru' => 'Data Staf Baru',
                            'jadwal_orientasi_staf_baru' => 'Jadwal Orientasi Staf Baru',
                            'rotasi_perawat' => 'Rotasi / Resign',
                            'beban_kerja' => 'Analisis Beban Kerja',
                            'laporan_bulanan' => 'Laporan Bulanan',
                            'analisis_kunjungan' => 'Analisis Kunjungan',
                            'kegiatan_harian' => 'Kegiatan Harian',
                            'patient_safety' => 'Patient Safety',
                            'laporan_rka' => 'Laporan RKA',
                            'laporan_katim' => 'Laporan Katim',
                            'permasalahan_tindak_lanjut' => 'Permasalahan & TL',
                            'penugasan_manajemen_keperawatan' => 'Penugasan Manajemen Keperawatan',
                            'laporan_harian_poliklinik' => 'Laporan Harian Poliklinik',
                            'daftar_spo' => 'Daftar SPO',
                            'generator_surat' => 'Generator Surat',
                            'distribusi_alat' => 'Distribusi Alat',
                            'p3k' => 'Penugasan P3K',
                            'user_profile' => 'Profil Saya',
                            'activity_log' => 'Aktivitas Log',
                            'struktur_organisasi' => 'Struktur Organisasi',
                            'google_drive_reader' => 'Google Drive Reader',
                            'rdk' => 'Refleksi Diskusi Kasus',
                            'coaching' => 'Coaching Staf Baru',
                            'bpjs_margin_operasi' => 'Analisa Margin Operasi BPJS',
                        ];
                        echo e($titles[$module] ?? 'Dashboard');
                        ?>
                    </h1>
                    <div class="page-subtitle">Divisi Keperawatan RS BaliMed Denpasar</div>

                    <a href="index.php?module=dashboard"
                       class="home-inline-btn"
                       title="Kembali ke Dashboard">
                        <i class="fas fa-home"></i>
                        <span>Home / Dashboard</span>
                    </a>
                </div>
            </div>

            <div class="user-menu">
                <div class="date-display">
                    <i class="fas fa-calendar-alt text-blue-500"></i>
                    <?= date('d F Y') ?>
                </div>

                <a href="index.php?module=permasalahan_tindak_lanjut&mark_notif=1"
                   class="notif-bell <?= $globalNotifCount > 0 ? 'has-unread' : '' ?>"
                   title="Lihat notifikasi permasalahan">
                    <i class="fas fa-bell text-lg"></i>

                    <?php if ($globalNotifCount > 0): ?>
                        <span class="notif-badge"><?= $globalNotifCount ?></span>
                    <?php endif; ?>
                </a>

                <div class="user-info">
                    <div class="user-avatar">
                        <?= strtoupper(substr((string)($user['full_name'] ?? $user['nama'] ?? 'U'), 0, 1)) ?>
                    </div>
                    <div class="user-details">
                        <div class="user-name"><?= e($user['full_name'] ?? $user['nama'] ?? '-') ?></div>
                        <div class="user-role">
                            <?= e(ucfirst((string)($user['role'] ?? 'user'))) ?>
                            • <?= e($user['jabatan'] ?? $user['position_name'] ?? '-') ?>
                        </div>
                    </div>
                </div>

                <a href="<?= e($logoutUrl) ?>" class="logout-btn" onclick="return confirm('Yakin ingin logout?')">
                    <i class="fas fa-sign-out-alt"></i>
                    Logout
                </a>
            </div>
        </div>

        <div class="content-area">
            <?php if ($module === 'dashboard'): ?>
                <div class="welcome-banner">
                    <div class="relative z-10">
                        <div class="text-sm uppercase tracking-wider font-medium text-blue-100 mb-2">Selamat datang</div>
                        <h2 class="text-2xl md:text-3xl font-extrabold mb-2"><?= e($user['full_name'] ?? $user['nama'] ?? '-') ?></h2>
                        <p class="text-blue-50 text-sm md:text-base">
                            Sistem informasi Divisi Keperawatan yang lebih modern, rapi, dan nyaman dipakai.
                        </p>
                    </div>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                    <div class="stat-card bg-stat-blue">
                        <div class="flex items-center justify-between gap-4">
                            <div>
                                <p class="text-slate-500 text-sm font-medium">Total Perawat</p>
                                <p class="text-3xl font-extrabold text-slate-800 mt-1"><?= (int)$totalPerawat ?></p>
                                <p class="text-xs text-slate-500 mt-2">Perawat & bidan aktif</p>
                            </div>
                            <div class="icon-wrap" style="background: linear-gradient(135deg,#3b82f6,#2563eb);">
                                <i class="fas fa-user-nurse"></i>
                            </div>
                        </div>
                    </div>

                    <div class="stat-card bg-stat-green">
                        <div class="flex items-center justify-between gap-4">
                            <div>
                                <p class="text-slate-500 text-sm font-medium">Total Unit</p>
                                <p class="text-3xl font-extrabold text-slate-800 mt-1"><?= (int)$totalUnit ?></p>
                                <p class="text-xs text-slate-500 mt-2">Unit aktif terdaftar</p>
                            </div>
                            <div class="icon-wrap" style="background: linear-gradient(135deg,#10b981,#059669);">
                                <i class="fas fa-building"></i>
                            </div>
                        </div>
                    </div>

                    <div class="stat-card bg-stat-purple">
                        <div class="flex items-center justify-between gap-4">
                            <div>
                                <p class="text-slate-500 text-sm font-medium">Surat Bulan Ini</p>
                                <p class="text-3xl font-extrabold text-slate-800 mt-1"><?= (int)$totalSurat ?></p>
                                <p class="text-xs text-slate-500 mt-2">Dokumen terbit bulan berjalan</p>
                            </div>
                            <div class="icon-wrap" style="background: linear-gradient(135deg,#8b5cf6,#7c3aed);">
                                <i class="fas fa-envelope"></i>
                            </div>
                        </div>
                    </div>

                    <div class="stat-card bg-stat-rose">
                        <div class="flex items-center justify-between gap-4">
                            <div>
                                <p class="text-slate-500 text-sm font-medium">Insiden Pasien</p>
                                <p class="text-3xl font-extrabold text-slate-800 mt-1"><?= (int)$totalInsiden ?></p>
                                <p class="text-xs text-slate-500 mt-2">Periode bulan ini</p>
                            </div>
                            <div class="icon-wrap" style="background: linear-gradient(135deg,#ef4444,#dc2626);">
                                <i class="fas fa-exclamation-triangle"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <?php
                $menuItems = [
                    ['module' => 'user_profile', 'icon' => 'fa-user-circle', 'label' => 'Profil Saya', 'desc' => 'Lihat & edit profil', 'bg' => 'linear-gradient(135deg,#0ea5e9,#2563eb)'],
                    ['module' => 'manage_user', 'icon' => 'fa-users-cog', 'label' => 'Manajemen User', 'desc' => 'Kelola akun & akses user', 'bg' => 'linear-gradient(135deg,#1d4ed8,#1e40af)'],
                    ['module' => 'struktur_organisasi', 'icon' => 'fa-sitemap', 'label' => 'Struktur Organisasi', 'desc' => 'Bagan organisasi keperawatan', 'bg' => 'linear-gradient(135deg,#8b5cf6,#6366f1)'],
                    ['module' => 'data_perawat', 'icon' => 'fa-user-nurse', 'label' => 'Kelola Perawat', 'desc' => 'Data perawat & bidan', 'bg' => 'linear-gradient(135deg,#14b8a6,#0f766e)'],
                    ['module' => 'data_perawat_per_unit', 'icon' => 'fa-users', 'label' => 'Perawat per Unit', 'desc' => 'Distribusi SDM', 'bg' => 'linear-gradient(135deg,#22c55e,#16a34a)'],
                    ['module' => 'data_staf_baru', 'icon' => 'fa-user-plus', 'label' => 'Data Staf Baru', 'desc' => 'Wawancara & rekrut', 'bg' => 'linear-gradient(135deg,#f59e0b,#ea580c)'],
                    ['module' => 'jadwal_orientasi_staf_baru', 'icon' => 'fa-calendar-week', 'label' => 'Penjadwalan Perawat', 'desc' => 'Input jadwal jaga manual', 'bg' => 'linear-gradient(135deg,#06b6d4,#0891b2)'],
                    ['module' => 'rotasi_perawat', 'icon' => 'fa-exchange-alt', 'label' => 'Rotasi / Resign', 'desc' => 'Mutasi & keluar', 'bg' => 'linear-gradient(135deg,#ec4899,#db2777)'],
                    ['module' => 'beban_kerja', 'icon' => 'fa-tasks', 'label' => 'Beban Kerja', 'desc' => 'Analisis rasio', 'bg' => 'linear-gradient(135deg,#3b82f6,#1d4ed8)'],
                    ['module' => 'laporan_bulanan', 'icon' => 'fa-file-alt', 'label' => 'Laporan Bulanan', 'desc' => 'Laporan unit', 'bg' => 'linear-gradient(135deg,#6366f1,#4f46e5)'],
                    ['module' => 'kegiatan_harian', 'icon' => 'fa-clock', 'label' => 'Kegiatan Harian', 'desc' => 'Monitoring aktivitas', 'bg' => 'linear-gradient(135deg,#0ea5e9,#0284c7)'],
                    ['module' => 'patient_safety', 'icon' => 'fa-shield-alt', 'label' => 'Patient Safety', 'desc' => 'Insiden pasien', 'bg' => 'linear-gradient(135deg,#ef4444,#b91c1c)'],
                    ['module' => 'laporan_katim', 'icon' => 'fa-clipboard-list', 'label' => 'Laporan Katim', 'desc' => 'Shift & beban', 'bg' => 'linear-gradient(135deg,#f97316,#ea580c)'],
                    ['module' => 'permasalahan_tindak_lanjut', 'icon' => 'fa-triangle-exclamation', 'label' => 'Permasalahan & TL', 'desc' => 'Monitoring masalah unit', 'bg' => 'linear-gradient(135deg,#f59e0b,#ef4444)'],
                    ['module' => 'laporan_harian_poliklinik', 'icon' => 'fa-stethoscope', 'label' => 'Laporan Harian Poliklinik', 'desc' => 'Input & rekap poli', 'bg' => 'linear-gradient(135deg,#0f766e,#115e59)'],
                    ['module' => 'import_poliklinik_doctors', 'icon' => 'fa-file-import', 'label' => 'Import Dokter Poliklinik', 'desc' => 'Import master dokter poli', 'bg' => 'linear-gradient(135deg,#7c3aed,#6d28d9)'],
                    ['module' => 'analisis_kunjungan', 'icon' => 'fa-chart-line', 'label' => 'Analisis Kunjungan', 'desc' => 'Dashboard analisis kunjungan', 'bg' => 'linear-gradient(135deg,#7c3aed,#5b21b6)'],
                    ['module' => 'daftar_spo', 'icon' => 'fa-file-alt', 'label' => 'Daftar SPO', 'desc' => 'Prosedur operasional', 'bg' => 'linear-gradient(135deg,#22c55e,#15803d)'],
                    ['module' => 'google_drive_reader', 'icon' => 'fa-folder-open', 'label' => 'Google Drive Reader', 'desc' => 'Apps Script frame', 'bg' => 'linear-gradient(135deg,#22c55e,#16a34a)'],
                    ['module' => 'generator_surat', 'icon' => 'fa-file-signature', 'label' => 'Generator Surat', 'desc' => 'Surat menyurat', 'bg' => 'linear-gradient(135deg,#eab308,#ca8a04)'],
                    ['module' => 'distribusi_alat', 'icon' => 'fa-truck', 'label' => 'Distribusi Alat', 'desc' => 'Logistik & WO', 'bg' => 'linear-gradient(135deg,#14b8a6,#0f766e)'],
                    ['module' => 'p3k', 'icon' => 'fa-first-aid', 'label' => 'Penugasan P3K', 'desc' => 'Kegiatan & jadwal', 'bg' => 'linear-gradient(135deg,#f43f5e,#e11d48)'],
                    ['module' => 'activity_log', 'icon' => 'fa-history', 'label' => 'Aktivitas Log', 'desc' => 'Riwayat aktivitas sistem', 'bg' => 'linear-gradient(135deg,#64748b,#334155)'],
                    [
                        'module' => 'rdk',
                        'icon'   => 'fa-stethoscope',
                        'label'  => 'RDK / Refleksi Kasus',
                        'desc'   => 'Refleksi diskusi kasus keperawatan',
                        'bg'     => 'linear-gradient(135deg,#6366f1,#4f46e5)'
                    ],
                    [
                        'module' => 'coaching',
                        'icon'   => 'fa-chalkboard-teacher',
                        'label'  => 'Coaching Staf Baru',
                        'desc'   => 'Jadwal coaching, penilaian, dan feedback staf baru',
                        'bg'     => 'linear-gradient(135deg,#0ea5e9,#2563eb)'
                    ],
                    [
                        'module' => 'bpjs_margin_operasi',
                        'icon'   => 'fa-chart-pie',
                        'label'  => 'Margin Operasi BPJS',
                        'desc'   => 'Analisa klaim, jasa RS, surplus/minus dan DPJP',
                        'bg'     => 'linear-gradient(135deg,#0f766e,#14b8a6)'
                    ],
                    
                    [
                        'module' => 'penugasan_manajemen_keperawatan',
                        'icon'   => 'fa-clipboard-check',
                        'label'  => 'Penugasan Manajemen',
                        'desc'   => 'Tugas, laporan hasil, dan rekap penyelesaian',
                        'bg'     => 'linear-gradient(135deg,#2563eb,#7c3aed)'
                    ],
                    
                    [
                        'module' => 'kalender_kegiatan_keperawatan',
                        'icon'   => 'fa-calendar-days',
                        'label'  => 'Kalender Kegiatan',
                        'desc'   => 'Agenda rapat, supervisi, audit, pelatihan, dan kegiatan keperawatan',
                        'bg'     => 'linear-gradient(135deg,#0ea5e9,#2563eb)'
                    ],
                ];
                $currentRole = strtolower((string)($user['role'] ?? 'user'));
                ?>

                <div class="mb-8">
                    <h2 class="content-section-title">
                        <span class="w-10 h-10 rounded-xl bg-gradient-to-br from-blue-600 to-indigo-600 text-white flex items-center justify-center shadow-lg">
                            <i class="fas fa-th-large"></i>
                        </span>
                        Menu Utama
                    </h2>

                    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-5">
                        <?php foreach ($menuItems as $item): ?>
                            <?php if (canAccessModule($currentRole, $item['module']) && moduleExists($item['module'])): ?>
                                <a href="?module=<?= e($item['module']) ?>" class="menu-card group">
                                    <div class="relative z-10 flex items-start gap-4">
                                        <div class="menu-icon" style="background: <?= e($item['bg']) ?>;">
                                            <i class="fas <?= e($item['icon']) ?>"></i>
                                        </div>
                                        <div class="flex-1 min-w-0">
                                            <h3 class="font-bold text-slate-800 text-base leading-tight"><?= e($item['label']) ?></h3>
                                            <p class="text-sm text-slate-500 mt-1"><?= e($item['desc']) ?></p>
                                            <div class="mt-3 text-xs font-semibold text-slate-400 group-hover:text-slate-600 transition">
                                                Buka modul <i class="fas fa-arrow-right ml-1"></i>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php else: ?>
                <div class="module-shell">
                    <?php loadModule($module); ?>
                </div>
            <?php endif; ?>
        </div>
    </main>

    <?php if ($shouldPlayGlobalNotif && $globalNotifCount > 0): ?>
    <audio id="globalNotifSound" preload="auto">
        <source src="https://actions.google.com/sounds/v1/alarms/alarm_clock.ogg" type="audio/ogg">
    </audio>

    <script>
    window.addEventListener('load', function () {
        const audio = document.getElementById('globalNotifSound');
        if (audio) {
            audio.volume = 1.0;
            audio.play().catch(() => {});
            setTimeout(() => {
                audio.play().catch(() => {});
            }, 900);
        }
    });
    </script>
    <?php endif; ?>
</body>
</html>
