<?php
/**
 * layouts/topbar.php
 * Christmond Investment Limited — M-Pesa Agent Management System
 * Schema: users, roles, businesses, locations, alerts, audit_logs
 */

/* Always ensure a live connection — index.php may have closed it already */
if (!isset($conn) || !($conn instanceof mysqli) || $conn->connect_errno) {
    include __DIR__ . '/dbconn.php';
} else {
    /* ping() returns false if the connection dropped; reconnect if so */
    if (!$conn->ping()) {
        $conn->close();
        include __DIR__ . '/dbconn.php';
    }
}

/* ── Guard ───────────────────────────────────────────────────────── */
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php'); exit();
}

$uid         = (int)$_SESSION['user_id'];
$business_id = (int)$_SESSION['business_id'];
$role        = $_SESSION['role_name']  ?? '';
$full_name   = $_SESSION['full_name']  ?? '';
$biz_name    = $_SESSION['business_name'] ?? 'Christmond Investment Ltd';
$is_admin    = in_array($role, ['super_admin', 'manager']);

/* ── Fresh user row (phone, email) ───────────────────────────────── */
$usr_stmt = $conn->prepare(
    "SELECT phone, email, updated_at FROM users WHERE id = ? LIMIT 1"
);
$usr_stmt->bind_param("i", $uid);
$usr_stmt->execute();
$usr_row = $usr_stmt->get_result()->fetch_assoc() ?? [];
$usr_stmt->close();

$phone = $usr_row['phone'] ?? ($_SESSION['phone'] ?? '');
$email = $usr_row['email'] ?? '';

/* ── Unresolved alerts (badge count) ─────────────────────────────── */
$al_stmt = $conn->prepare(
    "SELECT alert_type, severity, message, a.created_at,
            l.location_name
     FROM   alerts a
     LEFT   JOIN locations l ON l.id = a.location_id
     WHERE  a.business_id = ? AND a.is_resolved = 0
     ORDER  BY FIELD(a.severity,'critical','high','medium','low'),
               a.created_at DESC
     LIMIT  8"
);
$al_stmt->bind_param("i", $business_id);
$al_stmt->execute();
$alerts      = $al_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$alert_count = count($alerts);
$al_stmt->close();

/* ── Today's open session (agent only) ───────────────────────────── */
$my_session = null;
if (!$is_admin && isset($_SESSION['primary_location_id'])) {
    $loc_id  = (int)$_SESSION['primary_location_id'];
    $today   = date('Y-m-d');
    $ss_stmt = $conn->prepare(
        "SELECT id, status, opened_at FROM daily_sessions
         WHERE  location_id = ? AND business_date = ? LIMIT 1"
    );
    $ss_stmt->bind_param("is", $loc_id, $today);
    $ss_stmt->execute();
    $my_session = $ss_stmt->get_result()->fetch_assoc();
    $ss_stmt->close();
}

/* ── Recent audit log (admin notifications) ──────────────────────── */
$audit_items = [];
if ($is_admin) {
    $aud_stmt = $conn->prepare(
        "SELECT al.action, al.table_name, al.created_at, u.full_name agent_name
         FROM   audit_logs al
         LEFT   JOIN users u ON u.id = al.user_id
         WHERE  al.business_id = ?
           AND  al.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
         ORDER  BY al.created_at DESC
         LIMIT  8"
    );
    $aud_stmt->bind_param("i", $business_id);
    $aud_stmt->execute();
    $audit_items = $aud_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $aud_stmt->close();
}

/* ── Helpers ─────────────────────────────────────────────────────── */
function timeAgo(string $dt): string {
    $diff = time() - strtotime($dt);
    if ($diff < 60)     return 'Just now';
    if ($diff < 3600)   return floor($diff/60).'m ago';
    if ($diff < 86400)  return floor($diff/3600).'h ago';
    return date('d M', strtotime($dt));
}

function severityClass(string $s): string {
    return match($s) {
        'critical' => 'danger',
        'high'     => 'warning',
        'medium'   => 'info',
        default    => 'success',
    };
}

function auditIcon(string $action): string {
    return match($action) {
        'SESSION_OPENED'    => 'ri-play-circle-line',
        'RECONCILIATION_RUN'=> 'ri-file-list-3-line',
        'TXN_VOIDED'        => 'ri-close-circle-line',
        'LOGIN'             => 'ri-login-box-line',
        'LOGOUT'            => 'ri-logout-box-line',
        default             => 'ri-information-line',
    };
}
?>

