<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= esc($title ?? $app_name ?? 'Data Manager') ?> — <?= esc($app_name ?? 'FT Teluk Betung') ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/2.0.8/css/dataTables.bootstrap5.min.css">
<style>
:root { --sidebar-width: 260px; --sidebar-bg: #0f172a; --sidebar-hover: #1e293b; --sidebar-active: #3b82f6; }
body { background: #f1f5f9; font-size: 0.875rem; }
#sidebar {
    position: fixed; top: 0; left: 0; height: 100vh; width: var(--sidebar-width);
    background: var(--sidebar-bg); color: #cbd5e1; overflow-y: auto; z-index: 1000;
    display: flex; flex-direction: column;
}
#sidebar .sidebar-header {
    padding: 1.25rem 1rem; border-bottom: 1px solid #1e293b; flex-shrink: 0;
}
#sidebar .sidebar-header .app-name {
    font-size: 1rem; font-weight: 700; color: #f8fafc; line-height: 1.3;
}
#sidebar .sidebar-header .app-sub { font-size: 0.7rem; color: #64748b; }
#sidebar .nav-label {
    font-size: 0.65rem; font-weight: 700; letter-spacing: .08em;
    color: #475569; text-transform: uppercase; padding: .75rem 1rem .25rem;
}
#sidebar .nav-link {
    color: #94a3b8; padding: .45rem 1rem; font-size: 0.8rem; border-radius: 0;
    display: flex; align-items: center; gap: .5rem; white-space: nowrap;
}
#sidebar .nav-link:hover { background: var(--sidebar-hover); color: #e2e8f0; }
#sidebar .nav-link.active { background: var(--sidebar-active); color: #fff; }
#sidebar .nav-link i { width: 16px; text-align: center; flex-shrink: 0; }
#sidebar .nav-group .nav-link { padding-left: 1.75rem; font-size: 0.78rem; }
#sidebar .group-header {
    padding: .4rem 1rem .1rem; font-size: 0.7rem; font-weight: 600;
    color: #64748b; text-transform: uppercase; letter-spacing: .05em;
}
#main-content { margin-left: var(--sidebar-width); min-height: 100vh; }
#topbar {
    background: #fff; border-bottom: 1px solid #e2e8f0;
    padding: .6rem 1.5rem; display: flex; align-items: center; justify-content: space-between;
    position: sticky; top: 0; z-index: 999;
}
.page-body { padding: 1.5rem; }
.card { border: 1px solid #e2e8f0; box-shadow: 0 1px 3px rgba(0,0,0,.05); }
.card-header { background: #f8fafc; border-bottom: 1px solid #e2e8f0; font-weight: 600; }
.table th { font-size: .75rem; color: #64748b; font-weight: 600; }
.badge-role-admin { background: #dbeafe; color: #1d4ed8; }
.badge-role-viewer { background: #f0fdf4; color: #15803d; }
.dt-container .dt-search input { font-size: .8rem; }
</style>
<?= $this->renderSection('head_extra') ?>
</head>
<body>

<!-- SIDEBAR -->
<nav id="sidebar">
    <div class="sidebar-header">
        <div class="app-name"><?= esc($app_name ?? 'FT Teluk Betung') ?></div>
        <div class="app-sub">Data Manager</div>
    </div>

    <div class="flex-grow-1 pt-1 pb-3">
        <?php
        $currentUri = current_url();
        $baseUrl    = base_url();
        $isLinksActive = strpos($currentUri, '/links') !== false;
        ?>

        <!-- Links -->
        <div class="nav-label">Menu</div>
        <a href="<?= base_url('links') ?>" class="nav-link <?= $isLinksActive ? 'active' : '' ?>">
            <i class="bi bi-link-45deg"></i> Links
        </a>

        <!-- Data Categories -->
        <div class="nav-label mt-1">Data</div>
        <?php
        $catKey    = $catKey ?? '';
        $navCats   = $navCats ?? [];
        $groupOrder = ['ungrouped', 'DI319', 'DI321', 'MTD YTD'];
        $allGroups  = array_keys($navCats);
        $sortedGroups = array_unique(array_merge(
            array_intersect($groupOrder, $allGroups),
            $allGroups
        ));
        foreach ($sortedGroups as $group):
            if (! isset($navCats[$group])) continue;
            $cats = $navCats[$group];
            if ($group === 'ungrouped'):
                foreach ($cats as $c):
                    $isActive = ($catKey === $c['key']);
        ?>
            <a href="<?= base_url('dashboard?cat=' . $c['key']) ?>" class="nav-link <?= $isActive ? 'active' : '' ?>">
                <i class="bi bi-table"></i> <?= esc($c['label']) ?>
            </a>
        <?php
                endforeach;
            else:
        ?>
            <div class="group-header"><?= esc($group) ?></div>
            <div class="nav-group">
            <?php foreach ($cats as $c):
                $isActive = ($catKey === $c['key']); ?>
                <a href="<?= base_url('dashboard?cat=' . $c['key']) ?>" class="nav-link <?= $isActive ? 'active' : '' ?>">
                    <i class="bi bi-table"></i> <?= esc($c['label']) ?>
                </a>
            <?php endforeach; ?>
            </div>
        <?php
            endif;
        endforeach;
        ?>

        <!-- System -->
        <?php if (($role ?? '') === 'administrator'): ?>
        <div class="nav-label mt-1">Sistem</div>
        <?php
        $isUsersActive   = strpos($currentUri, '/users') !== false;
        $isLogsActive    = strpos($currentUri, '/logs') !== false;
        $isSettingsActive= strpos($currentUri, '/settings') !== false;
        ?>
        <a href="<?= base_url('users') ?>" class="nav-link <?= $isUsersActive ? 'active' : '' ?>">
            <i class="bi bi-people"></i> Manajemen User
        </a>
        <a href="<?= base_url('logs') ?>" class="nav-link <?= $isLogsActive ? 'active' : '' ?>">
            <i class="bi bi-journal-text"></i> Activity Log
        </a>
        <a href="<?= base_url('settings') ?>" class="nav-link <?= $isSettingsActive ? 'active' : '' ?>">
            <i class="bi bi-gear"></i> Pengaturan
        </a>
        <?php endif; ?>
    </div>
</nav>

<!-- MAIN CONTENT -->
<div id="main-content">
    <!-- TOP BAR -->
    <div id="topbar">
        <div class="fw-semibold text-dark" style="font-size:.875rem;">
            <?= esc($page_title ?? 'Dashboard') ?>
        </div>
        <div class="d-flex align-items-center gap-3">
            <span class="text-muted" style="font-size:.8rem;">
                <i class="bi bi-person-circle me-1"></i>
                <?= esc($nama ?? $username ?? '') ?>
                <span class="ms-1 badge badge-role-<?= ($role ?? '') === 'administrator' ? 'admin' : 'viewer' ?>">
                    <?= ($role ?? '') === 'administrator' ? 'Admin' : 'Viewer' ?>
                </span>
            </span>
            <a href="<?= base_url('logout') ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Yakin ingin logout?')">
                <i class="bi bi-box-arrow-right"></i> Logout
            </a>
        </div>
    </div>

    <!-- FLASH MESSAGES -->
    <?php if (session()->getFlashdata('error')): ?>
    <div class="alert alert-danger alert-dismissible m-3 mb-0 py-2" role="alert">
        <?= esc(session()->getFlashdata('error')) ?>
        <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    <?php if (session()->getFlashdata('success')): ?>
    <div class="alert alert-success alert-dismissible m-3 mb-0 py-2" role="alert">
        <?= esc(session()->getFlashdata('success')) ?>
        <button type="button" class="btn-close btn-sm" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <div class="page-body">
        <?= $this->renderSection('content') ?>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/2.0.8/js/dataTables.min.js"></script>
<script src="https://cdn.datatables.net/2.0.8/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
const BASE_URL = '<?= base_url() ?>';
function csrfToken()  { return '<?= csrf_token() ?>'; }
function csrfHash()   { return '<?= csrf_hash() ?>'; }
function postData(url, data, onSuccess, onError) {
    data[csrfToken()] = csrfHash();
    $.ajax({
        url: BASE_URL + url, type: 'POST', data: data,
        success: function(r) {
            if (r && r.success) onSuccess(r);
            else { Swal.fire('Error', (r && r.message) ? r.message : 'Terjadi kesalahan.', 'error'); if(onError) onError(r); }
        },
        error: function(xhr) {
            const r = xhr.responseJSON;
            if (xhr.status === 401) { window.location.href = BASE_URL + 'login'; return; }
            Swal.fire('Error', (r && r.message) ? r.message : 'Request gagal ('+xhr.status+').', 'error');
            if(onError) onError(r);
        }
    });
}
</script>
<?= $this->renderSection('scripts') ?>
</body>
</html>
