<?php
/* =============================================================================
 * File   : footer_mobile.php
 * Purpose: Mobile bottom menubar (modernized colors + accessible contrast)
 * Notes  : - Backwards-compatible with older pages (defines $fetch1, $hasTeam, AMS_Location)
 *          - Uses MySQLi only (no PDO). Charset/collation forced to utf8mb4_general_ci
 *          - Drop-in replacement: include this at the end of your page (before </body>)
 * ============================================================================= */

if (session_status() === PHP_SESSION_NONE) session_start();

/* --- Load config.php (user prefers config.php; fallback to reports-config.php) */
$cfg_main = __DIR__ . '/config.php';
$cfg_fall = __DIR__ . '/reports-config.php';
if (is_file($cfg_main)) {
    require_once $cfg_main;           // should provide $conn (mysqli)
} elseif (is_file($cfg_fall)) {
    require_once $cfg_fall;
}

/* --- Enforce charset & collation on mysqli links present ----------------- */
foreach (['conn','conn_crm','conn_crmplus'] as $k) {
    if (isset($$k) && $$k instanceof mysqli) {
        @mysqli_set_charset($$k, 'utf8mb4');
        @mysqli_query($$k, "SET NAMES 'utf8mb4' COLLATE 'utf8mb4_general_ci'");
    }
}

/* --- Ensure expected variables exist (back-compat) ---------------------- */
if (!isset($fetch1) || !is_array($fetch1)) {
    $fetch1 = [
        'empid'                => '',
        'Employee_Number'      => '',
        'Employee_Full_Name'   => '',
        'Team_Name'            => '',
        'AMS_Location'         => 'ALL',
        'Rider_Status'         => ''
    ];
    $uid = isset($_SESSION['user_id1']) ? (string)$_SESSION['user_id1'] : '';
    if ($uid !== '' && isset($conn) && $conn instanceof mysqli) {
        $esc = mysqli_real_escape_string($conn, $uid);
        $q = mysqli_query(
            $conn,
            "SELECT empid, Employee_Number, Employee_Full_Name, Team_Name, AMS_Location, Rider_Status
             FROM hr_dump
             WHERE empid='{$esc}' LIMIT 1"
        );
        if ($q && mysqli_num_rows($q) > 0) {
            $row = mysqli_fetch_assoc($q);
            $fetch1 = array_merge($fetch1, $row);
        }
    }
}

/* compute hasTeam if not present */
$hasTeam = $hasTeam ?? false;
if (!$hasTeam && !empty($fetch1['Employee_Number']) && isset($conn) && $conn instanceof mysqli) {
    $empNoEsc = mysqli_real_escape_string($conn, (string)$fetch1['Employee_Number']);
    $qt = mysqli_query($conn, "SELECT COUNT(*) c FROM hr_dump WHERE Functional_Reporting='{$empNoEsc}' AND (Status IS NULL OR Status!='Inactive')");
    if ($qt && ($r = mysqli_fetch_assoc($qt))) { $hasTeam = ((int)$r['c'] > 0); }
}

/* allowed IP map (optional include) */
$allowedIPs = [];
$ipMapFile = __DIR__ . '/include/ip_location.php';
if (is_file($ipMapFile)) {
    include $ipMapFile; // should set $allowedIPs
    if (!isset($allowedIPs) || !is_array($allowedIPs)) $allowedIPs = [];
}

/* pick visitor IP */
$userIP = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? ($_SERVER['REMOTE_ADDR'] ?? '');
if (strpos((string)$userIP, ',') !== false) { $userIP = trim(explode(',', $userIP)[0]); }

/* AMS_Location fallback */
$AMS_Location = (string)($fetch1['AMS_Location'] ?? 'ALL');

/* --- Paths --------------------------------------------------------------- */
$BASE   = defined('BASE_URL') ? rtrim(BASE_URL, '/') . '/' : '/';
$MOBILE = $BASE . 'mobile/';
$ASSET  = $BASE . 'mobile/';

/* --- Helpers ------------------------------------------------------------- */
if (!function_exists('h')) { function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); } }

$here = strtolower(basename($_SERVER['PHP_SELF'] ?? 'index.php'));
function is_active($names, $here){
    foreach ((array)$names as $n) {
        $n = strtolower(basename($n));
        if ($here === $n) return ' active';
    }
    return '';
}