<header id="page-topbar">
<div class="layout-width">
<div class="navbar-header">

    <!-- ── Left: hamburger + brand ──────────────────────────────── -->
    <div class="d-flex align-items-center gap-2">

        <button type="button"
                class="btn btn-sm px-3 fs-16 header-item vertical-menu-btn topnav-hamburger"
                id="topnav-hamburger-icon">
            <span class="hamburger-icon">
                <span></span><span></span><span></span>
            </span>
        </button>

        <!-- Brand wordmark (sidebar logo hidden on mobile) -->
        <a href="index.php" class="d-flex align-items-center text-decoration-none gap-2 ms-1">
            <div class="brand-icon d-flex align-items-center justify-content-center"
                 style="width:36px;height:36px;background:var(--mpesa-green);border-radius:8px;flex-shrink:0;">
                <span style="color:#fff;font-weight:900;font-size:1rem;">M</span>
            </div>
            <div class="d-none d-lg-block">
                <div style="font-size:.82rem;font-weight:700;color:#fff;line-height:1.1;">
                    <?= htmlspecialchars($biz_name) ?>
                </div>
                <div style="font-size:.68rem;color:rgba(255,255,255,.65);letter-spacing:.04em;">
                    M-PESA AGENT SYSTEM
                </div>
            </div>
        </a>

        <!-- Agent session status pill -->
        <?php if (!$is_admin): ?>
            <?php if ($my_session && $my_session['status'] === 'open'): ?>
                <span class="badge d-none d-md-inline-flex align-items-center gap-1"
                      style="background:rgba(255,255,255,.2);color:#fff;font-size:.72rem;">
                    <span style="width:7px;height:7px;background:#4ade80;border-radius:50%;display:inline-block;
                                 animation:blink 1.4s infinite;"></span>
                    Session Open
                </span>
            <?php elseif (!$my_session): ?>
                <a href="open_session.php"
                   class="badge d-none d-md-inline-flex align-items-center gap-1 text-decoration-none"
                   style="background:rgba(251,191,36,.25);color:#fbbf24;font-size:.72rem;">
                    <i class="ri-time-line"></i> No Session
                </a>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <!-- ── Right: actions ───────────────────────────────────────── -->
    <div class="d-flex align-items-center gap-1">

        <!-- Location chip (agent only) -->
        <?php if (!$is_admin && isset($_SESSION['primary_location_name'])): ?>
        <div class="d-none d-md-flex align-items-center gap-1 me-1"
             style="background:rgba(255,255,255,.12);border-radius:20px;padding:4px 12px;">
            <i class="ri-store-2-line" style="color:rgba(255,255,255,.7);font-size:.9rem;"></i>
            <span style="font-size:.78rem;color:#fff;font-weight:500;">
                <?= htmlspecialchars($_SESSION['primary_location_name']) ?>
            </span>
        </div>
        <?php endif; ?>

        <!-- ── Alerts bell ─────────────────────────────────────── -->
        <div class="dropdown">
            <button class="btn btn-icon btn-topbar btn-ghost-secondary rounded-circle position-relative"
                    data-bs-toggle="dropdown" data-bs-auto-close="outside"
                    title="Alerts & Notifications">
                <i class="ri-notification-3-line fs-20"></i>
                <?php if ($alert_count > 0): ?>
                <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger"
                      style="font-size:.65rem;padding:3px 5px;">
                    <?= min($alert_count, 99) ?>
                </span>
                <?php endif; ?>
            </button>

            <div class="dropdown-menu dropdown-menu-end dropdown-menu-lg p-0 shadow-lg"
                 style="border-radius:14px;min-width:340px;overflow:hidden;">

                <!-- Header -->
                <div class="p-3" style="background:linear-gradient(135deg,var(--mpesa-green-dark),var(--mpesa-green));">
                    <div class="d-flex justify-content-between align-items-center">
                        <h6 class="mb-0 text-white fw-semibold">
                            <i class="ri-alarm-warning-line me-1"></i>System Alerts
                        </h6>
                        <span class="badge" style="background:rgba(255,255,255,.2);color:#fff;font-size:.72rem;">
                            <?= $alert_count ?> Active
                        </span>
                    </div>
                </div>

                <!-- Alert items -->
                <div style="max-height:300px;overflow-y:auto;">
                    <?php if (empty($alerts)): ?>
                        <div class="text-center py-4 text-muted">
                            <i class="ri-checkbox-circle-line fs-2 text-success d-block mb-1"></i>
                            <small>No active alerts — all clear!</small>
                        </div>
                    <?php else: ?>
                        <?php foreach ($alerts as $al): ?>
                        <div class="d-flex align-items-start gap-2 px-3 py-2 border-bottom"
                             style="transition:background .15s;" onmouseover="this.style.background='#f8fffe'"
                             onmouseout="this.style.background=''">
                            <span class="badge bg-<?= severityClass($al['severity']) ?> mt-1"
                                  style="min-width:6px;padding:4px 6px;font-size:.65rem;">
                                <?= strtoupper($al['severity']) ?>
                            </span>
                            <div class="flex-grow-1">
                                <div style="font-size:.8rem;font-weight:600;color:#1a2e1a;">
                                    <?= htmlspecialchars($al['alert_type']) ?>
                                    <?php if ($al['location_name']): ?>
                                        <span class="text-muted fw-normal">
                                            — <?= htmlspecialchars($al['location_name']) ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <div style="font-size:.75rem;color:#6c757d;line-height:1.3;">
                                    <?= htmlspecialchars(substr($al['message'],0,75)) ?>…
                                </div>
                                <div style="font-size:.68rem;color:#adb5bd;margin-top:2px;">
                                    <?= timeAgo($al['created_at']) ?>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <?php if ($is_admin): ?>
                <div class="p-2 border-top text-center">
                    <a href="alerts.php" class="btn btn-sm w-100"
                       style="background:var(--mpesa-green);color:#fff;border-radius:8px;font-size:.8rem;">
                        View All Alerts
                    </a>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <!-- end alerts -->

        <!-- ── Audit / activity (admin) ──────────────────────────── -->
        <?php if ($is_admin): ?>
        <div class="dropdown">
            <button class="btn btn-icon btn-topbar btn-ghost-secondary rounded-circle"
                    data-bs-toggle="dropdown" data-bs-auto-close="outside"
                    title="Recent Activity">
                <i class="ri-history-line fs-20"></i>
            </button>

            <div class="dropdown-menu dropdown-menu-end dropdown-menu-lg p-0 shadow-lg"
                 style="border-radius:14px;min-width:320px;overflow:hidden;">
                <div class="p-3 border-bottom" style="background:#f8fffe;">
                    <h6 class="mb-0 fw-semibold" style="color:var(--mpesa-green-dark);">
                        <i class="ri-file-list-3-line me-1"></i>Recent Activity (24h)
                    </h6>
                </div>
                <div style="max-height:280px;overflow-y:auto;">
                    <?php if (empty($audit_items)): ?>
                        <div class="text-center py-4 text-muted"><small>No activity yet today.</small></div>
                    <?php else: ?>
                        <?php foreach ($audit_items as $ai): ?>
                        <div class="d-flex align-items-start gap-2 px-3 py-2 border-bottom"
                             style="font-size:.8rem;">
                            <div class="mt-1" style="width:28px;height:28px;border-radius:8px;
                                background:var(--light-green);display:flex;align-items:center;
                                justify-content:center;flex-shrink:0;">
                                <i class="<?= auditIcon($ai['action']) ?>"
                                   style="color:var(--mpesa-green);font-size:.85rem;"></i>
                            </div>
                            <div>
                                <div class="fw-semibold text-dark" style="font-size:.78rem;">
                                    <?= htmlspecialchars(str_replace('_',' ',$ai['action'])) ?>
                                    <span class="text-muted fw-normal">
                                        on <?= htmlspecialchars($ai['table_name']) ?>
                                    </span>
                                </div>
                                <div class="text-muted" style="font-size:.72rem;">
                                    <?= htmlspecialchars($ai['agent_name'] ?? 'System') ?>
                                    &bull; <?= timeAgo($ai['created_at']) ?>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <div class="p-2 border-top text-center">
                    <a href="audit_log.php" class="btn btn-sm w-100"
                       style="background:var(--mpesa-green);color:#fff;border-radius:8px;font-size:.8rem;">
                        Full Audit Log
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- ── User profile dropdown ─────────────────────────────── -->
        <div class="dropdown ms-1">
            <button class="btn d-flex align-items-center gap-2 px-2 py-1"
                    id="page-header-user-dropdown"
                    data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
                    style="background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);
                           border-radius:24px;transition:all .2s;">
                <!-- Avatar initials -->
                <div style="width:32px;height:32px;border-radius:50%;background:rgba(255,255,255,.25);
                            display:flex;align-items:center;justify-content:center;
                            font-weight:700;color:#fff;font-size:.85rem;flex-shrink:0;">
                    <?= strtoupper(substr($full_name,0,1)) ?>
                </div>
                <div class="d-none d-xl-block text-start">
                    <div style="font-size:.82rem;font-weight:600;color:#fff;line-height:1.1;max-width:130px;
                                white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                        <?= htmlspecialchars($full_name) ?>
                    </div>
                    <div style="font-size:.68rem;color:rgba(255,255,255,.65);">
                        <?= ucfirst(str_replace('_',' ',$role)) ?>
                    </div>
                </div>
                <i class="ri-arrow-down-s-line d-none d-xl-block" style="color:rgba(255,255,255,.7);"></i>
            </button>

            <div class="dropdown-menu dropdown-menu-end shadow-lg"
                 style="border-radius:14px;min-width:260px;overflow:hidden;padding:0;border:none;">

                <!-- Profile header -->
                <div class="p-3" style="background:linear-gradient(135deg,var(--mpesa-green-dark),var(--mpesa-green));">
                    <div class="d-flex align-items-center gap-3">
                        <div style="width:44px;height:44px;border-radius:50%;background:rgba(255,255,255,.25);
                                    display:flex;align-items:center;justify-content:center;
                                    font-weight:700;color:#fff;font-size:1.1rem;flex-shrink:0;">
                            <?= strtoupper(substr($full_name,0,1)) ?>
                        </div>
                        <div>
                            <div style="font-weight:600;color:#fff;font-size:.9rem;">
                                <?= htmlspecialchars($full_name) ?>
                            </div>
                            <div style="font-size:.72rem;color:rgba(255,255,255,.75);">
                                <?= htmlspecialchars($email) ?>
                            </div>
                            <span style="background:rgba(255,255,255,.2);color:#fff;font-size:.68rem;
                                         border-radius:10px;padding:2px 8px;margin-top:3px;display:inline-block;">
                                <?= ucfirst(str_replace('_',' ',$role)) ?>
                            </span>
                        </div>
                    </div>
                </div>

                <div style="padding:6px 0;">

                    <!-- Common items -->
                    <a class="dropdown-item py-2" href="profile.php">
                        <i class="ri-user-line me-2 text-muted"></i>My Profile
                    </a>
                    <a class="dropdown-item py-2" href="change_password.php">
                        <i class="ri-lock-password-line me-2 text-muted"></i>Change Password
                    </a>

                    <hr class="my-1">

                    <!-- Role-specific quick links -->
                    <?php if ($is_admin): ?>
                        <a class="dropdown-item py-2" href="users.php">
                            <i class="ri-group-line me-2 text-muted"></i>Manage Users
                        </a>
                        <a class="dropdown-item py-2" href="locations.php">
                            <i class="ri-store-2-line me-2 text-muted"></i>Manage Branches
                        </a>
                        <a class="dropdown-item py-2" href="reports.php">
                            <i class="ri-bar-chart-2-line me-2 text-muted"></i>Reports
                        </a>
                        <a class="dropdown-item py-2" href="audit_log.php">
                            <i class="ri-file-list-3-line me-2 text-muted"></i>Audit Log
                        </a>
                        <a class="dropdown-item py-2" href="commission_rates.php">
                            <i class="ri-percent-line me-2 text-muted"></i>Commission Rates
                        </a>
                    <?php else: ?>
                        <?php if ($my_session && $my_session['status'] === 'open'): ?>
                        <a class="dropdown-item py-2" href="transactions.php?session=<?= $my_session['id'] ?>">
                            <i class="ri-add-circle-line me-2" style="color:var(--mpesa-green);"></i>
                            <strong>Record Transaction</strong>
                        </a>
                        <a class="dropdown-item py-2" href="close_session.php?id=<?= $my_session['id'] ?>">
                            <i class="ri-stop-circle-line me-2 text-danger"></i>Close Session
                        </a>
                        <?php else: ?>
                        <a class="dropdown-item py-2" href="open_session.php">
                            <i class="ri-play-circle-line me-2" style="color:var(--mpesa-green);"></i>
                            <strong>Open Today's Session</strong>
                        </a>
                        <?php endif; ?>
                        <a class="dropdown-item py-2" href="my_sessions.php">
                            <i class="ri-calendar-check-line me-2 text-muted"></i>My Sessions
                        </a>
                        <a class="dropdown-item py-2" href="my_commissions.php">
                            <i class="ri-award-line me-2 text-muted"></i>My Commissions
                        </a>
                    <?php endif; ?>

                    <hr class="my-1">

                    <!-- System info -->
                    <?php if ($phone): ?>
                    <div class="px-3 py-1">
                        <small class="text-muted">
                            <i class="ri-phone-line me-1"></i><?= htmlspecialchars($phone) ?>
                        </small>
                    </div>
                    <?php endif; ?>

                    <?php if (!$is_admin && isset($_SESSION['primary_location_name'])): ?>
                    <div class="px-3 py-1">
                        <small class="text-muted">
                            <i class="ri-store-2-line me-1"></i>
                            <?= htmlspecialchars($_SESSION['primary_location_name']) ?>
                        </small>
                    </div>
                    <?php endif; ?>

                    <hr class="my-1">

                    <a class="dropdown-item py-2 text-danger" href="logout.php">
                        <i class="ri-logout-box-line me-2"></i>Logout
                    </a>
                </div>
            </div>
        </div>
        <!-- end user dropdown -->

    </div>
    <!-- end right actions -->

