<?php
// public/navbar.php
require_once __DIR__ . '/auth_stub.php';

// Har doim login bo‘lsin:
require_login();

// Joriy user ma'lumotlari
$userName     = current_user_name() ?: 'Foydalanuvchi';
$active       = $active ?? ''; // 'dashboard', 'marking', ...
$currentRole  = current_user_role_name() ?: 'user';

// Joriy foydalanuvchi permissions (code lar ro‘yxati)
$permAssoc = current_user_permissions();              // ['users.view' => true, ...]
$permList  = array_keys($permAssoc);                  // ['users.view', ...]
?>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary shadow-sm"
     style="background: linear-gradient(90deg, #0d6efd, #2563eb);">
  <div class="container-fluid page-wrapper">
    <a class="navbar-brand fw-semibold" href="index.php">
      <i class="fa-solid fa-water me-1"></i> Markirovka Tizimi
    </a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
      <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse justify-content-between" id="navbarNav">
      <ul class="navbar-nav">
        <!-- Bosh sahifa / Dashboard -->
        <li class="nav-item" data-permission="index.view">
          <a class="nav-link <?= $active === 'dashboard' ? 'active' : '' ?>" href="index.php">
            Bosh sahifa
          </a>
        </li>

        <!-- Marking -->
        <li class="nav-item" data-permission="marking.view">
          <a class="nav-link <?= $active === 'marking' ? 'active' : '' ?>" href="marking.php">
            Markirovka
          </a>
        </li>

        <!-- Products -->
        <li class="nav-item" data-permission="products.view">
          <a class="nav-link <?= $active === 'products' ? 'active' : '' ?>" href="products.php">
            Mahsulotlar
          </a>
        </li>

        <!-- Categories -->
        <li class="nav-item" data-permission="categories.view">
          <a class="nav-link <?= $active === 'categories' ? 'active' : '' ?>" href="categories.php">
            Kategoriyalar
          </a>
        </li>

        <!-- Clients -->
        <li class="nav-item" data-permission="clients.view">
          <a class="nav-link <?= $active === 'clients' ? 'active' : '' ?>" href="clients.php">
            Mijozlar
          </a>
        </li>

        <!-- Sales -->
        <li class="nav-item" data-permission="sales.view">
          <a class="nav-link <?= $active === 'sales' ? 'active' : '' ?>" href="sales.php">
            Sotuv
          </a>
        </li>

        <!-- Transport -->
        <li class="nav-item" data-permission="transport.view">
          <a class="nav-link <?= $active === 'transport' ? 'active' : '' ?>" href="transport.php">
            Transport
          </a>
        </li>

        <!-- Reports -->
        <li class="nav-item" data-permission="reports.view">
          <a class="nav-link <?= $active === 'reports' ? 'active' : '' ?>" href="reports.php">
            Hisobot
          </a>
        </li>

        <!-- KM tekshirish -->
        <li class="nav-item" data-permission="km.view">
          <a class="nav-link <?= $active === 'km' ? 'active' : '' ?>" href="km.php">
            KM tekshirish
          </a>
        </li>

        <!-- Users -->
        <li class="nav-item" data-permission="users.view">
          <a class="nav-link <?= $active === 'users' ? 'active' : '' ?>" href="users.php">
            Foydalanuvchilar
          </a>
        </li>

        <!-- Roles & permissions admin -->
        <li class="nav-item" data-permission="roles.manage">
          <a class="nav-link <?= $active === 'roles' ? 'active' : '' ?>" href="admin/roles_permissions.php">
            Role & ruxsatlar
          </a>
        </li>
      </ul>

      <span class="navbar-text">
        <span class="user-chip d-inline-flex align-items-center gap-2 px-3 py-1 rounded-pill bg-light bg-opacity-75">
          <span class="user-avatar rounded-circle bg-primary text-white d-inline-flex justify-content-center align-items-center"
                style="width:28px;height:28px;font-size:0.9rem;">
            <?= strtoupper(mb_substr($userName, 0, 1, 'UTF-8')) ?>
          </span>
          <span class="fw-semibold text-dark"><?= htmlspecialchars($userName) ?></span>
          <span class="user-role-badge badge bg-secondary text-white text-capitalize">
            <?= htmlspecialchars($currentRole) ?>
          </span>
        </span>
      </span>
    </div>
  </div>
</nav>

<!-- Joriy user permissions ni JS'ga chiqarib qo'yamiz -->
<script>
  window.USER_PERMISSIONS = <?=
    json_encode(array_values($permList), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
  ?>;
</script>

<script>
(function () {
  const AUTH_CHECK_URL = 'api/auth_check.php';
  const LOGIN_URL      = '/mark2/login.php?expired=1';

  // --- Sessiya tekshirish, har 10 soniyada ---
  function redirectToLogin() {
    window.location.href = LOGIN_URL;
  }

  function startAuthPolling() {
    function checkAuth() {
      fetch(AUTH_CHECK_URL, {
        method: 'GET',
        credentials: 'include'
      })
        .then(function (resp) {
          if (resp.status === 401) {
            redirectToLogin();
          }
        })
        .catch(function () {
          // serverga ulana olmasa – vaqtincha jim turamiz
        });
    }

    checkAuth();
    setInterval(checkAuth, 10000);
  }

  // --- Permissionlar bilan ishlash (faqat local massivdan) ---
  const permSet = new Set(Array.isArray(window.USER_PERMISSIONS) ? window.USER_PERMISSIONS : []);

  // Bitta permission: 'users.edit' yoki wildcard 'users.*'
  function hasPermission(code) {
    if (!code) return false;
    code = String(code).trim();
    if (!code) return false;

    // To‘g‘ridan-to‘g‘ri bor-mi?
    if (permSet.has(code)) return true;

    // Wildcard: 'users.edit' -> 'users.*'
    const dotPos = code.indexOf('.');
    if (dotPos !== -1) {
      const prefix = code.substring(0, dotPos);
      const wild   = prefix + '.*';
      if (permSet.has(wild)) return true;
    }

    return false;
  }

  // Data-permission="a|b|c" bo‘lsa – ulardan EN KAMIDA BITTASI bo‘lsa yetarli.
  function elementAllowed(requiredString) {
    if (!requiredString) return false;
    const parts = requiredString
      .split('|')
      .map(function (s) { return s.trim(); })
      .filter(Boolean);

    if (!parts.length) return false;

    for (let i = 0; i < parts.length; i++) {
      if (hasPermission(parts[i])) {
        return true;
      }
    }
    return false;
  }

  function applyPermissions() {
    const permElements = document.querySelectorAll('[data-permission]');
    permElements.forEach(function (el) {
      const required = (el.getAttribute('data-permission') || '').trim();
      if (!required) return;

      const allowed = elementAllowed(required);

      if (!allowed) {
        const navItem = el.classList && el.classList.contains('nav-item')
          ? el
          : el.closest && el.closest('.nav-item');

        if (navItem) {
          navItem.style.display = 'none';
        } else {
          el.style.display = 'none';
        }
      }
    });
  }

  // GLOBAL qilib qo'yamiz – AJAX dan keyin ham chaqira olamiz
  window.applyAclPermissions = applyPermissions;
  window.hasAclPermission    = hasPermission;

  document.addEventListener('DOMContentLoaded', function () {
    startAuthPolling();
    applyPermissions(); // sahifa birinchi yuklanganda
  });
})();
</script>