/* --- Role-aware CRM/DST route ------------------------------------------- */
$ME = $_SESSION['auth'] ?? [];
$ROLE_ID = isset($ME['role_id']) ? (int)$ME['role_id'] : 0;
$crmHref = $MOBILE . 'crm_mobile.php';
if     ($ROLE_ID === 4) $crmHref = $MOBILE . 'dst.php';
elseif ($ROLE_ID === 6) $crmHref = $MOBILE . 'crm_mobile.php';
$crmLabel = ($ROLE_ID === 4) ? 'DST CRM' : 'CRM';
?>
<!-- ===== Modern Menubar (mobile) ======================================== -->
<style>
 
 

  /* Modern color tokens (soft, accessible, contemporary) */
  :root{
    --menubar-height: 72px;
    --bg-glass: rgba(255,255,255,0.72);
    --menubar-bg: linear-gradient(180deg, rgba(250,250,252,0.95), rgba(243,245,250,0.95));
    --shadow-soft: 0 8px 22px rgba(25, 35, 55, 0.10);
    --icon-bg: linear-gradient(180deg, rgba(255,255,255,0.85), rgba(250,250,252,0.85));
    --muted: #6b7280;
    --accent: #2F4DB8;         /* header-like blue (active icon) */
  --accent-2: #FF7A59;      /* coral accent for gradient */
    --label-color: #6b7280;
  --label-active: var(--accent);
--ams-bg: linear-gradient(135deg, var(--accent), var(--accent-2));
    --ams-fg: #ffffff;
  }

  .theme-dark{
    --menubar-bg: linear-gradient(180deg, rgba(18,24,46,0.92), rgba(17,21,38,0.92));
    --bg-glass: rgba(20,28,46,0.76);
    --shadow-soft: 0 10px 28px rgba(0,0,0,0.55);
    --icon-bg: rgba(255,255,255,0.03);
    --muted: #cbd5e1;
    --accent: #60a5fa;
    --accent-2: #ff9b77;
    --label-color: #cbd5e1;
    --label-active: var(--accent);
    --ams-bg: linear-gradient(135deg,var(--accent), var(--accent-2));
    --ams-fg: #041224;
  }

  /* container */
  .menubar-area {
    position: fixed;
    left: 10px;
    right: 10px;
    bottom: 12px;
    z-index: 12000;
    height: var(--menubar-height);
    display:flex;
    align-items:center;
    justify-content:center;
    padding: 8px;
    border-radius: 16px;
    background: var(--menubar-bg);
    box-shadow: var(--shadow-soft);
    backdrop-filter: blur(8px) saturate(110%);
  }

  /* ensure content above menubar */
  .page-content, .content-inner { padding-bottom: calc(var(--menubar-height) + 32px) !important; }

  .toolbar-inner.menubar-nav {
    width:100%;
    max-width:1024px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:8px;
    padding:0 6px;
    box-sizing:border-box;
  }

  /* nav-link tile */
  .menubar-area .nav-link {
    text-decoration:none;
    display:inline-flex;
    flex-direction:column;
    align-items:center;
    justify-content:center;
    width:64px;
    height:56px;
    border-radius:12px;
    position:relative;
    color: var(--muted);
    transition: transform .18s cubic-bezier(.2,.9,.2,1), color .12s ease, box-shadow .12s ease;
    font-size:18px;
    gap:6px;
    -webkit-font-smoothing:antialiased;
    -moz-osx-font-smoothing:grayscale;
  }

  .menubar-area .nav-link:hover { transform: translateY(-4px); color: var(--label-active); }

  .menubar-area .icon-tile {
    display:inline-flex;
    width:44px;
    height:44px;
    border-radius:10px;
    align-items:center;
    justify-content:center;
    background: var(--icon-bg);
    box-shadow: 0 6px 18px rgba(15,22,40,0.06);
    transition: box-shadow .12s ease, transform .12s ease;
  }

  .menubar-area .nav-link.active .icon-tile {
    box-shadow: 0 10px 26px rgba(30, 60, 120, 0.12);
    transform: translateY(-2px) scale(1.03);
    color: var(--label-active);
  }

  .menubar-area .nav-label{
    font-size:11px;
    line-height:1;
    color: var(--label-color);
    letter-spacing:.16px;
    user-select:none;
    margin-top:2px;
  }

  /* force svgs follow currentColor */
  .menubar-area svg, .menubar-area svg * { color: inherit !important; fill: currentColor !important; stroke: currentColor !important; }

  /* center AMS / Add button */
  .menubar-area .nav-link.add-post{
    width:72px; height:72px;
    border-radius:16px;
    transform: translateY(-22px);
    display:flex; align-items:center; justify-content:center;
    padding:0; background: transparent;
  }
  .menubar-area .nav-link.add-post .ams-btn {
    width:64px; height:64px;
    border-radius:14px;
    display:flex; align-items:center; justify-content:center; flex-direction:column;
    text-decoration:none; font-weight:600;
    color: var(--ams-fg);
    background: var(--ams-bg);
    box-shadow: 0 18px 36px rgba(20,30,60,0.14);
    border: 2px solid rgba(255,255,255,0.06);
  }
  .menubar-area .nav-link.add-post .ams-label { font-size:11px; margin-top:4px; color: rgba(255,255,255,0.95); }

  /* small devices */
  @media (max-width:420px){
    .menubar-area { left:6px; right:6px; bottom:10px; }
    .menubar-area .nav-link { width:56px; height:50px; gap:4px; }
    .menubar-area .icon-tile { width:38px; height:38px; }
    .menubar-area .nav-link.add-post { width:66px; height:66px; transform: translateY(-24px); }
    .menubar-area .nav-link.add-post .ams-btn { width:58px; height:58px; }
    .menubar-area .nav-label{ font-size:10px; }
  }
