<?php
// ════════════════════════════════════════════════════════════════════════════════
// Header helpers
// ════════════════════════════════════════════════════════════════════════════════
$_hRole  = getSession('role') ?? '';
$_hName  = getSession('full_name') ?? 'User';
$_hCDir  = basename(dirname($_SERVER['PHP_SELF']));
$_hCFile = basename($_SERVER['PHP_SELF'], '.php');

function isActive($mod) {
    global $_hCDir, $_hCFile;
    return ($mod === $_hCDir || $mod === $_hCFile) ? 'active' : '';
}

if (!function_exists('canSee')) {
    function canSee($roles) {
        global $_hRole;
        return in_array($_hRole, $roles, true);
    }
}

// Notification count
$_notifCount = 0;
if (isLoggedIn()) {
    try {
        $uid = (int)getSession('user_id');
        if ($uid) {
            $db2 = getDBConnection();
            if (in_array($_hRole, array('super_admin','exn','sdo','je'))) {
                $_notifCount = (int)safeDbVal($db2,
                    "SELECT COUNT(*) FROM readings WHERE DATE(created_at)=CURDATE()");
            }
        }
    } catch (Throwable $e) {}
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="theme-color" content="#1a237e">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="EMRS">
    <link rel="manifest" href="<?php echo BASE_URL; ?>/manifest.json">
    <link rel="apple-touch-icon" href="<?php echo BASE_URL; ?>/assets/images/icon-192.png">
    <title><?php echo isset($pageTitle) ? h($pageTitle) . ' — ' : ''; ?><?php echo APP_NAME; ?></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="<?php echo BASE_URL; ?>/assets/css/style.css?v=<?php echo APP_VERSION; ?>">
    <?php if (isset($extraHead)) echo $extraHead; ?>
    <style>
        @keyframes erpSlideIn { from{opacity:0;transform:translateX(20px)} to{opacity:1;transform:translateX(0)} }
        @keyframes pulse { 0%,100%{opacity:1} 50%{opacity:.5} }
        .notif-pulse { animation: pulse 2s infinite; }
        .global-search-result { border-bottom: 1px solid #f0f2f8; transition: background .12s; }
        .global-search-result:hover { background: #f5f7ff; }
    </style>
</head>
<body>

<!-- ════════════════════════════════════════════════════════════════════════════════
     TOPBAR
     ════════════════════════════════════════════════════════════════════════════════ -->
<nav class="erp-topbar">
    <div class="erp-topbar-inner">

        <!-- Left: Hamburger + Brand -->
        <div class="erp-topbar-left">
            <button class="erp-hamburger" id="sidebarToggle" aria-label="Toggle menu">
                <i class="bi bi-list"></i>
            </button>
            <a class="erp-brand" href="<?php echo BASE_URL; ?>/modules/dashboard/index.php">
                <span class="erp-brand-icon"><i class="bi bi-lightning-charge-fill"></i></span>
                <span class="erp-brand-name"><?php echo APP_NAME; ?></span>
            </a>
        </div>

        <!-- Right: Actions -->
        <div class="erp-topbar-right">

            <!-- Dark mode -->
            <button class="erp-tb-btn" id="darkModeToggle" title="Toggle dark mode">
                <i class="bi bi-moon-stars-fill" id="darkModeIcon"></i>
            </button>

            <!-- Notifications -->
            <div class="dropdown">
                <button class="erp-tb-btn position-relative" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-bell"></i>
                    <?php if ($_notifCount > 0): ?>
                    <span class="erp-notif-dot notif-pulse"><?php echo $_notifCount; ?></span>
                    <?php endif; ?>
                </button>
                <ul class="dropdown-menu dropdown-menu-end erp-dropdown shadow erp-notif-menu">
                    <li><div class="px-3 py-2 fw-bold border-bottom" style="font-size:.85rem;">
                        Notifications
                    </div></li>
                    <?php if ($_notifCount > 0): ?>
                    <li>
                        <a class="dropdown-item py-2" href="<?php echo BASE_URL; ?>/modules/reports/index.php?type=solar" style="font-size:.82rem;">
                            <i class="bi bi-sun-fill text-warning me-2"></i>
                            <?php echo $_notifCount; ?> reading<?php echo $_notifCount > 1 ? 's' : ''; ?> submitted today
                            <div class="text-muted" style="font-size:.72rem;"><?php echo date('d M Y'); ?></div>
                        </a>
                    </li>
                    <?php else: ?>
                    <li><div class="px-3 py-3 text-center text-muted" style="font-size:.82rem;">
                        <i class="bi bi-check-circle text-success d-block fs-4 mb-1"></i>All caught up!
                    </div></li>
                    <?php endif; ?>
                </ul>
            </div>

            <!-- User dropdown -->
            <div class="dropdown">
                <button class="erp-user-btn" data-bs-toggle="dropdown" aria-expanded="false">
                    <span class="erp-avatar"><?php echo strtoupper(substr($_hName, 0, 1)); ?></span>
                    <i class="bi bi-chevron-down erp-chevron"></i>
                </button>
                <ul class="dropdown-menu dropdown-menu-end erp-dropdown shadow">
                    <li>
                        <div class="px-3 py-2 border-bottom">
                            <div class="fw-semibold" style="font-size:.88rem;"><?php echo h($_hName); ?></div>
                            <div class="mt-1"><?php echo roleBadge($_hRole); ?></div>
                        </div>
                    </li>
                    <li><a class="dropdown-item" href="<?php echo BASE_URL; ?>/modules/profile/index.php">
                        <i class="bi bi-person-circle me-2"></i>My Profile
                    </a></li>
                    <li><a class="dropdown-item" href="<?php echo BASE_URL; ?>/modules/profile/password.php">
                        <i class="bi bi-shield-lock me-2"></i>Change Password
                    </a></li>
                    <li><hr class="dropdown-divider my-1"></li>
                    <li>
                        <form method="POST" action="<?php echo BASE_URL; ?>/auth/logout.php" class="m-0">
                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                            <button type="submit" class="dropdown-item text-danger w-100 text-start border-0 bg-transparent">
                                <i class="bi bi-box-arrow-right me-2"></i>Logout
                            </button>
                        </form>
                    </li>
                </ul>
            </div>

        </div><!-- /topbar-right -->
    </div><!-- /topbar-inner -->
</nav>

<!-- ════════════════════════════════════════════════════════════════════════════════
     SIDEBAR
     ════════════════════════════════════════════════════════════════════════════════ -->
<aside class="erp-sidebar" id="erpSidebar">
    <div class="erp-sidebar-header">
        <span class="erp-sidebar-label"><?php echo h(roleLabel($_hRole)); ?> Menu</span>
    </div>
    <nav class="erp-sidebar-nav">
        <ul class="list-unstyled mb-0">

            <!-- Dashboard — all roles -->
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/dashboard/index.php" class="erp-nav-link <?php echo isActive('dashboard'); ?>">
                    <i class="bi bi-speedometer2"></i><span>Dashboard</span>
                </a>
            </li>

            <!-- ════════════════════════════════════════════════════════════════════════════════
                 MR (Meter Reader)
                 ════════════════════════════════════════════════════════════════════════════════ -->
            <?php if (canSee(array('mr'))): ?>
            <li class="erp-nav-group">Meter Reading</li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/readings/add.php?type=solar"
                   class="erp-nav-link <?php echo ($_hCFile==='add'&&($_GET['type']??'')==='solar') ? 'active':'' ?>">
                    <i class="bi bi-sun-fill text-warning"></i><span>Solar Reading</span>
                </a>
            </li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/readings/add.php?type=kcc"
                   class="erp-nav-link <?php echo ($_hCFile==='add'&&($_GET['type']??'')==='kcc') ? 'active':'' ?>">
                    <i class="bi bi-lightning-fill text-info"></i><span>KCC Reading</span>
                </a>
            </li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/bills/add.php"
                   class="erp-nav-link <?php echo ($_hCDir==='bills'&&$_hCFile==='add') ? 'active':'' ?>">
                    <i class="bi bi-receipt-cutoff text-success"></i><span>Bill Distribution</span>
                </a>
            </li>
            <li class="erp-nav-group">My History</li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/readings/index.php"
                   class="erp-nav-link <?php echo ($_hCDir==='readings'&&$_hCFile==='index') ? 'active':'' ?>">
                    <i class="bi bi-clock-history"></i><span>My Readings</span>
                </a>
            </li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/bills/index.php"
                   class="erp-nav-link <?php echo ($_hCDir==='bills'&&$_hCFile==='index') ? 'active':'' ?>">
                    <i class="bi bi-collection"></i><span>My Bills</span>
                </a>
            </li>
            <li class="erp-nav-group">Tracking</li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/tracking/index.php"
                   class="erp-nav-link <?php echo ($_hCDir==='tracking') ? 'active':'' ?>">
                    <i class="bi bi-calendar2-check text-success"></i><span>Monthly Tracking</span>
                </a>
            </li>
            <li class="erp-nav-group">My Profile</li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/profile/kyc.php"
                   class="erp-nav-link <?php echo ($_hCFile==='kyc') ? 'active':'' ?>">
                    <i class="bi bi-person-vcard-fill text-primary"></i><span>KYC Details</span>
                </a>
            </li>
            <?php endif; ?>

            <!-- ════════════════════════════════════════════════════════════════════════════════
                 JE / SDO / EXN (Staff)
                 ════════════════════════════════════════════════════════════════════════════════ -->
            <?php if (canSee(array('je','sdo','exn'))): ?>
            <li class="erp-nav-group">Tracking</li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/tracking/index.php"
                   class="erp-nav-link <?php echo ($_hCDir==='tracking') ? 'active':'' ?>">
                    <i class="bi bi-calendar2-check text-success"></i><span>Monthly Tracking</span>
                </a>
            </li>
            <li class="erp-nav-group">Reports</li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/reports/index.php?type=solar" class="erp-nav-link">
                    <i class="bi bi-sun-fill text-warning"></i><span>Solar Reports</span>
                </a>
            </li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/reports/index.php?type=kcc" class="erp-nav-link">
                    <i class="bi bi-lightning-fill text-info"></i><span>KCC Reports</span>
                </a>
            </li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/reports/index.php?type=bills" class="erp-nav-link">
                    <i class="bi bi-receipt-cutoff text-success"></i><span>Bill Reports</span>
                </a>
            </li>
            <?php endif; ?>

            <!-- ════════════════════════════════════════════════════════════════════════════════
                 Super Admin
                 ════════════════════════════════════════════════════════════════════════════════ -->
            <?php if (canSee(array('super_admin'))): ?>
            <li class="erp-nav-group">Tracking</li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/tracking/index.php"
                   class="erp-nav-link <?php echo ($_hCDir==='tracking') ? 'active':'' ?>">
                    <i class="bi bi-calendar2-check text-success"></i><span>Monthly Tracking</span>
                </a>
            </li>
            <li class="erp-nav-group">Administration</li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/admin/users.php" class="erp-nav-link <?php echo isActive('users'); ?>">
                    <i class="bi bi-people-fill"></i><span>Users</span>
                </a>
            </li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/admin/consumers.php" class="erp-nav-link <?php echo isActive('consumers'); ?>">
                    <i class="bi bi-person-badge-fill"></i><span>Consumers</span>
                </a>
            </li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/admin/mr_list.php" class="erp-nav-link <?php echo isActive('mr_list'); ?>">
                    <i class="bi bi-people-fill text-primary"></i><span>MR KYC List</span>
                </a>
            </li>
            <li class="erp-nav-group">Reports</li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/reports/index.php?type=solar" class="erp-nav-link">
                    <i class="bi bi-sun-fill text-warning"></i><span>Solar Reports</span>
                </a>
            </li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/reports/index.php?type=kcc" class="erp-nav-link">
                    <i class="bi bi-lightning-fill text-info"></i><span>KCC Reports</span>
                </a>
            </li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/reports/index.php?type=bills" class="erp-nav-link">
                    <i class="bi bi-receipt-cutoff text-success"></i><span>Bill Reports</span>
                </a>
            </li>
            <li>
                <a href="<?php echo BASE_URL; ?>/modules/reports/whatsapp_report.php" class="erp-nav-link <?php echo isActive('whatsapp_report'); ?>">
                    <i class="bi bi-whatsapp" style="color:#25d366;"></i><span>WhatsApp Report</span>
                </a>
            </li>
            <?php endif; ?>

            <!-- Logout — all roles -->
            <li class="mt-2">
                <form method="POST" action="<?php echo BASE_URL; ?>/auth/logout.php" class="m-0">
                    <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                    <button type="submit" class="erp-nav-link erp-nav-logout w-100 border-0 bg-transparent">
                        <i class="bi bi-box-arrow-right"></i><span>Logout</span>
                    </button>
                </form>
            </li>

        </ul>
    </nav>
</aside>

<!-- Overlay -->
<div class="erp-overlay" id="erpOverlay"></div>

<!-- ════════════════════════════════════════════════════════════════════════════════
     CONTENT WRAPPER
     ════════════════════════════════════════════════════════════════════════════════ -->
<div class="erp-content-wrapper" id="erpContentWrapper">
    <main class="erp-main">
        <div id="alertContainer"></div>

<!-- Global Search Modal -->
<div class="modal fade" id="globalSearchModal" tabindex="-1" aria-label="Global Search">
    <div class="modal-dialog modal-dialog-centered" style="max-width:520px;">
        <div class="modal-content border-0 shadow-lg" style="border-radius:14px;overflow:hidden;">
            <div class="modal-body p-0">
                <div class="p-3 border-bottom d-flex align-items-center gap-2">
                    <i class="bi bi-search text-muted"></i>
                    <input type="text" id="globalSearchInput" class="form-control border-0 shadow-none p-0"
                           placeholder="Search consumers, reports… (Ctrl+K)" autocomplete="off"
                           style="min-height:unset;font-size:15px;">
                    <kbd class="text-muted" style="font-size:.7rem;background:#f0f2f8;padding:2px 6px;border-radius:4px;">ESC</kbd>
                </div>
                <div id="globalSearchResults" style="max-height:320px;overflow-y:auto;"></div>
                <div class="px-3 py-2 border-top d-flex gap-3" style="background:#fafbff;font-size:.72rem;color:#a0aec0;">
                    <span><kbd style="background:#f0f2f8;padding:1px 5px;border-radius:3px;">↑↓</kbd> Navigate</span>
                    <span><kbd style="background:#f0f2f8;padding:1px 5px;border-radius:3px;">Enter</kbd> Open</span>
                    <span><kbd style="background:#f0f2f8;padding:1px 5px;border-radius:3px;">ESC</kbd> Close</span>
                </div>
            </div>
        </div>
    </div>
</div>