</div><!-- /navbar-header -->
</div><!-- /layout-width -->
</header>

<style>
:root {
    --mpesa-green:       #00a651;
    --mpesa-green-dark:  #007a3d;
    --mpesa-green-light: #34c470;
    --light-green:       #e8f8ef;
}

#page-topbar {
    background: linear-gradient(135deg, var(--mpesa-green-dark) 0%, var(--mpesa-green) 100%) !important;
    box-shadow: 0 2px 16px rgba(0,0,0,.15);
    position: fixed; top:0; left:0; right:0; z-index:1030;
    height: 64px;
}
#page-topbar .layout-width,
#page-topbar .navbar-header {
    height: 64px;
}
#page-topbar .navbar-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 1.25rem;
}

/* Hamburger */
.topnav-hamburger {
    background: rgba(255,255,255,.12);
    border: 1px solid rgba(255,255,255,.2);
    border-radius: 8px;
    color: #fff;
    transition: all .2s;
}
.topnav-hamburger:hover { background: rgba(255,255,255,.22); color: #fff; }
.hamburger-icon        { display:flex; flex-direction:column; gap:4px; }
.hamburger-icon span   { display:block; width:18px; height:2px; background:#fff; border-radius:2px; }

/* Ghost icon buttons */
.btn-ghost-secondary {
    background: rgba(255,255,255,.1);
    border: 1px solid rgba(255,255,255,.2);
    color: #fff;
    width: 38px; height: 38px;
    display: flex; align-items: center; justify-content: center;
    transition: all .2s;
}
.btn-ghost-secondary:hover {
    background: rgba(255,255,255,.22);
    color: #fff;
    transform: translateY(-1px);
}

/* User dropdown hover */
#page-header-user-dropdown:hover {
    background: rgba(255,255,255,.2) !important;
}

/* Dropdown items */
.dropdown-item {
    font-size: .83rem;
    border-radius: 6px;
    margin: 1px 6px;
    transition: background .15s;
}
.dropdown-item:hover {
    background: var(--light-green);
    color: var(--mpesa-green-dark);
}
.dropdown-item.text-danger:hover {
    background: #ffebee;
    color: #c0392b !important;
}

/* Scrollbar */
.dropdown-menu ::-webkit-scrollbar { width: 4px; }
.dropdown-menu ::-webkit-scrollbar-track { background: #f7fafc; }
.dropdown-menu ::-webkit-scrollbar-thumb { background: #cbd5e0; border-radius: 2px; }

/* Session blink */
@keyframes blink {
    0%,100% { opacity:1; }
    50%      { opacity:.3; }
}

/* Body offset */
body { padding-top: 64px; }

@media (max-width: 991px) {
    #page-topbar, #page-topbar .layout-width, #page-topbar .navbar-header { height: 58px; }
    body { padding-top: 58px; }
}
</style>