</style>

<div class="menubar-area" role="navigation" aria-label="Mobile menubar">
  <div class="toolbar-inner menubar-nav">

    <!-- Home -->
    <a href="<?php echo h($MOBILE.'index.php'); ?>"
       class="nav-link<?php echo is_active(['index.php','home_unified.php'], $here); ?>"
       aria-label="Home" title="Home">
      <span class="icon-tile" aria-hidden="true">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 22 22" aria-hidden="true"><path d="M21.44 11.035a.75.75 0 0 1-.69.465H18.5V19A2.25 2.25 0 0 1 16.25 21.25h-3a.75.75 0 0 1-.75-.75V16a.75.75 0 0 0-.75-.75h-1.5a.75.75 0 0 0-.75.75v4.5a.75.75 0 0 1-.75.75h-3A2.25 2.25 0 0 1 3.5 19v-7.5H1.25a.75.75 0 0 1-.69-.465.75.75 0 0 1 .158-.818l9.75-9.75A.75.75 0 0 1 11 .246a.75.75 0 0 1 .533.222l9.75 9.75a.75.75 0 0 1 .158.818z"/></svg>
      </span>
    </a>

    <!-- Projects / Search with label -->
    <a href="<?php echo h($MOBILE.'projects_mobile.php'); ?>"
       class="nav-link<?php echo is_active(['projects_mobile.php','projects_mobile'], $here); ?>"
       aria-label="Projects" title="Projects">
      <span class="icon-tile" aria-hidden="true">
        <svg width="20" height="20" viewBox="0 0 24 24" aria-hidden="true"><path d="M11 19C15.4183 19 19 15.4183 19 11C19 6.58172 15.4183 3 11 3C6.58172 3 3 6.58172 3 11C3 15.4183 6.58172 19 11 19Z" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/><path d="M21 21L16.65 16.65" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </span>
      <span class="nav-label">Projects</span>
    </a>

    <!-- Center AMS / Add -->
    <?php if ($ROLE_ID === 4): ?>
      <a href="<?php echo h($BASE . 'mobile/ams/user/dashboard.php'); ?>"
         class="nav-link add-post<?php echo is_active(['dashboard.php'], $here); ?>"
         aria-label="AMS - Clock In / Out" title="AMS">
        <span class="ams-btn" role="img" aria-hidden="true">
          <span class="ams-ico" style="width:14px;height:14px;border-radius:4px;display:block;background:rgba(255,255,255,0.9);"></span>
          <span class="ams-label">AMS</span>
        </span>
      </a>
    <?php else: ?>
      <a href="<?php echo h($MOBILE.'crm_add.php'); ?>"
         class="nav-link add-post<?php echo is_active(['crm_add.php'], $here); ?>"
         aria-label="Add new" title="Add">
        <span class="ams-btn" style="background:var(--icon-bg); color:var(--accent); border:0;">
          <i class="fa-solid fa-plus" aria-hidden="true" style="font-size:18px;"></i>
          <span class="ams-label">Add</span>
        </span>
      </a>
    <?php endif; ?>

    <!-- Chat / CRM -->
    <a href="<?php echo h($crmHref); ?>"
       class="nav-link<?php echo is_active(['crm_mobile.php','dst.php','chat.php'], $here); ?>"
       aria-label="<?php echo h($crmLabel); ?>" title="<?php echo h($crmLabel); ?>">
      <span class="icon-tile" aria-hidden="true">
        <svg width="20" height="20" viewBox="0 0 511.606 511.606" aria-hidden="true"><path d="M436.594 74.943c-99.917-99.917-261.637-99.932-361.568 0-80.348 80.347-95.531 199.817-48.029 294.96L.662 485.742c-3.423 15.056 10.071 28.556 25.133 25.133l115.839-26.335c168.429 84.092 369.846-37.653 369.846-228.812 0-68.29-26.595-132.494-74.886-180.785zM309.143 319.394h-160c-11.598 0-21-9.402-21-21s9.402-21 21-21h160c11.598 0 21 9.402 21 21s-9.402 21-21 21zm53.334-85.333H149.143c-11.598 0-21-9.402-21-21s9.402-21 21-21h213.334c11.598 0 21 9.402 21 21s-9.403 21-21 21z"/></svg>
      </span>
      <span class="nav-label"><?php echo h($crmLabel); ?></span>
    </a>

    <!-- Profile -->
    <a href="<?php echo h($MOBILE.'profile_mobile.php'); ?>"
       class="nav-link<?php echo is_active(['profile_mobile.php'], $here); ?>"
       aria-label="Profile" title="Profile">
      <span class="icon-tile" aria-hidden="true">
        <svg width="18" height="18" viewBox="0 0 16 21" aria-hidden="true"><path d="M8 7.75a3.75 3.75 0 1 0 0-7.5 3.75 3.75 0 1 0 0 7.5zm7.5 9v1.5a.75.75 0 0 1-.217.532C13.61 20.455 8.57 20.5 8 20.5s-5.61-.045-7.282-1.718A.75.75 0 0 1 .5 18.25v-1.5a7.5 7.5 0 1 1 15 0z"/></svg>
      </span>
    </a>

  </div>
