<?php

/**
 * UI Auto Shell (Dynamic Sidebar) — STRICT ACL
 * - No fallback, no static items.
 * - Renders menus from jos_admin_menus filtered by jos_admin_rolemenus (role_id + can_view=1).
 * - Role resolved from current_user(); if missing, tries jos_admin_users_roles → jos_admin_roles.
 *
 * REQUIREMENTS:
 *   - auth.php should: require this file, then call pacific_enable_autoshell();
 *   - $con (mysqli) available globally after auth bootstrap.
 */

if (!function_exists('pacific_enable_autoshell')) {

  function pacific_enable_autoshell()
  {
    if (defined('PACIFIC_NO_SHELL') && PACIFIC_NO_SHELL) return;
    static $once = false;
    if ($once) return;
    $once = true;
    if (!ob_get_level()) ob_start();

    register_shutdown_function(function () {
      $CONTENT = ob_get_clean();

      // If not HTML, passthrough
      foreach (headers_list() as $h) {
        $hl = strtolower($h);
        if (strpos($hl, 'content-disposition: attachment') === 0) {
          echo $CONTENT;
          return;
        }
        if (strpos($hl, 'content-type:') === 0 && strpos($hl, 'text/html') === false) {
          echo $CONTENT;
          return;
        }
      }

      // ---------- helpers ----------
      $con = $GLOBALS['con'] ?? null;

      $user = null;
      if (function_exists('current_user')) {
        $user = current_user();
      } else {
        // minimal session-based fallback for identity only (NOT for menus)
        $user = [
          'id'        => (int)($_SESSION['admin_user']['id'] ?? 0),
          'name'      => (string)($_SESSION['admin_user']['name'] ?? ($_SESSION['username'] ?? 'Administrator')),
          'role_id'   => (int)($_SESSION['admin_user']['role_id'] ?? 0),
          'role_name' => (string)($_SESSION['admin_user']['role'] ?? ''),
        ];
      }

      $title    = $GLOBALS['page_title'] ?? 'Dashboard';
      // ---- Force userName to come from DB ----
      $userId = (int)($user['id'] ?? 0);
      $userName = 'Administrator';

      if ($userId > 0 && isset($GLOBALS['con']) && $GLOBALS['con'] instanceof mysqli) {
        $stmt = $GLOBALS['con']->prepare("SELECT name FROM jos_admin_users WHERE id = ? LIMIT 1");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res && $row = $res->fetch_assoc()) {
          $userName = $row['name'];
        }
        $stmt->close();
      }

      $iconBase = '/adminconsole/assets/menuicons/'; // local icons base

      // ---- tiny DB helpers ----
      $table_exists = function (mysqli $con, string $t): bool {
        $t = mysqli_real_escape_string($con, $t);
        $r = mysqli_query($con, "SHOW TABLES LIKE '$t'");
        return ($r && mysqli_num_rows($r) > 0);
      };
      $col_exists = function (mysqli $con, string $t, string $c): bool {
        $t = mysqli_real_escape_string($con, $t);
        $c = mysqli_real_escape_string($con, $c);
        $r = mysqli_query($con, "SHOW COLUMNS FROM `$t` LIKE '$c'");
        return ($r && mysqli_num_rows($r) > 0);
      };

      // ---- resolve role if missing ----
      $resolve_role = function (mysqli $con, int $user_id) use ($table_exists, $col_exists): ?array {
        if ($user_id <= 0) return null;
        if (!$table_exists($con, 'jos_admin_users_roles') || !$table_exists($con, 'jos_admin_roles')) return null;
        if (!$col_exists($con, 'jos_admin_users_roles', 'user_id') || !$col_exists($con, 'jos_admin_users_roles', 'role_id')) return null;
        if (!$col_exists($con, 'jos_admin_roles', 'id') || !$col_exists($con, 'jos_admin_roles', 'name')) return null;

        $has_status  = $col_exists($con, 'jos_admin_roles', 'status');
        $has_orderby = $col_exists($con, 'jos_admin_roles', 'orderby');

        $sql = "
        SELECT r.id AS role_id, r.name AS role_name
        FROM jos_admin_users_roles ur
        JOIN jos_admin_roles r ON r.id = ur.role_id
        WHERE ur.user_id = ?
      ";
        if ($has_status)  $sql .= " AND r.status = 1";
        if ($has_orderby) $sql .= " ORDER BY r.orderby ASC, r.id ASC";
        else              $sql .= " ORDER BY r.id ASC";
        $sql .= " LIMIT 1";

        $st = $con->prepare($sql);
        $st->bind_param('i', $user_id);
        $st->execute();
        $res = $st->get_result();
        $row = $res->fetch_assoc();
        $st->close();
        return $row ?: null;
      };

      // ---- STRICT ACL fetcher (MAIN MENU ONLY) ----
      $fetch_sections_strict = function (mysqli $con, array $user) use ($table_exists, $col_exists): array {
        $role_id = (int)($user['role_id'] ?? 0);
        if ($role_id <= 0) {
          $maybe = ($user['id'] ?? 0) ? ($GLOBALS['__role_cache'] ?? null) : null;
          if (!$maybe && isset($user['id'])) {
            $maybe = ($GLOBALS['__role_cache'] = (function () use ($con, $user, $table_exists, $col_exists) {
              $has_tbl_ur = $table_exists($con, 'jos_admin_users_roles');
              $has_tbl_r  = $table_exists($con, 'jos_admin_roles');
              if (!$has_tbl_ur || !$has_tbl_r) return null;
              $st = $con->prepare("
              SELECT r.id AS role_id, r.name AS role_name
              FROM jos_admin_users_roles ur
              JOIN jos_admin_roles r ON r.id = ur.role_id
              WHERE ur.user_id = ?
              ORDER BY r.id ASC
              LIMIT 1
            ");
              $uid = (int)$user['id'];
              $st->bind_param('i', $uid);
              $st->execute();
              $res = $st->get_result();
              $row = $res->fetch_assoc();
              $st->close();
              return $row ?: null;
            })());
          }
          if (!empty($maybe['role_id'])) $role_id = (int)$maybe['role_id'];
        }
        if ($role_id <= 0) return [];

        // Ensure ACL tables/columns exist
        if (!$table_exists($con, 'jos_admin_rolemenus')) return [];
        foreach (['menu_id', 'role_id', 'can_view'] as $c) if (!$col_exists($con, 'jos_admin_rolemenus', $c)) return [];

        if (!$table_exists($con, 'jos_admin_menus')) return [];
        foreach (['id', 'menu_name', 'menu_link', 'icon', 'parent_id', 'orderby', 'status'] as $c) if (!$col_exists($con, 'jos_admin_menus', $c)) return [];
        $has_section = $col_exists($con, 'jos_admin_menus', 'section');

        // *** CHANGED: restrict to MAIN items only (parent_id = 0) ***
        $sql = "
SELECT 
    m.id,
    m.menu_name,
    m.menu_link,
    m.icon,
    m.parent_id,
    m.orderby,
    COALESCE(m.section,'Main') AS section
FROM jos_admin_menus m
INNER JOIN jos_admin_rolemenus rm
        ON rm.menu_id = m.id
       AND rm.can_view = 1
WHERE m.status = 1
AND rm.role_id = ?
ORDER BY m.parent_id ASC,
         m.orderby ASC,
         m.menu_name ASC
";
        $st = $con->prepare($sql);
        $st->bind_param('i', $role_id);
        $st->execute();
        $res  = $st->get_result();

        // Group by section (no children/submenus)
        $sections = [];
        $menus = [];
        $children = [];

        while ($r = $res->fetch_assoc()) {

          if ((int)$r['parent_id'] === 0) {
            $menus[$r['id']] = $r;
            $menus[$r['id']]['children'] = [];
          } else {
            $children[] = $r;
          }
        }

        /* attach children */
        foreach ($children as $child) {
          $pid = (int)$child['parent_id'];

          if (isset($menus[$pid])) {
            $menus[$pid]['children'][] = $child;
          }
        }

        /* group by section */
        foreach ($menus as $menu) {
          $sec = $menu['section'] ?: 'Main';
          $sections[$sec][] = $menu;
        }
        $st->close();
        return $sections;
      };

      // ---- Build sections (strict) ----
      $sections = [];
      if ($con instanceof mysqli) {
        $sections = $fetch_sections_strict($con, $user ?? []);
      }

?>
      <!doctype html>
      <html lang="en">

      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1">
        <title><?= htmlspecialchars($title) ?> • Admin Console</title>
        <style>
          .content .logout-top {
            display: none !important
          }

          :root {
            --bg: #ffffff;
            --panel: #e9f0ff;
            --text: #000000;
            --muted: #000000;
            --brand: #5C89C1
          }

          * {
            box-sizing: border-box
          }

          body {
            margin: 0;
            background: var(--bg);
            color: var(--text);
            font: 500 15px/1.45 system-ui, Segoe UI, Roboto, Arial
          }

          /* --- nav-topbar Fixed --- */
          .nav-topbar {
            position: sticky;
            top: 0;
            z-index: 9999;
            height: 70px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 20px;
            background: linear-gradient(90deg, #5C89C1, #5C89C1);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
          }

          /* Left button */
          .nav-hamb {
            border: none;
            background: rgba(255, 255, 255, 0.15);
            color: #fff;
            border-radius: 8px;
            padding: 10px 14px;
            cursor: pointer;
            font-size: 20px;
          }

          .nav-hamb:hover {
            background: rgba(255, 255, 255, 0.25);
          }

          /* Hello user text */
          .nav-topbar span {
            color: #fff !important;
            font-weight: 600;
            font-size: 16px;
          }

          /* Logout button */
          .logout-top {
            background: #ef4444;
            color: #fff !important;
            text-decoration: none;
            padding: 10px 18px;
            border-radius: 8px;
            font-weight: 600;
            transition: 0.3s;
          }

          .logout-top:hover {
            background: #dc2626;
          }

          /* Fix content overlap */
          .content {
            padding: 20px;
            background: #f8fafc;
            min-height: calc(100vh - 70px);
          }

          .nav-topbar .grow {
            flex: 1
          }

          .nav-hamb {
            border: 1px solid rgba(255, 255, 255, .18);
            background: rgba(255, 255, 255, .06);
            border-radius: 10px;
            padding: 8px 10px;
            cursor: pointer
          }







          .brand-text {
            font-weight: 700
          }


          .nav a {
            display: flex;
            gap: 10px;
            align-items: center;
            color: var(--text);
            text-decoration: none;
            padding: 8px 10px;
            border-radius: 8px
          }

          .nav a:hover {
            background: rgba(255, 255, 255, .06)
          }

          .nav .ico {
            width: 20px;
            height: 20px;
            object-fit: contain
          }

          .label {
            display: inline
          }
        </style>
      </head>
      <style id="cards-grid-css">
        /* --- Dashboard/Masters cards --- */
        .grid {
          display: grid;
          gap: 16px;
          grid-template-columns: repeat(auto-fit, minmax(240px, 1fr))
        }

        .card {
          background: #1e293b;
          border: 1px solid rgba(255, 255, 255, .08);
          border-radius: 14px;
          padding: 16px;
          box-shadow: 0 8px 30px rgba(0, 0, 0, .18)
        }

        .card h2 {
          margin: 0 0 6px 0;
          font-size: 28px
        }

        .card .muted {
          color: #000000;
          font-size: 13px
        }

        .btn {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          background: #1e293b;
          color: #fff;
          text-decoration: none;
          border: 1px solid rgba(255, 255, 255, .14);
          padding: 8px 12px;
          border-radius: 10px
        }

        .btn.primary {
          background: linear-gradient(90deg, #60a5fa, #22d3ee);
          border-color: transparent
        }

        .masters-list .card {
          padding: 18px
        }

        .masters-list .card h3 {
          margin: 0 0 6px
        }

        .masters-list .card p {
          margin: 0 0 10px;
          color: #000000
        }

        @media(max-width:768px) {
          .grid {
            gap: 12px
          }

          .card {
            padding: 14px
          }
        }

        /*  .nav .ico {*/
        /*  filter: brightness(0) invert(1);*/
        /*}*/
        /* ===== NAVBAR ===== */

        .nav-topbar {
          position: sticky;
          top: 0;
          z-index: 9999;
          height: 70px;
          background: #5C89C1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 20px;
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
        }

        .logo {
          height: 45px;
        }

        .navbar {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 22px;
          flex: 1;
        }

        .navbar a {
          color: #fff;
          text-decoration: none;
          font-weight: 500;
          display: flex;
          align-items: center;
          gap: 6px;
          transition: 0.3s;
        }

        .navbar a:hover {
          opacity: 0.8;
        }

        .navbar .ico {
          width: 18px;
          height: 18px;
          object-fit: contain;
        }


        .user-area {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-left: auto;
          flex-shrink: 0;
        }

        .admin-name {
          color: #fff;
          font-size: 16px;
          font-weight: 600;
        }

        .nav-left {
          min-width: 220px;
        }

        .user-area {
          min-width: 220px;
          justify-content: flex-end;
        }

        .logout-btn {
          background: #ef4444;
          color: #fff !important;
          text-decoration: none;
          padding: 10px 16px;
          border-radius: 8px;
          font-weight: 600;
          transition: 0.3s;
        }

        .logout-btn:hover {
          background: #dc2626;
        }

        /* hide mobile logout on desktop */
        .mobile-logout {
          display: none !important;
        }

        .nav-hamb {
          display: none;
          border: none;
          background: rgba(255, 255, 255, 0.2);
          color: white;
          font-size: 24px;
          padding: 8px 14px;
          border-radius: 8px;
          cursor: pointer;
        }

        /* CONTENT */
        .content {
          padding: 20px;
          min-height: calc(100vh - 70px);
          background: #f8fafc;
        }

        /* MOBILE */
        @media(max-width:768px) {

          .nav-hamb {
            display: block;
            order: 3;
          }

          /* hide desktop right area */
          .admin-name {
            display: none;
          }

          .desktop-logout {
            display: none;
          }

          .user-area {
            min-width: auto;
          }

          /* mobile menu */
          .navbar {
            position: absolute;
            top: 70px;
            left: 0;
            width: 100%;
            background: #5C89C1;
            display: none;
            flex-direction: column;
            align-items: stretch;
            padding: 0;
            gap: 0;
            z-index: 9999;
          }

          .navbar.active {
            display: flex;
          }

          /* main nav items */
          .menu-item {
            width: 100%;
            padding: 0;
          }

          .menu-item>a {
            width: 100%;
            padding: 14px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.15);
            justify-content: flex-start;
          }

          /* IMPORTANT: hide submenus on mobile */
          .submenu {
            display: none !important;
          }

          .menu-item:hover .submenu {
            display: none !important;
          }

          /* mobile logout */
          .mobile-logout {
            display: block !important;
            width: 100%;
            text-align: left;
            padding: 14px 20px;
            border-radius: 0;
            margin: 0;
            background: #ef4444;
          }
        }

        /* DROPDOWN MENU */

        .menu-item {
          position: relative;
        }

        .submenu {
          position: absolute;
          top: 100%;
          left: 0;

          min-width: 420px;

          background: #fff;
          border-radius: 12px;
          box-shadow: 0 10px 30px rgba(0, 0, 0, .15);

          padding: 15px;

          /* HIDE DEFAULT */
          display: none;

          grid-template-columns: repeat(4, 1fr);
          gap: 8px;

          z-index: 999;
        }

        .submenu a {
          color: #1e293b !important;
          padding: 10px;
          border-radius: 8px;
          text-decoration: none;
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
        }

        /* bullet before submenu text */
        .submenu a::before {
          /* content: "➣"; */
          content: "●";
          font-size: 10px;
          font-weight: bold;
          color: #000000;
          line-height: 1;
        }

        .submenu a:hover {
          background: #5C89C1;
          color: #000000 !important;
          ;
        }

        /* hover show */
        .menu-item:hover .submenu {
          display: grid;
        }
      </style>

      <body>
        <div class="nav-topbar">

          <div class="nav-left">
            <a href="/adminconsole/index.php" class="logo-link">
              <img src="/adminconsole/uploads/logo.png" alt="Logo" class="logo">
            </a>
          </div>

          <!-- Desktop Menu -->
          <div class="navbar" id="navbarMenu">
            <?php if (!empty($sections)): ?>
              <?php foreach ($sections as $sec => $roots): ?>
                <?php foreach ($roots as $r): ?>

                  <div class="menu-item">

                    <a href="<?= htmlspecialchars($r['menu_link']) ?>">

                      <?php if (!empty($r['icon'])): ?>
                        <img class="ico"
                          src="<?= htmlspecialchars($iconBase . $r['icon']) ?>"
                          alt="">
                      <?php endif; ?>

                      <?= htmlspecialchars($r['menu_name']) ?>

                    </a>

                    <?php if (!empty($r['children'])): ?>
                      <div class="submenu">

                        <?php foreach ($r['children'] as $sub): ?>

                          <a href="<?= htmlspecialchars($sub['menu_link']) ?>">
                            <?= htmlspecialchars($sub['menu_name']) ?>
                          </a>

                        <?php endforeach; ?>

                      </div>
                    <?php endif; ?>

                  </div>

                <?php endforeach; ?>
              <?php endforeach; ?>
            <?php endif; ?>
            <a href="/adminconsole/logout.php"
              class="logout-btn mobile-logout">
              Logout
            </a>
          </div>
          <div class="user-area">

            <span class="admin-name">
              Hello, <?= htmlspecialchars($userName) ?>
            </span>

            <a href="/adminconsole/logout.php"
              class="logout-btn desktop-logout">
              Logout
            </a>

          </div>

          <!-- Mobile nav-hamburger -->
          <button id="menuToggle" class="nav-hamb">
            ☰
          </button>

        </div>


        <main class="content">
          <?= $CONTENT ?>
        </main>

        <script>
          document.getElementById("menuToggle")
            .addEventListener("click", function() {

              document.getElementById("navbarMenu")
                .classList.toggle("active");

            });

          // Auto-highlight active link
          (function() {
            var p = location.pathname.replace(/\/$/, "");
            document.querySelectorAll(".navbar a").forEach(function(a) {
              var h = a.getAttribute("href");
              if (!h) return;
              var u = document.createElement("a");
              u.href = h;
              var hp = u.pathname.replace(/\/$/, "");
              if (p === hp || p.indexOf(hp + "/") === 0) {
                a.classList.add("active");
              }
            });
          })();
        </script>
      </body>

      </html>
<?php
    });
  }
}
