<?php
$currentUserName = $userName ?? session()->get('userName') ?? '-';
$currentUserRole = $userRole ?? session()->get('userRole') ?? '-';
$currentUserEmail = $userEmail ?? session()->get('userEmail') ?? '-';
$currentUserPhoto = session()->get('userPhoto');
$roleLabel = match ($currentUserRole ?? '') {
    'administrator' => 'Administrator',
    'kasir' => 'Kasir',
    default => ucfirst((string) $currentUserRole),
};
$initial = strtoupper(substr((string) $currentUserName, 0, 1));
$lowStockItems = [];

if (($currentUserRole ?? '') === 'administrator') {
    try {
        $db = \Config\Database::connect();

        if (in_array('barang', $db->listTables(), true)) {
            $lowStockItems = $db->table('barang')
                ->select('id, kode_barang, nama_barang, stok, stok_minimum, lokasi_barang')
                ->where('stok <= stok_minimum')
                ->orderBy('stok', 'ASC')
                ->orderBy('nama_barang', 'ASC')
                ->get()
                ->getResultArray();
        }
    } catch (Throwable $exception) {
        $lowStockItems = [];
    }
}

$lowStockCount = count($lowStockItems);
?>

<main class="main-area">
    <header class="topbar">
        <button class="btn btn-light topbar-sidebar-toggle" type="button" id="sidebarCollapseToggle" aria-label="Perkecil sidebar" title="Perkecil sidebar">
            <i class="bi bi-layout-sidebar-inset"></i>
        </button>

        <div class="topbar-spacer"></div>

        <?php if (($currentUserRole ?? '') === 'administrator') : ?>
            <div class="dropdown">
                <button class="notification-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" title="Notifikasi stok hampir habis" aria-label="Notifikasi stok hampir habis">
                    <i class="bi bi-bell"></i>
                    <?php if ($lowStockCount > 0) : ?>
                        <span class="badge rounded-pill text-bg-danger"><?= esc((string) min($lowStockCount, 99)) ?></span>
                    <?php endif; ?>
                </button>

                <div class="dropdown-menu dropdown-menu-end shadow-sm notification-menu">
                    <div class="px-3 py-2">
                        <div class="fw-bold">Stok Hampir Habis</div>
                        <div class="small text-secondary"><?= esc((string) $lowStockCount) ?> barang perlu diperhatikan.</div>
                    </div>

                    <div class="notification-list">
                        <?php if ($lowStockCount === 0) : ?>
                            <div class="px-3 py-4 text-center text-secondary border-top">
                                Tidak ada barang yang hampir habis.
                            </div>
                        <?php else : ?>
                            <?php foreach ($lowStockItems as $item) : ?>
                                <a href="<?= site_url('admin/barang/detail/' . $item['id']) ?>" class="notification-item">
                                    <div class="d-flex justify-content-between gap-2">
                                        <div class="min-w-0">
                                            <div class="notification-item-code text-truncate"><?= esc($item['kode_barang']) ?></div>
                                            <div class="fw-semibold text-truncate"><?= esc($item['nama_barang']) ?></div>
                                            <div class="small text-secondary text-truncate">
                                                <?= ! empty($item['lokasi_barang']) ? esc($item['lokasi_barang']) : 'Lokasi belum diisi' ?>
                                            </div>
                                        </div>
                                        <div class="text-end flex-shrink-0">
                                            <div class="badge text-bg-warning">Stok <?= esc((string) $item['stok']) ?></div>
                                            <div class="small text-secondary mt-1">Min. <?= esc((string) $item['stok_minimum']) ?></div>
                                        </div>
                                    </div>
                                </a>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="dropdown">
            <button class="profile-chip user-menu-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                <?php if (! empty($currentUserPhoto)) : ?>
                    <img src="<?= base_url('uploads/users/' . $currentUserPhoto) ?>" alt="Foto <?= esc($currentUserName) ?>" class="avatar user-menu-photo">
                <?php else : ?>
                    <div class="avatar"><?= esc($initial) ?></div>
                <?php endif; ?>

                <div class="text-start min-w-0">
                    <div class="fw-semibold lh-sm text-truncate"><?= esc($currentUserName) ?></div>
                    <div class="small text-secondary text-truncate"><?= esc($roleLabel) ?></div>
                </div>
                <i class="bi bi-chevron-down small text-secondary"></i>
            </button>

            <ul class="dropdown-menu dropdown-menu-end shadow-sm user-menu">
                <li class="px-3 py-2">
                    <div class="fw-semibold text-truncate"><?= esc($currentUserName) ?></div>
                    <div class="small text-secondary text-truncate"><?= esc($currentUserEmail) ?></div>
                    <span class="badge text-bg-light mt-2"><?= esc($roleLabel) ?></span>
                </li>
                <li><hr class="dropdown-divider"></li>
                <li>
                    <a class="dropdown-item" href="<?= site_url('admin/profile') ?>">
                        <i class="bi bi-person-circle me-2"></i>Update Profil
                    </a>
                </li>
                <li>
                    <a class="dropdown-item" href="<?= site_url('admin/change-password') ?>">
                        <i class="bi bi-key me-2"></i>Ganti Password
                    </a>
                </li>
                <li><hr class="dropdown-divider"></li>
                <li>
                    <a class="dropdown-item text-danger" href="<?= site_url('logout') ?>">
                        <i class="bi bi-box-arrow-right me-2"></i>Logout
                    </a>
                </li>
            </ul>
        </div>
    </header>

    <section class="content-area page-heading-area">
        <div class="page-heading">
            <div class="min-w-0">
                <div class="page-title"><?= esc($pageTitle ?? 'Admin') ?></div>
                <?php if (! empty($pageSubtitle)) : ?>
                    <div class="text-secondary"><?= esc($pageSubtitle) ?></div>
                <?php endif; ?>
            </div>

            <?php if (! empty($topbarAction)) : ?>
                <div class="page-heading-action">
                    <?= $topbarAction ?>
                </div>
            <?php endif; ?>
        </div>
    </section>