</div>

<!-- ===== Scripts (safe paths) =========================================== -->
<script>
  // Load local jquery only if no jQuery exists already
  (function(){
    if (typeof window.jQuery === 'undefined') {
      var s = document.createElement('script');
      s.src = "<?php echo h($ASSET.'assets/js/jquery.js'); ?>";
      s.async = false;
      document.head.appendChild(s);
      console.info("[Footer] local jquery loaded:", s.src);
    } else {
      console.info("[Footer] jQuery already present; skipping local jquery include.");
    }
  })();
</script>

<script src="<?php echo h($ASSET.'assets/vendor/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
<script src="<?php echo h($ASSET.'assets/vendor/swiper/swiper-bundle.min.js'); ?>"></script>
<script src="<?php echo h($ASSET.'assets/vendor/bootstrap-touchspin/dist/jquery.bootstrap-touchspin.min.js'); ?>"></script>
<script src="<?php echo h($ASSET.'assets/js/dz.carousel.js'); ?>"></script>
<script src="<?php echo h($ASSET.'assets/js/settings.js'); ?>"></script>
<script src="<?php echo h($ASSET.'assets/js/custom.js'); ?>"></script>

<script>
  // theme toggle hook (if present in header)
  document.getElementById('toggle-dark-menu')?.addEventListener('change', function(){
    (document.body || document.documentElement).classList.toggle('theme-dark', this.checked);
  });

  // Hide AMS button on its own dashboard page (optional)
  (function(){
    const here = "<?php echo h($here); ?>";
    if (here === 'dashboard.php') {
      document.querySelectorAll('.menubar-area .nav-link.add-post').forEach(n => n.style.display = 'none');
    }
  })();
