<?php
require_once __DIR__ . '/../includes/katim_notif_helper.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

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

$conn = getConnection();

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

$currentRole = strtolower((string)($_SESSION['user_role'] ?? $_SESSION['user']['role'] ?? 'user'));
$currentName = $_SESSION['full_name'] ?? ($_SESSION['user']['full_name'] ?? $_SESSION['user']['name'] ?? 'Pengguna');
$currentUnit = $_SESSION['unit'] ?? ($_SESSION['user']['unit'] ?? '-');
$currentJabatan = $_SESSION['jabatan'] ?? '-';

/**
 * Helper permission sederhana
 */
if (!function_exists('dashboard_can_access_module')) {
    function dashboard_can_access_module(string $role, string $module): bool
    {
        $role = strtolower(trim($role));

        $viewerOnly = [
            'dashboard',
            'laporan_katim',
            'laporan_harian_poliklinik',
            'user_profile',
            'activity_log',
            'struktur_organisasi',
        ];

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

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

        if ($role === 'viewer') {
            return in_array($module, $viewerOnly, true);
        }

        return in_array($module, [
            'dashboard',
            'laporan_katim',
            'laporan_harian_poliklinik',
            'user_profile',
            'activity_log',
            'struktur_organisasi',
        ], true);
    }
}

/**
 * Query helper aman
 */
function dashboard_query_rows(mysqli $conn, string $sql): array
{
    $rows = [];
    $result = $conn->query($sql);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
    }
    return $rows;
}

function dashboard_scalar(mysqli $conn, string $sql, int $default = 0): int
{
    $result = $conn->query($sql);
    if ($result) {
        $row = $result->fetch_row();
        if ($row && isset($row[0])) {
            return (int)$row[0];
        }
    }
    return $default;
}

// Get recent activities
$activities = dashboard_query_rows(
    $conn,
    "SELECT a.*, e.full_name
     FROM activity_logs a
     LEFT JOIN employees e ON a.employee_id = e.id
     ORDER BY a.created_at DESC
     LIMIT 10"
);

// Get upcoming events
$events = dashboard_query_rows(
    $conn,
    "SELECT *
     FROM schedule_events
     WHERE event_date >= CURDATE()
     ORDER BY event_date ASC
     LIMIT 5"
);

// Get open incidents
$incidents = dashboard_query_rows(
    $conn,
    "SELECT *
     FROM patient_incidents
     WHERE status != 'ditutup'
     ORDER BY created_at DESC
     LIMIT 5"
);

// Summary counts
$totalActivities = dashboard_scalar($conn, "SELECT COUNT(*) FROM activity_logs", 0);
$totalEvents     = dashboard_scalar($conn, "SELECT COUNT(*) FROM schedule_events WHERE event_date >= CURDATE()", 0);
$totalOpenInc    = dashboard_scalar($conn, "SELECT COUNT(*) FROM patient_incidents WHERE status != 'ditutup'", 0);
$totalEmployees  = dashboard_scalar($conn, "SELECT COUNT(*) FROM employees WHERE employment_status = 'aktif'", 0);

// Notifikasi otomatis Laporan Katim yang belum masuk pada shift sebelumnya.
// Tidak disimpan sebagai data yang bisa dihapus; hilang otomatis setelah laporan dibuat.
$katimMissingAlerts = katim_get_missing_shift_alerts($conn);
$katimMissingCount  = count($katimMissingAlerts);

$quickActions = [
    [
        'module' => 'generator_surat',
        'icon'   => 'fa-file-signature',
        'label'  => 'Buat Surat',
        'desc'   => 'Generate surat cepat',
        'bg'     => 'linear-gradient(135deg,#2563eb,#1d4ed8)',
    ],
    [
        'module' => 'data_perawat',
        'icon'   => 'fa-user-plus',
        'label'  => 'Tambah Perawat',
        'desc'   => 'Input pegawai baru',
        'bg'     => 'linear-gradient(135deg,#10b981,#047857)',
    ],
    [
        'module' => 'patient_safety',
        'icon'   => 'fa-exclamation-triangle',
        'label'  => 'Lapor Insiden',
        'desc'   => 'Input insiden pasien',
        'bg'     => 'linear-gradient(135deg,#f59e0b,#ea580c)',
    ],
    [
        'module' => 'laporan_bulanan',
        'icon'   => 'fa-calendar-alt',
        'label'  => 'Laporan Bulanan',
        'desc'   => 'Input laporan unit',
        'bg'     => 'linear-gradient(135deg,#8b5cf6,#6d28d9)',
    ],
];