</script>
<!-- Debug helper: shows console warnings if assets / deps are missing -->
<script>
(function(){
  try {
    console.groupCollapsed("[Footer Debug] Mobile Menubar Diagnostics");
    console.log("PHP-provided paths: BASE=%o, MOBILE=%o, ASSET=%o", "<?php echo addslashes($BASE ?? ''); ?>", "<?php echo addslashes($MOBILE ?? ''); ?>", "<?php echo addslashes($ASSET ?? ''); ?>");

    // 1) Check jQuery
    if (typeof jQuery === 'undefined') {
      console.warn("[Footer Debug] jQuery NOT found. Many scripts depend on jQuery.");
      addBanner("jQuery not loaded — check <?php echo addslashes($ASSET.'assets/js/jquery.js'); ?>");
    } else {
      console.log("[Footer Debug] jQuery version:", jQuery.fn && jQuery.fn.jquery ? jQuery.fn.jquery : "(unknown)");
    }

    // 2) Check for FontAwesome (common indicator: <i class='fa' or .fa styles)
    var faPresent = !!document.querySelector("link[href*='fontawesome'], link[href*='font-awesome'], i.fa, i.fas, i.fa-solid");
    if (!faPresent) {
      console.warn("[Footer Debug] FontAwesome not detected. Icons may be missing.");
      addBanner("FontAwesome not loaded — icons may be missing.");
    } else {
      console.log("[Footer Debug] Font / icon library detected.");
    }

    // 3) Check menubar element and computed styles
    var menubar = document.querySelector('.menubar-area');
    if (!menubar) {
      console.error("[Footer Debug] .menubar-area element not found on the page.");
      addBanner("Menubar not present in DOM. Check include placement.");
    } else {
      var cs = getComputedStyle(menubar);
      console.log("[Footer Debug] .menubar-area computed:", {
        display: cs.display,
        position: cs.position,
        bottom: cs.bottom,
        background: cs.backgroundImage || cs.backgroundColor,
        borderRadius: cs.borderRadius,
        boxShadow: cs.boxShadow
      });
      // If background is 'none' or transparent, flag it
      if ((!cs.backgroundImage || cs.backgroundImage === "none") && (cs.backgroundColor === "rgba(0, 0, 0, 0)" || cs.backgroundColor === "transparent")) {
        console.warn("[Footer Debug] Menubar has no visible background — maybe CSS overridden.");
        addBanner("Menubar CSS overridden — background appears transparent.");
      }
    }

    // 4) Check scripts loaded (simple attempt)
    var scripts = Array.from(document.scripts).slice(-12).map(s=>s.src || "[inline]").filter(Boolean);
    console.log("[Footer Debug] last scripts loaded:", scripts);

    // 5) Attach global error handler for the session (visible notice + console)
    window.__footerDebugErrors = window.__footerDebugErrors || [];
    window.addEventListener('error', function(e){
      window.__footerDebugErrors.push(e.error || (e.message + " @ " + e.filename + ":" + e.lineno));
      console.error("[Footer Debug] Uncaught error:", e.message, "at", e.filename+":"+e.lineno);
      addBanner("JS error: " + (e.message || "see console"));
    });
    window.addEventListener('unhandledrejection', function(ev){
      console.error("[Footer Debug] Unhandled Promise rejection:", ev.reason);
      addBanner("Promise rejection — see console");
    });

    console.groupEnd();

    /* Helper to create a small non-obtrusive banner (top-right) */
    function addBanner(msg){
      try {
        if (document.getElementById('footer-debug-banner')) {
          var el = document.getElementById('footer-debug-banner');
          el.innerText = el.innerText + " | " + msg;
          return;
        }
        var d = document.createElement('div');
        d.id = 'footer-debug-banner';
        d.style.position = 'fixed';
        d.style.right = '12px';
        d.style.top = '12px';
        d.style.zIndex = 999999;
        d.style.background = 'linear-gradient(90deg,#ffcccb,#ffefef)';
        d.style.color = '#2b2b2b';
        d.style.padding = '8px 12px';
        d.style.borderRadius = '10px';
        d.style.boxShadow = '0 6px 16px rgba(0,0,0,0.12)';
        d.style.fontSize = '13px';
        d.style.maxWidth = '320px';
        d.style.fontFamily = 'Arial, sans-serif';
        d.innerText = msg;
        document.body.appendChild(d);
      } catch(ex) { console.warn("[Footer Debug] banner create failed:", ex); }
    }
  } catch(ex) {
    console.error("[Footer Debug] internal debug script failed:", ex);
  }
})();
</script>

</body>
</html>