?>
<style>
    .dash-wrap {
        color: #0f172a;
    }

    .dash-hero {
        position: relative;
        overflow: hidden;
        border-radius: 32px;
        background:
            linear-gradient(135deg, rgba(37,99,235,0.98), rgba(124,58,237,0.95)),
            linear-gradient(135deg, #2563eb, #7c3aed);
        color: #fff;
        padding: 1.75rem;
        box-shadow: 0 24px 50px rgba(59,130,246,0.20);
    }

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

    .dash-hero::before {
        width: 220px;
        height: 220px;
        right: -60px;
        top: -80px;
    }

    .dash-hero::after {
        width: 130px;
        height: 130px;
        left: -20px;
        bottom: -30px;
    }

    .dash-card {
        background: rgba(255,255,255,0.95);
        border: 1px solid rgba(226,232,240,0.9);
        border-radius: 26px;
        box-shadow: 0 12px 30px rgba(15,23,42,0.05);
    }

    .dash-stat {
        position: relative;
        overflow: hidden;
        border-radius: 24px;
        padding: 1.2rem;
        box-shadow: 0 14px 30px rgba(15,23,42,0.06);
        transition: all 0.25s ease;
    }

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

    .dash-stat::after {
        content: '';
        position: absolute;
        width: 110px;
        height: 110px;
        border-radius: 999px;
        right: -30px;
        bottom: -40px;
        background: rgba(255,255,255,0.18);
    }

    .dash-stat-blue   { background: linear-gradient(135deg,#eff6ff,#dbeafe); }
    .dash-stat-green  { background: linear-gradient(135deg,#ecfdf5,#d1fae5); }
    .dash-stat-amber  { background: linear-gradient(135deg,#fffbeb,#fde68a); }
    .dash-stat-purple { background: linear-gradient(135deg,#f5f3ff,#ede9fe); }

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

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

    .dash-section-badge {
        width: 40px;
        height: 40px;
        border-radius: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        background: linear-gradient(135deg,#2563eb,#7c3aed);
        box-shadow: 0 12px 20px rgba(37,99,235,0.18);
    }

    .dash-action {
        display: flex;
        align-items: center;
        gap: 0.9rem;
        border-radius: 22px;
        padding: 1rem;
        background: #fff;
        border: 1px solid #e2e8f0;
        box-shadow: 0 10px 24px rgba(15,23,42,0.04);
        transition: all 0.22s ease;
        text-decoration: none;
        color: inherit;
    }

    .dash-action:hover {
        transform: translateY(-2px);
        box-shadow: 0 18px 30px rgba(15,23,42,0.08);
    }

    .dash-action-icon {
        width: 52px;
        height: 52px;
        border-radius: 18px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 1.15rem;
        box-shadow: 0 12px 24px rgba(15,23,42,0.10);
        flex-shrink: 0;
    }

    .dash-list-item {
        transition: all 0.2s ease;
    }

    .dash-list-item:hover {
        background: #f8fafc;
    }


    .katim-alert-box {
        background: linear-gradient(135deg,#fff7ed,#fee2e2);
        border: 1px solid #fecaca;
        border-left: 6px solid #ef4444;
        border-radius: 24px;
        box-shadow: 0 14px 30px rgba(239,68,68,0.08);
    }

    @media (max-width: 768px) {
        .dash-hero {
            border-radius: 24px;
            padding: 1.3rem;
        }
    }
</style>

<div class="dash-wrap space-y-6">
    <div class="dash-hero">
        <div class="relative z-10">
            <div class="text-sm uppercase tracking-[0.2em] text-blue-100 font-medium mb-2">Dashboard Internal</div>
            <h2 class="text-2xl md:text-3xl font-extrabold mb-2">Selamat Datang, <?= e($currentName) ?>!</h2>
            <p class="text-blue-50 max-w-3xl text-sm md:text-base">
                Sistem Informasi Keperawatan RS BaliMed Denpasar untuk memantau aktivitas, insiden pasien, jadwal mendatang, dan akses cepat ke modul penting.
            </p>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-3 mt-5">
                <div class="bg-white/12 backdrop-blur rounded-2xl px-4 py-3 border border-white/15">
                    <div class="text-xs text-blue-100 uppercase tracking-wide">Unit</div>
                    <div class="font-bold text-white mt-1"><?= e($currentUnit ?: '-') ?></div>
                </div>
                <div class="bg-white/12 backdrop-blur rounded-2xl px-4 py-3 border border-white/15">
                    <div class="text-xs text-blue-100 uppercase tracking-wide">Jabatan</div>
                    <div class="font-bold text-white mt-1"><?= e($currentJabatan ?: '-') ?></div>
                </div>
                <div class="bg-white/12 backdrop-blur rounded-2xl px-4 py-3 border border-white/15">
                    <div class="text-xs text-blue-100 uppercase tracking-wide">Role</div>
                    <div class="font-bold text-white mt-1"><?= e(ucfirst($currentRole)) ?></div>
                </div>
            </div>
        </div>
    </div>

    <?php if (!empty($katimMissingAlerts)): ?>
        <div class="katim-alert-box p-5 md:p-6">
            <div class="flex flex-col md:flex-row md:items-start md:justify-between gap-4">
                <div class="flex items-start gap-4">
                    <div class="w-12 h-12 rounded-2xl bg-red-600 text-white flex items-center justify-center shadow-lg shrink-0">
                        <i class="fas fa-bell"></i>
                    </div>
                    <div>
                        <div class="text-xs uppercase tracking-[0.18em] font-bold text-red-600">Notifikasi Wajib Laporan Katim</div>
                        <h3 class="text-xl font-extrabold text-slate-900 mt-1">Ada <?= (int)$katimMissingCount ?> laporan shift sebelumnya belum masuk</h3>
                        <p class="text-sm text-slate-600 mt-1">Notifikasi ini otomatis muncul di halaman depan dan tidak bisa dihapus manual. Status akan hilang setelah laporan unit/shift terkait disubmit.</p>
                    </div>
                </div>
                <a href="?module=laporan_katim&action=form" class="inline-flex items-center justify-center px-4 py-2 rounded-xl bg-red-600 text-white font-semibold hover:bg-red-700">
                    <i class="fas fa-plus mr-2"></i>Input Laporan
                </a>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3 mt-4">
                <?php foreach ($katimMissingAlerts as $alert): ?>
                    <div class="bg-white/80 border border-red-100 rounded-2xl p-4">
                        <div class="font-bold text-red-700"><?= e($alert['message']) ?></div>
                        <div class="text-xs text-slate-500 mt-1">
                            Tanggal: <?= e(date('d/m/Y', strtotime($alert['tanggal']))) ?> • Unit: <?= e($alert['unit_name']) ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    <?php endif; ?>

    <!-- Summary -->
    <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-5">
        <div class="dash-stat dash-stat-blue">
            <div class="relative z-10 flex items-center justify-between gap-4">
                <div>
                    <div class="text-sm text-slate-500 font-medium">Aktivitas Tercatat</div>
                    <div class="text-3xl font-extrabold text-slate-800 mt-1"><?= (int)$totalActivities ?></div>
                    <div class="text-xs text-slate-500 mt-2">Total log sistem</div>
                </div>
                <div class="dash-icon" style="background:linear-gradient(135deg,#3b82f6,#2563eb);">
                    <i class="fas fa-history"></i>
                </div>
            </div>
        </div>

        <div class="dash-stat dash-stat-green">
            <div class="relative z-10 flex items-center justify-between gap-4">
                <div>
                    <div class="text-sm text-slate-500 font-medium">Jadwal Mendatang</div>
                    <div class="text-3xl font-extrabold text-slate-800 mt-1"><?= (int)$totalEvents ?></div>
                    <div class="text-xs text-slate-500 mt-2">Event aktif</div>
                </div>
                <div class="dash-icon" style="background:linear-gradient(135deg,#10b981,#047857);">
                    <i class="fas fa-calendar-check"></i>
                </div>
            </div>
        </div>

        <div class="dash-stat dash-stat-amber">
            <div class="relative z-10 flex items-center justify-between gap-4">
                <div>
                    <div class="text-sm text-slate-500 font-medium">Insiden Terbuka</div>
                    <div class="text-3xl font-extrabold text-slate-800 mt-1"><?= (int)$totalOpenInc ?></div>
                    <div class="text-xs text-slate-500 mt-2">Perlu tindak lanjut</div>
                </div>
                <div class="dash-icon" style="background:linear-gradient(135deg,#f59e0b,#ea580c);">
                    <i class="fas fa-exclamation-circle"></i>
                </div>
            </div>
        </div>

        <div class="dash-stat dash-stat-purple">
            <div class="relative z-10 flex items-center justify-between gap-4">
                <div>
                    <div class="text-sm text-slate-500 font-medium">Pegawai Aktif</div>
                    <div class="text-3xl font-extrabold text-slate-800 mt-1"><?= (int)$totalEmployees ?></div>
                    <div class="text-xs text-slate-500 mt-2">Data employees aktif</div>
                </div>
                <div class="dash-icon" style="background:linear-gradient(135deg,#8b5cf6,#7c3aed);">
                    <i class="fas fa-users"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="dash-card p-5 md:p-6">
        <h3 class="dash-section-title">
            <span class="dash-section-badge"><i class="fas fa-bolt"></i></span>
            Aksi Cepat
        </h3>

        <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
            <?php foreach ($quickActions as $action): ?>
                <?php if (dashboard_can_access_module($currentRole, $action['module'])): ?>
                    <a href="?module=<?= e($action['module']) ?>" class="dash-action">
                        <div class="dash-action-icon" style="background: <?= e($action['bg']) ?>;">
                            <i class="fas <?= e($action['icon']) ?>"></i>
                        </div>
                        <div>
                            <div class="font-bold text-slate-800"><?= e($action['label']) ?></div>
                            <div class="text-sm text-slate-500"><?= e($action['desc']) ?></div>
                        </div>
                    </a>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Two Column -->
    <div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
        <!-- Recent Activities -->
        <div class="dash-card overflow-hidden">
            <div class="px-5 py-4 bg-gradient-to-r from-slate-800 to-slate-700">
                <h3 class="text-white font-bold flex items-center">
                    <i class="fas fa-history mr-2"></i>
                    Aktivitas Terbaru
                </h3>
            </div>

            <div class="divide-y divide-slate-100 max-h-[430px] overflow-y-auto">
                <?php if (empty($activities)): ?>
                    <div class="p-6 text-center text-slate-500">Belum ada aktivitas.</div>
                <?php else: ?>
                    <?php foreach ($activities as $act): ?>
                        <?php
                        $icon = 'fa-circle-info';
                        $iconBg = 'linear-gradient(135deg,#3b82f6,#2563eb)';

                        if (($act['action'] ?? '') === 'create') {
                            $icon = 'fa-plus-circle';
                            $iconBg = 'linear-gradient(135deg,#10b981,#047857)';
                        } elseif (($act['action'] ?? '') === 'update') {
                            $icon = 'fa-pen';
                            $iconBg = 'linear-gradient(135deg,#f59e0b,#ea580c)';
                        } elseif (($act['action'] ?? '') === 'delete') {
                            $icon = 'fa-trash';
                            $iconBg = 'linear-gradient(135deg,#ef4444,#dc2626)';
                        } elseif (($act['action'] ?? '') === 'login') {
                            $icon = 'fa-sign-in-alt';
                            $iconBg = 'linear-gradient(135deg,#6366f1,#4f46e5)';
                        }
                        ?>
                        <div class="dash-list-item p-4 md:p-5">
                            <div class="flex items-start gap-3">
                                <div class="w-11 h-11 rounded-2xl text-white flex items-center justify-center shadow"
                                     style="background: <?= e($iconBg) ?>;">
                                    <i class="fas <?= e($icon) ?>"></i>
                                </div>
                                <div class="flex-1 min-w-0">
                                    <div class="text-sm md:text-[15px] text-slate-800 font-medium">
                                        <?= e($act['description'] ?? '-') ?>
                                    </div>
                                    <div class="text-xs text-slate-500 mt-1">
                                        <?= e($act['full_name'] ?? 'System') ?> •
                                        <?= !empty($act['created_at']) ? date('d M Y H:i', strtotime($act['created_at'])) : '-' ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <!-- Upcoming Events -->
        <div class="dash-card overflow-hidden">
            <div class="px-5 py-4 bg-gradient-to-r from-emerald-600 to-teal-600">
                <h3 class="text-white font-bold flex items-center">
                    <i class="fas fa-calendar-check mr-2"></i>
                    Jadwal Mendatang
                </h3>
            </div>

            <div class="divide-y divide-slate-100 max-h-[430px] overflow-y-auto">
                <?php if (empty($events)): ?>
                    <div class="p-6 text-center text-slate-500">Tidak ada jadwal mendatang.</div>
                <?php else: ?>
                    <?php foreach ($events as $event): ?>
                        <div class="dash-list-item p-4 md:p-5">
                            <div class="flex items-center justify-between gap-3">
                                <div class="min-w-0">
                                    <div class="font-bold text-slate-800"><?= e($event['event_title'] ?? '-') ?></div>
                                    <div class="text-sm text-slate-500 mt-1">
                                        <i class="fas fa-map-marker-alt mr-1 text-slate-400"></i>
                                        <?= e($event['location'] ?? 'Belum ditentukan') ?>
                                    </div>
                                </div>
                                <div class="text-right shrink-0">
                                    <div class="text-sm font-bold text-emerald-600">
                                        <?= !empty($event['event_date']) ? date('d M', strtotime($event['event_date'])) : '-' ?>
                                    </div>
                                    <?php if (!empty($event['start_time'])): ?>
                                        <div class="text-xs text-slate-500"><?= e(substr((string)$event['start_time'], 0, 5)) ?> WITA</div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Open Incidents -->
    <div class="dash-card overflow-hidden">
        <div class="px-5 py-4 bg-gradient-to-r from-rose-600 to-red-600">
            <h3 class="text-white font-bold flex items-center">
                <i class="fas fa-exclamation-circle mr-2"></i>
                Insiden Pasien Terbuka
            </h3>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full min-w-[760px]">
                <thead class="bg-slate-50 border-b border-slate-200">
                    <tr>
                        <th class="px-5 py-3 text-left text-xs font-bold text-slate-500 uppercase">No. Insiden</th>
                        <th class="px-5 py-3 text-left text-xs font-bold text-slate-500 uppercase">Tanggal</th>
                        <th class="px-5 py-3 text-left text-xs font-bold text-slate-500 uppercase">Pasien</th>
                        <th class="px-5 py-3 text-left text-xs font-bold text-slate-500 uppercase">Jenis</th>
                        <th class="px-5 py-3 text-left text-xs font-bold text-slate-500 uppercase">Status</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php if (empty($incidents)): ?>
                        <tr>
                            <td colspan="5" class="px-5 py-6 text-center text-slate-500">Tidak ada insiden terbuka.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($incidents as $inc): ?>
                            <?php
                            $status = strtolower((string)($inc['status'] ?? ''));
                            $statusClass = 'bg-slate-100 text-slate-700';

                            if ($status === 'open') {
                                $statusClass = 'bg-amber-100 text-amber-700';
                            } elseif ($status === 'investigasi') {
                                $statusClass = 'bg-blue-100 text-blue-700';
                            } elseif ($status === 'selesai' || $status === 'closed' || $status === 'ditutup') {
                                $statusClass = 'bg-emerald-100 text-emerald-700';
                            }
                            ?>
                            <tr class="hover:bg-slate-50 transition">
                                <td class="px-5 py-4 text-sm font-semibold text-slate-800"><?= e($inc['incident_number'] ?? '-') ?></td>
                                <td class="px-5 py-4 text-sm text-slate-600">
                                    <?= !empty($inc['incident_date']) ? date('d/m/Y', strtotime($inc['incident_date'])) : '-' ?>
                                </td>
                                <td class="px-5 py-4 text-sm text-slate-600"><?= e($inc['patient_name'] ?? '-') ?></td>
                                <td class="px-5 py-4 text-sm text-slate-600"><?= e($inc['incident_type'] ?? '-') ?></td>
                                <td class="px-5 py-4">
                                    <span class="px-3 py-1 rounded-full text-xs font-semibold <?= e($statusClass) ?>">
                                        <?= e(ucfirst($inc['status'] ?? '-')) ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>